Merge branch 'nibu/rtd-cut10b-volumetrics' into nibu/rtd-integrate-w2

This commit is contained in:
Meta Vens 2026-12-05 21:18:12 +01:00
commit ad0bbece4b
17 changed files with 3886 additions and 1203 deletions

View file

@ -70,7 +70,7 @@ public partial class ArenaRenderer : Node3D
}
private const int MaxVfxBeams = 512;
private const int MaxVfxSpheres = 512;
private const int MaxVfxSpheres = 64;
private const int MaxVfxRings = 128;
private VehicleAssetCache _assetCache = null!;
@ -80,6 +80,8 @@ public partial class ArenaRenderer : Node3D
private PomDecalPool _pomDecals = null!;
private DebrisSystem _debris = null!;
private ParticlePool _particles = null!;
private readonly VolumetricEmitterPool _volumetrics = new();
private GpuSparksSystem _gpuSparks = null!;
private MeshInstance3D _safeRingMesh = null!;
private ImmediateMesh _safeRingImm = null!;
@ -89,8 +91,9 @@ public partial class ArenaRenderer : Node3D
private MultiMesh _dropPillarMm = null!;
private MultiMeshInstance3D _dropPillarMmi = null!;
// Pooled weapon VFX MultiMeshes (beams/tracers, explosive detonation cores, shockwave rings)
// Pooled weapon VFX MultiMeshes (analytic volumetric capsule beams, optional spheres, shockwave rings)
private ShaderMaterial _vfxMat = null!;
private ShaderMaterial _vfxBeamMat = null!;
private MultiMesh _vfxBeamMm = null!;
private MultiMeshInstance3D _vfxBeamMmi = null!;
private MultiMesh _vfxSphereMm = null!;
@ -99,8 +102,9 @@ public partial class ArenaRenderer : Node3D
private MultiMeshInstance3D _vfxRingMmi = null!;
private readonly List<TransientVfx> _transientVfx = new(128);
private readonly ClientOrdnanceMirror _ordnanceMirror = new();
private readonly List<(Transform3D Xf, Color Col)> _mirrorSpheres = new(64);
private readonly List<(Transform3D Xf, Color Col)> _mirrorSpheres = new(32);
private readonly List<(Transform3D Xf, Color Col)> _mirrorRings = new(128);
private readonly List<ClientOrdnanceMirror.ActiveBeamSpec> _mirrorBeams = new(64);
private int _activeBeamCount;
// Continuous emitter rate limiters (keyed by (IsContender, EntityId))
@ -126,6 +130,8 @@ public partial class ArenaRenderer : Node3D
public VehicleAssetCache AssetCache => _assetCache;
public DebrisSystem Debris => _debris;
public ParticlePool Particles => _particles;
public VolumetricEmitterPool Volumetrics => _volumetrics;
public GpuSparksSystem GpuSparks => _gpuSparks;
internal MultiMeshPartPool PartPool => _partPool;
internal PomDecalPool PomDecals => _pomDecals;
internal ClientOrdnanceMirror OrdnanceMirror => _ordnanceMirror;
@ -167,12 +173,15 @@ public partial class ArenaRenderer : Node3D
_pomDecals = new PomDecalPool { Name = "PomDecals" };
_debris = new DebrisSystem { Name = "Debris" };
_particles = new ParticlePool { Name = "ParticlePool" };
_gpuSparks = new GpuSparksSystem { Name = "GpuSparks" };
_particles.BindTargets(_volumetrics, _gpuSparks);
AddChild(_staticGroup);
AddChild(_actorsGroup);
AddChild(_partPool);
AddChild(_pomDecals);
AddChild(_debris);
AddChild(_particles);
AddChild(_gpuSparks);
_coverMat = new StandardMaterial3D { AlbedoColor = CoverRust, Roughness = 0.88f, Metallic = 0.25f };
_bermMat = new StandardMaterial3D { AlbedoColor = BermDark, Roughness = 0.94f, Metallic = 0.1f };
@ -229,9 +238,14 @@ public partial class ArenaRenderer : Node3D
};
_vfxMat = new ShaderMaterial { Shader = vfxShader };
Shader beamShader = GD.Load<Shader>("res://volumetric_capsule_beam.gdshader")
?? throw new InvalidOperationException("Failed to load res://volumetric_capsule_beam.gdshader");
_vfxBeamMat = new ShaderMaterial { Shader = beamShader };
_vfxBeamMm = new MultiMesh
{
TransformFormat = MultiMesh.TransformFormatEnum.Transform3D,
UseColors = true,
UseCustomData = true,
Mesh = new BoxMesh { Size = Vector3.One },
InstanceCount = MaxVfxBeams,
@ -241,7 +255,7 @@ public partial class ArenaRenderer : Node3D
{
Name = "VfxBeams",
Multimesh = _vfxBeamMm,
MaterialOverride = _vfxMat,
MaterialOverride = _vfxBeamMat,
CastShadow = GeometryInstance3D.ShadowCastingSetting.Off,
CustomAabb = new Aabb(new Vector3(-1600f, -60f, -1600f), new Vector3(3200f, 450f, 3200f)),
PhysicsInterpolationMode = PhysicsInterpolationModeEnum.Off,
@ -357,17 +371,19 @@ public partial class ArenaRenderer : Node3D
SyncOrbitalPods(session, alpha, hasCam, camPos);
_mirrorSpheres.Clear();
_mirrorRings.Clear();
_mirrorBeams.Clear();
_ordnanceMirror.StepAndSubmit(
dt,
session,
_assetCache,
_partPool,
_particles,
_volumetrics,
state.Terrain,
hasCam,
camPos,
(xf, col) => _mirrorRings.Add((xf, col)),
(xf, col) => _mirrorSpheres.Add((xf, col)));
beam => _mirrorBeams.Add(beam));
_debris.Step(dt, state.Terrain);
_debris.SubmitToPool(_partPool);
_partPool.EndFrame();
@ -397,6 +413,7 @@ public partial class ArenaRenderer : Node3D
_assetCache,
_debris,
_particles,
_volumetrics,
hasCam,
camPos,
spec => AddTransient(new TransientVfx
@ -424,6 +441,7 @@ public partial class ArenaRenderer : Node3D
ConsumeDropPodEvents(session, events, camPos, hasCam);
UpdateExplosiveRingsAndCores(events, stepDt);
_particles.AdvanceAndCommit(stepDt);
_volumetrics.Step(stepDt);
}
private VehicleVisualInstance? ResolveEntityVisual(bool isContender, int id) =>
@ -513,10 +531,13 @@ public partial class ArenaRenderer : Node3D
_pomDecals.ClearAll();
_debris.ClearAll();
_particles.ClearAll();
_volumetrics.ClearAll();
_gpuSparks.ClearAll();
_transientVfx.Clear();
_ordnanceMirror.Clear();
_mirrorSpheres.Clear();
_mirrorRings.Clear();
_mirrorBeams.Clear();
_tireDustNextTime.Clear();
_thermalVentNextTime.Clear();
_damageSmokeNextTime.Clear();
@ -1256,7 +1277,7 @@ public partial class ArenaRenderer : Node3D
lifetime: petalLife);
}
// Touchdown retro shockwave ring + brief detonation core
// Touchdown retro shockwave ring (fireball & radial dust handled by VolumetricEmitterPool + GpuSparksSystem)
Vector3 upRef = MathF.Abs(normal.Y) > 0.92f ? Vector3.Forward : Vector3.Up;
Vector3 right = upRef.Cross(normal).Normalized();
Vector3 fwd = normal.Cross(right).Normalized();
@ -1274,19 +1295,6 @@ public partial class ArenaRenderer : Node3D
Age = 0f,
Lifetime = isContender ? 0.42f : 0.30f
});
AddTransient(new TransientVfx
{
Shape = VfxShape.Sphere,
Position = pos + normal * 0.65f,
Velocity = normal * 1.8f,
BaseRotation = Basis.Identity,
StartScale = Vector3.One * (isContender ? 1.2f : 0.7f),
EndScale = Vector3.One * (isContender ? 4.4f : 2.6f),
ColorStart = new Color(3.8f, 2.2f, 0.65f, 0.90f),
ColorEnd = new Color(0.85f, 0.25f, 0.06f, 0.0f),
Age = 0f,
Lifetime = isContender ? 0.28f : 0.20f
});
}
}
@ -1299,90 +1307,69 @@ public partial class ArenaRenderer : Node3D
var t = tracers[i];
Vector3 start = new(t.StartX, t.StartY, t.StartZ);
Vector3 end = new(t.EndX, t.EndY, t.EndZ);
Vector3 delta = end - start;
float dist = delta.Length();
if (dist < 0.1f)
if (start.DistanceSquaredTo(end) < 0.01f)
{
continue;
}
Vector3 dir = delta / dist;
Vector3 up = MathF.Abs(dir.Dot(Vector3.Up)) > 0.95f ? Vector3.Right : Vector3.Up;
Basis lookBasis = Basis.LookingAt(dir, up);
Vector3 mid = (start + end) * 0.5f;
switch (t.WeaponClass)
{
case WeaponVisualClass.KineticLight:
{
bool isPd = string.Equals(t.WeaponId, "pd_flak", StringComparison.Ordinal);
Color col = isPd
? new Color(2.8f, 1.35f, 0.35f, 0.94f)
: new Color(2.6f, 2.35f, 1.15f, 0.92f);
EmitBeam(ref beamIdx, lookBasis, mid, new Vector3(isPd ? 0.09f : 0.06f, isPd ? 0.09f : 0.06f, dist), col);
? new Color(3.2f, 1.55f, 0.42f, 0.94f)
: new Color(3.0f, 2.55f, 1.25f, 0.92f);
SubmitCapsuleBeam(ref beamIdx, start, end, isPd ? 0.075f : 0.055f, col, coreSharpness: 3.0f, coreRadiusFrac: 0.36f, tailFade: 1.0f);
break;
}
case WeaponVisualClass.Autocannon:
{
EmitBeam(ref beamIdx, lookBasis, mid, new Vector3(0.20f, 0.20f, dist), new Color(2.5f, 0.85f, 0.14f, 0.72f));
EmitBeam(ref beamIdx, lookBasis, mid, new Vector3(0.08f, 0.08f, dist), new Color(3.6f, 2.7f, 1.3f, 0.98f));
SubmitCapsuleBeam(ref beamIdx, start, end, 0.14f, new Color(3.4f, 1.35f, 0.28f, 0.96f), coreSharpness: 2.8f, coreRadiusFrac: 0.36f, tailFade: 1.0f);
break;
}
case WeaponVisualClass.Explosive:
{
bool isRecoilless = string.Equals(t.WeaponId, "recoilless", StringComparison.Ordinal);
float w = isRecoilless ? 0.22f : 0.12f;
EmitBeam(ref beamIdx, lookBasis, mid, new Vector3(w, w, dist), new Color(3.2f, 1.25f, 0.25f, 0.96f));
SubmitCapsuleBeam(ref beamIdx, start, end, isRecoilless ? 0.17f : 0.10f, new Color(3.6f, 1.45f, 0.32f, 0.96f), coreSharpness: 2.6f, coreRadiusFrac: 0.34f, tailFade: 1.0f);
break;
}
case WeaponVisualClass.ThermalBeam:
{
bool isLance = string.Equals(t.WeaponId, "gilded_lance", StringComparison.Ordinal);
float outerW = isLance ? 0.34f : 0.20f;
float coreW = isLance ? 0.13f : 0.08f;
Color outerCol = isLance
? new Color(2.8f, 1.95f, 0.45f, 0.62f)
: new Color(0.45f, 2.35f, 2.95f, 0.65f);
Color coreCol = isLance
? new Color(1.6f, 3.6f, 3.8f, 0.98f)
: new Color(2.4f, 3.4f, 3.8f, 0.98f);
EmitBeam(ref beamIdx, lookBasis, mid, new Vector3(outerW, outerW, dist), outerCol);
EmitBeam(ref beamIdx, lookBasis, mid, new Vector3(coreW, coreW, dist), coreCol);
float outerR = isLance ? 0.24f : 0.15f;
Color beamCol = isLance
? new Color(3.4f, 2.35f, 0.55f, 0.96f)
: new Color(0.55f, 2.80f, 3.60f, 0.96f);
SubmitCapsuleBeam(ref beamIdx, start, end, outerR, beamCol, coreSharpness: 3.2f, coreRadiusFrac: 0.38f, tailFade: 0.0f, pulsePhase: 12f);
break;
}
case WeaponVisualClass.GaussRail:
{
EmitBeam(ref beamIdx, lookBasis, mid, new Vector3(0.30f, 0.30f, dist), new Color(0.25f, 1.85f, 3.4f, 0.68f));
EmitBeam(ref beamIdx, lookBasis, mid, new Vector3(0.10f, 0.10f, dist), new Color(2.2f, 3.6f, 4.0f, 0.98f));
SubmitCapsuleBeam(ref beamIdx, start, end, 0.22f, new Color(0.42f, 2.45f, 3.80f, 0.98f), coreSharpness: 3.6f, coreRadiusFrac: 0.34f, tailFade: 0.0f, pulsePhase: 18f);
break;
}
case WeaponVisualClass.PlasmaPpc:
{
EmitBeam(ref beamIdx, lookBasis, mid, new Vector3(0.36f, 0.36f, dist), new Color(0.18f, 2.25f, 2.65f, 0.65f));
EmitBeam(ref beamIdx, lookBasis, mid, new Vector3(0.14f, 0.14f, dist), new Color(1.2f, 3.5f, 3.8f, 0.98f));
SubmitCapsuleBeam(ref beamIdx, start, end, 0.25f, new Color(0.28f, 2.85f, 3.40f, 0.96f), coreSharpness: 2.6f, coreRadiusFrac: 0.40f, tailFade: 0.0f, pulsePhase: 14f);
break;
}
case WeaponVisualClass.RocketSalvo:
{
EmitBeam(ref beamIdx, lookBasis, mid, new Vector3(0.22f, 0.22f, dist), new Color(3.2f, 1.45f, 0.30f, 0.92f));
SubmitCapsuleBeam(ref beamIdx, start, end, 0.16f, new Color(3.6f, 1.65f, 0.38f, 0.94f), coreSharpness: 2.6f, coreRadiusFrac: 0.36f, tailFade: 1.0f);
break;
}
case WeaponVisualClass.SwarmSmart:
{
EmitBeam(ref beamIdx, lookBasis, mid, new Vector3(0.16f, 0.16f, dist), new Color(1.4f, 2.8f, 0.45f, 0.85f));
EmitBeam(ref beamIdx, lookBasis, mid, new Vector3(0.07f, 0.07f, dist), new Color(2.0f, 0.95f, 3.2f, 0.96f));
SubmitCapsuleBeam(ref beamIdx, start, end, 0.12f, new Color(1.65f, 3.20f, 0.58f, 0.95f), coreSharpness: 2.8f, coreRadiusFrac: 0.36f, tailFade: 1.0f);
break;
}
}
}
for (int i = 0; i < _mirrorBeams.Count; i++)
{
var b = _mirrorBeams[i];
SubmitCapsuleBeam(ref beamIdx, b.Start, b.End, b.Radius, b.HdrTint, b.CoreSharpness, b.CoreRadiusFrac, b.TailFade);
}
_activeBeamCount = beamIdx;
_vfxBeamMm.VisibleInstanceCount = beamIdx;
_vfxBeamMmi.Visible = beamIdx > 0;
@ -1421,7 +1408,6 @@ public partial class ArenaRenderer : Node3D
normal = normal.Normalized();
bool isRecoilless = string.Equals(ev.WeaponId, "recoilless", StringComparison.Ordinal);
float detSize = isRecoilless || wClass == WeaponVisualClass.RocketSalvo ? 3.2f : 1.9f;
float ringSize = isRecoilless || wClass == WeaponVisualClass.RocketSalvo ? 6.2f : 3.4f;
Color coreStart = wClass switch
{
@ -1435,19 +1421,6 @@ public partial class ArenaRenderer : Node3D
WeaponVisualClass.SwarmSmart => new Color(0.55f, 0.25f, 0.85f, 0f),
_ => new Color(0.85f, 0.28f, 0.08f, 0f)
};
AddTransient(new TransientVfx
{
Shape = VfxShape.Sphere,
Position = pos + normal * 0.25f,
Velocity = normal * 1.4f,
BaseRotation = Basis.Identity,
StartScale = Vector3.One * 0.5f,
EndScale = Vector3.One * detSize,
ColorStart = coreStart,
ColorEnd = coreEnd,
Age = 0f,
Lifetime = isRecoilless ? 0.28f : 0.22f
});
Vector3 upRef = MathF.Abs(normal.Y) > 0.92f ? Vector3.Forward : Vector3.Up;
Vector3 right = upRef.Cross(normal).Normalized();
@ -1689,14 +1662,34 @@ public partial class ArenaRenderer : Node3D
return fallbackPos + new Vector3(0f, halfHeight * 0.7f, 0f);
}
private void EmitBeam(ref int beamIdx, Basis lookBasis, Vector3 mid, Vector3 scale, Color color)
private void SubmitCapsuleBeam(
ref int beamIdx,
Vector3 start,
Vector3 end,
float outerRadius,
Color hdrTint,
float coreSharpness,
float coreRadiusFrac,
float tailFade,
float pulsePhase = 0f)
{
if (beamIdx >= MaxVfxBeams)
{
return;
}
Vector3 delta = end - start;
float len = delta.Length();
Vector3 dir = len > 0.01f ? delta / len : Vector3.Forward;
Vector3 up = MathF.Abs(dir.Dot(Vector3.Up)) > 0.95f ? Vector3.Right : Vector3.Up;
Basis lookBasis = Basis.LookingAt(dir, up);
Vector3 mid = (start + end) * 0.5f;
float r = MathF.Max(0.01f, outerRadius);
Vector3 scale = new(2f * r, 2f * r, len + 2f * r);
_vfxBeamMm.SetInstanceTransform(beamIdx, new Transform3D(lookBasis * Basis.FromScale(scale), mid));
_vfxBeamMm.SetInstanceCustomData(beamIdx, color);
_vfxBeamMm.SetInstanceColor(beamIdx, hdrTint);
_vfxBeamMm.SetInstanceCustomData(beamIdx, new Color(coreSharpness, coreRadiusFrac, tailFade, pulsePhase));
beamIdx++;
}

View file

@ -21,6 +21,11 @@ public partial class AtmosphereSystem : Node
private CanvasLayer _filmGrainLayer = null!;
private ColorRect _filmGrainRect = null!;
private ShaderMaterial _filmGrainMat = null!;
private Texture3Drd? _flowTexRd;
private ImageTexture3D? _dummyFlowTex;
private VolumetricCompositorEffect? _volumetricEffect;
private Compositor? _compositor;
private VolumetricEmitterPool _emitterPool = new();
private bool _initialized;
public WorldEnvironment WorldEnvironment => _worldEnv;
@ -29,6 +34,8 @@ public partial class AtmosphereSystem : Node
public FogVolume ValleyFogVolume => _valleyFog;
public CanvasLayer FilmGrainLayer => _filmGrainLayer;
public AtmosphereLutBaker.BakedAtmosphere? CurrentBaked { get; private set; }
public VolumetricCompositorEffect? VolumetricEffect => _volumetricEffect;
public VolumetricEmitterPool EmitterPool => _emitterPool;
public override void _Ready()
{
@ -122,6 +129,34 @@ public partial class AtmosphereSystem : Node
Name = "WorldEnv",
Environment = _env
};
Vector3 defaultInvExtent = new(
1f / (VolumetricCompositorEffect.FlowDimX * VolumetricCompositorEffect.FlowVoxelSizeMeters),
1f / (VolumetricCompositorEffect.FlowDimY * VolumetricCompositorEffect.FlowVoxelSizeMeters),
1f / (VolumetricCompositorEffect.FlowDimZ * VolumetricCompositorEffect.FlowVoxelSizeMeters));
RegisterGlobalParamIfMissing("rtd_flow_origin", RenderingServer.GlobalShaderParameterType.Vec3, Vector3.Zero);
RegisterGlobalParamIfMissing("rtd_flow_inv_extent", RenderingServer.GlobalShaderParameterType.Vec3, defaultInvExtent);
if (RenderingServer.GetRenderingDevice() is not null)
{
_flowTexRd = new Texture3Drd();
RegisterGlobalParamIfMissing("rtd_flow_field", RenderingServer.GlobalShaderParameterType.Sampler3D, _flowTexRd);
_volumetricEffect = new VolumetricCompositorEffect(_flowTexRd, _emitterPool);
_compositor = new Compositor
{
CompositorEffects = new Godot.Collections.Array<CompositorEffect> { _volumetricEffect }
};
_worldEnv.Compositor = _compositor;
}
else
{
var dummyImg = Image.CreateEmpty(1, 1, false, Image.Format.Rgbah);
dummyImg.SetPixel(0, 0, new Color(0f, 0f, 0f, 0f));
_dummyFlowTex = new ImageTexture3D();
_dummyFlowTex.Create(Image.Format.Rgbah, 1, 1, 1, false, new Godot.Collections.Array<Image> { dummyImg });
RegisterGlobalParamIfMissing("rtd_flow_field", RenderingServer.GlobalShaderParameterType.Sampler3D, _dummyFlowTex);
}
AddChild(_worldEnv);
_sun = new DirectionalLight3D
@ -233,5 +268,81 @@ public partial class AtmosphereSystem : Node
_env.FogDensity = preset.DepthFogDensity;
_env.FogAerialPerspective = preset.DepthFogAerialPerspective;
_env.FogSunScatter = preset.DepthFogSunScatter;
if (_volumetricEffect is not null)
{
Color ambCol = new(
MathF.Max(0.10f, haze.R * 0.55f),
MathF.Max(0.12f, haze.G * 0.55f),
MathF.Max(0.14f, haze.B * 0.58f));
_volumetricEffect.SetAtmosphere(
baked.SunDirection,
baked.SunLightEnergy,
baked.SunLightColor,
ambCol,
extinctionScale: mapKind == ArenaMapKind.Sion ? 1.85f : 1.70f);
}
}
public void BindEmitterPool(VolumetricEmitterPool pool)
{
_emitterPool = pool ?? throw new ArgumentNullException(nameof(pool));
_volumetricEffect?.SetEmitterPool(pool);
}
public override void _ExitTree()
{
if (_worldEnv is not null && GodotObject.IsInstanceValid(_worldEnv))
{
_worldEnv.Compositor = null;
}
if (_flowTexRd is not null)
{
_flowTexRd.TextureRdRid = new Rid();
}
if (AreFlowGlobalsRegistered && RenderingServer.Singleton is not null)
{
_dummyFlowTex ??= CreateDummyFlowTexture();
RenderingServer.GlobalShaderParameterSet("rtd_flow_field", _dummyFlowTex);
}
if (_volumetricEffect is not null)
{
_volumetricEffect.Enabled = false;
if (RenderingServer.GetRenderingDevice() is not null)
{
RenderingServer.CallOnRenderThread(Callable.From(_volumetricEffect.DisposeRdResources));
RenderingServer.ForceSync();
}
}
}
private static ImageTexture3D CreateDummyFlowTexture()
{
var dummyImg = Image.CreateEmpty(1, 1, false, Image.Format.Rgbah);
dummyImg.SetPixel(0, 0, new Color(0f, 0f, 0f, 0f));
var tex = new ImageTexture3D();
tex.Create(Image.Format.Rgbah, 1, 1, 1, false, new Godot.Collections.Array<Image> { dummyImg });
return tex;
}
private static readonly System.Collections.Generic.HashSet<string> RegisteredGlobals = new();
public static bool AreFlowGlobalsRegistered =>
RegisteredGlobals.Contains("rtd_flow_field") &&
RegisteredGlobals.Contains("rtd_flow_origin") &&
RegisteredGlobals.Contains("rtd_flow_inv_extent");
private static void RegisterGlobalParamIfMissing(
StringName name,
RenderingServer.GlobalShaderParameterType type,
Variant defaultValue)
{
string key = name.ToString();
if (RegisteredGlobals.Contains(key))
{
RenderingServer.GlobalShaderParameterSet(name, defaultValue);
return;
}
RegisteredGlobals.Add(key);
RenderingServer.GlobalShaderParameterAdd(name, type, defaultValue);
}
}

View file

@ -27,6 +27,15 @@ public sealed class ClientOrdnanceMirror
Color ColorEnd,
float Lifetime);
public readonly record struct ActiveBeamSpec(
Vector3 Start,
Vector3 End,
float Radius,
Color HdrTint,
float CoreSharpness,
float CoreRadiusFrac,
float TailFade);
private struct MirroredSlot
{
public bool Active;
@ -39,6 +48,7 @@ public sealed class ClientOrdnanceMirror
public Color Color;
public float ManufacturerRoleIndex;
public Vector3 Pos;
public Vector3 TailPos;
public Vector3 Vel;
public Vector3 AnchorPos;
public int TargetEntityId;
@ -82,6 +92,7 @@ public sealed class ClientOrdnanceMirror
VehicleAssetCache cache,
DebrisSystem debris,
ParticlePool particles,
VolumetricEmitterPool volumetrics,
bool hasCam,
Vector3 camPos,
Action<TransientVfxSpec> emitTransient)
@ -186,16 +197,10 @@ public sealed class ClientOrdnanceMirror
RemoveById(ev.OrdnanceId);
float splashR = def is not null && def.SplashRadius > 0.5f ? def.SplashRadius : 4.2f;
particles.EmitOrdnanceBurst(pos, col, sparkCount: 6, radiusScale: Math.Clamp(splashR / 4.5f, 0.7f, 1.6f), camPos, hasCam);
emitTransient(new TransientVfxSpec(
IsSphere: true,
Position: pos + Vector3.Up * 0.2f,
Velocity: Vector3.Up * 1.2f,
Rotation: Basis.Identity,
StartScale: Vector3.One * 0.55f,
EndScale: Vector3.One * Math.Clamp(splashR * 0.75f, 1.8f, 4.8f),
ColorStart: new Color(col.R * 3.2f, col.G * 3.2f, col.B * 3.2f, 0.92f),
ColorEnd: new Color(col.R * 0.8f, col.G * 0.3f, col.B * 0.2f, 0f),
Lifetime: 0.26f));
if (!hasCam || pos.DistanceSquaredTo(camPos) <= 280f * 280f)
{
volumetrics.EmitOrdnanceDetonation(pos, col, splashR);
}
emitTransient(new TransientVfxSpec(
IsSphere: false,
Position: pos + Vector3.Up * 0.16f,
@ -227,11 +232,12 @@ public sealed class ClientOrdnanceMirror
VehicleAssetCache cache,
MultiMeshPartPool partPool,
ParticlePool particles,
VolumetricEmitterPool volumetrics,
TerrainField terrain,
bool hasCam,
Vector3 camPos,
Action<Transform3D, Color> submitActiveRing,
Action<Transform3D, Color> submitActiveSphere)
Action<ActiveBeamSpec> submitActiveBeam)
{
if (_activeCount == 0)
{
@ -273,6 +279,8 @@ public sealed class ClientOrdnanceMirror
}
AdvanceSlotKinematics(ref s, def, state, terrain, stepDt);
float tailLerp = 1f - MathF.Exp(-stepDt * 18f);
s.TailPos = s.TailPos.Lerp(s.Pos, tailLerp);
}
if (hasCam && s.Pos.DistanceSquaredTo(camPos) > 340f * 340f)
@ -293,9 +301,6 @@ public sealed class ClientOrdnanceMirror
Transform3D ringXf = new(Basis.FromScale(new Vector3(radius * 2f * pulse, 0.35f, radius * 2f * pulse)), poolPos);
submitActiveRing(ringXf, new Color(s.Color.R * 2.6f, s.Color.G * 2.6f, s.Color.B * 2.6f, 0.78f));
Transform3D discXf = new(Basis.FromScale(new Vector3(radius * 1.4f * pulse, 0.14f, radius * 1.4f * pulse)), poolPos - new Vector3(0f, 0.04f, 0f));
submitActiveSphere(discXf, new Color(s.Color.R * 2.1f, s.Color.G * 2.1f, s.Color.B * 2.1f, 0.42f));
if (stepDt > 0f)
{
s.EmberTimer += stepDt;
@ -303,6 +308,10 @@ public sealed class ClientOrdnanceMirror
{
s.EmberTimer = 0f;
particles.EmitThermalPoolEmber(poolPos, radius, s.Color, camPos, hasCam);
if (!hasCam || poolPos.DistanceSquaredTo(camPos) <= 220f * 220f)
{
volumetrics.EmitThermalPoolPlume(poolPos, radius, s.Color);
}
}
}
continue;
@ -349,10 +358,13 @@ public sealed class ClientOrdnanceMirror
if (stepDt > 0f)
{
s.TrailTimer += stepDt;
if (s.TrailTimer >= 0.055f)
if (s.TrailTimer >= 0.075f)
{
s.TrailTimer = 0f;
particles.EmitOrdnanceTrail(s.Pos, s.Vel, s.Color, isRocket: def?.Motion != OrdnanceMotion.LoiterOrbit, camPos, hasCam);
if (!hasCam || s.Pos.DistanceSquaredTo(camPos) <= 240f * 240f)
{
volumetrics.EmitOrdnanceTrailCapsule(s.TailPos, s.Pos, s.Vel, s.Color, isRocket: def?.Motion != OrdnanceMotion.LoiterOrbit);
}
}
}
continue;
@ -382,19 +394,30 @@ public sealed class ClientOrdnanceMirror
def?.Motion is OrdnanceMotion.RocketBoosted or OrdnanceMotion.HomingMissile;
partPool.Submit(projMesh, in projXf, new Color(0f, isRocket ? 0.65f : 0.25f, s.ManufacturerRoleIndex, 1f), wantsShadow: false);
if (isRocket)
{
Transform3D thrusterXf = new(Basis.FromScale(Vector3.One * 0.42f), s.Pos - dir * 0.22f);
submitActiveSphere(thrusterXf, new Color(s.Color.R * 3.2f, s.Color.G * 3.2f, s.Color.B * 3.2f, 0.90f));
}
// Connected [TailPos, Pos] volumetric capsule streak
Vector3 tailStart = s.Pos.DistanceSquaredTo(s.TailPos) > 0.04f ? s.TailPos : s.Pos - dir * 1.4f;
Color beamCol = isRocket
? new Color(s.Color.R * 3.4f, s.Color.G * 2.4f, s.Color.B * 1.4f, 0.94f)
: new Color(s.Color.R * 3.0f, s.Color.G * 3.0f, s.Color.B * 3.0f, 0.92f);
submitActiveBeam(new ActiveBeamSpec(
Start: tailStart,
End: s.Pos - dir * 0.16f,
Radius: isRocket ? 0.24f : 0.15f,
HdrTint: beamCol,
CoreSharpness: 2.8f,
CoreRadiusFrac: 0.36f,
TailFade: 1.0f));
if (stepDt > 0f)
{
s.TrailTimer += stepDt;
if (s.TrailTimer >= (isRocket ? 0.035f : 0.055f))
if (s.TrailTimer >= (isRocket ? 0.055f : 0.075f))
{
s.TrailTimer = 0f;
particles.EmitOrdnanceTrail(s.Pos - dir * 0.18f, s.Vel, s.Color, isRocket, camPos, hasCam);
if (!hasCam || s.Pos.DistanceSquaredTo(camPos) <= 240f * 240f)
{
volumetrics.EmitOrdnanceTrailCapsule(s.TailPos, s.Pos - dir * 0.18f, s.Vel, s.Color, isRocket);
}
}
}
}
@ -565,6 +588,7 @@ public sealed class ClientOrdnanceMirror
Color = col,
ManufacturerRoleIndex = mfgRole,
Pos = pos,
TailPos = pos,
Vel = vel,
AnchorPos = pos,
TargetEntityId = ev.TargetEntityId,

214
client/GpuSparksSystem.cs Normal file
View file

@ -0,0 +1,214 @@
using System;
using Godot;
namespace RustToDust.Client;
/// <summary>
/// Flow-coupled GPU particle system (<see cref="GpuParticles3D"/>, 65,536 capacity) driven by
/// the global <c>rtd_flow_field</c> <see cref="Texture3Drd"/> + <c>Tri3D</c> curl streams for
/// stochastic opaque HDR sparks, buoyant embers, flow-entrained dust motes, and muzzle starbursts.
/// </summary>
public partial class GpuSparksSystem : Node3D
{
public const int Capacity = 65536;
public const int TypeVelocitySpark = 0;
public const int TypeBuoyantEmber = 1;
public const int TypeDustMote = 2;
public const int TypeMuzzleStarburst = 3;
private const uint EmitFlagsAll = (uint)(
GpuParticles3D.EmitFlags.Position |
GpuParticles3D.EmitFlags.Velocity |
GpuParticles3D.EmitFlags.Color |
GpuParticles3D.EmitFlags.Custom);
private GpuParticles3D _particles = null!;
private ShaderMaterial _processMat = null!;
private ShaderMaterial _drawMat = null!;
private bool _initialized;
private uint _rng = 0x9E3779B9u;
public int TotalEmittedCount { get; private set; }
public GpuParticles3D ParticlesNode => _particles;
public override void _Ready()
{
EnsureInitialized();
}
public void EnsureInitialized()
{
if (_initialized)
{
return;
}
_initialized = true;
Shader processShader = GD.Load<Shader>("res://gpu_sparks_process.gdshader")
?? throw new InvalidOperationException("Failed to load res://gpu_sparks_process.gdshader");
Shader drawShader = GD.Load<Shader>("res://gpu_sparks_draw.gdshader")
?? throw new InvalidOperationException("Failed to load res://gpu_sparks_draw.gdshader");
_processMat = new ShaderMaterial { Shader = processShader };
_drawMat = new ShaderMaterial { Shader = drawShader };
var quad = new QuadMesh
{
Size = Vector2.One,
Material = _drawMat
};
_particles = new GpuParticles3D
{
Name = "GpuSparks3D",
Amount = Capacity,
LocalCoords = false,
Emitting = true,
AmountRatio = 0.0f, // Keep GPU process active with zero automatic spawns
Lifetime = 2.5f,
FixedFps = 0,
Explosiveness = 0.0f,
CastShadow = GeometryInstance3D.ShadowCastingSetting.Off,
VisibilityAabb = new Aabb(new Vector3(-1800f, -200f, -1800f), new Vector3(3600f, 2200f, 3600f)),
PhysicsInterpolationMode = PhysicsInterpolationModeEnum.Off,
ProcessMaterial = _processMat,
DrawPass1 = quad
};
AddChild(_particles);
}
public void ClearAll()
{
EnsureInitialized();
TotalEmittedCount = 0;
_particles.Restart();
_particles.Emitting = true;
_particles.AmountRatio = 0.0f;
}
public void Prewarm(Vector3 nearPos)
{
EnsureInitialized();
EmitRaw(nearPos + new Vector3(0f, -20f, 0f), Vector3.Up * 0.1f, new Color(1f, 1f, 1f, 0.01f), 0.02f, 0.05f, TypeVelocitySpark, 1.0f);
TotalEmittedCount = 0;
}
public void EmitMuzzleStarburst(Vector3 pos, Color hdrColor, float sizeM, float lifetimeSec)
{
EnsureInitialized();
EmitRaw(pos, Vector3.Zero, hdrColor, Math.Clamp(sizeM, 0.25f, 0.90f), Math.Clamp(lifetimeSec, 0.05f, 0.14f), TypeMuzzleStarburst, 0f);
}
public void EmitSparkBurst(Vector3 pos, Vector3 normal, int count, Color hdrColor, float speed, float widthM = 0.026f)
{
EnsureInitialized();
Vector3 n = normal.LengthSquared() > 1e-4f ? normal.Normalized() : Vector3.Up;
for (int i = 0; i < count; i++)
{
Vector3 rand = new(NextSigned(), MathF.Abs(NextSigned()) + 0.28f, NextSigned());
Vector3 dir = (n * 0.65f + rand).Normalized();
float spd = speed * (0.55f + 0.85f * NextFloat());
float life = 0.24f + 0.34f * NextFloat();
Vector3 spawnPos = pos + new Vector3(NextSigned() * 0.14f, NextFloat() * 0.12f, NextSigned() * 0.14f);
EmitRaw(spawnPos, dir * spd, hdrColor, widthM, life, TypeVelocitySpark, 0.85f);
}
}
public void EmitEmberBurst(Vector3 pos, int count, Color hdrColor, float spreadSpeed, float widthM = 0.030f)
{
EnsureInitialized();
for (int i = 0; i < count; i++)
{
Vector3 vel = new(NextSigned() * spreadSpeed, 2.5f + NextFloat() * 5.5f, NextSigned() * spreadSpeed);
float life = 0.90f + NextFloat() * 1.25f;
EmitRaw(pos + new Vector3(NextSigned() * 0.7f, NextFloat() * 0.6f, NextSigned() * 0.7f), vel, hdrColor, widthM, life, TypeBuoyantEmber, 1.5f);
}
}
public void EmitDustMotes(Vector3 pos, Vector3 normal, int count, Color dustColor, float speed, float widthM = 0.065f)
{
EnsureInitialized();
Vector3 n = normal.LengthSquared() > 1e-4f ? normal.Normalized() : Vector3.Up;
for (int i = 0; i < count; i++)
{
float ang = NextFloat() * MathF.Tau;
float spd = speed * (0.55f + 0.70f * NextFloat());
Vector3 vel = new Vector3(MathF.Cos(ang) * spd, 0.8f + NextFloat() * 1.4f, MathF.Sin(ang) * spd) + n * (0.4f * spd);
float life = 0.45f + NextFloat() * 0.45f;
EmitRaw(pos + new Vector3(NextSigned() * 0.35f, 0.08f, NextSigned() * 0.35f), vel, dustColor, widthM, life, TypeDustMote, 3.6f);
}
}
public void EmitThermalPoolEmber(Vector3 pos, float radius, Color accentCol)
{
EnsureInitialized();
float ang = NextFloat() * MathF.Tau;
float r = MathF.Sqrt(NextFloat()) * MathF.Max(0.5f, radius * 0.85f);
Vector3 p = pos + new Vector3(MathF.Cos(ang) * r, 0.18f, MathF.Sin(ang) * r);
Vector3 vel = new(NextSigned() * 0.7f, 2.0f + NextFloat() * 1.8f, NextSigned() * 0.7f);
Color hdr = new(accentCol.R * 3.8f, accentCol.G * 3.8f, accentCol.B * 3.8f, 0.95f);
EmitRaw(p, vel, hdr, 0.055f, 0.65f + NextFloat() * 0.45f, TypeBuoyantEmber, 1.4f);
}
public void EmitPodRetroSparksAndDust(Vector3 podBasePos, float agl, Color groundTint, bool isContender)
{
EnsureInitialized();
float scale = isContender ? 1.2f : 0.85f;
Color sparkHdr = new(4.8f, 2.6f, 0.65f, 0.98f);
int sparkCount = isContender ? 14 : 8;
for (int i = 0; i < sparkCount; i++)
{
Vector3 vel = new(NextSigned() * 7.5f, -(11f + NextFloat() * 7f), NextSigned() * 7.5f);
EmitRaw(podBasePos + new Vector3(NextSigned() * 0.7f, 0.1f, NextSigned() * 0.7f), vel, sparkHdr, 0.028f * scale, 0.24f + NextFloat() * 0.16f, TypeVelocitySpark, 1.2f);
}
if (agl < 60f)
{
float washT = Math.Clamp(1f - agl / 60f, 0.2f, 1f);
Vector3 groundPos = podBasePos - new Vector3(0f, MathF.Max(0f, agl), 0f) + new Vector3(0f, 0.22f, 0f);
Color dustCol = new(groundTint.R * 1.1f, groundTint.G * 1.1f, groundTint.B * 1.1f, 0.78f * washT);
int moteCount = isContender ? 24 : 14;
for (int d = 0; d < moteCount; d++)
{
float ang = NextFloat() * MathF.Tau;
float spd = (7.5f + NextFloat() * 8.5f) * washT * scale;
Vector3 vel = new(MathF.Cos(ang) * spd, 1.0f + NextFloat() * 1.6f, MathF.Sin(ang) * spd);
EmitRaw(groundPos + new Vector3(MathF.Cos(ang) * 0.9f, 0f, MathF.Sin(ang) * 0.9f), vel, dustCol, 0.055f * scale, 0.55f + NextFloat() * 0.30f, TypeDustMote, 3.4f);
}
}
}
public void EmitPodTouchdownSparksAndDust(Vector3 pos, Vector3 normal, Color groundTint, bool isContender)
{
EnsureInitialized();
float scale = isContender ? 1.3f : 0.95f;
EmitSparkBurst(pos + normal * 0.45f, normal, isContender ? 160 : 90, new Color(5.2f, 2.8f, 0.70f, 0.98f), 19f * scale, 0.028f);
EmitEmberBurst(pos + normal * 0.45f, isContender ? 85 : 48, new Color(4.0f, 1.6f, 0.35f, 0.95f), 7.5f * scale, 0.032f);
EmitDustMotes(pos + normal * 0.25f, normal, isContender ? 75 : 45, groundTint with { A = 0.82f }, 10f * scale, 0.058f);
}
private void EmitRaw(Vector3 pos, Vector3 vel, Color hdrColor, float widthM, float lifetimeSec, int type, float drag)
{
float packedTypeAndDrag = type + Math.Clamp(drag, 0f, 19.9f) * 0.05f;
_particles.EmitParticle(
new Transform3D(Basis.Identity, pos),
vel,
hdrColor,
new Color(widthM, 0f, lifetimeSec, packedTypeAndDrag),
EmitFlagsAll);
TotalEmittedCount++;
}
private float NextFloat()
{
uint x = _rng;
x ^= x << 13;
x ^= x >> 17;
x ^= x << 5;
_rng = x;
return (x & 0x00FFFFFFu) / 16777216f;
}
private float NextSigned() => NextFloat() * 2f - 1f;
}

View file

@ -150,6 +150,7 @@ public partial class Main : Node3D
_arena = new ArenaRenderer { Name = "Arena" };
AddChild(_arena);
_arena.AssetCache.PreloadAll();
_atmosphere.BindEmitterPool(_arena.Volumetrics);
_audio = new ArenaAudioSystem { Name = "ArenaAudio" };
AddChild(_audio);
@ -304,6 +305,11 @@ public partial class Main : Node3D
{
_perfTargetFrames = perfFrames;
ArenaSession.PerfEnabled = true;
RenderingServer.ViewportSetMeasureRenderTime(GetViewport().GetViewportRid(), true);
if (_atmosphere.VolumetricEffect is not null)
{
_atmosphere.VolumetricEffect.ProfilingEnabled = true;
}
}
else if (int.TryParse(System.Environment.GetEnvironmentVariable("RTD_AUTO_EXIT_FRAMES"), out int autoExitFrames) && autoExitFrames > 0)
{
@ -895,6 +901,7 @@ public partial class Main : Node3D
Vector3 startVec = new(localStart.X, localStart.Y, localStart.Z);
Vector3 startFwd = new(MathF.Sin(localStart.Yaw), 0f, MathF.Cos(localStart.Yaw));
_arena.Particles.PrewarmFlashLights(startVec, startFwd);
_arena.GpuSparks.Prewarm(startVec);
_arena.PomDecals.PrewarmShader(startVec);
_hud.Sync(_session);
}
@ -1505,7 +1512,14 @@ public partial class Main : Node3D
GD.Print($"UpdateCameraMs/frame: avg={_perfCamMsSum / _perfFrameMs.Count:F2}");
int ticks = Math.Max(1, _perfPhysicsTicks);
GD.Print($"StepBreakdownMs/tick: ring={ArenaSession.PerfRingMs / ticks:F2} ai={ArenaSession.PerfAiMs / ticks:F2} drive={ArenaSession.PerfDriveMs / ticks:F2} world={ArenaSession.PerfWorldMs / ticks:F2} sync={ArenaSession.PerfBodySyncMs / ticks:F2} detect={ArenaSession.PerfDetectMs / ticks:F2} weapons={ArenaSession.PerfWeaponsMs / ticks:F2}");
GD.Print($"CombatProbes: syncDamageHeatMsTotal={VehicleVisualInstance.PerfDamageHeatMs:F2} matDups={VehicleVisualInstance.PerfMaterialDupCount} bakeTileMsTotal={TerrainRenderer.PerfBakeTileMs:F2} bakeTileCalls={TerrainRenderer.PerfBakeTileCalls} debrisActive={_arena.Debris.ActiveCount} particlesActive={_arena.Particles.ActiveParticleCount} flashLightsPeak={_arena.Particles.PeakFlashLightCount} tracers={_session?.ViewState.Tracers.Count ?? 0}");
GD.Print($"CombatProbes: syncDamageHeatMsTotal={VehicleVisualInstance.PerfDamageHeatMs:F2} matDups={VehicleVisualInstance.PerfMaterialDupCount} bakeTileMsTotal={TerrainRenderer.PerfBakeTileMs:F2} bakeTileCalls={TerrainRenderer.PerfBakeTileCalls} debrisActive={_arena.Debris.ActiveCount} gpuSparksEmitted={_arena.GpuSparks.TotalEmittedCount} volEmitters={_arena.Volumetrics.ActiveEmitterCount} volImpulses={_arena.Volumetrics.ActiveImpulseCount} flashLightsPeak={_arena.Particles.PeakFlashLightCount} tracers={_session?.ViewState.Tracers.Count ?? 0}");
if (_atmosphere.VolumetricEffect is { } volFx)
{
Rid vpRid = GetViewport().GetViewportRid();
double vpGpuMs = RenderingServer.ViewportGetMeasuredRenderTimeGpu(vpRid);
double vpCpuMs = RenderingServer.ViewportGetMeasuredRenderTimeCpu(vpRid);
GD.Print($"Cut10bGpuMs: total={volFx.LastTotalGpuMs:F3} flow={volFx.LastFlowGpuMs:F3} cull={volFx.LastCullGpuMs:F3} march={volFx.LastMarchGpuMs:F3} comp={volFx.LastCompGpuMs:F3} viewportGpuMs={vpGpuMs:F2} viewportCpuMs={vpCpuMs:F2}");
}
if (_session is not null)
{
var net = _session.ConnectionStatus;

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,689 @@
using System;
using System.Runtime.InteropServices;
using Godot;
namespace RustToDust.Client;
/// <summary>
/// 4-pass Forward+ Vulkan compute pipeline (<c>PostOpaque</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 = 256;
[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;
}
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;
// 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 VolumetricCompositorEffect() : this(new Texture3Drd(), new VolumetricEmitterPool())
{
}
public VolumetricCompositorEffect(Texture3Drd flowTexRd, VolumetricEmitterPool emitterPool)
{
_flowTexRd = flowTexRd;
_emitterPool = emitterPool;
EffectCallbackType = EffectCallbackTypeEnum.PostOpaque;
AccessResolvedColor = true;
AccessResolvedDepth = true;
Enabled = true;
}
public void SetEmitterPool(VolumetricEmitterPool pool)
{
_emitterPool = pool ?? throw new ArgumentNullException(nameof(pool));
}
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.PostOpaque || _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;
}
Vector2I halfSize = new(Math.Max(1, (fullSize.X + 1) / 2), Math.Max(1, (fullSize.Y + 1) / 2));
int tilesX = Math.Max(1, (halfSize.X + TileSizeHalfRes - 1) / TileSizeHalfRes);
int tilesY = Math.Max(1, (halfSize.Y + TileSizeHalfRes - 1) / TileSizeHalfRes);
int totalTiles = tilesX * tilesY;
EnsureHalfResAndTileBuffers(rd, halfSize, 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));
Vector3 sunDir;
float sunEnergy;
Color sunCol, ambCol;
float extScale;
lock (_atmoLock)
{
sunDir = _sunDir;
sunEnergy = _sunEnergy;
sunCol = _sunColor;
ambCol = _ambientColor;
extScale = _globalExtinctionScale;
}
_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)halfSize.X,
HalfH = (uint)halfSize.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
};
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();
}
}
}

File diff suppressed because it is too large Load diff

129
client/flow_field_step.glsl Normal file
View file

@ -0,0 +1,129 @@
#version 450
layout(local_size_x = 8, local_size_y = 4, local_size_z = 8) in;
struct FlowImpulse {
vec4 posRadius;
vec4 dirStrength;
vec4 shellParams;
};
layout(set = 0, binding = 0, std140) uniform VolumetricFrame {
mat4 invProj;
vec4 camPosTime;
vec4 camRightAspect;
vec4 camUpTanHalfFov;
vec4 camFwdNearFar;
vec4 sunDirIntensity;
vec4 sunColorExt;
vec4 ambientColorFog;
vec4 viewportInfo;
uvec4 tileGridParams;
vec4 flowOriginVoxel;
vec4 flowInvExtentDt;
ivec4 flowDeltaImpulse;
} u_frame;
layout(set = 0, binding = 1, std430) readonly buffer FlowImpulseBuffer {
FlowImpulse impulses[];
} u_impulses;
layout(set = 0, binding = 2) uniform sampler3D u_prevFlow;
layout(set = 0, binding = 3, rgba16f) uniform writeonly image3D u_nextFlow;
shared FlowImpulse sImp[64];
void main() {
uint tid = gl_LocalInvocationIndex;
uint impulseCount = min(uint(max(0, u_frame.flowDeltaImpulse.w)), 64u);
if (tid < impulseCount) {
sImp[tid] = u_impulses.impulses[tid];
}
memoryBarrierShared();
barrier();
ivec3 g = ivec3(gl_GlobalInvocationID.xyz);
const ivec3 gridDim = ivec3(64, 24, 64);
if (any(greaterThanEqual(g, gridDim))) {
return;
}
float voxelSize = u_frame.flowOriginVoxel.w;
float dt = clamp(u_frame.flowInvExtentDt.w, 0.0, 0.05);
float elapsed = u_frame.camPosTime.w;
// Gentle planetary wind that shifts subtly with time so idle smoke plumes breathe
vec3 ambientWind = vec3(
1.25 + 0.35 * sin(elapsed * 0.23),
0.18,
0.55 + 0.25 * cos(elapsed * 0.19)
);
ivec3 prevIdx = g + u_frame.flowDeltaImpulse.xyz;
bool inPrev = all(greaterThanEqual(prevIdx, ivec3(0))) && all(lessThan(prevIdx, gridDim));
vec3 prevVel = inPrev ? texelFetch(u_prevFlow, prevIdx, 0).rgb : ambientWind;
vec3 srcUv = (vec3(prevIdx) + vec3(0.5) - (prevVel * dt) / voxelSize) / vec3(gridDim);
vec4 advected = (inPrev && all(greaterThanEqual(srcUv, vec3(0.0))) && all(lessThanEqual(srcUv, vec3(1.0))))
? textureLod(u_prevFlow, srcUv, 0.0)
: vec4(ambientWind, 0.0);
vec3 vel = mix(ambientWind, advected.rgb, exp(-dt * 1.45));
float shockP = advected.a * exp(-dt * 4.5);
vec3 worldP = u_frame.flowOriginVoxel.xyz + (vec3(g) + vec3(0.5)) * voxelSize;
for (uint i = 0u; i < impulseCount; i++) {
FlowImpulse imp = sImp[i];
uint typeBits = floatBitsToUint(imp.shellParams.z);
float radius = max(0.5, imp.posRadius.w);
float strength = imp.dirStrength.w;
if (typeBits == 0u) {
// ShockShell: expanding radial blast shell
vec3 delta = worldP - imp.posRadius.xyz;
float dist = length(delta);
float thick = max(1.5, imp.shellParams.x);
float dShell = (dist - radius) / thick;
if (abs(dShell) < 3.0) {
float shell = exp(-dShell * dShell);
vec3 rDir = dist > 0.05 ? delta / dist : vec3(0.0, 1.0, 0.0);
vel += rDir * (strength * shell);
shockP = max(shockP, imp.shellParams.y * shell);
}
} else if (typeBits == 1u) {
// RetroDownwash: radial ground deflection from pod retro thruster
vec3 d = worldP - imp.posRadius.xyz;
float rXZ = length(d.xz);
float rNorm = rXZ / radius;
float hNorm = abs(d.y) / max(3.0, radius * 0.55);
if (rNorm < 1.35 && hNorm < 1.35) {
float rFall = exp(-rNorm * rNorm * 1.6) * smoothstep(1.35, 0.08, rNorm);
float hFall = exp(-hNorm * hNorm * 1.4);
vec2 rXZDir = rXZ > 0.1 ? d.xz / rXZ : vec2(1.0, 0.0);
vec3 outDir = normalize(vec3(rXZDir.x, 0.28, rXZDir.y));
float w = rFall * hFall;
vel += outDir * (strength * w);
shockP = max(shockP, imp.shellParams.y * w);
}
} else {
// ThermalUpdraft: buoyant rising column above fireballs & thermal pools
vec3 d = worldP - imp.posRadius.xyz;
float rXZ = length(d.xz);
float rNorm = rXZ / radius;
if (rNorm < 1.3 && d.y > -2.5 && d.y < radius * 2.8) {
float hFall = smoothstep(-2.5, 1.5, d.y) * smoothstep(radius * 2.8, 0.0, max(0.0, d.y));
float colFall = exp(-rNorm * rNorm * 1.5) * hFall;
vel += vec3(0.0, strength * colFall, 0.0);
}
}
}
float vLen = length(vel);
if (vLen > 120.0) {
vel *= 120.0 / vLen;
}
shockP = clamp(shockP, 0.0, 2.0);
imageStore(u_nextFlow, g, vec4(vel, shockP));
}

View file

@ -0,0 +1,151 @@
shader_type spatial;
render_mode unshaded, cull_disabled, depth_draw_opaque;
varying vec4 v_color;
varying vec2 v_uvCentered;
varying vec2 v_kite;
varying float v_ageNorm;
varying float v_type;
varying float v_camFade;
void vertex() {
vec3 worldPos = MODEL_MATRIX[3].xyz;
vec3 velWorld = MODEL_MATRIX[0].xyz;
float widthM = max(0.012, INSTANCE_CUSTOM.x);
float ageNorm = clamp(INSTANCE_CUSTOM.y / max(0.01, INSTANCE_CUSTOM.z), 0.0, 1.0);
float pType = floor(INSTANCE_CUSTOM.w + 0.001);
v_color = COLOR;
v_ageNorm = ageNorm;
v_type = pType;
v_uvCentered = UV * 2.0 - vec2(1.0);
// Kite-stretch trick: rotate quad coordinates 45 degrees so pointed ears align directly along velocity:
// (-1,-1) -> u=-1,v=0 (tail tip); (+1,+1) -> u=+1,v=0 (nose tip); (+1,-1)/(-1,+1) -> v=±1 (side ears)
float uKite = 0.5 * (v_uvCentered.x + v_uvCentered.y);
float vKite = 0.5 * (v_uvCentered.x - v_uvCentered.y);
v_kite = vec2(uKite, vKite);
vec3 camRight = INV_VIEW_MATRIX[0].xyz;
vec3 camUp = INV_VIEW_MATRIX[1].xyz;
vec3 toCamVec = CAMERA_POSITION_WORLD - worldPos;
float toCamLen2 = dot(toCamVec, toCamVec);
float distToCam = sqrt(toCamLen2);
v_camFade = smoothstep(1.2, 2.8, distToCam);
if (distToCam < 1.2) {
MODELVIEW_MATRIX = VIEW_MATRIX;
VERTEX = worldPos;
} else {
vec3 toCam = toCamLen2 > 1e-6 ? toCamVec * inversesqrt(toCamLen2) : INV_VIEW_MATRIX[2].xyz;
if (pType > 2.5) {
// Type 3: Stationary 4-point HDR muzzle starburst
float pulse = sin(ageNorm * 3.14159265);
float sz = min(widthM * (0.65 + 0.45 * pulse), distToCam * 0.032);
vec3 displacedWorld = worldPos + camRight * (v_uvCentered.x * sz) + camUp * (v_uvCentered.y * sz);
MODELVIEW_MATRIX = VIEW_MATRIX;
VERTEX = displacedWorld;
} else {
float speed = length(velWorld);
vec3 vProj = velWorld - toCam * dot(velWorld, toCam);
float vProjLen2 = dot(vProj, vProj);
vec3 axisWorld = vProjLen2 > 1e-4 ? vProj * inversesqrt(vProjLen2) : camRight;
vec3 rawPerp = cross(toCam, axisWorld);
float rawPerpLen2 = dot(rawPerp, rawPerp);
vec3 perpWorld = rawPerpLen2 > 1e-6 ? rawPerp * inversesqrt(rawPerpLen2) : camUp;
float dist = distToCam;
float halfWidth;
float halfLen;
if (pType > 1.5) {
// Type 2: Tiny flow-blown grit / dust mote
float minGritPx = dist * 0.0010;
halfWidth = max(clamp(widthM * (0.75 + 0.30 * ageNorm), 0.020, 0.055), minGritPx);
halfLen = halfWidth + clamp(speed * 0.006, 0.01, 0.09);
} else {
// Type 0 (VelocitySpark) & Type 1 (BuoyantEmber): crisp short punchy streaks (halfLen capped 0.04..0.16m)
float minSparkPx = dist * 0.0012;
halfWidth = max(clamp(widthM * mix(0.82, 0.38, ageNorm), 0.012, 0.030), minSparkPx);
float baseLen = clamp(halfWidth * 1.6 + speed * 0.008, 0.04, 0.16);
halfLen = max(halfWidth * 1.8, min(0.16, max(baseLen, minSparkPx * 2.6)));
}
// Near-camera angular cap so sparks & dust motes at 1.8-2.5m never blow up into giant halftone spears
float maxAngLen = dist * 0.022;
halfLen = min(halfLen, maxAngLen);
halfWidth = min(halfWidth, maxAngLen * 0.32);
vec3 displacedWorld = worldPos + axisWorld * (uKite * halfLen) + perpWorld * (vKite * halfWidth);
MODELVIEW_MATRIX = VIEW_MATRIX;
VERTEX = displacedWorld;
}
}
}
void fragment() {
if (v_camFade < 0.02) {
discard;
}
float fade = (1.0 - v_ageNorm * v_ageNorm) * clamp(v_color.a, 0.0, 1.0) * v_camFade;
if (fade < 0.02) {
discard;
}
// Temporally animated Interleaved Gradient Noise for stochastic opaque TAA coverage (depth_draw_opaque)
float frameIdx = mod(floor(TIME * 60.0), 64.0);
float dither = fract(52.9829189 * fract(dot(FRAGCOORD.xy + 5.588238 * frameIdx, vec2(0.06711056, 0.00583715))));
if (v_type > 2.5) {
// 4-point HDR muzzle starburst
float r = length(v_uvCentered);
if (r > 1.0) {
discard;
}
float cx = exp(-abs(v_uvCentered.y) * 9.5) * smoothstep(1.0, 0.05, abs(v_uvCentered.x));
float cy = exp(-abs(v_uvCentered.x) * 9.5) * smoothstep(1.0, 0.05, abs(v_uvCentered.y));
float core = smoothstep(0.55, 0.0, r);
float mask = max(core, max(cx, cy) * 0.90);
float coverage = clamp(mask * fade * 1.25, 0.0, 1.0);
if (coverage <= dither) {
discard;
}
ALBEDO = max(v_color.rgb, vec3(0.0)) * (1.0 + core * 0.95);
} else if (v_type > 1.5) {
// Flow-entrained grit / dust mote
float r = length(v_kite);
if (r > 0.92) {
discard;
}
float coverage = smoothstep(0.92, 0.14, r) * fade * 0.85;
if (coverage <= dither) {
discard;
}
ALBEDO = max(v_color.rgb, vec3(0.0));
} else {
// Molten slag spark / ember: white-gold -> amber -> deep copper-orange cooling ramp
float rKite = length(vec2(v_kite.x, v_kite.y * 1.15));
if (rKite > 1.0) {
discard;
}
float core = pow(clamp(1.0 - rKite, 0.0, 1.0), 1.45);
float hotCenter = smoothstep(0.50, 0.0, rKite);
float coverage = clamp(core * fade * 1.20, 0.0, 1.0);
if (coverage <= dither) {
discard;
}
vec3 whiteGold = vec3(6.2, 4.2, 1.65);
vec3 moltenAmber = vec3(4.3, 1.85, 0.30);
vec3 copperEmber = vec3(1.85, 0.42, 0.05);
vec3 ramp = v_ageNorm < 0.38
? mix(whiteGold, moltenAmber, v_ageNorm / 0.38)
: mix(moltenAmber, copperEmber, clamp((v_ageNorm - 0.38) / 0.62, 0.0, 1.0));
// Subtle caller tint (20%) so plasma/thermal slag still reads predominantly as molten fire
vec3 tintRgb = max(v_color.rgb, vec3(0.0));
vec3 moltenRgb = mix(ramp, tintRgb, 0.20);
ALBEDO = mix(moltenRgb, whiteGold * 1.15, hotCenter * (1.0 - 0.55 * v_ageNorm));
}
}

View file

@ -0,0 +1,154 @@
shader_type particles;
render_mode disable_velocity;
global uniform sampler3D rtd_flow_field;
global uniform vec3 rtd_flow_origin;
global uniform vec3 rtd_flow_inv_extent;
float tri(float x) {
return abs(fract(x) - 0.5);
}
vec3 tri3(vec3 p) {
return vec3(
tri(p.z + tri(p.y)),
tri(p.z + tri(p.x)),
tri(p.y + tri(p.x))
);
}
vec3 safeNorm(vec3 v) {
float l2 = dot(v, v);
return l2 > 1e-8 ? v * inversesqrt(l2) : vec3(0.0, 1.0, 0.0);
}
vec3 aetheriaCurl(vec3 pos, float flowScale, float scrollSpeed, float t) {
vec3 field = pos / max(0.5, flowScale);
float s1 = t * scrollSpeed;
float s2 = t * scrollSpeed * 1.61803398875;
vec3 t1 = safeNorm(tri3(field - vec3(0.0, s1, 0.0)));
vec3 t2 = safeNorm(tri3(field * 1.61803398875 - vec3(0.0, s2, 0.0)));
return cross(t1, t2);
}
uint hashU32(uint x) {
x ^= x >> 16u;
x *= 0x7FEB352Du;
x ^= x >> 15u;
x *= 0x846CA68Bu;
x ^= x >> 16u;
return x;
}
float hash01(uint x) {
return float(hashU32(x) & 0x00FFFFFFu) / 16777216.0;
}
void start() {
ACTIVE = true;
float pType = floor(CUSTOM.w + 0.001);
if (pType > 2.5) {
// Type 3: MuzzleStarburst stays stationary at muzzle
VELOCITY = vec3(0.0);
TRANSFORM[0].xyz = vec3(1.0, 0.0, 0.0);
TRANSFORM[1].xyz = vec3(0.0, 1.0, 0.0);
TRANSFORM[2].xyz = vec3(0.0, 0.0, 1.0);
} else {
uint seed = INDEX ^ (NUMBER * 747796405u) ^ floatBitsToUint(TIME);
float r0 = hash01(seed + 1u);
float r1 = hash01(seed + 17u);
float r2 = hash01(seed + 53u);
float r3 = hash01(seed + 131u);
float r4 = hash01(seed + 257u);
float r5 = hash01(seed + 509u);
// Wide log-normal speed dispersion (0.25x..2.8x) + 3D directional chaos to shatter radial shell fans
float gauss = (r0 + r1 - 1.0) * 1.45;
float speedMult = clamp(exp(gauss * 0.72), 0.25, 2.80);
float baseSpeed = length(VELOCITY);
vec3 dirJitter = vec3(r2 * 2.0 - 1.0, r4 * 2.0 - 1.0, r5 * 2.0 - 1.0);
VELOCITY = VELOCITY * speedMult + dirJitter * (baseSpeed * 0.30);
// Sub-frame / burst-window birth offset (0..55ms) with immediate curl + gravity advection
float dt0 = r3 * 0.055;
vec3 curl0 = aetheriaCurl(TRANSFORM[3].xyz, 3.0, 0.90, TIME);
if (pType < 0.5) {
VELOCITY += curl0 * (18.0 * dt0);
VELOCITY.y -= 11.0 * dt0;
} else if (pType < 1.5) {
VELOCITY += curl0 * (14.0 * dt0);
VELOCITY.y += 2.6 * dt0;
} else {
VELOCITY += curl0 * (10.0 * dt0);
VELOCITY.y -= 1.2 * dt0;
}
TRANSFORM[3].xyz += VELOCITY * dt0;
CUSTOM.y = min(CUSTOM.z * 0.35, dt0 * 0.65);
TRANSFORM[0].xyz = VELOCITY;
TRANSFORM[1].xyz = vec3(0.0, 1.0, 0.0);
TRANSFORM[2].xyz = vec3(0.0, 0.0, 1.0);
}
}
void process() {
float age = CUSTOM.y + DELTA;
float maxLife = max(0.01, CUSTOM.z);
if (age >= maxLife) {
ACTIVE = false;
} else {
CUSTOM.y = age;
float pType = floor(CUSTOM.w + 0.001);
float drag = fract(CUSTOM.w) * 20.0;
if (pType > 2.5) {
// Type 3: MuzzleStarburst (stationary HDR flash)
VELOCITY = vec3(0.0);
TRANSFORM[0].xyz = vec3(1.0, 0.0, 0.0);
TRANSFORM[1].xyz = vec3(0.0, 1.0, 0.0);
TRANSFORM[2].xyz = vec3(0.0, 0.0, 1.0);
} else {
vec3 worldPos = TRANSFORM[3].xyz;
vec3 flowUv = (worldPos - rtd_flow_origin) * rtd_flow_inv_extent;
vec4 flowSample = vec4(0.0);
if (all(greaterThanEqual(flowUv, vec3(0.0))) && all(lessThanEqual(flowUv, vec3(1.0)))) {
flowSample = textureLod(rtd_flow_field, flowUv, 0.0);
}
vec3 flowVel = flowSample.rgb;
float shockP = flowSample.a;
vec3 curl = aetheriaCurl(worldPos, 3.2, 0.85, TIME);
if (pType < 0.5) {
// Type 0: VelocitySpark (ballistic + wispy Tri3D curl streams + flow drag + shock kick)
VELOCITY += (flowVel - VELOCITY) * min(1.0, drag * DELTA);
VELOCITY += curl * (22.0 * DELTA);
VELOCITY.y -= 11.0 * DELTA;
if (shockP > 0.20) {
VELOCITY += flowVel * (shockP * 0.55 * DELTA);
}
} else if (pType < 1.5) {
// Type 1: BuoyantEmber (upward buoyancy + swirling Tri3D thermal streams)
VELOCITY += (flowVel - VELOCITY) * min(1.0, drag * DELTA);
VELOCITY += curl * (15.5 * DELTA);
VELOCITY.y += 3.0 * DELTA;
if (shockP > 0.20) {
VELOCITY += flowVel * (shockP * 0.70 * DELTA);
}
} else {
// Type 2: DustMote (heavily flow-entrained ground grit + curl wisps)
float dustDrag = max(drag, 3.2);
VELOCITY += (flowVel - VELOCITY) * min(1.0, dustDrag * DELTA);
VELOCITY += curl * (11.0 * DELTA);
VELOCITY.y -= 1.2 * DELTA;
}
TRANSFORM[3].xyz += VELOCITY * DELTA;
// Pass world VELOCITY to gpu_sparks_draw.gdshader cleanly via MODEL_MATRIX[0]
TRANSFORM[0].xyz = VELOCITY;
TRANSFORM[1].xyz = vec3(0.0, 1.0, 0.0);
TRANSFORM[2].xyz = vec3(0.0, 0.0, 1.0);
}
}
}

View file

@ -1,108 +0,0 @@
shader_type spatial;
render_mode unshaded, cull_disabled, blend_mix, depth_draw_never;
// Forward+ Vulkan single-draw-call billboard particle shader for MultiMeshInstance3D.
// Zero texture binds; packs shape mode, normalized age, HDR emissive, and 2D rotation into INSTANCE_CUSTOM,
// and sRGB RGB tint (converted to linear in vertex()) + alpha fade into COLOR.
//
// INSTANCE_CUSTOM layout:
// x = mode (0.0 = soft wisp dust/smoke, 1.0 = 4-point HDR muzzle starburst, 2.0 = spark/ember streak, 3.0 = steam/fireball puff)
// y = age_norm (0.0..1.0)
// z = emissive (0.0..4.0+ HDR multiplier)
// w = rot_rad (2D billboard roll angle in radians)
varying vec4 v_color;
varying vec4 v_custom;
float hash21(vec2 p) {
p = fract(p * vec2(127.1, 311.7));
p += dot(p, p + 34.43);
return fract(p.x * p.y);
}
float soft_noise(vec2 p) {
return 0.5 + 0.25 * sin(p.x * 2.7 + p.y * 1.9) + 0.25 * cos(p.y * 2.3 - p.x * 1.7);
}
vec3 srgb_to_linear(vec3 c) {
vec3 lo = c / 12.92;
vec3 hi = pow((c + vec3(0.055)) / 1.055, vec3(2.4));
return mix(lo, hi, step(vec3(0.04045), c));
}
void vertex() {
v_color = vec4(srgb_to_linear(max(COLOR.rgb, vec3(0.0))), COLOR.a);
v_custom = INSTANCE_CUSTOM;
float rot = INSTANCE_CUSTOM.w;
float c = cos(rot);
float s = sin(rot);
VERTEX.xy = vec2(VERTEX.x * c - VERTEX.y * s, VERTEX.x * s + VERTEX.y * c);
vec3 world_pos = MODEL_MATRIX[3].xyz;
float sx = length(MODEL_MATRIX[0].xyz);
float sy = length(MODEL_MATRIX[1].xyz);
MODELVIEW_MATRIX = VIEW_MATRIX * mat4(
vec4(INV_VIEW_MATRIX[0].xyz * sx, 0.0),
vec4(INV_VIEW_MATRIX[1].xyz * sy, 0.0),
vec4(INV_VIEW_MATRIX[2].xyz, 0.0),
vec4(world_pos, 1.0)
);
}
void fragment() {
vec2 centered = UV * 2.0 - vec2(1.0);
float r = length(centered);
if (r > 1.0) {
discard;
}
float mode = floor(v_custom.x + 0.5);
float age_norm = clamp(v_custom.y, 0.0, 1.0);
float emissive = max(v_custom.z, 0.0);
float shape_alpha = 0.0;
float core_mask = 0.0;
if (mode < 0.5) {
// Mode 0: Soft wisp dust / smoke plume
float wisp = soft_noise(centered * 2.4 + vec2(v_custom.w * 1.7, age_norm * 1.5));
float radial = smoothstep(1.0, 0.14, r + (wisp - 0.5) * 0.34);
shape_alpha = radial * (0.72 + 0.28 * wisp);
core_mask = smoothstep(0.65, 0.0, r) * 0.4;
} else if (mode < 1.5) {
// Mode 1: Crisp 4-point HDR muzzle starburst
float ax = abs(centered.x);
float ay = abs(centered.y);
float cross_x = exp(-ay * 10.5) * smoothstep(1.0, 0.08, ax);
float cross_y = exp(-ax * 10.5) * smoothstep(1.0, 0.08, ay);
float core = smoothstep(0.58, 0.0, r);
float flash = max(core, max(cross_x, cross_y) * 0.92);
shape_alpha = clamp(flash, 0.0, 1.0);
core_mask = clamp(core * 1.35 + (cross_x + cross_y) * 0.55, 0.0, 1.5);
} else if (mode < 2.5) {
// Mode 2: Elongated spark / hot shrapnel streak
vec2 stretched = vec2(centered.x * 1.0, centered.y * 2.6);
float sr = length(stretched);
float streak = smoothstep(1.0, 0.05, sr);
shape_alpha = streak * streak;
core_mask = smoothstep(0.75, 0.0, sr);
} else {
// Mode 3: Steam / fireball / thermal puff
float billow = soft_noise(centered * 3.1 - vec2(age_norm * 1.9, v_custom.w));
float radial = smoothstep(1.0, 0.08, r + (billow - 0.5) * 0.26);
float hot_core = smoothstep(0.62, 0.0, r);
shape_alpha = radial;
core_mask = hot_core * (1.0 - age_norm * 0.55);
}
float alpha = clamp(shape_alpha * v_color.a, 0.0, 1.0);
if (alpha < 0.005) {
discard;
}
vec3 rgb = max(v_color.rgb, vec3(0.0)) * (1.0 + emissive * core_mask);
ALBEDO = rgb;
ALPHA = alpha;
}

View file

@ -279,6 +279,7 @@ public partial class Smoke : Node
await VerifyOrbitalDropSequenceAsync();
await VerifyCut7bModularOrdnanceAsync();
VerifyForwardPlusAtmosphere();
await VerifyGpuSparksRenderAsync(isHeadless);
}
private async Task VerifyHudAndShadersAsync(bool isHeadless)
@ -1231,11 +1232,34 @@ public partial class Smoke : Node
$"Expected zero StandardMaterial3D duplicates, got {VehicleVisualInstance.PerfMaterialDupCount}");
}
// 12. Cut 5d-2: Unified SimEvent -> ParticlePool idempotency + OmniLight3D[4] cap + CameraJuice zero-idle-jitter + Hud X-flash & vignette
// 12. Cut 5d-2 + Cut 10b: Unified SimEvent -> GpuSparksSystem + VolumetricEmitterPool idempotency + OmniLight3D[2] cap + global rtd_flow_field + CameraJuice + Hud X-flash
{
var particles = _main.Arena.Particles;
var volumetrics = _main.Arena.Volumetrics;
var gpuSparks = _main.Arena.GpuSparks;
particles.ClearAll();
int beforeCount = particles.ActiveParticleCount;
volumetrics.ClearAll();
gpuSparks.ClearAll();
// Verify Cut 10b structural subtraction & GPUParticles3D / global shader param wiring
Check(!FileAccess.FileExists("res://particle_billboard.gdshader"),
"Expected obsolete particle_billboard.gdshader to be deleted");
int particleMmiCount = 0;
foreach (Node ch in particles.GetChildren())
{
if (ch is MultiMeshInstance3D) particleMmiCount++;
}
Check(particleMmiCount == 0,
$"Expected zero MultiMeshInstance3D nodes inside collapsed ParticlePool, found {particleMmiCount}");
Check(gpuSparks.ParticlesNode.Amount == GpuSparksSystem.Capacity && gpuSparks.ParticlesNode.AmountRatio == 0.0f,
$"Expected GpuSparksSystem Amount={GpuSparksSystem.Capacity} AmountRatio=0.0f, got {gpuSparks.ParticlesNode.Amount} ratio={gpuSparks.ParticlesNode.AmountRatio}");
Check(AtmosphereSystem.AreFlowGlobalsRegistered,
"Expected global rtd_flow_* shader parameters registered in AtmosphereSystem");
int beforeSparks = gpuSparks.TotalEmittedCount;
int beforeVol = volumetrics.ActiveEmitterCount;
int beforeImp = volumetrics.ActiveImpulseCount;
int tracerId = _main.Session.ViewState.AllocateTracerId();
var localC = _main.Session.LocalContender;
@ -1260,15 +1284,17 @@ public partial class Smoke : Node
var simBatch = new List<ISimEvent> { shotEvent };
var emptyFootsteps = new List<FootstepPulse>();
_main.Arena.ConsumeEvents(_main.Session, simBatch, emptyFootsteps, 0f, _main.SampleCurrentMapGroundTint);
int afterFirst = particles.ActiveParticleCount;
Check(afterFirst == beforeCount + 5,
$"Expected recoilless ShotFiredEvent #{tracerId} to spawn 1 muzzle starburst + 4 smoke puffs (+5 particles), got +{afterFirst - beforeCount}");
int afterSparks = gpuSparks.TotalEmittedCount;
int afterVol = volumetrics.ActiveEmitterCount;
int afterImp = volumetrics.ActiveImpulseCount;
Check(afterSparks >= beforeSparks + 1 && afterVol >= beforeVol + 1 && afterImp >= beforeImp + 1,
$"Expected recoilless ShotFiredEvent #{tracerId} to emit GPU muzzle flash/sparks (+{afterSparks - beforeSparks}), volumetric breech puff (+{afterVol - beforeVol}), and flow impulse (+{afterImp - beforeImp})");
// Re-consume with dt=0: idempotent TracerId dedupe must NOT double-emit
_main.Arena.ConsumeEvents(_main.Session, simBatch, emptyFootsteps, 0f, _main.SampleCurrentMapGroundTint);
_main.Arena.ConsumeEvents(_main.Session, simBatch, emptyFootsteps, 0f, _main.SampleCurrentMapGroundTint);
Check(particles.ActiveParticleCount == afterFirst,
$"Expected duplicate ShotFiredEvent #{tracerId} across dt=0 frames to spawn once, got {afterFirst} -> {particles.ActiveParticleCount}");
Check(gpuSparks.TotalEmittedCount == afterSparks && volumetrics.ActiveEmitterCount == afterVol && volumetrics.ActiveImpulseCount == afterImp,
$"Expected duplicate ShotFiredEvent #{tracerId} across dt=0 frames to spawn once, got sparks {afterSparks}->{gpuSparks.TotalEmittedCount}, vol {afterVol}->{volumetrics.ActiveEmitterCount}");
// OmniLight3D[2] pool strictly capped at <= 2 active lights even under 12 simultaneous flashes
particles.ClearAll();
@ -1286,8 +1312,10 @@ public partial class Smoke : Node
Check(particles.FlashLightPoolSize == 2 && particles.ActiveFlashLightCount <= 2 && particles.PeakFlashLightCount <= 2,
$"Expected OmniLight3D pool capped at <= 2, got active={particles.ActiveFlashLightCount} peak={particles.PeakFlashLightCount}");
// Far walker footstep pulse (>70m static LOD, <=110m) still emits terrain-tinted dust in ParticlePool
// Far walker footstep pulse (>70m static LOD, <=110m) emits GPU dust motes + optional volumetric puff
particles.ClearAll();
volumetrics.ClearAll();
gpuSparks.ClearAll();
var farStep = new FootstepPulse(
IsContender: true,
EntityId: 99,
@ -1297,9 +1325,11 @@ public partial class Smoke : Node
LoadG: 1.25f,
WorldPos: new System.Numerics.Vector3(pPos.X + 85f, pPos.Y, pPos.Z));
_main.Arena.ConsumeEvents(_main.Session, Array.Empty<ISimEvent>(), new[] { farStep }, 0f, _main.SampleCurrentMapGroundTint);
Check(particles.ActiveParticleCount >= 3,
$"Expected far walker (85m > 70m static LOD) footstep to emit dust puffs, got {particles.ActiveParticleCount}");
Check(gpuSparks.TotalEmittedCount >= 4 && volumetrics.ActiveEmitterCount >= 1,
$"Expected far walker (85m > 70m static LOD) footstep to emit GPU dust motes ({gpuSparks.TotalEmittedCount}) + volumetric puff ({volumetrics.ActiveEmitterCount})");
particles.ClearAll();
volumetrics.ClearAll();
gpuSparks.ClearAll();
// CameraJuiceState zero-idle-jitter & ComputeCenterScreenAim invariance under trauma
var juice = _main.CameraJuice;
@ -1593,10 +1623,14 @@ public partial class Smoke : Node
Check(audio.CountActiveUiVoicesForClip("mech_quick_bolt") == 1,
$"Expected first ContenderLoadoutEvent (1 -> 2) after ResetForSession to play mech_quick_bolt, got {audio.CountActiveUiVoicesForClip("mech_quick_bolt")}");
// Finding 3: Out-of-PVS deaths spawn zero phantom particles, lights, or audio
// Finding 3: Out-of-PVS deaths spawn zero phantom volumetric emitters, GPU sparks, lights, or audio
audio.ResetForSession(_main.Session);
var particles3 = _main.Arena.Particles;
var volumetrics3 = _main.Arena.Volumetrics;
var gpuSparks3 = _main.Arena.GpuSparks;
particles3.ClearAll();
volumetrics3.ClearAll();
gpuSparks3.ClearAll();
var hiddenSession = new HiddenRemoteDeathsSession(_main.Session);
var spec0 = _main.Session.ViewState.Spectators.Spectators[0];
var hiddenDeaths = new ISimEvent[]
@ -1607,9 +1641,11 @@ public partial class Smoke : Node
particles3.ConsumeEvents(hiddenSession, hiddenDeaths, listener, hasCam: true, _main.SampleCurrentMapGroundTint);
particles3.AdvanceAndCommit(0f);
audio.ConsumeSimEvents(hiddenSession, hiddenDeaths, listener);
Check(particles3.ActiveParticleCount == 0 && particles3.ActiveFlashLightCount == 0 && audio.ActiveOneShotVoiceCount == 0,
$"Expected out-of-PVS deaths to spawn 0 VFX/SFX, got particles={particles3.ActiveParticleCount} lights={particles3.ActiveFlashLightCount} voices={audio.ActiveOneShotVoiceCount}");
Check(gpuSparks3.TotalEmittedCount == 0 && volumetrics3.ActiveEmitterCount == 0 && particles3.ActiveFlashLightCount == 0 && audio.ActiveOneShotVoiceCount == 0,
$"Expected out-of-PVS deaths to spawn 0 VFX/SFX, got sparks={gpuSparks3.TotalEmittedCount} vol={volumetrics3.ActiveEmitterCount} lights={particles3.ActiveFlashLightCount} voices={audio.ActiveOneShotVoiceCount}");
particles3.ClearAll();
volumetrics3.ClearAll();
gpuSparks3.ClearAll();
GD.Print($"SMOKE INFO: Audio verified (haven={audio.Bank.HavenClipCount}, proc={audio.Bank.ProceduralClipCount}, dummy={audio.IsDummyAudio}, kestrelPitch={kestrelPitch:F3}, bastionPitch={bastionPitch:F3})");
}
@ -2370,6 +2406,74 @@ public partial class Smoke : Node
GD.Print($"SMOKE INFO: Cut 8 Forward+ verified (method={method}, sionZenithT={sionBaked.ZenithTransmittanceMean:F4}, desertZenithT={desertBaked.ZenithTransmittanceMean:F4}, desertHaze=({desertBaked.HazeColor.R:F3},{desertBaked.HazeColor.G:F3},{desertBaked.HazeColor.B:F3}), sionHaze=({sionBaked.HazeColor.R:F3},{sionBaked.HazeColor.G:F3},{sionBaked.HazeColor.B:F3}), grainLayer={atmo.FilmGrainLayer.Layer})");
}
private async Task VerifyGpuSparksRenderAsync(bool isHeadless)
{
if (isHeadless)
{
return;
}
var sparkVp = new SubViewport
{
Size = new Vector2I(128, 128),
OwnWorld3D = true,
TransparentBg = true,
RenderTargetUpdateMode = SubViewport.UpdateMode.Always
};
var env = new Godot.Environment
{
BackgroundMode = Godot.Environment.BGMode.Color,
BackgroundColor = new Color(0f, 0f, 0f, 0f)
};
sparkVp.AddChild(new WorldEnvironment { Environment = env });
var cam = new Camera3D
{
Position = new Vector3(0f, 0f, 5.5f),
Current = true
};
sparkVp.AddChild(cam);
var sparks = new GpuSparksSystem { Name = "SmokeSparkProbe" };
sparkVp.AddChild(sparks);
AddChild(sparkVp);
cam.LookAt(Vector3.Zero, Vector3.Up);
sparks.EnsureInitialized();
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
var idleImg = sparkVp.GetTexture().GetImage();
int idleLit = CountNonZeroAlphaPixels(idleImg, 0.05f);
Check(idleLit == 0, $"Expected 0 rendered spark pixels with AmountRatio=0.0f before EmitParticle, got {idleLit}");
sparks.EmitSparkBurst(Vector3.Zero, Vector3.Up, 128, new Color(4.5f, 2.5f, 0.75f, 1.0f), 8.0f, 0.05f);
sparks.EmitMuzzleStarburst(Vector3.Zero, new Color(5.0f, 3.0f, 1.0f, 1.0f), 0.75f, 0.14f);
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
var activeImg = sparkVp.GetTexture().GetImage();
int brightPixels = 0;
int w = activeImg.GetWidth();
int h = activeImg.GetHeight();
for (int y = 0; y < h; y++)
{
for (int x = 0; x < w; x++)
{
Color c = activeImg.GetPixel(x, y);
float lum = c.R * 0.2126f + c.G * 0.7152f + c.B * 0.0722f;
if (c.A > 0.05f && lum > 0.35f)
{
brightPixels++;
}
}
}
GD.Print($"SMOKE INFO: GpuSparksSystem Vulkan render probe idleLit={idleLit} brightPixels={brightPixels}");
Check(brightPixels > 25, $"Expected > 25 bright HDR spark pixels after EmitSparkBurst (start() ACTIVE=true), got {brightPixels}");
sparkVp.QueueFree();
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
}
private void CheckFinitePositiveLut(string label, Image img, int expectedW, int expectedH)
{
Check(img.GetFormat() == Image.Format.Rgbah, $"Expected {label} format Rgbah, got {img.GetFormat()}");

View file

@ -0,0 +1,155 @@
shader_type spatial;
render_mode unshaded, cull_front, blend_mix, depth_draw_never, depth_test_disabled;
uniform sampler2D depth_tex : hint_depth_texture, filter_nearest;
varying flat vec4 v_color;
varying flat vec4 v_custom;
varying flat vec3 v_ro;
varying flat float v_radius;
varying flat float v_halfLen;
varying vec3 v_fragCap;
void vertex() {
v_color = COLOR;
v_custom = INSTANCE_CUSTOM;
vec3 eX = normalize(MODEL_MATRIX[0].xyz);
vec3 eY = normalize(MODEL_MATRIX[1].xyz);
vec3 eZ = normalize(MODEL_MATRIX[2].xyz);
v_radius = max(0.005, 0.5 * length(MODEL_MATRIX[0].xyz));
v_halfLen = max(0.0, 0.5 * length(MODEL_MATRIX[2].xyz) - v_radius);
vec3 mid = MODEL_MATRIX[3].xyz;
mat3 invR = transpose(mat3(eX, eY, eZ));
v_ro = invR * (CAMERA_POSITION_WORLD - mid);
vec3 worldVert = (MODEL_MATRIX * vec4(VERTEX, 1.0)).xyz;
v_fragCap = invR * (worldVert - mid);
}
bool hitSphere(vec3 oc, vec3 rd, float r2, out float t0, out float t1) {
float b = dot(oc, rd);
float c = dot(oc, oc) - r2;
float disc = b * b - c;
if (disc <= 0.0) {
return false;
}
float sq = sqrt(disc);
t0 = -b - sq;
t1 = -b + sq;
return true;
}
bool hitLocalCapsule(vec3 ro, vec3 rd, float h, float r, out float outEnter, out float outExit) {
float r2 = r * r;
if (h < 0.005) {
return hitSphere(ro, rd, r2, outEnter, outExit);
}
outEnter = 1e9;
outExit = -1e9;
bool hit = false;
float s0, s1;
if (hitSphere(ro - vec3(0.0, 0.0, -h), rd, r2, s0, s1)) {
outEnter = min(outEnter, s0);
outExit = max(outExit, s1);
hit = true;
}
if (hitSphere(ro - vec3(0.0, 0.0, h), rd, r2, s0, s1)) {
outEnter = min(outEnter, s0);
outExit = max(outExit, s1);
hit = true;
}
// Infinite Z-axis cylinder x^2 + y^2 <= r^2 clipped to z in [-h, +h]
float a = dot(rd.xy, rd.xy);
float b = dot(ro.xy, rd.xy);
float c = dot(ro.xy, ro.xy) - r2;
float disc = b * b - a * c;
if (disc >= 0.0 && a > 1e-6) {
float sq = sqrt(disc);
float ct0 = (-b - sq) / a;
float ct1 = (-b + sq) / a;
if (abs(rd.z) > 1e-6) {
float tz0 = (-h - ro.z) / rd.z;
float tz1 = (h - ro.z) / rd.z;
ct0 = max(ct0, min(tz0, tz1));
ct1 = min(ct1, max(tz0, tz1));
if (ct1 > ct0) {
outEnter = min(outEnter, ct0);
outExit = max(outExit, ct1);
hit = true;
}
} else if (abs(ro.z) <= h) {
outEnter = min(outEnter, ct0);
outExit = max(outExit, ct1);
hit = true;
}
}
return hit && (outExit > outEnter);
}
void fragment() {
vec3 rd = normalize(v_fragCap - v_ro);
float tEnter, tExit;
if (!hitLocalCapsule(v_ro, rd, v_halfLen, v_radius, tEnter, tExit)) {
discard;
}
tEnter = max(0.0, tEnter);
if (tExit <= tEnter) {
discard;
}
float rawDepth = texture(depth_tex, SCREEN_UV).r;
float tScene = 1e6;
if (rawDepth > 0.0) {
vec4 viewPos = INV_PROJECTION_MATRIX * vec4(SCREEN_UV * 2.0 - 1.0, rawDepth, 1.0);
tScene = length(viewPos.xyz / viewPos.w);
}
float tClipExit = min(tExit, tScene);
if (tClipExit <= tEnter) {
discard;
}
float depthFade = clamp((tScene - tEnter) / max(0.06, v_radius * 0.45), 0.0, 1.0);
// Closest approach between clamped ray segment [tEnter, tClipExit] and capsule axis z in [-h, +h]
float xy2 = dot(rd.xy, rd.xy);
float tCyl = xy2 > 1e-6 ? -dot(v_ro.xy, rd.xy) / xy2 : 0.5 * (tEnter + tClipExit);
float tBest = clamp(tCyl, tEnter, tClipExit);
float s = v_ro.z + tBest * rd.z;
if (abs(s) > v_halfLen) {
s = clamp(s, -v_halfLen, v_halfLen);
tBest = clamp(-dot(v_ro - vec3(0.0, 0.0, s), rd), tEnter, tClipExit);
s = clamp(v_ro.z + tBest * rd.z, -v_halfLen, v_halfLen);
}
vec3 pRay = v_ro + rd * tBest;
float dMin = length(pRay - vec3(0.0, 0.0, s));
float rFrac = clamp(dMin / v_radius, 0.0, 1.0);
float chord = sqrt(max(0.0, 1.0 - rFrac * rFrac));
float coreSharpness = max(1.0, v_custom.x);
float coreFrac = clamp(v_custom.y, 0.08, 0.85);
float core = pow(clamp(1.0 - smoothstep(0.0, coreFrac, rFrac), 0.0, 1.0), coreSharpness);
float sheath = pow(chord, 1.75);
// Basis.LookingAt puts -Z forward: start (tail) is at +v_halfLen, end (head) is at -v_halfLen
float tailT = v_halfLen > 0.01 ? clamp(0.5 - 0.5 * (s / v_halfLen), 0.0, 1.0) : 1.0;
float axial = mix(1.0, smoothstep(0.0, 0.78, tailT), v_custom.z * step(0.01, v_halfLen));
float pulse = v_custom.w > 0.0 ? (0.88 + 0.12 * sin(s * 2.4 + TIME * v_custom.w)) : 1.0;
vec3 hotCore = vec3(3.8, 3.8, 4.0);
vec3 rgb = mix(max(v_color.rgb, vec3(0.0)), hotCore, core * 0.82) * (0.45 + 0.55 * chord) * pulse;
float alpha = clamp(max(core, sheath * 0.85) * axial * depthFade * v_color.a, 0.0, 1.0);
if (alpha < 0.005) {
discard;
}
ALBEDO = rgb;
ALPHA = alpha;
}

View file

@ -0,0 +1,123 @@
#version 450
layout(local_size_x = 16, local_size_y = 16, local_size_z = 1) in;
#define MAX_TILE_EMITTERS 24u
struct TileData {
uint count;
float minDepth;
float maxDepth;
uint _pad;
uint packedKeys[MAX_TILE_EMITTERS];
};
layout(set = 0, binding = 0, std140) uniform VolumetricFrame {
mat4 invProj;
vec4 camPosTime;
vec4 camRightAspect;
vec4 camUpTanHalfFov;
vec4 camFwdNearFar;
vec4 sunDirIntensity;
vec4 sunColorExt;
vec4 ambientColorFog;
vec4 viewportInfo;
uvec4 tileGridParams;
vec4 flowOriginVoxel;
vec4 flowInvExtentDt;
ivec4 flowDeltaImpulse;
} u_frame;
layout(set = 0, binding = 1) uniform sampler2D u_depthTex;
layout(set = 0, binding = 2) uniform sampler2D u_halfVolTex;
layout(set = 0, binding = 3, rgba16f) uniform image2D u_colorImg;
layout(set = 0, binding = 4, std430) readonly buffer TileBuffer {
TileData tiles[];
} u_tiles;
float linearizeReverseZ(float rawDepth) {
if (rawDepth <= 0.0) {
return u_frame.viewportInfo.z;
}
float zN = u_frame.ambientColorFog.w;
float zF = u_frame.viewportInfo.z;
return (zN * zF) / max(1e-5, zN + rawDepth * (zF - zN));
}
float halfQuadMaxDepth(ivec2 hpx, ivec2 fullRes) {
ivec2 basePx = hpx * 2;
float dMax = 0.0;
for (int dy = 0; dy < 2; dy++) {
for (int dx = 0; dx < 2; dx++) {
ivec2 sp = min(basePx + ivec2(dx, dy), fullRes - ivec2(1));
dMax = max(dMax, linearizeReverseZ(texelFetch(u_depthTex, sp, 0).r));
}
}
return dMax;
}
void main() {
ivec2 fullRes = ivec2(u_frame.viewportInfo.xy);
ivec2 px = ivec2(gl_GlobalInvocationID.xy);
if (any(greaterThanEqual(px, fullRes))) {
return;
}
// Empty-tile fast exit: coherent across the 16x16 workgroup (32x32 full-res tile)
ivec2 tileCoord = px / 32;
uint tileIdx = uint(tileCoord.y) * u_frame.tileGridParams.z + uint(tileCoord.x);
if (u_tiles.tiles[tileIdx].count == 0u) {
return;
}
ivec2 halfRes = ivec2(u_frame.tileGridParams.xy);
float dFull = linearizeReverseZ(texelFetch(u_depthTex, px, 0).r);
// 2x2 depth-aware bilateral upsample from half-res volumetric buffer
vec2 hCoord = (vec2(px) + vec2(0.5)) * 0.5 - vec2(0.5);
ivec2 h0 = clamp(ivec2(floor(hCoord)), ivec2(0), halfRes - ivec2(1));
vec2 f = clamp(hCoord - vec2(h0), vec2(0.0), vec2(1.0));
float depthScale = max(0.45, 0.055 * dFull);
vec4 volSum = vec4(0.0);
float wSum = 0.0;
float wRawSum = 0.0;
float minHalfDepth = 1e9;
ivec2 offsets[4] = ivec2[4](ivec2(0, 0), ivec2(1, 0), ivec2(0, 1), ivec2(1, 1));
float spatialW[4] = float[4](
(1.0 - f.x) * (1.0 - f.y),
f.x * (1.0 - f.y),
(1.0 - f.x) * f.y,
f.x * f.y
);
for (int i = 0; i < 4; i++) {
ivec2 hp = min(h0 + offsets[i], halfRes - ivec2(1));
vec4 vSample = texelFetch(u_halfVolTex, hp, 0);
float dHalf = halfQuadMaxDepth(hp, fullRes);
minHalfDepth = min(minHalfDepth, dHalf);
float wDepth = exp(-abs(dFull - dHalf) / depthScale);
float wRaw = spatialW[i] * wDepth;
wRawSum += wRaw;
float w = max(1e-5, wRaw);
volSum += vSample * w;
wSum += w;
}
// Thin foreground occluder (spark/edge strictly in front of ALL 4 half-res background depth taps):
// do not smear background smoke over it
if (wRawSum < 1e-3 && dFull < minHalfDepth * 0.92) {
return;
}
vec4 vol = volSum / max(1e-5, wSum);
// Skip write when completely transparent
if (vol.a > 0.999 && dot(vol.rgb, vol.rgb) < 1e-7) {
return;
}
vec4 scene = imageLoad(u_colorImg, px);
scene.rgb = scene.rgb * clamp(vol.a, 0.0, 1.0) + max(vol.rgb, vec3(0.0));
imageStore(u_colorImg, px, scene);
}

View file

@ -0,0 +1,509 @@
#version 450
layout(local_size_x = 16, local_size_y = 16, local_size_z = 1) in;
#define MAX_TILE_EMITTERS 24u
struct VolumetricEmitter {
vec4 posRadius;
vec4 endRadiusTemp;
vec4 params;
vec4 tintSoftness;
};
struct TileData {
uint count;
float minDepth;
float maxDepth;
uint _pad;
uint packedKeys[MAX_TILE_EMITTERS];
};
layout(set = 0, binding = 0, std140) uniform VolumetricFrame {
mat4 invProj;
vec4 camPosTime;
vec4 camRightAspect;
vec4 camUpTanHalfFov;
vec4 camFwdNearFar;
vec4 sunDirIntensity;
vec4 sunColorExt;
vec4 ambientColorFog;
vec4 viewportInfo;
uvec4 tileGridParams;
vec4 flowOriginVoxel;
vec4 flowInvExtentDt;
ivec4 flowDeltaImpulse;
} u_frame;
layout(set = 0, binding = 1, std430) readonly buffer EmitterBuffer {
VolumetricEmitter emitters[];
} u_emitters;
layout(set = 0, binding = 2, std430) readonly buffer TileBuffer {
TileData tiles[];
} u_tiles;
layout(set = 0, binding = 3) uniform sampler2D u_depthTex;
layout(set = 0, binding = 4) uniform sampler3D u_flowField;
layout(set = 0, binding = 5, rgba16f) uniform writeonly image2D u_halfVol;
shared uint sTileCount;
shared VolumetricEmitter sEmitters[MAX_TILE_EMITTERS];
float linearizeReverseZ(float rawDepth) {
if (rawDepth <= 0.0) {
return u_frame.viewportInfo.z;
}
float zN = u_frame.ambientColorFog.w;
float zF = u_frame.viewportInfo.z;
return (zN * zF) / max(1e-5, zN + rawDepth * (zF - zN));
}
vec3 computeRayDirWorld(vec2 fullUv, out float invCosView) {
vec2 ndcXY = fullUv * 2.0 - 1.0;
float tanY = u_frame.camUpTanHalfFov.w;
float aspect = u_frame.camRightAspect.w;
vec3 viewVec = vec3(ndcXY.x * aspect * tanY, (1.0 - 2.0 * fullUv.y) * tanY, -1.0);
invCosView = length(viewVec);
return normalize(u_frame.camRightAspect.xyz * viewVec.x
+ u_frame.camUpTanHalfFov.xyz * viewVec.y
+ u_frame.camFwdNearFar.xyz);
}
// --- Aetheria Volumetric.cginc math (ported cleanly with NaN-safe normalize) ---
float tri(float x) {
return abs(fract(x) - 0.5);
}
vec3 tri3(vec3 p) {
return vec3(
tri(p.z + tri(p.y)),
tri(p.z + tri(p.x)),
tri(p.y + tri(p.x))
);
}
vec3 safeNorm(vec3 v) {
float l2 = dot(v, v);
return l2 > 1e-8 ? v * inversesqrt(l2) : vec3(0.0, 1.0, 0.0);
}
vec3 Tri3D(vec3 P, vec3 PGolden) {
vec3 t1 = safeNorm(tri3(P));
vec3 t2 = safeNorm(tri3(PGolden));
return cross(t1, t2);
}
float triNoise3d(vec3 p, float flowTime) {
float z = 1.4;
float rz = 0.001;
vec3 bp = p;
for (int i = 0; i < 2; i++) {
vec3 dg = tri3(bp * 2.0);
p += dg + flowTime;
bp *= 1.8;
z *= 1.5;
p *= 1.2;
rz += tri(p.z + tri(p.x + tri(p.y))) / z;
bp += 0.14;
}
return rz;
}
vec3 aetheriaFlow(vec3 pos, float flowScale, float scrollSpeed, float time) {
vec3 field = pos / max(0.5, flowScale);
float s1 = time * scrollSpeed;
float s2 = time * scrollSpeed * 1.61803398875;
vec3 fl = Tri3D(field - vec3(0.0, s1, 0.0), field * 1.61803398875 - vec3(0.0, s2, 0.0));
fl.y *= 0.5;
return fl;
}
bool intersectSphere(vec3 oc, vec3 rd, float r2, out float t0, out float t1) {
float b = dot(oc, rd);
float c = dot(oc, oc) - r2;
float disc = b * b - c;
if (disc <= 0.0) {
return false;
}
float sq = sqrt(disc);
t0 = -b - sq;
t1 = -b + sq;
return true;
}
bool intersectCapsule(vec3 ro, vec3 rd, vec3 A, vec3 B, float R, out float outNear, out float outFar) {
float r2 = R * R;
vec3 ba = B - A;
float baba = dot(ba, ba);
if (baba < 0.0025) {
return intersectSphere(ro - A, rd, r2, outNear, outFar);
}
outNear = 1e9;
outFar = -1e9;
bool hit = false;
float s0, s1;
if (intersectSphere(ro - A, rd, r2, s0, s1)) {
outNear = min(outNear, s0);
outFar = max(outFar, s1);
hit = true;
}
if (intersectSphere(ro - B, rd, r2, s0, s1)) {
outNear = min(outNear, s0);
outFar = max(outFar, s1);
hit = true;
}
vec3 oa = ro - A;
float bard = dot(ba, rd);
float baoa = dot(ba, oa);
float rdoa = dot(rd, oa);
float oaoa = dot(oa, oa);
float a = baba - bard * bard;
float b = baba * rdoa - baoa * bard;
float c = baba * oaoa - baoa * baoa - r2 * baba;
float h = b * b - a * c;
if (h >= 0.0 && a > 1e-6) {
float sq = sqrt(h);
float ct0 = (-b - sq) / a;
float ct1 = (-b + sq) / a;
if (abs(bard) > 1e-6) {
float tEnd0 = -baoa / bard;
float tEnd1 = (baba - baoa) / bard;
float tCapMin = min(tEnd0, tEnd1);
float tCapMax = max(tEnd0, tEnd1);
ct0 = max(ct0, tCapMin);
ct1 = min(ct1, tCapMax);
if (ct1 > ct0) {
outNear = min(outNear, ct0);
outFar = max(outFar, ct1);
hit = true;
}
} else if (baoa >= 0.0 && baoa <= baba) {
outNear = min(outNear, ct0);
outFar = max(outFar, ct1);
hit = true;
}
}
return hit && (outFar > outNear);
}
vec3 blackbodyRamp(float temp) {
// Tuned for AgX (TonemapAgxWhite=6.0) + GlowHdrThreshold=1.0: blazing white-gold cores -> molten orange-red edges
vec3 c0 = vec3(0.55, 0.04, 0.003);
vec3 c1 = vec3(1.85, 0.28, 0.015);
vec3 c2 = vec3(3.60, 0.92, 0.075);
vec3 c3 = vec3(5.60, 2.35, 0.34);
vec3 c4 = vec3(7.60, 4.45, 1.35);
if (temp < 0.35) return mix(c0, c1, smoothstep(0.10, 0.35, temp));
if (temp < 0.72) return mix(c1, c2, (temp - 0.35) / 0.37);
if (temp < 1.10) return mix(c2, c3, (temp - 0.72) / 0.38);
return mix(c3, c4, clamp((temp - 1.10) / 0.50, 0.0, 1.0));
}
float hgPhase(float cosTheta, float g) {
float g2 = g * g;
float denom = max(0.05, 1.0 + g2 - 2.0 * g * cosTheta);
return (1.0 - g2) / (12.5663706 * pow(denom, 1.5));
}
void main() {
uint tid = gl_LocalInvocationIndex;
ivec2 tileCoord = ivec2(gl_WorkGroupID.xy);
uint tilesX = u_frame.tileGridParams.z;
uint tileIdx = uint(tileCoord.y) * tilesX + uint(tileCoord.x);
if (tid == 0u) {
sTileCount = min(u_tiles.tiles[tileIdx].count, MAX_TILE_EMITTERS);
}
memoryBarrierShared();
barrier();
ivec2 halfRes = ivec2(u_frame.tileGridParams.xy);
ivec2 px = ivec2(gl_GlobalInvocationID.xy);
// Empty-tile fast exit (uniform across workgroup)
if (sTileCount == 0u) {
if (all(lessThan(px, halfRes))) {
imageStore(u_halfVol, px, vec4(0.0, 0.0, 0.0, 1.0));
}
return;
}
if (tid < sTileCount) {
uint eIdx = u_tiles.tiles[tileIdx].packedKeys[tid] & 0x7Fu;
sEmitters[tid] = u_emitters.emitters[eIdx];
}
memoryBarrierShared();
barrier();
if (any(greaterThanEqual(px, halfRes))) {
return;
}
ivec2 fullRes = ivec2(u_frame.viewportInfo.xy);
ivec2 basePx = px * 2;
float dMax = 0.0;
for (int dy = 0; dy < 2; dy++) {
for (int dx = 0; dx < 2; dx++) {
ivec2 sp = min(basePx + ivec2(dx, dy), fullRes - ivec2(1));
float linD = linearizeReverseZ(texelFetch(u_depthTex, sp, 0).r);
dMax = max(dMax, linD);
}
}
vec2 fullUv = (vec2(px) * 2.0 + vec2(1.0)) / vec2(fullRes);
float invCosView;
vec3 rd = computeRayDirWorld(fullUv, invCosView);
vec3 ro = u_frame.camPosTime.xyz;
float tSceneMax = dMax * invCosView;
// Exact per-pixel capsule intersections sorted ascending by t0 for monotonic sweep-line
uint hitPack[MAX_TILE_EMITTERS];
float hitT1[MAX_TILE_EMITTERS];
uint hitCount = 0u;
float tEndMax = 0.0;
for (uint k = 0u; k < sTileCount; k++) {
VolumetricEmitter em = sEmitters[k];
float rBound = max(em.posRadius.w, em.params.y) * 1.85;
float t0, t1;
if (intersectCapsule(ro, rd, em.posRadius.xyz, em.endRadiusTemp.xyz, rBound, t0, t1)) {
t0 = max(2.0, t0);
t1 = min(tSceneMax, t1);
if (t1 > t0 + 1e-3) {
uint key = (floatBitsToUint(t0) & 0xFFFFFFE0u) | (k & 0x1Fu);
uint ins = hitCount;
while (ins > 0u && hitPack[ins - 1u] > key) {
hitPack[ins] = hitPack[ins - 1u];
hitT1[ins] = hitT1[ins - 1u];
ins--;
}
hitPack[ins] = key;
hitT1[ins] = t1;
hitCount++;
tEndMax = max(tEndMax, t1);
}
}
}
if (hitCount == 0u) {
imageStore(u_halfVol, px, vec4(0.0, 0.0, 0.0, 1.0));
return;
}
// Interleaved Gradient Noise temporal jitter
float frameF = float(u_frame.tileGridParams.w & 63u);
float ign = fract(52.9829189 * fract(dot(vec2(px) + 5.588238 * frameF, vec2(0.06711056, 0.00583715))));
float elapsed = u_frame.camPosTime.w;
vec3 sunDir = u_frame.sunDirIntensity.xyz;
float cosTheta = dot(rd, sunDir);
float phase = mix(hgPhase(cosTheta, 0.68), hgPhase(cosTheta, -0.25), 0.22);
vec3 sunRad = u_frame.sunColorExt.rgb * u_frame.sunDirIntensity.w;
vec3 ambRad = u_frame.ambientColorFog.rgb;
float extScale = u_frame.sunColorExt.w;
vec3 L = vec3(0.0);
float T = 1.0;
uint nextIdx = 0u;
uint activeMask = 0u;
float t = 0.0;
int steps = 0;
const int MaxSteps = 16;
while ((nextIdx < hitCount || activeMask != 0u) && t < tEndMax && T >= 0.015 && steps < MaxSteps) {
// Empty-space jump directly to nextIdx's t0 whenever no emitter is currently active
if (activeMask == 0u) {
float minNext = uintBitsToFloat(hitPack[nextIdx] & 0xFFFFFFE0u);
float nextT1 = hitT1[nextIdx];
float chord = max(0.0, nextT1 - minNext);
float dsLeap = max(0.36, 0.26 + 0.011 * minNext);
float jitter = ign * min(dsLeap, max(0.05, chord * 0.45));
t = min(max(t, minNext) + jitter, tEndMax - 1e-4);
if (t >= tEndMax) {
break;
}
}
float ds = max(0.36, 0.26 + 0.011 * t);
float tLo = t - 0.5 * ds;
float tHi = t + 0.5 * ds;
// Monotonic sweep-line admission: advance nextIdx forward, never re-scanning earlier entries
while (nextIdx < hitCount) {
float b0 = uintBitsToFloat(hitPack[nextIdx] & 0xFFFFFFE0u);
if (b0 > tHi) {
break;
}
if (hitT1[nextIdx] >= tLo) {
activeMask |= (1u << nextIdx);
}
nextIdx++;
}
// Retire emitters already exited
uint amCheck = activeMask;
while (amCheck != 0u) {
int bit = findLSB(amCheck);
amCheck &= amCheck - 1u;
if (hitT1[bit] < tLo) {
activeMask &= ~(1u << uint(bit));
}
}
if (activeMask == 0u) {
continue;
}
// Near-camera fade (2.0..6.8m) so lens-adjacent plumes never blind the viewport or stall raymarching
if (t >= 2.0) {
float nearFade = smoothstep(2.0, 6.8, t);
float emitNearFade = smoothstep(2.5, 8.5, t);
if (nearFade > 0.001) {
vec3 worldPos = ro + rd * t;
vec3 flowUv = (worldPos - u_frame.flowOriginVoxel.xyz) * u_frame.flowInvExtentDt.xyz;
vec4 flowSample = (all(greaterThanEqual(flowUv, vec3(0.0))) && all(lessThanEqual(flowUv, vec3(1.0))))
? textureLod(u_flowField, flowUv, 0.0)
: vec4(0.0);
float shock = clamp(flowSample.a, 0.0, 1.5);
float rhoSum = 0.0;
vec3 albedoSum = vec3(0.0);
vec3 radialSum = vec3(0.0);
float tempSum = 0.0;
float noiseSum = 0.0;
float plasmaSum = 0.0;
vec3 stepCurl = aetheriaFlow(worldPos - flowSample.rgb * 0.20, 3.0, 0.68, elapsed);
uint am = activeMask;
while (am != 0u) {
int hitSlot = findLSB(am);
am &= am - 1u;
uint k = hitPack[hitSlot] & 0x1Fu;
VolumetricEmitter em = sEmitters[k];
uint flags = floatBitsToUint(em.params.w);
uint emType = flags & 0xFu;
float ageNorm = float((flags >> 4u) & 0xFFu) / 255.0;
float seed = float((flags >> 12u) & 0xFFu) * 0.371;
float rA = em.posRadius.w;
float rB = em.params.y;
float radAvg = max(0.35, 0.5 * (rA + rB));
vec3 A = em.posRadius.xyz;
vec3 B = em.endRadiusTemp.xyz;
vec3 ab = B - A;
float ab2 = dot(ab, ab);
// Conservative un-displaced distance guard before running triNoise3d
float preSegT = ab2 > 1e-5 ? clamp(dot(worldPos - A, ab) / ab2, 0.0, 1.0) : 0.0;
float preRad = mix(rA, rB, preSegT);
if (length(worldPos - (A + ab * preSegT)) > 1.05 * preRad + 0.80 * radAvg) {
continue;
}
// Bound flow + curl displacement strictly inside rBound (1.85 * rad) so zero spherical/tile clipping occurs
vec3 flowOffset = flowSample.rgb * (0.16 + 0.12 * ageNorm);
float fOffLen = length(flowOffset);
if (fOffLen > 0.30 * radAvg) {
flowOffset *= (0.30 * radAvg) / fOffLen;
}
vec3 advectedPos = worldPos - flowOffset;
float curlScale = 0.48 * radAvg * clamp(0.65 + 0.45 * abs(em.params.z), 0.55, 1.10);
vec3 evalPos = advectedPos + stepCurl * curlScale;
float segT = ab2 > 1e-5 ? clamp(dot(evalPos - A, ab) / ab2, 0.0, 1.0) : 0.0;
vec3 closest = A + ab * segT;
float taper = ab2 > 0.15 ? mix(1.02, 0.72, segT) : 1.0;
float rad = mix(rA, rB, segT) * taper * (0.86 + 0.18 * clamp(stepCurl.x + stepCurl.y, -0.8, 0.8));
vec3 radialVec = evalPos - closest;
float distNorm = length(radialVec) / max(0.15, rad);
if (distNorm < 1.04) {
float softness = clamp(em.tintSoftness.a, 0.18, 0.75);
float baseFall = 1.0 - smoothstep(1.0 - softness, 1.04, distNorm);
if (baseFall > 0.04) {
// Aetheria Volumetric.cginc:201-212 sculpted pocket carving (macro triNoise3d - 0.5 * high-freq triNoise3d)
vec3 nCoord = evalPos / max(1.35, rad * 0.95) + vec3(seed);
float noise1 = triNoise3d(nCoord, elapsed * 0.36);
float noise2 = triNoise3d(nCoord * 5.5, elapsed * 0.56);
float billow = clamp((noise1 - 0.5 * noise2) * 2.55, 0.0, 1.0);
float rawDensity = billow * 0.66 + baseFall * 0.76 - 0.30 * distNorm;
float eroded = smoothstep(0.18, 0.74, rawDensity);
float rho_k = baseFall * eroded * em.params.x * nearFade;
// Shock-front cavity carving + adiabatic compression rim
rho_k *= clamp(1.0 - shock * 0.42, 0.32, 1.0) * (1.0 + 0.45 * smoothstep(0.2, 0.9, shock));
if (rho_k > 1e-4) {
rhoSum += rho_k;
albedoSum += em.tintSoftness.rgb * rho_k;
radialSum += safeNorm(radialVec + vec3(0.0, 0.28 * rad, 0.0)) * rho_k;
// Tight radial temperature falloff: outer 65-75% cools to un-emissive rolling soot
float coreRadial = pow(clamp(1.0 - distNorm, 0.0, 1.0), 1.65);
float localTemp = max(em.endRadiusTemp.w * coreRadial, shock * 0.22);
tempSum += localTemp * rho_k;
noiseSum += clamp(noise1 * 2.5, 0.0, 1.0) * rho_k;
if (emType == 3u || emType == 4u) {
plasmaSum += rho_k;
}
}
}
}
}
if (rhoSum > 0.002) {
float rawDens = rhoSum;
float coreTemp = tempSum / rhoSum;
float stepNoise = noiseSum / rhoSum;
vec3 albedo = albedoSum / rhoSum;
vec3 localUpOrRadial = safeNorm(radialSum);
// Layer 1 & 2: Aetheria inverse-density charcoal soot contour (CloudShader.shader:96-97)
// Thin wispy outer rims stay bright sunlit vapor (~0.85-1.0); dense mid-body folds plunge into velvety charcoal soot (~0.10-0.22)
float sootContour = 1.0 / (1.0 + 3.2 * rawDens);
float rimBias = 0.65 + 0.45 * clamp(dot(localUpOrRadial, sunDir), -1.0, 1.0);
vec3 vaporAlbedo = mix(albedo, max(albedo, vec3(0.24, 0.23, 0.22)), 0.35 * sootContour);
float vaporEdgeFade = smoothstep(0.0, 0.10, rawDens);
vec3 scatterLum = vaporAlbedo * (sootContour * vaporEdgeFade) * (sunRad * (rimBias + phase * 2.4) + ambRad * 0.48);
// Layer 3: Sharp turbulent core-only combustion (ignites only in hottest dense inner core pockets)
vec3 plasmaEmit = vec3(0.0);
float coreGate = smoothstep(0.68, 0.96, coreTemp * (0.72 + 0.55 * stepNoise));
if (coreGate > 0.001) {
float coreGlow = pow(clamp(rawDens, 0.0, 1.5), 2.3) * coreGate;
vec3 bb = blackbodyRamp(coreTemp);
float plasmaMix = plasmaSum / rhoSum;
if (plasmaMix > 0.01) {
bb = mix(bb, albedo * (1.55 + 2.05 * coreTemp), 0.75 * plasmaMix);
}
plasmaEmit = bb * (coreGlow * 7.2) * emitNearFade;
}
float sigmaT = rawDens * extScale;
float stepTrans = exp(-sigmaT * ds);
// CloudShader.shader:96-97: do NOT multiply scatterLum by sigmaT before dividing by sigmaT
float integDivExt = sigmaT > 1e-4 ? (1.0 - stepTrans) / sigmaT : ds;
vec3 stepLight = (scatterLum + plasmaEmit) * integDivExt * nearFade;
L += T * stepLight;
T *= stepTrans;
if (T < 0.015) {
T = 0.0;
break;
}
}
}
}
t += ds;
steps++;
}
imageStore(u_halfVol, px, vec4(min(L, vec3(24.0)), clamp(T, 0.0, 1.0)));
}

View file

@ -0,0 +1,206 @@
#version 450
layout(local_size_x = 16, local_size_y = 16, local_size_z = 1) in;
#define MAX_TILE_EMITTERS 24u
struct VolumetricEmitter {
vec4 posRadius;
vec4 endRadiusTemp;
vec4 params;
vec4 tintSoftness;
};
struct TileData {
uint count;
float minDepth;
float maxDepth;
uint _pad;
uint packedKeys[MAX_TILE_EMITTERS];
};
layout(set = 0, binding = 0, std140) uniform VolumetricFrame {
mat4 invProj;
vec4 camPosTime;
vec4 camRightAspect;
vec4 camUpTanHalfFov;
vec4 camFwdNearFar;
vec4 sunDirIntensity;
vec4 sunColorExt;
vec4 ambientColorFog;
vec4 viewportInfo;
uvec4 tileGridParams;
vec4 flowOriginVoxel;
vec4 flowInvExtentDt;
ivec4 flowDeltaImpulse;
} u_frame;
layout(set = 0, binding = 1, std430) readonly buffer EmitterBuffer {
VolumetricEmitter emitters[];
} u_emitters;
layout(set = 0, binding = 2, std430) writeonly buffer TileBuffer {
TileData tiles[];
} u_tiles;
layout(set = 0, binding = 3) uniform sampler2D u_depthTex;
shared uint sMinDepthBits;
shared uint sMaxDepthBits;
shared uint sTileCount;
shared uint sKeys[128];
float linearizeReverseZ(float rawDepth) {
if (rawDepth <= 0.0) {
return u_frame.viewportInfo.z;
}
float zN = u_frame.ambientColorFog.w;
float zF = u_frame.viewportInfo.z;
return (zN * zF) / max(1e-5, zN + rawDepth * (zF - zN));
}
void main() {
uint tid = gl_LocalInvocationIndex;
ivec2 tileCoord = ivec2(gl_WorkGroupID.xy);
uint tilesX = u_frame.tileGridParams.z;
uint tileIdx = uint(tileCoord.y) * tilesX + uint(tileCoord.x);
if (tid == 0u) {
sMinDepthBits = 0x7F7FFFFFu;
sMaxDepthBits = 0u;
sTileCount = 0u;
}
if (tid < 128u) {
sKeys[tid] = 0xFFFFFFFFu;
}
memoryBarrierShared();
barrier();
ivec2 halfRes = ivec2(u_frame.tileGridParams.xy);
ivec2 fullRes = ivec2(u_frame.viewportInfo.xy);
ivec2 hx = ivec2(gl_GlobalInvocationID.xy);
float dMin = u_frame.viewportInfo.z;
float dMax = 0.0;
if (all(lessThan(hx, halfRes))) {
ivec2 basePx = hx * 2;
for (int dy = 0; dy < 2; dy++) {
for (int dx = 0; dx < 2; dx++) {
ivec2 sp = min(basePx + ivec2(dx, dy), fullRes - ivec2(1));
float rawD = texelFetch(u_depthTex, sp, 0).r;
float linD = linearizeReverseZ(rawD);
dMin = min(dMin, linD);
dMax = max(dMax, linD);
}
}
atomicMin(sMinDepthBits, floatBitsToUint(max(0.0, dMin)));
atomicMax(sMaxDepthBits, floatBitsToUint(max(0.0, dMax)));
}
memoryBarrierShared();
barrier();
float tileMinDepth = uintBitsToFloat(sMinDepthBits);
float tileMaxDepth = uintBitsToFloat(sMaxDepthBits);
if (tileMaxDepth <= 0.0) {
tileMaxDepth = u_frame.viewportInfo.z;
}
// Tile frustum bounds in view space (view looks down -Z, +X right, +Y up)
vec2 tileMinPx = vec2(tileCoord * 16) * 2.0;
vec2 tileMaxPx = min(vec2((tileCoord + ivec2(1)) * 16) * 2.0, vec2(fullRes));
vec2 uv0 = tileMinPx / vec2(fullRes);
vec2 uv1 = tileMaxPx / vec2(fullRes);
float tanY = u_frame.camUpTanHalfFov.w;
float aspect = u_frame.camRightAspect.w;
float x0 = (uv0.x * 2.0 - 1.0) * aspect * tanY;
float x1 = (uv1.x * 2.0 - 1.0) * aspect * tanY;
float yTop = (1.0 - 2.0 * uv0.y) * tanY;
float yBot = (1.0 - 2.0 * uv1.y) * tanY;
vec3 nLeft = normalize(vec3(-1.0, 0.0, -x0));
vec3 nRight = normalize(vec3(1.0, 0.0, x1));
vec3 nTop = normalize(vec3(0.0, 1.0, yTop));
vec3 nBot = normalize(vec3(0.0, -1.0, -yBot));
uint emitterCount = min(uint(max(0.0, u_frame.viewportInfo.w + 0.5)), 128u);
if (tid < emitterCount) {
VolumetricEmitter em = u_emitters.emitters[tid];
float rA = em.posRadius.w;
float rB = em.params.y;
float rBound = max(rA, rB) * 1.85;
vec3 wA = em.posRadius.xyz - u_frame.camPosTime.xyz;
vec3 wB = em.endRadiusTemp.xyz - u_frame.camPosTime.xyz;
vec3 camR = u_frame.camRightAspect.xyz;
vec3 camU = u_frame.camUpTanHalfFov.xyz;
vec3 camF = u_frame.camFwdNearFar.xyz;
// View-space coordinates: +X right, +Y up, -Z forward
vec3 vA = vec3(dot(wA, camR), dot(wA, camU), -dot(wA, camF));
vec3 vB = vec3(dot(wB, camR), dot(wB, camU), -dot(wB, camF));
float dMinEm = min(-vA.z - rBound, -vB.z - rBound);
float dMaxEm = max(-vA.z + rBound, -vB.z + rBound);
// Reject only behind camera or completely behind tileMaxDepth (NEVER clip against tileMinDepth!)
bool visible = (dMaxEm > 0.0) && (dMinEm < tileMaxDepth);
if (visible) {
if (dot(vA, nLeft) > rBound && dot(vB, nLeft) > rBound) visible = false;
else if (dot(vA, nRight) > rBound && dot(vB, nRight) > rBound) visible = false;
else if (dot(vA, nTop) > rBound && dot(vB, nTop) > rBound) visible = false;
else if (dot(vA, nBot) > rBound && dot(vB, nBot) > rBound) visible = false;
}
if (visible) {
vec3 ab = vB - vA;
float ab2 = dot(ab, ab);
float segT = ab2 > 1e-5 ? clamp(dot(-vA, ab) / ab2, 0.0, 1.0) : 0.0;
vec3 closest = vA + ab * segT;
float tMinConservative = max(0.0, length(closest) - rBound);
uint packedKey = (floatBitsToUint(tMinConservative) & 0xFFFFFF80u) | (tid & 0x7Fu);
uint slot = atomicAdd(sTileCount, 1u);
if (slot < 128u) {
sKeys[slot] = packedKey;
}
}
}
memoryBarrierShared();
barrier();
// Adaptive Bitonic sort (skip when <= 1; sort smallest power-of-2 >= count up to 128)
uint count = sTileCount;
if (count > 1u) {
uint sortN = count <= 16u ? 16u : (count <= 32u ? 32u : (count <= 64u ? 64u : 128u));
for (uint k = 2u; k <= sortN; k <<= 1u) {
for (uint j = k >> 1u; j > 0u; j >>= 1u) {
if (tid < sortN) {
uint ixj = tid ^ j;
if (ixj > tid) {
bool ascending = ((tid & k) == 0u);
uint a = sKeys[tid];
uint b = sKeys[ixj];
if ((a > b) == ascending) {
sKeys[tid] = b;
sKeys[ixj] = a;
}
}
}
memoryBarrierShared();
barrier();
}
}
}
if (tid == 0u) {
uint outCount = min(sTileCount, MAX_TILE_EMITTERS);
u_tiles.tiles[tileIdx].count = outCount;
u_tiles.tiles[tileIdx].minDepth = tileMinDepth;
u_tiles.tiles[tileIdx].maxDepth = tileMaxDepth;
u_tiles.tiles[tileIdx]._pad = 0u;
}
if (tid < MAX_TILE_EMITTERS) {
u_tiles.tiles[tileIdx].packedKeys[tid] = sKeys[tid];
}
}