RustToDust/client/VolumetricCompositorEffect.cs

724 lines
29 KiB
C#

using System;
using System.Runtime.InteropServices;
using Godot;
namespace RustToDust.Client;
/// <summary>
/// 4-pass Forward+ Vulkan compute pipeline (<c>PostSky</c>) owning:
/// Pass 0: <c>flow_field_step.glsl</c> (camera-snapped 3m 64x24x64 RGBA16F ping-pong -> <see cref="Texture3Drd"/>)
/// Pass 1: <c>volumetric_tile_cull.glsl</c> (16x16 half-res tiles + 128-element Bitonic sort)
/// Pass 2: <c>volumetric_raymarch.glsl</c> (sorted monotonic sweep-line + Aetheria curl/triNoise + shock cavity + 2 shadow taps)
/// Pass 3: <c>volumetric_composite.glsl</c> (2x2 bilateral depth upsample pre-tonemap)
/// </summary>
public sealed partial class VolumetricCompositorEffect : CompositorEffect
{
public const int FlowDimX = 64;
public const int FlowDimY = 24;
public const int FlowDimZ = 64;
public const float FlowVoxelSizeMeters = 3.0f;
public const int TileSizeHalfRes = 16;
public const int TileStrideBytes = 112;
public const int FrameUboBytes = 272;
[StructLayout(LayoutKind.Sequential, Pack = 4)]
private struct VolumetricFrameUbo
{
public Vector4 InvProj0, InvProj1, InvProj2, InvProj3;
public Vector4 CamPosTime;
public Vector4 CamRightAspect;
public Vector4 CamUpTanHalfFov;
public Vector4 CamFwdNearFar;
public Vector4 SunDirIntensity;
public Vector4 SunColorExt;
public Vector4 AmbientColorFog;
public Vector4 ViewportInfo;
public uint HalfW, HalfH, TilesX, FrameIndex;
public Vector4 FlowOriginVoxel;
public Vector4 FlowInvExtentDt;
public int DeltaX, DeltaY, DeltaZ, ImpulseCount;
public uint MaxSteps, MaxIter, IsFullRes, QualityPad;
}
private readonly Texture3Drd _flowTexRd;
private VolumetricEmitterPool _emitterPool;
// Atmosphere parameters updated from game thread via volatile/lock
private readonly object _atmoLock = new();
private Vector3 _sunDir = new Vector3(0.45f, 0.55f, 0.70f).Normalized();
private float _sunEnergy = 1.25f;
private Color _sunColor = Colors.White;
private Color _ambientColor = new(0.28f, 0.34f, 0.42f);
private float _globalExtinctionScale = 0.28f;
private VfxResolutionScale _resolutionScale = VfxResolutionScale.Half;
private VolumetricSamples _volumetricSamples = VolumetricSamples.Medium;
// Render-thread RD state
private RenderingDevice? _rd;
private bool _rdInitialized;
private bool _rdFailed;
private Rid _flowShaderRid, _flowPipeRid;
private Rid _cullShaderRid, _cullPipeRid;
private Rid _marchShaderRid, _marchPipeRid;
private Rid _compShaderRid, _compPipeRid;
private readonly Rid[] _flowTexRids = new Rid[2];
private int _flowReadIdx;
private Vector3I _prevFlowVoxelOrigin;
private bool _hasPrevFlowOrigin;
private Rid _nearestSamplerRid;
private Rid _linearSamplerRid;
private Rid _frameUboRid;
private Rid _emitterSsboRid;
private Rid _impulseSsboRid;
private Rid _tileSsboRid;
private int _tileSsboCapacityTiles;
private Rid _halfVolRid;
private Vector2I _halfVolSize;
private uint _frameCounter;
// Pre-allocated CPU staging buffers (zero per-frame allocations)
private readonly byte[] _uboBytes = new byte[FrameUboBytes];
private readonly byte[] _emitterUploadBytes = new byte[VolumetricEmitterPool.MaxEmitters * VolumetricEmitterPool.EmitterStrideBytes];
private readonly byte[] _impulseUploadBytes = new byte[VolumetricEmitterPool.MaxFlowImpulses * VolumetricEmitterPool.ImpulseStrideBytes];
// Lightweight RD timestamp telemetry (populated when ProfilingEnabled == true)
public bool ProfilingEnabled { get; set; }
private ulong _lastSampledTimestampFrame = ulong.MaxValue;
public double LastFlowGpuMs { get; private set; }
public double LastCullGpuMs { get; private set; }
public double LastMarchGpuMs { get; private set; }
public double LastCompGpuMs { get; private set; }
public double LastTotalGpuMs => LastFlowGpuMs + LastCullGpuMs + LastMarchGpuMs + LastCompGpuMs;
public Vector2I LastMarchSize { get; private set; }
public int CurrentMaxSteps { get; private set; } = 10;
public int CurrentMaxIter { get; private set; } = 15;
public VolumetricCompositorEffect() : this(new Texture3Drd(), new VolumetricEmitterPool())
{
}
public VolumetricCompositorEffect(Texture3Drd flowTexRd, VolumetricEmitterPool emitterPool)
{
_flowTexRd = flowTexRd;
_emitterPool = emitterPool;
EffectCallbackType = EffectCallbackTypeEnum.PostSky;
AccessResolvedColor = true;
AccessResolvedDepth = true;
Enabled = true;
}
public void SetEmitterPool(VolumetricEmitterPool pool)
{
_emitterPool = pool ?? throw new ArgumentNullException(nameof(pool));
}
public void ApplyGraphicsSettings(GraphicsSettings settings)
{
ArgumentNullException.ThrowIfNull(settings);
lock (_atmoLock)
{
_resolutionScale = settings.VfxResolution;
_volumetricSamples = settings.VolumetricSamples;
}
}
public void SetAtmosphere(Vector3 sunDir, float sunEnergy, Color sunColor, Color ambientColor, float extinctionScale = 0.28f)
{
lock (_atmoLock)
{
_sunDir = sunDir.LengthSquared() > 1e-5f ? sunDir.Normalized() : Vector3.Up;
_sunEnergy = MathF.Max(0.05f, sunEnergy);
_sunColor = sunColor;
_ambientColor = ambientColor;
_globalExtinctionScale = Math.Clamp(extinctionScale, 0.05f, 2.0f);
}
}
public override void _RenderCallback(int effectCallbackType, RenderData renderData)
{
if (effectCallbackType != (int)EffectCallbackTypeEnum.PostSky || _rdFailed)
{
return;
}
RenderingDevice? rd = RenderingServer.GetRenderingDevice();
if (rd is null)
{
return;
}
if (!_rdInitialized && !TryInitializeRd(rd))
{
_rdFailed = true;
return;
}
if (renderData.GetRenderSceneBuffers() is not RenderSceneBuffersRD sceneBuffers)
{
return;
}
RenderSceneData sceneData = renderData.GetRenderSceneData();
if (sceneData is null)
{
return;
}
Vector2I fullSize = sceneBuffers.GetInternalSize();
if (fullSize.X < 2 || fullSize.Y < 2)
{
return;
}
VfxResolutionScale resScale;
VolumetricSamples volSamples;
Vector3 sunDir;
float sunEnergy;
Color sunCol, ambCol;
float extScale;
lock (_atmoLock)
{
resScale = _resolutionScale;
volSamples = _volumetricSamples;
sunDir = _sunDir;
sunEnergy = _sunEnergy;
sunCol = _sunColor;
ambCol = _ambientColor;
extScale = _globalExtinctionScale;
}
bool isFullRes = resScale == VfxResolutionScale.Full;
float resFactor = GraphicsSettings.GetResolutionScaleFactor(resScale);
Vector2I marchSize = isFullRes
? fullSize
: new Vector2I(
Math.Max(1, (int)MathF.Round(fullSize.X * resFactor)),
Math.Max(1, (int)MathF.Round(fullSize.Y * resFactor)));
int tilesX = Math.Max(1, (marchSize.X + TileSizeHalfRes - 1) / TileSizeHalfRes);
int tilesY = Math.Max(1, (marchSize.Y + TileSizeHalfRes - 1) / TileSizeHalfRes);
int totalTiles = tilesX * tilesY;
(int maxSteps, int maxIter) = GraphicsSettings.GetVolumetricStepBudget(volSamples);
LastMarchSize = marchSize;
CurrentMaxSteps = maxSteps;
CurrentMaxIter = maxIter;
EnsureHalfResAndTileBuffers(rd, marchSize, totalTiles);
uint viewCount = Math.Max(1u, sceneData.GetViewCount());
const uint view = 0u;
Transform3D camXf = sceneData.GetCamTransform();
Projection rawProj = sceneData.GetViewProjection(view);
// Validate reverse-Z projection convention [1..0]
Vector4 testNear = rawProj * new Vector4(0f, 0f, -0.05f, 1f);
Projection revProj = (testNear.W != 0f && (testNear.Z / testNear.W) < 0f)
? Projection.CreateDepthCorrection(flipY: false) * rawProj
: rawProj;
Projection invProj = revProj.Inverse();
Vector4 nearView = invProj * new Vector4(0f, 0f, 1f, 1f);
Vector4 farView = invProj * new Vector4(0f, 0f, 0f, 1f);
float zNear = MathF.Max(0.01f, MathF.Abs(nearView.W) > 1e-6f ? -nearView.Z / nearView.W : 0.05f);
float zFar = MathF.Abs(farView.W) > 1e-6f && (-farView.Z / farView.W) > zNear + 1f
? -farView.Z / farView.W
: 4800f;
float tanHalfFovY = 1f / MathF.Max(1e-4f, MathF.Abs(rawProj.Y.Y));
float aspect = MathF.Abs(rawProj.Y.Y) / MathF.Max(1e-4f, MathF.Abs(rawProj.X.X));
Vector3 camPos = camXf.Origin;
Vector3 camRight = camXf.Basis.X.Normalized();
Vector3 camUp = camXf.Basis.Y.Normalized();
Vector3 camFwd = (-camXf.Basis.Z).Normalized();
_emitterPool.CopyRenderSnapshot(
_emitterUploadBytes,
_impulseUploadBytes,
out int emitterCount,
out int impulseCount,
out float elapsedTime,
out float dt);
Vector3I newVoxelOrigin = new(
(int)MathF.Floor((camPos.X - 96f) / FlowVoxelSizeMeters),
(int)MathF.Floor((camPos.Y - 24f) / FlowVoxelSizeMeters),
(int)MathF.Floor((camPos.Z - 96f) / FlowVoxelSizeMeters));
Vector3I flowDelta = _hasPrevFlowOrigin ? (newVoxelOrigin - _prevFlowVoxelOrigin) : Vector3I.Zero;
_prevFlowVoxelOrigin = newVoxelOrigin;
_hasPrevFlowOrigin = true;
Vector3 flowOriginWorld = new(
newVoxelOrigin.X * FlowVoxelSizeMeters,
newVoxelOrigin.Y * FlowVoxelSizeMeters,
newVoxelOrigin.Z * FlowVoxelSizeMeters);
Vector3 flowInvExtent = new(
1f / (FlowDimX * FlowVoxelSizeMeters),
1f / (FlowDimY * FlowVoxelSizeMeters),
1f / (FlowDimZ * FlowVoxelSizeMeters));
_frameCounter++;
var ubo = new VolumetricFrameUbo
{
InvProj0 = invProj.X,
InvProj1 = invProj.Y,
InvProj2 = invProj.Z,
InvProj3 = invProj.W,
CamPosTime = new Vector4(camPos.X, camPos.Y, camPos.Z, elapsedTime),
CamRightAspect = new Vector4(camRight.X, camRight.Y, camRight.Z, aspect),
CamUpTanHalfFov = new Vector4(camUp.X, camUp.Y, camUp.Z, tanHalfFovY),
CamFwdNearFar = new Vector4(camFwd.X, camFwd.Y, camFwd.Z, 0f),
SunDirIntensity = new Vector4(sunDir.X, sunDir.Y, sunDir.Z, sunEnergy),
SunColorExt = new Vector4(sunCol.R, sunCol.G, sunCol.B, extScale),
AmbientColorFog = new Vector4(ambCol.R, ambCol.G, ambCol.B, zNear),
ViewportInfo = new Vector4(fullSize.X, fullSize.Y, zFar, emitterCount),
HalfW = (uint)marchSize.X,
HalfH = (uint)marchSize.Y,
TilesX = (uint)tilesX,
FrameIndex = _frameCounter,
FlowOriginVoxel = new Vector4(flowOriginWorld.X, flowOriginWorld.Y, flowOriginWorld.Z, FlowVoxelSizeMeters),
FlowInvExtentDt = new Vector4(flowInvExtent.X, flowInvExtent.Y, flowInvExtent.Z, dt),
DeltaX = flowDelta.X,
DeltaY = flowDelta.Y,
DeltaZ = flowDelta.Z,
ImpulseCount = impulseCount,
MaxSteps = (uint)maxSteps,
MaxIter = (uint)maxIter,
IsFullRes = isFullRes ? 1u : 0u,
QualityPad = 0u
};
MemoryMarshal.Write(_uboBytes, in ubo);
rd.BufferUpdate(_frameUboRid, 0, FrameUboBytes, _uboBytes);
if (emitterCount > 0)
{
uint emBytes = (uint)(emitterCount * VolumetricEmitterPool.EmitterStrideBytes);
rd.BufferUpdate(_emitterSsboRid, 0, emBytes, _emitterUploadBytes);
}
if (impulseCount > 0)
{
uint impBytes = (uint)(impulseCount * VolumetricEmitterPool.ImpulseStrideBytes);
rd.BufferUpdate(_impulseSsboRid, 0, impBytes, _impulseUploadBytes);
}
int writeIdx = 1 - _flowReadIdx;
Rid prevFlowRid = _flowTexRids[_flowReadIdx];
Rid nextFlowRid = _flowTexRids[writeIdx];
bool captureThisFrame = ProfilingEnabled && (_frameCounter & 7u) == 0u && _frameCounter >= 24u && rd.GetCapturedTimestampsCount() < 180;
if (ProfilingEnabled)
{
SamplePreviousFrameTimestamps(rd);
}
if (captureThisFrame)
{
rd.CaptureTimestamp("Cut10b_FlowStart");
}
// Compute pass list (Pass 0 always; Passes 1-3 whenever active emitters exist)
long computeList = rd.ComputeListBegin();
// Pass 0: flow_field_step (64x24x64 / 8x4x8 = 8x6x8 groups)
Rid flowSet = GetPass0UniformSet(prevFlowRid, nextFlowRid);
rd.ComputeListBindComputePipeline(computeList, _flowPipeRid);
rd.ComputeListBindUniformSet(computeList, flowSet, 0);
rd.ComputeListDispatch(computeList, 8, 6, 8);
if (emitterCount > 0)
{
for (uint v = 0; v < viewCount; v++)
{
Rid colorLayer = sceneBuffers.GetColorLayer(v, false);
Rid depthLayer = sceneBuffers.GetDepthLayer(v, false);
if (!colorLayer.IsValid || !depthLayer.IsValid)
{
continue;
}
// Pass 1: volumetric_tile_cull
rd.ComputeListAddBarrier(computeList);
if (captureThisFrame && v == 0)
{
rd.ComputeListEnd();
rd.CaptureTimestamp("Cut10b_CullStart");
computeList = rd.ComputeListBegin();
}
Rid cullSet = GetPass1UniformSet(depthLayer);
rd.ComputeListBindComputePipeline(computeList, _cullPipeRid);
rd.ComputeListBindUniformSet(computeList, cullSet, 0);
rd.ComputeListDispatch(computeList, (uint)tilesX, (uint)tilesY, 1);
// Pass 2: volumetric_raymarch (reading freshly updated nextFlowRid!)
rd.ComputeListAddBarrier(computeList);
if (captureThisFrame && v == 0)
{
rd.ComputeListEnd();
rd.CaptureTimestamp("Cut10b_MarchStart");
computeList = rd.ComputeListBegin();
}
Rid marchSet = GetPass2UniformSet(depthLayer, nextFlowRid);
rd.ComputeListBindComputePipeline(computeList, _marchPipeRid);
rd.ComputeListBindUniformSet(computeList, marchSet, 0);
rd.ComputeListDispatch(computeList, (uint)tilesX, (uint)tilesY, 1);
// Pass 3: volumetric_composite (2x2 bilateral depth upsample -> colorLayer)
rd.ComputeListAddBarrier(computeList);
if (captureThisFrame && v == 0)
{
rd.ComputeListEnd();
rd.CaptureTimestamp("Cut10b_CompStart");
computeList = rd.ComputeListBegin();
}
Rid compSet = GetPass3UniformSet(depthLayer, colorLayer);
rd.ComputeListBindComputePipeline(computeList, _compPipeRid);
rd.ComputeListBindUniformSet(computeList, compSet, 0);
uint compGroupsX = (uint)((fullSize.X + 15) / 16);
uint compGroupsY = (uint)((fullSize.Y + 15) / 16);
rd.ComputeListDispatch(computeList, compGroupsX, compGroupsY, 1);
}
}
rd.ComputeListEnd();
if (captureThisFrame)
{
rd.CaptureTimestamp("Cut10b_End");
}
// Advance ping-pong & update global Texture3Drd + flow origin for GPUParticles3D
_flowReadIdx = writeIdx;
_flowTexRd.TextureRdRid = nextFlowRid;
RenderingServer.GlobalShaderParameterSet("rtd_flow_origin", flowOriginWorld);
RenderingServer.GlobalShaderParameterSet("rtd_flow_inv_extent", flowInvExtent);
}
private void SamplePreviousFrameTimestamps(RenderingDevice rd)
{
uint count = rd.GetCapturedTimestampsCount();
if (count == 0)
{
return;
}
ulong tsFrame = rd.GetCapturedTimestampsFrame();
if (tsFrame == _lastSampledTimestampFrame)
{
return;
}
_lastSampledTimestampFrame = tsFrame;
ulong tFlow = 0, tCull = 0, tMarch = 0, tComp = 0, tEnd = 0;
for (uint i = 0; i < count; i++)
{
string name = rd.GetCapturedTimestampName(i);
switch (name)
{
case "Cut10b_FlowStart": tFlow = rd.GetCapturedTimestampGpuTime(i); break;
case "Cut10b_CullStart": tCull = rd.GetCapturedTimestampGpuTime(i); break;
case "Cut10b_MarchStart": tMarch = rd.GetCapturedTimestampGpuTime(i); break;
case "Cut10b_CompStart": tComp = rd.GetCapturedTimestampGpuTime(i); break;
case "Cut10b_End": tEnd = rd.GetCapturedTimestampGpuTime(i); break;
}
}
// Godot 4.7 Vulkan GetCapturedTimestampGpuTime empirically returns nanoseconds (confirmed vs --gpu-profile; GodotSharp.xml's "microseconds" doc is stale)
if (tFlow > 0 && tEnd >= tFlow)
{
if (tCull > tFlow && tMarch > tCull && tComp > tMarch && tEnd >= tComp)
{
LastFlowGpuMs = (tCull - tFlow) / 1_000_000.0;
LastCullGpuMs = (tMarch - tCull) / 1_000_000.0;
LastMarchGpuMs = (tComp - tMarch) / 1_000_000.0;
LastCompGpuMs = (tEnd - tComp) / 1_000_000.0;
}
else
{
LastFlowGpuMs = (tEnd - tFlow) / 1_000_000.0;
LastCullGpuMs = 0.0;
LastMarchGpuMs = 0.0;
LastCompGpuMs = 0.0;
}
}
}
private bool TryInitializeRd(RenderingDevice rd)
{
_rd = rd;
if (!TryCompileCompute(rd, "res://flow_field_step.glsl", "flow_field_step", out _flowShaderRid, out _flowPipeRid) ||
!TryCompileCompute(rd, "res://volumetric_tile_cull.glsl", "volumetric_tile_cull", out _cullShaderRid, out _cullPipeRid) ||
!TryCompileCompute(rd, "res://volumetric_raymarch.glsl", "volumetric_raymarch", out _marchShaderRid, out _marchPipeRid) ||
!TryCompileCompute(rd, "res://volumetric_composite.glsl", "volumetric_composite", out _compShaderRid, out _compPipeRid))
{
return false;
}
var nearestState = new RDSamplerState
{
MinFilter = RenderingDevice.SamplerFilter.Nearest,
MagFilter = RenderingDevice.SamplerFilter.Nearest,
RepeatU = RenderingDevice.SamplerRepeatMode.ClampToEdge,
RepeatV = RenderingDevice.SamplerRepeatMode.ClampToEdge,
RepeatW = RenderingDevice.SamplerRepeatMode.ClampToEdge
};
_nearestSamplerRid = rd.SamplerCreate(nearestState);
var linearState = new RDSamplerState
{
MinFilter = RenderingDevice.SamplerFilter.Linear,
MagFilter = RenderingDevice.SamplerFilter.Linear,
RepeatU = RenderingDevice.SamplerRepeatMode.ClampToEdge,
RepeatV = RenderingDevice.SamplerRepeatMode.ClampToEdge,
RepeatW = RenderingDevice.SamplerRepeatMode.ClampToEdge
};
_linearSamplerRid = rd.SamplerCreate(linearState);
var flowFmt = new RDTextureFormat
{
TextureType = RenderingDevice.TextureType.Type3D,
Format = RenderingDevice.DataFormat.R16G16B16A16Sfloat,
Width = FlowDimX,
Height = FlowDimY,
Depth = FlowDimZ,
Mipmaps = 1,
ArrayLayers = 1,
Samples = RenderingDevice.TextureSamples.Samples1,
UsageBits = RenderingDevice.TextureUsageBits.SamplingBit | RenderingDevice.TextureUsageBits.StorageBit
};
byte[] zero3d = new byte[FlowDimX * FlowDimY * FlowDimZ * 8];
var initArr = new Godot.Collections.Array<byte[]> { zero3d };
_flowTexRids[0] = rd.TextureCreate(flowFmt, new RDTextureView(), initArr);
_flowTexRids[1] = rd.TextureCreate(flowFmt, new RDTextureView(), initArr);
_flowReadIdx = 0;
_flowTexRd.TextureRdRid = _flowTexRids[0];
_frameUboRid = rd.UniformBufferCreate(FrameUboBytes, new byte[FrameUboBytes]);
_emitterSsboRid = rd.StorageBufferCreate(
(uint)(VolumetricEmitterPool.MaxEmitters * VolumetricEmitterPool.EmitterStrideBytes),
new byte[VolumetricEmitterPool.MaxEmitters * VolumetricEmitterPool.EmitterStrideBytes]);
_impulseSsboRid = rd.StorageBufferCreate(
(uint)(VolumetricEmitterPool.MaxFlowImpulses * VolumetricEmitterPool.ImpulseStrideBytes),
new byte[VolumetricEmitterPool.MaxFlowImpulses * VolumetricEmitterPool.ImpulseStrideBytes]);
_rdInitialized = true;
return true;
}
private static bool TryCompileCompute(
RenderingDevice rd,
string resPath,
string debugName,
out Rid shaderRid,
out Rid pipeRid)
{
shaderRid = new Rid();
pipeRid = new Rid();
string source = FileAccess.GetFileAsString(resPath);
if (string.IsNullOrWhiteSpace(source))
{
GD.PrintErr($"VolumetricCompositorEffect: missing compute shader '{resPath}'");
return false;
}
using var rdSrc = new RDShaderSource
{
Language = RenderingDevice.ShaderLanguage.Glsl,
SourceCompute = source
};
using RDShaderSpirV spirv = rd.ShaderCompileSpirVFromSource(rdSrc, allowCache: true);
string err = spirv.CompileErrorCompute;
if (!string.IsNullOrEmpty(err))
{
GD.PrintErr($"VolumetricCompositorEffect: SPIR-V compile error in '{resPath}': {err}");
return false;
}
shaderRid = rd.ShaderCreateFromSpirV(spirv, debugName);
if (!shaderRid.IsValid)
{
GD.PrintErr($"VolumetricCompositorEffect: ShaderCreateFromSpirV failed for '{resPath}'");
return false;
}
pipeRid = rd.ComputePipelineCreate(shaderRid);
if (!pipeRid.IsValid)
{
GD.PrintErr($"VolumetricCompositorEffect: ComputePipelineCreate failed for '{resPath}'");
return false;
}
return true;
}
private void EnsureHalfResAndTileBuffers(RenderingDevice rd, Vector2I halfSize, int totalTiles)
{
if (!_halfVolRid.IsValid || _halfVolSize != halfSize)
{
if (_halfVolRid.IsValid)
{
rd.FreeRid(_halfVolRid);
}
var fmt = new RDTextureFormat
{
TextureType = RenderingDevice.TextureType.Type2D,
Format = RenderingDevice.DataFormat.R16G16B16A16Sfloat,
Width = (uint)halfSize.X,
Height = (uint)halfSize.Y,
Depth = 1,
Mipmaps = 1,
ArrayLayers = 1,
Samples = RenderingDevice.TextureSamples.Samples1,
UsageBits = RenderingDevice.TextureUsageBits.SamplingBit | RenderingDevice.TextureUsageBits.StorageBit
};
_halfVolRid = rd.TextureCreate(fmt, new RDTextureView());
_halfVolSize = halfSize;
}
if (!_tileSsboRid.IsValid || _tileSsboCapacityTiles < totalTiles)
{
if (_tileSsboRid.IsValid)
{
rd.FreeRid(_tileSsboRid);
}
_tileSsboCapacityTiles = Math.Max(totalTiles, 2048);
uint sizeBytes = (uint)(_tileSsboCapacityTiles * TileStrideBytes);
_tileSsboRid = rd.StorageBufferCreate(sizeBytes, new byte[sizeBytes]);
}
}
private Rid GetPass0UniformSet(Rid prevFlowRid, Rid nextFlowRid)
{
var u0 = new RDUniform { UniformType = RenderingDevice.UniformType.UniformBuffer, Binding = 0 };
u0.AddId(_frameUboRid);
var u1 = new RDUniform { UniformType = RenderingDevice.UniformType.StorageBuffer, Binding = 1 };
u1.AddId(_impulseSsboRid);
var u2 = new RDUniform { UniformType = RenderingDevice.UniformType.SamplerWithTexture, Binding = 2 };
u2.AddId(_linearSamplerRid);
u2.AddId(prevFlowRid);
var u3 = new RDUniform { UniformType = RenderingDevice.UniformType.Image, Binding = 3 };
u3.AddId(nextFlowRid);
return UniformSetCacheRD.GetCache(_flowShaderRid, 0, new Godot.Collections.Array<RDUniform> { u0, u1, u2, u3 });
}
private Rid GetPass1UniformSet(Rid depthLayer)
{
var u0 = new RDUniform { UniformType = RenderingDevice.UniformType.UniformBuffer, Binding = 0 };
u0.AddId(_frameUboRid);
var u1 = new RDUniform { UniformType = RenderingDevice.UniformType.StorageBuffer, Binding = 1 };
u1.AddId(_emitterSsboRid);
var u2 = new RDUniform { UniformType = RenderingDevice.UniformType.StorageBuffer, Binding = 2 };
u2.AddId(_tileSsboRid);
var u3 = new RDUniform { UniformType = RenderingDevice.UniformType.SamplerWithTexture, Binding = 3 };
u3.AddId(_nearestSamplerRid);
u3.AddId(depthLayer);
return UniformSetCacheRD.GetCache(_cullShaderRid, 0, new Godot.Collections.Array<RDUniform> { u0, u1, u2, u3 });
}
private Rid GetPass2UniformSet(Rid depthLayer, Rid flowTexRid)
{
var u0 = new RDUniform { UniformType = RenderingDevice.UniformType.UniformBuffer, Binding = 0 };
u0.AddId(_frameUboRid);
var u1 = new RDUniform { UniformType = RenderingDevice.UniformType.StorageBuffer, Binding = 1 };
u1.AddId(_emitterSsboRid);
var u2 = new RDUniform { UniformType = RenderingDevice.UniformType.StorageBuffer, Binding = 2 };
u2.AddId(_tileSsboRid);
var u3 = new RDUniform { UniformType = RenderingDevice.UniformType.SamplerWithTexture, Binding = 3 };
u3.AddId(_nearestSamplerRid);
u3.AddId(depthLayer);
var u4 = new RDUniform { UniformType = RenderingDevice.UniformType.SamplerWithTexture, Binding = 4 };
u4.AddId(_linearSamplerRid);
u4.AddId(flowTexRid);
var u5 = new RDUniform { UniformType = RenderingDevice.UniformType.Image, Binding = 5 };
u5.AddId(_halfVolRid);
return UniformSetCacheRD.GetCache(_marchShaderRid, 0, new Godot.Collections.Array<RDUniform> { u0, u1, u2, u3, u4, u5 });
}
private Rid GetPass3UniformSet(Rid depthLayer, Rid colorLayer)
{
var u0 = new RDUniform { UniformType = RenderingDevice.UniformType.UniformBuffer, Binding = 0 };
u0.AddId(_frameUboRid);
var u1 = new RDUniform { UniformType = RenderingDevice.UniformType.SamplerWithTexture, Binding = 1 };
u1.AddId(_nearestSamplerRid);
u1.AddId(depthLayer);
var u2 = new RDUniform { UniformType = RenderingDevice.UniformType.SamplerWithTexture, Binding = 2 };
u2.AddId(_nearestSamplerRid);
u2.AddId(_halfVolRid);
var u3 = new RDUniform { UniformType = RenderingDevice.UniformType.Image, Binding = 3 };
u3.AddId(colorLayer);
var u4 = new RDUniform { UniformType = RenderingDevice.UniformType.StorageBuffer, Binding = 4 };
u4.AddId(_tileSsboRid);
return UniformSetCacheRD.GetCache(_compShaderRid, 0, new Godot.Collections.Array<RDUniform> { u0, u1, u2, u3, u4 });
}
public void DisposeRdResources()
{
if (!_rdInitialized || _rd is null)
{
return;
}
_rdInitialized = false;
Enabled = false;
if (_flowTexRd is not null)
{
_flowTexRd.TextureRdRid = new Rid();
}
FreeIfValid(_rd, ref _flowTexRids[0]);
FreeIfValid(_rd, ref _flowTexRids[1]);
FreeIfValid(_rd, ref _halfVolRid);
FreeIfValid(_rd, ref _frameUboRid);
FreeIfValid(_rd, ref _emitterSsboRid);
FreeIfValid(_rd, ref _impulseSsboRid);
FreeIfValid(_rd, ref _tileSsboRid);
FreeIfValid(_rd, ref _nearestSamplerRid);
FreeIfValid(_rd, ref _linearSamplerRid);
// Free shaders (automatically cleans up dependent pipelines in Godot RD)
_flowPipeRid = new Rid();
_cullPipeRid = new Rid();
_marchPipeRid = new Rid();
_compPipeRid = new Rid();
FreeIfValid(_rd, ref _flowShaderRid);
FreeIfValid(_rd, ref _cullShaderRid);
FreeIfValid(_rd, ref _marchShaderRid);
FreeIfValid(_rd, ref _compShaderRid);
_rd = null;
}
public override void _Notification(int what)
{
if (what != NotificationPredelete)
{
return;
}
// Only release if still alive and not already cleaned up in AtmosphereSystem._ExitTree
if (_flowTexRd is not null)
{
_flowTexRd.TextureRdRid = new Rid();
}
if (_rdInitialized && RenderingServer.GetRenderingDevice() is not null)
{
DisposeRdResources();
}
}
private static void FreeIfValid(RenderingDevice rd, ref Rid rid)
{
if (rid.IsValid)
{
rd.FreeRid(rid);
rid = new Rid();
}
}
}