Integrate CultMesh UI and URP cleanup

This commit is contained in:
Meta Vens 2026-06-30 19:14:49 +01:00
commit 4d7bb65868
131 changed files with 7209 additions and 5084 deletions

View file

@ -3,8 +3,10 @@ using System.Linq;
using System.Collections;
using System.Collections.Generic;
using GameCult.Aetheria.State.Verse;
using GameCult.Mesh;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.RenderGraphModule;
/// <summary>
/// Based on github.com/yangrc1234/VolumeCloud
@ -33,11 +35,11 @@ public class HaltonSequence
/// <summary>
/// Cloud renderer post processing.
/// </summary>
[ImageEffectAllowedInSceneView]
[ExecuteInEditMode,RequireComponent(typeof(Camera))]
[ImageEffectOpaque]
public class VolumeCloudRenderer : EffectBase
{
private static readonly Dictionary<Camera, VolumeCloudRenderer> RenderersByCamera = new Dictionary<Camera, VolumeCloudRenderer>();
[Header("Render Settings")]
[Range(0, 2)]
public int downSample = 1;
@ -50,16 +52,73 @@ public class VolumeCloudRenderer : EffectBase
private Matrix4x4 prevV;
private Camera mcam;
private HaltonSequence sequence = new HaltonSequence() { radix = 3 };
private const int TemporalHistoryVersion = 4;
private int appliedTemporalHistoryVersion = -1;
// The index of 4x4 pixels.
private int frameIndex = 0;
private bool firstFrame = true;
private AetheriaClientState _runtimeState;
private int _debugRenderCount;
private int _debugLastRenderFrame = -1;
[SerializeField]
private Shader cloudShader;
[SerializeField]
private Texture2D ditherTexture;
public static bool TryGetRenderer(Camera camera, out VolumeCloudRenderer renderer)
{
renderer = null;
return camera != null
&& RenderersByCamera.TryGetValue(camera, out renderer)
&& renderer != null
&& renderer.isActiveAndEnabled;
}
public int DebugRenderCount => _debugRenderCount;
public int DebugLastRenderFrame => _debugLastRenderFrame;
public RenderTexture DebugUndersampleBuffer => undersampleBuffer;
public RenderTexture DebugHistoryBuffer => fullBuffer != null && fullBuffer.Length > 0 ? fullBuffer[fullBufferIndex] : null;
public RenderTexture DebugCurrentCloudBuffer => fullBuffer != null && fullBuffer.Length > 1 ? fullBuffer[fullBufferIndex ^ 1] : null;
public bool DebugFirstFrame => firstFrame;
private void OnEnable()
{
var camera = GetComponent<Camera>();
if (camera != null)
RenderersByCamera[camera] = this;
ResetTemporalHistory();
}
private void OnDisable()
{
var camera = GetComponent<Camera>();
if (camera != null && RenderersByCamera.TryGetValue(camera, out var renderer) && renderer == this)
RenderersByCamera.Remove(camera);
}
void EnsureMaterial(bool force = false) {
if (cloudShader == null)
cloudShader = Shader.Find("Aetheria/CloudShader");
if (mat == null || force) {
mat = new Material(cloudShader);
ResetTemporalHistory();
}
}
private void ResetTemporalHistory()
{
firstFrame = true;
appliedTemporalHistoryVersion = TemporalHistoryVersion;
if (fullBuffer != null)
{
for (var i = 0; i < fullBuffer.Length; i++)
{
if (fullBuffer[i] != null)
fullBuffer[i].DiscardContents();
}
}
}
@ -94,8 +153,8 @@ public class VolumeCloudRenderer : EffectBase
{
try
{
return AetheriaUnityRuntimeClientProvider
.CurrentPlayerSettings("unity-volume-cloud-renderer");
_runtimeState ??= AetheriaUnityRuntimeClientProvider.RuntimeState("unity-volume-cloud-renderer");
return _runtimeState.PlayerSettings.Latest();
}
catch (Exception ex)
{
@ -105,31 +164,73 @@ public class VolumeCloudRenderer : EffectBase
return null;
}
[ImageEffectOpaque]
private void OnRenderImage(RenderTexture source, RenderTexture destination) {
if (cloudShader == null) {
Graphics.Blit(source, destination);
return;
}
public void RenderClouds(UnsafeCommandBuffer cmd, Camera camera, TextureHandle colorTarget, TextureHandle depthTarget)
{
mcam = GetComponent<Camera>();
if (camera != mcam || cloudShader == null)
return;
_debugRenderCount++;
_debugLastRenderFrame = Time.frameCount;
var width = mcam.pixelWidth >> downSample;
var height = mcam.pixelHeight >> downSample;
if (width <= 0 || height <= 0)
return;
this.EnsureMaterial();
EnsureMaterial();
EnsureDitherTexture();
if (appliedTemporalHistoryVersion != TemporalHistoryVersion)
ResetTemporalHistory();
EnsureArray(ref fullBuffer, 2);
firstFrame |= EnsureRenderTarget(ref fullBuffer[0], width, height, RenderTextureFormat.ARGBFloat, FilterMode.Bilinear);
firstFrame |= EnsureRenderTarget(ref fullBuffer[1], width, height, RenderTextureFormat.ARGBFloat, FilterMode.Bilinear);
firstFrame |= EnsureRenderTarget(ref undersampleBuffer, width , height, RenderTextureFormat.ARGBFloat, FilterMode.Bilinear);
firstFrame |= EnsureRenderTarget(ref undersampleBuffer, width, height, RenderTextureFormat.ARGBFloat, FilterMode.Bilinear);
frameIndex = (frameIndex + 1)% 16;
frameIndex = (frameIndex + 1) % 16;
fullBufferIndex = (fullBufferIndex + 1) % 2;
/* Some code is from playdead TAA. */
ApplyQualityKeywords();
//1. Pass1, Render a undersampled buffer. The buffer is dithered using blue noise and halton sequence.
//If it's first frame, force a high quality sample to make the initial history buffer good enough.
var gpuProjection = GL.GetGPUProjectionMatrix(mcam.projectionMatrix, true);
mat.SetMatrix("_CamInvProj", (gpuProjection * mcam.worldToCameraMatrix).inverse);
mat.SetVector("_ProjectionExtents", mcam.GetProjectionExtents());
mat.SetFloat("_RaymarchOffset", sequence.Get());
mat.SetVector("_TexelSize", undersampleBuffer.texelSize);
mat.SetFloat("_ResetHistory", firstFrame ? 1.0f : 0.0f);
mat.SetTexture("_UndersampleCloudTex", undersampleBuffer);
mat.SetMatrix("_PrevVP", gpuProjection * prevV);
cmd.SetRenderTarget(undersampleBuffer);
cmd.SetViewport(new Rect(0, 0, width, height));
cmd.ClearRenderTarget(false, true, Color.clear);
cmd.DrawProcedural(Matrix4x4.identity, mat, 0, MeshTopology.Triangles, 3, 1);
mat.SetTexture("_MainTex", firstFrame ? undersampleBuffer : fullBuffer[fullBufferIndex]);
cmd.SetRenderTarget(fullBuffer[fullBufferIndex ^ 1]);
cmd.SetViewport(new Rect(0, 0, width, height));
cmd.ClearRenderTarget(false, true, Color.clear);
cmd.DrawProcedural(Matrix4x4.identity, mat, 1, MeshTopology.Triangles, 3, 1);
mat.SetTexture("_CloudTex", fullBuffer[fullBufferIndex ^ 1]);
if (depthTarget.IsValid())
cmd.SetRenderTarget(colorTarget, depthTarget);
else
cmd.SetRenderTarget(colorTarget);
cmd.SetViewport(mcam.pixelRect);
cmd.DrawProcedural(Matrix4x4.identity, mat, 2, MeshTopology.Triangles, 3, 1);
prevV = mcam.worldToCameraMatrix;
firstFrame = false;
}
private void ApplyQualityKeywords()
{
if (firstFrame || quality == Quality.Ultra) {
mat.EnableKeyword("ULTRA_QUALITY");
mat.DisableKeyword("HIGH_QUALITY");
@ -151,30 +252,22 @@ public class VolumeCloudRenderer : EffectBase
mat.DisableKeyword("MEDIUM_QUALITY");
mat.EnableKeyword("LOW_QUALITY");
}
mat.SetMatrix("_CamInvProj", (Camera.current.projectionMatrix * Camera.current.worldToCameraMatrix).inverse);
mat.SetVector("_ProjectionExtents", mcam.GetProjectionExtents());
mat.SetFloat("_RaymarchOffset", sequence.Get());
mat.SetVector("_TexelSize", undersampleBuffer.texelSize);
Graphics.Blit(null, undersampleBuffer, mat, 0);
//2. Pass 2, blend undersampled image with history buffer to new buffer.
mat.SetTexture("_UndersampleCloudTex", undersampleBuffer);
mat.SetMatrix("_PrevVP", GL.GetGPUProjectionMatrix(mcam.projectionMatrix,false) * prevV);
mat.SetVector("_ProjectionExtents", mcam.GetProjectionExtents());
if (firstFrame) { //Wait, is this the first frame? If it is, the history buffer is empty yet. It will cause glitch if we use it directly. Fill it using the undersample buffer.
Graphics.Blit(undersampleBuffer, fullBuffer[fullBufferIndex]);
}
Graphics.Blit(fullBuffer[fullBufferIndex], fullBuffer[fullBufferIndex ^ 1], mat, 1);
//3. Pass3, Calculate lighting, blend final cloud image with final image.
mat.SetTexture("_CloudTex", fullBuffer[fullBufferIndex ^ 1]);
Graphics.Blit(source, destination, mat, 2);
//4. Cleanup
prevV = mcam.worldToCameraMatrix;
firstFrame = false;
}
private void EnsureDitherTexture()
{
if (ditherTexture == null)
ditherTexture = Resources.Load<Texture2D>("LDR_LLL1_0");
if (ditherTexture == null)
return;
Shader.SetGlobalTexture("_DitheringTex", ditherTexture);
Shader.SetGlobalVector("_DitheringCoords", new Vector4(
(float)Math.Max(1, Screen.width) / ditherTexture.width,
(float)Math.Max(1, Screen.height) / ditherTexture.height,
0,
0));
}
}

View file

@ -11,6 +11,7 @@ using UnityEngine.Rendering;
using UnityEngine.Serialization;
using static Unity.Mathematics.math;
using static Unity.Mathematics.noise;
using System.Collections.Generic;
/// <summary>
/// Drives the volume render.
@ -19,6 +20,7 @@ using static Unity.Mathematics.noise;
[RequireComponent( typeof( Camera ) )]
public class VolumeSampling : MonoBehaviour
{
private static readonly List<VolumeSampling> ActiveSamplers = new List<VolumeSampling>();
public Transform GridMesh;
public Camera GridCamera;
public GameSettings Settings;
@ -29,16 +31,58 @@ public class VolumeSampling : MonoBehaviour
public RenderTexture NebulaTint;
public AetheriaUnityRenderSplatViewportSource SplatViewportSource;
public AetheriaRenderSplatLayerRenderer SplatLayerRenderer;
public AetheriaSceneRenderSplatSource SceneSplatSource;
[SerializeField]
private bool useRuntimeRenderSplats;
[SerializeField]
private bool renderSplatsEveryFrame;
[SerializeField]
private float splatRenderIntervalSeconds = 0.25f;
private MeshRenderer _gridMeshRenderer;
private float _flowScroll;
private Transform _gridTransform;
private Camera _ownerCamera;
private Vector2 _lastSplatCenter;
private Vector2 _lastSplatSize;
private Vector2 _publishedSplatCenter;
private Vector2 _publishedSplatSize;
private float _nextSplatRenderTime;
private bool _hasRenderedSplats;
private GlobalKeyword _keywordFlowGlobal;
private GlobalKeyword _keywordFlowSlope;
private GlobalKeyword _keywordNoiseSlope;
public static void RenderForCamera(Camera camera)
{
if (camera == null)
return;
for (var i = 0; i < ActiveSamplers.Count; i++)
{
var sampler = ActiveSamplers[i];
if (sampler != null && sampler.TargetsCamera(camera))
sampler.RenderSamplingPass();
}
}
private void OnEnable()
{
if (!ActiveSamplers.Contains(this))
ActiveSamplers.Add(this);
}
private void OnDisable()
{
ActiveSamplers.Remove(this);
}
private void Start()
{
_ownerCamera = GetComponent<Camera>();
_keywordFlowGlobal = GlobalKeyword.Create("FLOW_GLOBAL");
_keywordFlowSlope = GlobalKeyword.Create("FLOW_SLOPE");
_keywordNoiseSlope = GlobalKeyword.Create("NOISE_SLOPE");
@ -53,12 +97,28 @@ public class VolumeSampling : MonoBehaviour
{
if(_gridTransform==null)
_gridTransform = GridCamera?.transform;
// Shader needs to know the position and scale of cameras used to render input textures
if(GridCamera != null)
Shader.SetGlobalVector("_GridTransform", new Vector4(_gridTransform.position.x,_gridTransform.position.z,GridCamera.orthographicSize*2));
RenderSplatTextures();
_flowScroll += Settings.DefaultEnvironment.Flow.GlobalScrollSpeed * Time.deltaTime;
UpdateGridMeshBounds();
}
private bool TargetsCamera(Camera camera)
{
_ownerCamera ??= GetComponent<Camera>();
return camera == _ownerCamera;
}
private void RenderSamplingPass()
{
if (_gridTransform == null)
_gridTransform = GridCamera?.transform;
RenderSplatTexturesIfNeeded();
PublishSamplingGlobals();
}
private void UpdateGridMeshBounds()
{
var environment = Settings.DefaultEnvironment;
if (GridMesh != null)
@ -70,7 +130,19 @@ public class VolumeSampling : MonoBehaviour
// GridMesh.position = new Vector3(_gridTransform.position.x, environment.Grid.Offset, _gridTransform.position.z);
// GridMesh.localScale = new Vector3(GridCamera.orthographicSize, 1, GridCamera.orthographicSize);
}
}
private void PublishSamplingGlobals()
{
var environment = Settings.DefaultEnvironment;
ResolveSplatViewport(out var center, out var size);
_publishedSplatCenter = center;
_publishedSplatSize = size;
// Shader sampling must use the same world-space viewport that produced the splat textures.
Shader.SetGlobalVector("_GridTransform", new Vector4(center.x, center.y, size.x));
// Volumetric sampling parameters are used by several shaders
Shader.SetGlobalTexture("_NebulaSurfaceHeight", NebulaSurfaceHeight);
Shader.SetGlobalTexture("_NebulaPatchHeight", NebulaPatchHeight);
@ -105,7 +177,6 @@ public class VolumeSampling : MonoBehaviour
Shader.SetGlobalFloat("_FlowAmplitude", environment.Flow.GlobalAmplitude);
Shader.SetGlobalFloat("_FlowSlopeAmplitude", environment.Flow.SlopeAmplitude);
Shader.SetGlobalFloat("_FlowSwirlAmplitude", environment.Flow.SwirlAmplitude);
_flowScroll += environment.Flow.GlobalScrollSpeed * Time.deltaTime;
Shader.SetGlobalFloat("_FlowScroll", _flowScroll);
Shader.SetGlobalFloat("_FlowPeriod", environment.Flow.Period);
@ -114,20 +185,33 @@ public class VolumeSampling : MonoBehaviour
Shader.SetKeyword(_keywordNoiseSlope, environment.Noise.SlopeExponent != 0);
}
private void RenderSplatTextures()
private void RenderSplatTexturesIfNeeded()
{
ResolveSplatRenderers();
if (SplatViewportSource == null)
if (SplatLayerRenderer == null)
return;
var size = GridCamera != null
? new Vector2(GridCamera.orthographicSize * 2, GridCamera.orthographicSize * 2)
: new Vector2(1024, 1024);
var center = _gridTransform != null
? new Vector2(_gridTransform.position.x, _gridTransform.position.z)
: Vector2.zero;
SplatViewportSource.SetViewport(center, size);
SplatViewportSource.RenderLatest();
ResolveSplatViewport(out var center, out var size);
var document = ResolveSceneSplatDocument(center, size);
if (document == null && useRuntimeRenderSplats)
document = ResolveRuntimeSplatDocument(center, size);
if (document == null)
return;
var viewportChanged = !_hasRenderedSplats ||
!Approximately(center, _lastSplatCenter) ||
!Approximately(size, _lastSplatSize);
var intervalElapsed = Time.unscaledTime >= _nextSplatRenderTime;
if (!renderSplatsEveryFrame && !viewportChanged && !intervalElapsed)
return;
SplatLayerRenderer.Render(document, Mathf.RoundToInt(size.x), Mathf.RoundToInt(size.y));
_lastSplatCenter = center;
_lastSplatSize = size;
_publishedSplatCenter = center;
_publishedSplatSize = size;
_nextSplatRenderTime = Time.unscaledTime + Mathf.Max(0.02f, splatRenderIntervalSeconds);
_hasRenderedSplats = true;
if (SplatLayerRenderer == null)
return;
@ -138,6 +222,52 @@ public class VolumeSampling : MonoBehaviour
NebulaTint = ResolveLayerTexture(AetheriaRuntimeRenderSplatLayerKeys.FogTint, NebulaTint);
}
private AetheriaRuntimeRenderSplatsViewportDocument ResolveSceneSplatDocument(Vector2 center, Vector2 size)
{
if (SceneSplatSource == null)
SceneSplatSource = GetComponent<AetheriaSceneRenderSplatSource>();
return SceneSplatSource != null
? SceneSplatSource.BuildDocument(BuildViewportBounds(center, size))
: null;
}
private AetheriaRuntimeRenderSplatsViewportDocument ResolveRuntimeSplatDocument(Vector2 center, Vector2 size)
{
if (SplatViewportSource == null)
return null;
SplatViewportSource.SetViewport(center, size);
return SplatViewportSource.CurrentDocument;
}
private void ResolveSplatViewport(out Vector2 center, out Vector2 size)
{
size = GridCamera != null
? new Vector2(GridCamera.orthographicSize * 2, GridCamera.orthographicSize * 2)
: new Vector2(1024, 1024);
center = _gridTransform != null
? new Vector2(_gridTransform.position.x, _gridTransform.position.z)
: Vector2.zero;
}
private static AetheriaRuntimeRtsViewportBounds BuildViewportBounds(Vector2 center, Vector2 size)
{
var halfSize = size * 0.5f;
return new AetheriaRuntimeRtsViewportBounds
{
MinX = center.x - halfSize.x,
MinY = center.y - halfSize.y,
MaxX = center.x + halfSize.x,
MaxY = center.y + halfSize.y
};
}
private static bool Approximately(Vector2 lhs, Vector2 rhs)
{
return Mathf.Abs(lhs.x - rhs.x) < 0.001f &&
Mathf.Abs(lhs.y - rhs.y) < 0.001f;
}
private RenderTexture ResolveLayerTexture(string layerKey, RenderTexture fallback)
{
return SplatLayerRenderer.TryGetTexture(layerKey, out var texture) && texture != null
@ -152,9 +282,13 @@ public class VolumeSampling : MonoBehaviour
if (SplatLayerRenderer == null)
SplatLayerRenderer = gameObject.AddComponent<AetheriaRenderSplatLayerRenderer>();
if (!useRuntimeRenderSplats)
return;
if (SplatViewportSource == null)
SplatViewportSource = GetComponent<AetheriaUnityRenderSplatViewportSource>();
if (SplatViewportSource == null)
SplatViewportSource = gameObject.AddComponent<AetheriaUnityRenderSplatViewportSource>();
SplatViewportSource.RenderInLateUpdate = false;
}
}

View file

@ -8,6 +8,7 @@ using System.Collections.Generic;
using System.Linq;
using Cinemachine;
using GameCult.Aetheria.State.Verse;
using GameCult.Mesh;
using UnityEngine;
using UnityEngine.Serialization;
using Object = UnityEngine.Object;
@ -29,6 +30,7 @@ public class ZoneRenderer : MonoBehaviour
public CinemachineVirtualCamera SceneCamera;
public Camera[] FogCameras;
public Camera[] MinimapCameras;
private AetheriaClientState _runtimeState;
public bool UseRenderSplatTextureLayers = true;
public Material FogMaterial;
public float FogFarFadeFraction = .125f;
@ -1199,8 +1201,8 @@ public class ZoneRenderer : MonoBehaviour
{
try
{
return AetheriaUnityRuntimeClientProvider
.CurrentCatalog("unity-zone-renderer");
_runtimeState ??= AetheriaUnityRuntimeClientProvider.RuntimeState("unity-zone-renderer");
return _runtimeState.Catalog.Latest();
}
catch (Exception ex)
{