feat(vfx): Phase C.1 — PES particle renderer + post-review fixes

Ports retail's ParticleEmitterInfo / Particle::Init / Particle::Update
(0x005170d0..0x0051d400) and PhysicsScript runtime to a C# data-layer
plus a Silk.NET billboard renderer. Sky-PES path is debug-only behind
ACDREAM_ENABLE_SKY_PES because named-retail decomp confirms GameSky
copies SkyObject.pes_id but never reads it (CreateDeletePhysicsObjects
0x005073c0, MakeObject 0x00506ee0, UseTime 0x005075b0).

Post-review fixes folded into this commit:

H1: AttachLocal (is_parent_local=1) follows live parent each frame.
    ParticleSystem.UpdateEmitterAnchor + ParticleHookSink.UpdateEntityAnchor
    let the owning subsystem refresh AnchorPos every tick — matches
    ParticleEmitter::UpdateParticles 0x0051d2d4 which re-reads the live
    parent frame when is_parent_local != 0. Drops the renderer-side
    cameraOffset hack that only worked when the parent was the camera.

H3: Strip the long stale comment in GfxObjMesh.cs that contradicted the
    retail-faithful (1 - translucency) opacity formula. The code was
    right; the comment was a leftover from an earlier hypothesis and
    would have invited a wrong "fix".

M1: SkyRenderer tracks textures whose wrap mode it set to ClampToEdge
    and restores them to Repeat at end-of-pass, so non-sky renderers
    that share the GL handle can't silently inherit clamped wrap state.

M2: Post-scene Z-offset (-120m) only fires when the SkyObject is
    weather-flagged AND bit 0x08 is clear, matching retail
    GameSky::UpdatePosition 0x00506dd0. The old code applied it to
    every post-scene object — a no-op today (every Dereth post-scene
    entry happens to be weather-flagged) but a future post-scene-only
    sun rim would have been pushed below the camera.

M4: ParticleSystem.EmitterDied event lets ParticleHookSink prune dead
    handles from the per-entity tracking dictionaries, fixing a slow
    leak where naturally-expired emitters' handles stayed in the
    ConcurrentBag forever during long sessions.

M5: SkyPesEntityId moves the post-scene flag bit to 0x08000000 so it
    can't ever overlap the object-index range. Synthetic IDs stay in
    the reserved 0xFxxxxxxx space.

New tests (ParticleSystemTests + ParticleHookSinkTests):
- UpdateEmitterAnchor_AttachLocal_ParticlePositionFollowsLiveAnchor
- UpdateEmitterAnchor_AttachLocalCleared_ParticleFrozenAtSpawnOrigin
- EmitterDied_FiresOncePerHandle_AfterAllParticlesExpire
- Birthrate_PerSec_EmitsOnePerTickWhenIntervalElapsed (retail-faithful
  single-emit-per-frame behavior)
- UpdateEntityAnchor_WithAttachLocal_MovesParticleToLiveAnchor
- EmitterDied_PrunesPerEntityHandleTracking

dotnet build green, dotnet test green: 695 / 393 / 243 = 1331 passed
(up from 1325).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Erik 2026-04-28 22:47:11 +02:00
parent 1f82b7604e
commit ec1bbb4f43
28 changed files with 2444 additions and 780 deletions

View file

@ -200,21 +200,14 @@ public static class GfxObjMesh
// docs/research/2026-04-23-sky-retail-verbatim.md §6).
var translucency = TranslucencyKind.Opaque;
var luminosity = 0f;
// SurfTranslucency = the OPACITY multiplier the shader applies
// to fragment alpha. 1.0 = fully opaque (default, non-Translucent
// surfaces). For Translucent-flag surfaces, retail's
// D3DPolyRender::SetSurface at 0x59c7a6 (decomp lines 425255-
// 425260) computes curr_alpha = _ftol2(translucency × 255) and
// feeds that as vertex.color.alpha — so the dat's Translucency
// float is the OPACITY directly (NOT inverted). For rain
// (translucency=0.5) opacity is 0.5; for cloud surface
// 0x08000023 (translucency=0.25) opacity is 0.25 — that's why
// retail's clouds are dim and acdream's were 3× too bright
// before this fix (we used 1-translucency, inverting the
// semantic). ACViewer's TextureCache.cs:142 and WorldBuilder's
// ObjectMeshManager.cs:1115 also use 1-translucency and are
// both wrong by the same misread.
var surfTranslucency = 1.0f;
// SurfOpacity = (1 - Surface.Translucency) for Translucent
// surfaces, 1.0 otherwise. See
// TranslucencyKindExtensions.OpacityFromSurfaceTranslucency for
// the decomp citation (CMaterial::SetTranslucencySimple at
// 0x005396f0 writes material alpha as 1 - translucency).
var diffuse = 1f;
var surfOpacity = 1f;
var disableFog = false;
if (dats is not null)
{
var surface = dats.Get<Surface>(surfaceId);
@ -222,13 +215,16 @@ public static class GfxObjMesh
{
translucency = TranslucencyKindExtensions.FromSurfaceType(surface.Type);
luminosity = surface.Luminosity;
diffuse = surface.Diffuse;
// Apply the dat's Translucency value as opacity ONLY
// when the Translucent flag (0x10) is set on the
// Surface. Without this gate, surfaces with
// Translucency=0 (non-Translucent default) would
// render fully transparent.
if (((uint)surface.Type & (uint)DatReaderWriter.Enums.SurfaceType.Translucent) != 0)
surfTranslucency = surface.Translucency;
surfOpacity = TranslucencyKindExtensions.OpacityFromSurfaceTranslucency(
surface.Type,
surface.Translucency);
disableFog = TranslucencyKindExtensions.DisablesFixedFunctionFog(surface.Type);
}
}
@ -256,8 +252,10 @@ public static class GfxObjMesh
{
Translucency = translucency,
Luminosity = luminosity,
Diffuse = diffuse,
NeedsUvRepeat = needsUvRepeat,
SurfTranslucency = surfTranslucency,
SurfOpacity = surfOpacity,
DisableFog = disableFog,
});
}
return result;

View file

@ -13,67 +13,40 @@ public sealed record GfxObjSubMesh(
{
/// <summary>
/// How this sub-mesh should be composited into the frame.
/// Populated from Surface.Type flags at upload time (requires a DatCollection).
/// Defaults to <see cref="TranslucencyKind.Opaque"/> so offline fixtures
/// that don't supply dat access compile and pass unchanged.
/// Populated from Surface.Type flags at upload time.
/// </summary>
public TranslucencyKind Translucency { get; init; } = TranslucencyKind.Opaque;
/// <summary>
/// Self-illumination strength of the Surface (<c>Surface.Luminosity</c>
/// field, 0..1 fraction — NOT the <c>SurfaceType.Luminous</c> flag bit).
/// Retail uses this as an emissive coefficient in the per-vertex
/// lighting formula:
/// <code>
/// tint = clamp(vec3(Luminosity) + AmbColor + diffuse * DirColor, 0, 1)
/// fragment = texture * tint
/// </code>
/// For Dereth's sky meshes, the DOME (0x010015EE) and SUN/MOON
/// (0x01001348) have <c>Luminosity=1.0</c> (self-illuminated — emissive
/// saturates the lighting math so the baked texture always renders
/// at full brightness). CLOUDS (0x010015EF, 0x01004C36) have
/// <c>Luminosity=0.0</c> (lit by ambient+diffuse — pick up the
/// time-of-day tint). See
/// <c>docs/research/2026-04-23-sky-retail-verbatim.md</c> §6.
/// Defaults to 0.0 (fully lit) so non-sky meshes render through the
/// normal lighting path without change.
/// Surface.Luminosity. Retail uses this as material emissive.
/// </summary>
public float Luminosity { get; init; } = 0f;
/// <summary>
/// True when at least one vertex's UV component lies outside the
/// <c>[0, 1]</c> range, meaning the mesh was authored to have its
/// texture tile across the geometry (i.e. it expects
/// <c>GL_REPEAT</c>/<c>D3DTADDRESS_WRAP</c>). The sky renderer reads
/// this to decide between <c>GL_REPEAT</c> (this flag set, or any
/// scrolling layer) and <c>GL_CLAMP_TO_EDGE</c> (all UVs strictly
/// in <c>[0,1]</c>), which avoids wall-seam bleed on the dome
/// (UVs in <c>[0,1]</c>) while still tiling the inner star/cloud
/// layers (UVs in <c>[~0.4, ~4.6]</c>) correctly.
/// Defaults to false so non-sky consumers get the previous behavior.
/// Surface.Diffuse. Retail sky keyframes route SkyObjectReplace.MaxBright
/// through CPhysicsObj::SetDiffusion (0x005119e0), which lands in
/// CMaterial::SetDiffuseSimple (0x00539750).
/// </summary>
public float Diffuse { get; init; } = 1f;
/// <summary>
/// True when at least one vertex UV component lies outside [0, 1], so
/// the mesh expects texture repeat instead of clamp.
/// </summary>
public bool NeedsUvRepeat { get; init; } = false;
/// <summary>
/// <c>Surface.Translucency</c> float (0..1) treated as an OPACITY
/// multiplier on fragment alpha. 1.0 = fully opaque (default for
/// non-Translucent surfaces). Distinct from the
/// <see cref="TranslucencyKind"/> classifier above, which buckets the
/// flag bits. Retail's <c>D3DPolyRender::SetSurface</c> at
/// <c>0x59c7a6</c> (decomp lines 425255-425260) reads
/// <c>Surface.Translucency</c> when the <c>Translucent</c> (0x10) bit
/// is set, computes <c>curr_alpha = _ftol2(translucency × 255)</c>,
/// and writes that as vertex alpha — i.e. the dat's Translucency float
/// is used DIRECTLY as opacity, NOT inverted. ACViewer
/// (<c>TextureCache.cs:142</c>) and WorldBuilder
/// (<c>ObjectMeshManager.cs:1115</c>) both use <c>1 - translucency</c>
/// and are wrong by the same misread.
/// For the rain Surface 0x080000C5 (translucency=0.5): opacity = 0.5;
/// with the <c>(SrcAlpha, One)</c> additive blend the rain streaks
/// contribute at half intensity. For cloud surface 0x08000023
/// (translucency=0.25): opacity = 0.25 (matches retail's dim clouds).
/// Defaults to 1.0 (fully opaque) so non-Translucent surfaces render
/// at full opacity without change.
/// Final opacity multiplier derived from Surface.Translucency. Retail
/// translucency is transparency: 0.0 is opaque and 1.0 is invisible.
/// CMaterial::SetTranslucencySimple at 0x005396f0 writes material alpha
/// as 1 - translucency.
/// </summary>
public float SurfTranslucency { get; init; } = 1f;
public float SurfOpacity { get; init; } = 1f;
/// <summary>
/// True when the raw Surface.Type has the Additive bit. Retail disables
/// fixed-function fog alpha for this raw bit even if the final blend mode
/// is forced to AlphaBlend by the Translucent+ClipMap branch.
/// </summary>
public bool DisableFog { get; init; } = false;
}

View file

@ -106,4 +106,25 @@ public static class TranslucencyKindExtensions
return TranslucencyKind.Opaque;
}
/// <summary>
/// Retail translucency is transparency: 0 = opaque, 1 = invisible.
/// CMaterial::SetTranslucencySimple at 0x005396f0 writes material alpha
/// as <c>1 - translucency</c>.
/// </summary>
public static float OpacityFromSurfaceTranslucency(SurfaceType type, float translucency)
{
if ((type & SurfaceType.Translucent) == 0)
return 1f;
return Math.Clamp(1f - translucency, 0f, 1f);
}
/// <summary>
/// D3DPolyRender::SetSurface at 0x0059c882 disables fixed-function fog
/// alpha whenever the raw Additive surface bit is present, even when the
/// Translucent+ClipMap branch later forces alpha blending.
/// </summary>
public static bool DisablesFixedFunctionFog(SurfaceType type)
=> (type & SurfaceType.Additive) != 0;
}

View file

@ -37,9 +37,9 @@ public static class SurfaceDecoder
PixelFormat.PFID_R8G8B8 => DecodeR8G8B8(rs),
PixelFormat.PFID_A8R8G8B8 => DecodeA8R8G8B8(rs),
PixelFormat.PFID_X8R8G8B8 => DecodeX8R8G8B8(rs),
PixelFormat.PFID_DXT1 => DecodeBc(rs, CompressionFormat.Bc1),
PixelFormat.PFID_DXT3 => DecodeBc(rs, CompressionFormat.Bc2),
PixelFormat.PFID_DXT5 => DecodeBc(rs, CompressionFormat.Bc3),
PixelFormat.PFID_DXT1 => DecodeBc(rs, CompressionFormat.Bc1, isClipMap),
PixelFormat.PFID_DXT3 => DecodeBc(rs, CompressionFormat.Bc2, isClipMap),
PixelFormat.PFID_DXT5 => DecodeBc(rs, CompressionFormat.Bc3, isClipMap),
PixelFormat.PFID_A8 or PixelFormat.PFID_CUSTOM_LSCAPE_ALPHA => DecodeA8(rs),
PixelFormat.PFID_P8 when palette is not null => DecodeP8(rs, palette, isClipMap),
PixelFormat.PFID_INDEX16 when palette is not null => DecodeIndex16(rs, palette, isClipMap),
@ -245,7 +245,7 @@ public static class SurfaceDecoder
return new DecodedTexture(rgba, rs.Width, rs.Height);
}
private static DecodedTexture DecodeBc(RenderSurface rs, CompressionFormat format)
private static DecodedTexture DecodeBc(RenderSurface rs, CompressionFormat format, bool isClipMap)
{
var pixels = BcDecoder.DecodeRaw(rs.SourceData, rs.Width, rs.Height, format);
var rgba = new byte[rs.Width * rs.Height * 4];
@ -256,6 +256,8 @@ public static class SurfaceDecoder
rgba[s + 1] = pixels[i].g;
rgba[s + 2] = pixels[i].b;
rgba[s + 3] = pixels[i].a;
if (isClipMap && rgba[s + 0] == 0 && rgba[s + 1] == 0 && rgba[s + 2] == 0)
rgba[s + 3] = 0;
}
return new DecodedTexture(rgba, rs.Width, rs.Height);
}

View file

@ -1,73 +1,38 @@
using System;
using System.Collections.Concurrent;
using System.Numerics;
using DatReaderWriter;
using DatParticleEmitter = DatReaderWriter.DBObjs.ParticleEmitter;
using DatEmitterType = DatReaderWriter.Enums.EmitterType;
using DatParticleType = DatReaderWriter.Enums.ParticleType;
namespace AcDream.Core.Vfx;
/// <summary>
/// Resolves <see cref="EmitterDesc"/> instances by their retail emitter
/// dat id (<c>0x32xxxxxx</c> range). The current build of
/// Chorizite.DatReaderWriter (v2.1.7) doesn't yet ship a
/// <c>ParticleEmitterInfo</c> DBObj class, so we maintain a small
/// registry of synthesized descriptors for the handful of emitters
/// acdream actually needs (portal swirl, chimney smoke, fireplace
/// flames, footstep dust, spell auras, weapon trails) and fall back to
/// a generic "puff" for unknown ids. When a future DRW release adds
/// the dat-type, this class will additionally load + cache from dats.
///
/// <para>
/// Field mapping once the dat-type arrives (docs/research/deepdives/
/// r04-vfx-particles.md §1 + references/DatReaderWriter's own generated
/// <c>ParticleEmitterInfo.generated.cs</c>):
/// <list type="bullet">
/// <item><description>
/// <c>Birthrate</c> → <c>1 / EmitRate</c> (retail stores the avg
/// time between spawns, not the rate).
/// </description></item>
/// <item><description>
/// <c>Lifespan ± LifespanRand</c> → <c>LifetimeMin / LifetimeMax</c>
/// range.
/// </description></item>
/// <item><description>
/// <c>A, MinA, MaxA</c> → primary initial velocity with magnitude
/// jitter; <c>B</c> / <c>C</c> are secondary spread components.
/// </description></item>
/// <item><description>
/// <c>StartScale, FinalScale</c> / <c>StartTrans, FinalTrans</c>
/// interpolate linearly over life.
/// </description></item>
/// </list>
/// </para>
/// Resolves retail <c>ParticleEmitterInfo</c> dat records
/// (<c>0x32xxxxxx</c>) into acdream runtime descriptors.
/// </summary>
public sealed class EmitterDescRegistry
{
private const uint FallbackEmitterId = 0xFFFFFFFFu;
private readonly Func<uint, DatParticleEmitter?>? _resolver;
private readonly ConcurrentDictionary<uint, EmitterDesc> _byId = new();
public EmitterDescRegistry()
: this((Func<uint, DatParticleEmitter?>?)null)
{
// Seed with a handful of well-known AC emitter ids plus a
// fallback. Ids here come from empirical ACViewer dat dumps —
// see r04 §5.2 for the more complete inventory.
Register(new EmitterDesc
{
DatId = 0xFFFFFFFFu, // "default" sentinel
Type = ParticleType.LocalVelocity,
Flags = EmitterFlags.Billboard | EmitterFlags.FaceCamera,
EmitRate = 10f,
MaxParticles = 32,
LifetimeMin = 0.6f,
LifetimeMax = 1.2f,
OffsetDir = new Vector3(0, 0, 1),
MinOffset = 0f,
MaxOffset = 0.1f,
SpawnDiskRadius = 0.1f,
InitialVelocity = new Vector3(0, 0, 0.5f),
VelocityJitter = 0.3f,
StartSize = 0.25f,
EndSize = 0.6f,
StartAlpha = 0.85f,
EndAlpha = 0f,
});
}
public EmitterDescRegistry(DatCollection dats)
: this(id => SafeGet(dats, id))
{
}
public EmitterDescRegistry(Func<uint, DatParticleEmitter?>? resolver)
{
_resolver = resolver;
Register(BuildFallback());
}
public void Register(EmitterDesc desc)
@ -78,10 +43,159 @@ public sealed class EmitterDescRegistry
public EmitterDesc Get(uint emitterId)
{
if (_byId.TryGetValue(emitterId, out var desc)) return desc;
if (_byId.TryGetValue(0xFFFFFFFFu, out var fallback)) return fallback;
if (_byId.TryGetValue(emitterId, out var desc))
return desc;
if (_resolver is not null)
{
var dat = _resolver(emitterId);
if (dat is not null)
{
desc = FromDat(emitterId, dat);
_byId[emitterId] = desc;
return desc;
}
}
if (_byId.TryGetValue(FallbackEmitterId, out var fallback))
return fallback;
throw new InvalidOperationException("No default emitter registered in registry.");
}
public int Count => _byId.Count;
public static EmitterDesc FromDat(uint emitterId, DatParticleEmitter dat)
{
ArgumentNullException.ThrowIfNull(dat);
float birthrate = MathF.Max(0f, (float)dat.Birthrate);
float lifespan = MathF.Max(0f, (float)dat.Lifespan);
float lifespanRand = MathF.Abs((float)dat.LifespanRand);
float lifetimeMin = MathF.Max(0f, lifespan - lifespanRand);
float lifetimeMax = MathF.Max(lifetimeMin, lifespan + lifespanRand);
// ParticleEmitterInfo has no "additive" field; retail derives blend
// state from the particle GfxObj surface material.
var flags = EmitterFlags.Billboard | EmitterFlags.FaceCamera;
if (dat.IsParentLocal)
flags |= EmitterFlags.AttachLocal;
// ParticleEmitterInfo stores translucency, not opacity. Retail feeds
// StartTrans/FinalTrans to PhysicsPart::SetTranslucency; the GL path
// uses the complement as source alpha.
float startOpacity = 1f - Math.Clamp((float)dat.StartTrans, 0f, 1f);
float endOpacity = 1f - Math.Clamp((float)dat.FinalTrans, 0f, 1f);
return new EmitterDesc
{
DatId = emitterId,
Type = MapParticleType(dat.ParticleType),
EmitterKind = MapEmitterKind(dat.EmitterType),
Flags = flags,
GfxObjId = dat.GfxObjId.DataId,
HwGfxObjId = dat.HwGfxObjId.DataId,
Birthrate = birthrate,
EmitRate = dat.EmitterType == DatEmitterType.BirthratePerSec && birthrate > 0f
? 1f / birthrate
: 0f,
MaxParticles = Math.Max(1, dat.MaxParticles),
InitialParticles = Math.Max(0, dat.InitialParticles),
TotalParticles = Math.Max(0, dat.TotalParticles),
TotalDuration = MathF.Max(0f, (float)dat.TotalSeconds),
Lifespan = lifespan,
LifespanRand = lifespanRand,
LifetimeMin = lifetimeMin,
LifetimeMax = lifetimeMax,
OffsetDir = dat.OffsetDir,
MinOffset = dat.MinOffset,
MaxOffset = dat.MaxOffset,
SpawnDiskRadius = dat.MaxOffset,
InitialVelocity = dat.A,
Gravity = dat.B,
A = dat.A,
MinA = dat.MinA,
MaxA = dat.MaxA,
B = dat.B,
MinB = dat.MinB,
MaxB = dat.MaxB,
C = dat.C,
MinC = dat.MinC,
MaxC = dat.MaxC,
StartSize = dat.StartScale,
EndSize = dat.FinalScale,
ScaleRand = dat.ScaleRand,
StartAlpha = startOpacity,
EndAlpha = endOpacity,
TransRand = dat.TransRand,
};
}
private static DatParticleEmitter? SafeGet(DatCollection dats, uint id)
{
if (dats is null)
return null;
try
{
return dats.Get<DatParticleEmitter>(id);
}
catch
{
return null;
}
}
private static EmitterDesc BuildFallback() => new()
{
DatId = FallbackEmitterId,
Type = ParticleType.LocalVelocity,
EmitterKind = ParticleEmitterKind.BirthratePerSec,
Flags = EmitterFlags.Billboard | EmitterFlags.FaceCamera,
Birthrate = 0.1f,
EmitRate = 10f,
MaxParticles = 32,
LifetimeMin = 0.6f,
LifetimeMax = 1.2f,
Lifespan = 0.9f,
LifespanRand = 0.3f,
OffsetDir = new Vector3(0, 0, 1),
MinOffset = 0f,
MaxOffset = 0.1f,
SpawnDiskRadius = 0.1f,
InitialVelocity = new Vector3(0, 0, 0.5f),
VelocityJitter = 0.3f,
A = new Vector3(0, 0, 0.5f),
MinA = 1f,
MaxA = 1f,
B = Vector3.Zero,
C = Vector3.Zero,
StartSize = 0.25f,
EndSize = 0.6f,
StartAlpha = 0.85f,
EndAlpha = 0f,
};
private static ParticleEmitterKind MapEmitterKind(DatEmitterType type) => type switch
{
DatEmitterType.BirthratePerSec => ParticleEmitterKind.BirthratePerSec,
DatEmitterType.BirthratePerMeter => ParticleEmitterKind.BirthratePerMeter,
_ => ParticleEmitterKind.Unknown,
};
private static ParticleType MapParticleType(DatParticleType type) => type switch
{
DatParticleType.Still => ParticleType.Still,
DatParticleType.LocalVelocity => ParticleType.LocalVelocity,
DatParticleType.ParabolicLVGA => ParticleType.ParabolicLVGA,
DatParticleType.ParabolicLVGAGR => ParticleType.ParabolicLVGAGR,
DatParticleType.Swarm => ParticleType.Swarm,
DatParticleType.Explode => ParticleType.Explode,
DatParticleType.Implode => ParticleType.Implode,
DatParticleType.ParabolicLVLA => ParticleType.ParabolicLVLA,
DatParticleType.ParabolicLVLALR => ParticleType.ParabolicLVLALR,
DatParticleType.ParabolicGVGA => ParticleType.ParabolicGVGA,
DatParticleType.ParabolicGVGAGR => ParticleType.ParabolicGVGAGR,
DatParticleType.GlobalVelocity => ParticleType.GlobalVelocity,
_ => ParticleType.Unknown,
};
}

View file

@ -1,6 +1,7 @@
using System;
using System.Collections.Concurrent;
using System.Numerics;
using System.Threading;
using AcDream.Core.Physics;
using DatReaderWriter.Types;
@ -62,10 +63,30 @@ public sealed class ParticleHookSink : IAnimationHookSink
// key ("the smoke trail I spawned 2 seconds ago"), so we track by
// (entity, emitterId).
private readonly ConcurrentDictionary<(uint EntityId, uint EmitterId), int> _handlesByKey = new();
// entityId → set of live emitter handles. Dictionary-as-set so we can
// remove individual handles when their emitter dies (M4 fix —
// ConcurrentBag couldn't drop entries, so handles for naturally-expired
// emitters used to leak).
private readonly ConcurrentDictionary<uint, ConcurrentDictionary<int, byte>> _handlesByEntity = new();
// Reverse lookup: handle → (entity, key) for O(1) cleanup on EmitterDied.
private readonly ConcurrentDictionary<int, (uint EntityId, uint KeyId)> _trackingByHandle = new();
private readonly ConcurrentDictionary<uint, ParticleRenderPass> _renderPassByEntity = new();
private readonly ConcurrentDictionary<uint, Quaternion> _rotationByEntity = new();
private int _anonymousEmitterSerial;
public ParticleHookSink(ParticleSystem system)
{
_system = system ?? throw new ArgumentNullException(nameof(system));
_system.EmitterDied += OnEmitterDied;
}
private void OnEmitterDied(int handle)
{
if (!_trackingByHandle.TryRemove(handle, out var t))
return;
_handlesByKey.TryRemove((t.EntityId, t.KeyId), out _);
if (_handlesByEntity.TryGetValue(t.EntityId, out var bag))
bag.TryRemove(handle, out _);
}
public void OnHook(uint entityId, Vector3 entityWorldPosition, AnimationHook hook)
@ -104,6 +125,54 @@ public sealed class ParticleHookSink : IAnimationHookSink
}
}
public void SetEntityRenderPass(uint entityId, ParticleRenderPass renderPass)
=> _renderPassByEntity[entityId] = renderPass;
public void SetEntityRotation(uint entityId, Quaternion rotation)
=> _rotationByEntity[entityId] = rotation;
public void ClearEntityRenderPass(uint entityId)
=> _renderPassByEntity.TryRemove(entityId, out _);
/// <summary>
/// Refresh every live emitter on this entity to a new world anchor +
/// rotation. The owning subsystem (sky-PES driver, animation tick)
/// drives this each frame for AttachLocal emitters so they track their
/// moving parent — retail-faithful via
/// <c>ParticleEmitter::UpdateParticles</c> at <c>0x0051d2d4</c>, which
/// re-reads the parent frame each tick when <c>is_parent_local != 0</c>.
/// Safe to call for entities with no live emitters (no-op).
/// </summary>
public void UpdateEntityAnchor(uint entityId, Vector3 anchor, Quaternion rotation)
{
_rotationByEntity[entityId] = rotation;
if (!_handlesByEntity.TryGetValue(entityId, out var bag))
return;
foreach (var handle in bag.Keys)
_system.UpdateEmitterAnchor(handle, anchor, rotation);
}
public void StopAllForEntity(uint entityId, bool fadeOut)
{
if (_handlesByEntity.TryRemove(entityId, out var handles))
{
foreach (var handle in handles.Keys)
{
_system.StopEmitter(handle, fadeOut);
_trackingByHandle.TryRemove(handle, out _);
}
}
foreach (var key in _handlesByKey.Keys)
{
if (key.EntityId == entityId)
_handlesByKey.TryRemove(key, out _);
}
ClearEntityRenderPass(entityId);
_rotationByEntity.TryRemove(entityId, out _);
}
private void SpawnFromHook(
uint entityId,
Vector3 worldPos,
@ -115,15 +184,35 @@ public sealed class ParticleHookSink : IAnimationHookSink
// Spawn position: entity pose + hook offset. PartIndex will be
// used when the renderer passes per-part transforms through; for
// now, fold it into the root pos.
var anchor = worldPos + offset;
var rotation = _rotationByEntity.TryGetValue(entityId, out var rot)
? rot
: Quaternion.Identity;
var anchor = worldPos + Vector3.Transform(offset, rotation);
var renderPass = _renderPassByEntity.TryGetValue(entityId, out var pass)
? pass
: ParticleRenderPass.Scene;
int handle = _system.SpawnEmitterById(
emitterId: emitterInfoId,
anchor: anchor,
rot: Quaternion.Identity,
rot: rotation,
attachedObjectId: entityId,
attachedPartIndex: partIndex);
attachedPartIndex: partIndex,
renderPass: renderPass);
_handlesByKey[(entityId, logicalId)] = handle;
uint keyId = logicalId != 0
? logicalId
: 0x80000000u | (uint)Interlocked.Increment(ref _anonymousEmitterSerial);
if (logicalId != 0 && _handlesByKey.TryRemove((entityId, keyId), out var oldHandle))
{
_system.StopEmitter(oldHandle, fadeOut: false);
_trackingByHandle.TryRemove(oldHandle, out _);
}
_handlesByKey[(entityId, keyId)] = handle;
_handlesByEntity
.GetOrAdd(entityId, _ => new ConcurrentDictionary<int, byte>())
.TryAdd(handle, 0);
_trackingByHandle[handle] = (entityId, keyId);
}
}

View file

@ -5,33 +5,18 @@ using System.Numerics;
namespace AcDream.Core.Vfx;
/// <summary>
/// Runtime particle orchestrator — port of retail's <c>CParticleManager</c>
/// (r04 §2). Owns a pool of active <see cref="ParticleEmitter"/> instances,
/// advances each per-frame via one of 13 motion integrators, fades colour /
/// scale over life, and exposes a flat particle stream for the renderer.
///
/// <para>
/// Not thread-safe — called only from the render thread (same thread that
/// drives TickAnimations).
/// </para>
///
/// <para>
/// Handle-based API so callers can stop a specific emitter later (cast
/// interrupt, fadeout). <see cref="SpawnEmitter"/> returns a positive
/// integer; <see cref="StopEmitter"/> accepts it.
/// </para>
/// Runtime particle orchestrator. The data and update rules are a direct
/// port of retail's <c>ParticleEmitterInfo</c>, <c>ParticleEmitter</c>, and
/// <c>Particle::Update</c> paths from the named retail decompilation.
/// </summary>
public sealed class ParticleSystem : IParticleSystem
{
private readonly EmitterDescRegistry _registry;
private readonly Random _rng;
// All live emitters keyed by our handle. Lookup is cheap; iteration is
// per-frame so we also keep a flat list for stable ordering (draw order).
private readonly Dictionary<int, ParticleEmitter> _byHandle = new();
private readonly List<int> _handleOrder = new();
private int _nextHandle = 1;
private int _nextHandle = 1;
private float _time;
private int _activeParticleCount;
@ -49,7 +34,8 @@ public sealed class ParticleSystem : IParticleSystem
Vector3 anchor,
Quaternion? rot = null,
uint attachedObjectId = 0,
int attachedPartIndex = -1)
int attachedPartIndex = -1,
ParticleRenderPass renderPass = ParticleRenderPass.Scene)
{
ArgumentNullException.ThrowIfNull(desc);
@ -61,43 +47,45 @@ public sealed class ParticleSystem : IParticleSystem
AnchorRot = rot ?? Quaternion.Identity,
AttachedObjectId = attachedObjectId,
AttachedPartIndex = attachedPartIndex,
RenderPass = renderPass,
Particles = new Particle[Math.Max(1, desc.MaxParticles)],
StartedAt = _time,
LastEmitTime = _time,
LastEmitOffset = anchor,
};
_byHandle[handle] = emitter;
_handleOrder.Add(handle);
for (int i = 0; i < desc.InitialParticles; i++)
SpawnOne(emitter, allowWhenFull: false);
return handle;
}
/// <summary>
/// Convenience: spawn by retail emitter id — the registry resolves to
/// the correct <see cref="EmitterDesc"/>, or falls back to the default
/// if unknown. Used by the hook sink when a CreateParticleHook arrives.
/// </summary>
public int SpawnEmitterById(
uint emitterId,
Vector3 anchor,
Quaternion? rot = null,
uint attachedObjectId = 0,
int attachedPartIndex = -1)
int attachedPartIndex = -1,
ParticleRenderPass renderPass = ParticleRenderPass.Scene)
{
var desc = _registry.Get(emitterId);
return SpawnEmitter(desc, anchor, rot, attachedObjectId, attachedPartIndex);
return SpawnEmitter(desc, anchor, rot, attachedObjectId, attachedPartIndex, renderPass);
}
public void PlayScript(uint scriptId, uint targetObjectId, float modifier = 1f)
{
// Full PhysicsScript dispatch is on hold until the DatReaderWriter
// library exposes ParticleEmitterInfo / PhysicsScript. For now,
// this is a no-op — callers use SpawnEmitter or the hook sink.
// Full PhysicsScript scheduling lives in PhysicsScriptRunner.
}
public void StopEmitter(int handle, bool fadeOut)
{
if (!_byHandle.TryGetValue(handle, out var em)) return;
if (!_byHandle.TryGetValue(handle, out var em))
return;
em.Finished = true;
// fadeOut=false would stop instantly; our renderer currently drops
// Finished emitters that have no living particles each tick.
if (!fadeOut)
{
for (int i = 0; i < em.Particles.Length; i++)
@ -105,259 +93,454 @@ public sealed class ParticleSystem : IParticleSystem
}
}
/// <summary>
/// Refresh an active emitter's world anchor + orientation. Required for
/// retail's <c>is_parent_local=1</c> (acdream's
/// <see cref="EmitterFlags.AttachLocal"/>) semantics: retail
/// <c>ParticleEmitter::UpdateParticles</c> at <c>0x0051d2d4</c> reads the
/// LIVE parent frame each tick when <c>is_parent_local != 0</c>. The
/// caller (typically a tick loop tracking a moving parent — the camera
/// for sky-PES, an entity for animation hooks) drives this every frame.
/// </summary>
public void UpdateEmitterAnchor(int handle, Vector3 anchor, Quaternion? rot = null)
{
if (!_byHandle.TryGetValue(handle, out var em))
return;
em.AnchorPos = anchor;
if (rot.HasValue)
em.AnchorRot = rot.Value;
}
/// <summary>True when the given handle still maps to a live emitter.</summary>
public bool IsEmitterAlive(int handle) => _byHandle.ContainsKey(handle);
/// <summary>
/// Fired exactly once per emitter when it is removed from the live set
/// (either because it finished naturally or was stopped without fade).
/// Subscribers (e.g. <see cref="ParticleHookSink"/>) use this to prune
/// per-entity handle tracking so the per-entity bag doesn't grow without
/// bound during a long session.
/// </summary>
public event Action<int>? EmitterDied;
public void Tick(float dt)
{
if (dt <= 0f) return;
if (dt <= 0f)
return;
_time += dt;
_activeParticleCount = 0;
// Iterate handles by a snapshot so StopEmitter-inside-emit is safe.
for (int i = 0; i < _handleOrder.Count; i++)
{
int handle = _handleOrder[i];
if (!_byHandle.TryGetValue(handle, out var em)) continue;
if (!_byHandle.TryGetValue(handle, out var em))
continue;
AdvanceEmitter(em, dt);
_activeParticleCount += CountAlive(em);
AdvanceEmitter(em);
int live = CountAlive(em);
em.ActiveCount = live;
_activeParticleCount += live;
bool durationDone = em.Desc.TotalDuration > 0f
&& (_time - em.StartedAt) > em.Desc.TotalDuration;
if (durationDone) em.Finished = true;
if (em.Desc.TotalDuration > 0f && (_time - em.StartedAt) > em.Desc.TotalDuration)
em.Finished = true;
// Drop emitter entirely when it has no live particles AND is
// marked finished (duration elapsed, StopEmitter, etc).
if (em.Finished && CountAlive(em) == 0)
if (em.Desc.TotalParticles > 0 && em.TotalEmitted >= em.Desc.TotalParticles)
em.Finished = true;
if (em.Finished && live == 0)
{
_byHandle.Remove(handle);
_handleOrder.RemoveAt(i);
i--;
EmitterDied?.Invoke(handle);
}
}
}
/// <summary>
/// Enumerate every live particle with its emitter description for
/// the renderer. Yields (emitter, particleIndex) so the caller can
/// read <c>em.Particles[idx]</c> directly.
/// </summary>
public IEnumerable<(ParticleEmitter Emitter, int Index)> EnumerateLive()
{
foreach (var handle in _handleOrder)
{
if (!_byHandle.TryGetValue(handle, out var em)) continue;
if (!_byHandle.TryGetValue(handle, out var em))
continue;
for (int i = 0; i < em.Particles.Length; i++)
{
if (em.Particles[i].Alive) yield return (em, i);
if (em.Particles[i].Alive)
yield return (em, i);
}
}
}
// ── Private: emission + integration ──────────────────────────────────────
private void AdvanceEmitter(ParticleEmitter em, float dt)
private void AdvanceEmitter(ParticleEmitter em)
{
if (!em.Finished && em.Desc.EmitRate > 0f)
{
em.EmittedAccumulator += dt * em.Desc.EmitRate;
while (em.EmittedAccumulator >= 1.0f)
{
em.EmittedAccumulator -= 1.0f;
SpawnOne(em);
}
}
// Update every particle slot.
for (int i = 0; i < em.Particles.Length; i++)
{
ref var p = ref em.Particles[i];
if (!p.Alive) continue;
if (!p.Alive)
continue;
p.Age += dt;
if (p.Age >= p.Lifetime)
p.Age = _time - p.SpawnedAt;
if (p.Lifetime <= 0f || p.Age >= p.Lifetime)
{
p.Alive = false;
continue;
}
Integrate(ref p, em, dt);
p.Position = ComputePosition(em, p);
float tLife = Math.Clamp(p.Age / p.Lifetime, 0f, 1f);
p.Size = Lerp(em.Desc.StartSize, em.Desc.EndSize, tLife);
float alpha = Lerp(em.Desc.StartAlpha, em.Desc.EndAlpha, tLife);
p.Size = Lerp(p.StartSize, p.EndSize, tLife);
p.Rotation = Lerp(em.Desc.StartRotation, em.Desc.EndRotation, tLife);
float alpha = Lerp(p.StartAlpha, p.EndAlpha, tLife);
p.ColorArgb = Color32(alpha, em.Desc.StartColorArgb, em.Desc.EndColorArgb, tLife);
}
if (em.Finished || _time < em.StartedAt + em.Desc.StartDelay)
return;
while (ShouldEmitParticle(em))
{
if (!SpawnOne(em, allowWhenFull: false))
break;
}
if (em.Desc.Birthrate <= 0f && em.Desc.EmitRate > 0f)
{
float dt = _time - em.LastEmitTime;
em.EmittedAccumulator += dt * em.Desc.EmitRate;
em.LastEmitTime = _time;
while (em.EmittedAccumulator >= 1f)
{
em.EmittedAccumulator -= 1f;
if (!SpawnOne(em, allowWhenFull: false))
break;
}
}
}
private void SpawnOne(ParticleEmitter em)
private bool ShouldEmitParticle(ParticleEmitter em)
{
// Find a free slot; overwrite the oldest if pool is full.
int slot = -1;
for (int i = 0; i < em.Particles.Length; i++)
var desc = em.Desc;
if (desc.TotalParticles > 0 && em.TotalEmitted >= desc.TotalParticles)
return false;
if (CountAlive(em) >= desc.MaxParticles)
return false;
if (desc.Birthrate <= 0f)
return false;
return desc.EmitterKind switch
{
if (!em.Particles[i].Alive) { slot = i; break; }
}
ParticleEmitterKind.BirthratePerSec => (_time - em.LastEmitTime) > desc.Birthrate,
ParticleEmitterKind.BirthratePerMeter =>
Vector3.DistanceSquared(em.AnchorPos, em.LastEmitOffset) > desc.Birthrate * desc.Birthrate,
_ => false,
};
}
private bool SpawnOne(ParticleEmitter em, bool allowWhenFull)
{
int slot = FindFreeSlot(em);
if (slot < 0 && allowWhenFull)
slot = FindOldestSlot(em);
if (slot < 0)
{
// Pool saturated; overwrite the slot closest to dying (oldest
// by age / lifetime ratio). Matches retail's behaviour of
// recycling the expiring particle rather than dropping.
float best = -1f;
for (int i = 0; i < em.Particles.Length; i++)
{
ref var p = ref em.Particles[i];
float r = p.Lifetime > 0 ? p.Age / p.Lifetime : 1f;
if (r > best) { best = r; slot = i; }
}
if (slot < 0) return;
}
return false;
ref var particle = ref em.Particles[slot];
particle = default;
particle.Alive = true;
particle.Age = 0f;
particle.Lifetime = Lerp(em.Desc.LifetimeMin, em.Desc.LifetimeMax,
(float)_rng.NextDouble());
// Position = emitter anchor + random offset in a disk perpendicular
// to OffsetDir. This models the retail annulus.
Vector3 disk = RandomDiskVector(em.Desc.OffsetDir, em.Desc.MaxOffset);
particle.Position = em.AnchorPos + disk;
particle.SpawnedAt = _time;
particle.Lifetime = RandomLifespan(em.Desc);
particle.EmissionOrigin = em.AnchorPos;
particle.SpawnRotation = em.AnchorRot;
// Velocity = initial vector ± jitter in all three axes.
Vector3 v = em.Desc.InitialVelocity;
if (em.Desc.VelocityJitter > 0f)
Vector3 localOffset = RandomOffset(em.Desc);
Vector3 localA = RandomVector(em.Desc.A, em.Desc.MinA, em.Desc.MaxA);
Vector3 localB = RandomVector(em.Desc.B, em.Desc.MinB, em.Desc.MaxB);
Vector3 localC = RandomVector(em.Desc.C, em.Desc.MinC, em.Desc.MaxC);
if (localA == Vector3.Zero && em.Desc.InitialVelocity != Vector3.Zero)
{
v += new Vector3(
RandomCentered(em.Desc.VelocityJitter),
RandomCentered(em.Desc.VelocityJitter),
RandomCentered(em.Desc.VelocityJitter));
localA = em.Desc.InitialVelocity;
if (em.Desc.VelocityJitter > 0f)
{
localA += new Vector3(
RandomCentered(em.Desc.VelocityJitter),
RandomCentered(em.Desc.VelocityJitter),
RandomCentered(em.Desc.VelocityJitter));
}
}
particle.Velocity = v;
particle.Size = em.Desc.StartSize;
particle.Rotation = em.Desc.StartRotation;
particle.ColorArgb = em.Desc.StartColorArgb;
if (localB == Vector3.Zero && em.Desc.Gravity != Vector3.Zero)
localB = em.Desc.Gravity;
InitParticleVectors(em, ref particle, localOffset, localA, localB, localC);
particle.Velocity = particle.A;
particle.StartSize = RandomScale(em.Desc.StartSize, em.Desc.ScaleRand);
particle.EndSize = RandomScale(em.Desc.EndSize, em.Desc.ScaleRand);
particle.StartAlpha = RandomTrans(em.Desc.StartAlpha, em.Desc.TransRand);
particle.EndAlpha = RandomTrans(em.Desc.EndAlpha, em.Desc.TransRand);
particle.Size = particle.StartSize;
particle.ColorArgb = Color32(particle.StartAlpha, em.Desc.StartColorArgb, em.Desc.EndColorArgb, 0f);
particle.Position = ComputePosition(em, particle);
em.TotalEmitted++;
em.LastEmitTime = _time;
em.LastEmitOffset = em.AnchorPos;
return true;
}
// ── 13 retail motion integrators (r04 §3) ────────────────────────────────
private void Integrate(ref Particle p, ParticleEmitter em, float dt)
private Vector3 ComputePosition(ParticleEmitter em, Particle p)
{
float t = p.Age;
Vector3 origin = (em.Desc.Flags & EmitterFlags.AttachLocal) != 0
? em.AnchorPos
: p.EmissionOrigin;
Vector3 offset = p.Offset;
Vector3 a = p.A;
Vector3 b = p.B;
Vector3 c = p.C;
return em.Desc.Type switch
{
ParticleType.Still => origin + offset,
ParticleType.LocalVelocity or ParticleType.GlobalVelocity =>
origin + offset + t * a,
ParticleType.ParabolicLVGA or ParticleType.ParabolicLVLA or ParticleType.ParabolicGVGA =>
origin + offset + t * a + 0.5f * t * t * b,
ParticleType.ParabolicLVGAGR or ParticleType.ParabolicLVLALR or ParticleType.ParabolicGVGAGR =>
origin + offset + t * a + 0.5f * t * t * b,
ParticleType.Swarm =>
origin + offset + t * a + new Vector3(
MathF.Cos(t * b.X) * c.X,
MathF.Sin(t * b.Y) * c.Y,
MathF.Cos(t * b.Z) * c.Z),
ParticleType.Explode =>
origin + offset + new Vector3(
(t * b.X + c.X * a.X) * t,
(t * b.Y + c.Y * a.X) * t,
(t * b.Z + c.Z * a.X + a.Z) * t),
ParticleType.Implode =>
origin + offset + MathF.Cos(a.X * t) * c + t * t * b,
_ => origin + offset + t * a,
};
}
private void InitParticleVectors(
ParticleEmitter em,
ref Particle particle,
Vector3 localOffset,
Vector3 localA,
Vector3 localB,
Vector3 localC)
{
// Retail Particle::Init 0x0051c930 resolves local/global vector
// spaces once at spawn; Particle::Update 0x0051c290 then integrates
// those stored world-space coefficients each frame.
particle.Offset = ToSpawnWorld(em, localOffset);
particle.A = localA;
particle.B = localB;
particle.C = localC;
switch (em.Desc.Type)
{
case ParticleType.Still:
// No motion. Age + fade only.
break;
case ParticleType.LocalVelocity:
// Constant spawn velocity, no acceleration.
p.Position += p.Velocity * dt;
break;
case ParticleType.GlobalVelocity:
// Uses emitter's InitialVelocity (global/world-space);
// each particle keeps its own copy already (set at spawn),
// so behaves identically to LocalVelocity at runtime.
p.Position += p.Velocity * dt;
break;
case ParticleType.Parabolic:
case ParticleType.ParabolicLVGV:
case ParticleType.ParabolicLVGA:
particle.A = ToSpawnWorld(em, localA);
break;
case ParticleType.ParabolicLVLA:
case ParticleType.ParabolicGVGA:
case ParticleType.ParabolicGVLA:
case ParticleType.ParabolicLALV:
// Velocity decays with gravity; position integrates.
p.Velocity += em.Desc.Gravity * dt;
p.Position += p.Velocity * dt;
particle.A = ToSpawnWorld(em, localA);
particle.B = ToSpawnWorld(em, localB);
break;
case ParticleType.ParabolicLVGAGR:
particle.A = ToSpawnWorld(em, localA);
particle.C = localC;
break;
case ParticleType.Swarm:
// Orbital drift around anchor. Apply a tangential swirl.
{
Vector3 toCenter = em.AnchorPos - p.Position;
Vector3 axis = em.Desc.OffsetDir == Vector3.Zero ? Vector3.UnitZ : em.Desc.OffsetDir;
Vector3 tangent = Vector3.Normalize(Vector3.Cross(axis, toCenter));
p.Velocity = Vector3.Lerp(p.Velocity, tangent * em.Desc.InitialVelocity.Length(), dt * 4f);
p.Position += p.Velocity * dt;
}
particle.A = ToSpawnWorld(em, localA);
break;
case ParticleType.Explode:
// Push outward along (position - anchor).
{
Vector3 dir = p.Position - em.AnchorPos;
if (dir.LengthSquared() < 1e-6f) dir = Vector3.UnitZ;
else dir = Vector3.Normalize(dir);
p.Velocity = dir * em.Desc.InitialVelocity.Length();
p.Position += p.Velocity * dt;
}
particle.A = localA;
particle.B = localB;
particle.C = RandomExplodeDirection(localC);
break;
case ParticleType.Implode:
// Pull inward toward anchor.
{
Vector3 dir = em.AnchorPos - p.Position;
float dist = dir.Length();
if (dist < 0.01f) { p.Alive = false; break; }
dir /= dist;
p.Velocity = dir * em.Desc.InitialVelocity.Length();
p.Position += p.Velocity * dt;
}
particle.A = localA;
particle.B = localB;
particle.Offset = new Vector3(
particle.Offset.X * localC.X,
particle.Offset.Y * localC.Y,
particle.Offset.Z * localC.Z);
particle.C = particle.Offset;
break;
default:
p.Position += p.Velocity * dt;
case ParticleType.ParabolicLVLALR:
particle.A = ToSpawnWorld(em, localA);
particle.B = ToSpawnWorld(em, localB);
particle.C = ToSpawnWorld(em, localC);
break;
case ParticleType.ParabolicGVGAGR:
particle.C = localC;
break;
}
}
// ── Utility ──────────────────────────────────────────────────────────────
private static Vector3 ToSpawnWorld(ParticleEmitter em, Vector3 value)
=> em.AnchorRot == Quaternion.Identity ? value : Vector3.Transform(value, em.AnchorRot);
private Vector3 RandomExplodeDirection(Vector3 localC)
{
float yaw = RandomRange(-MathF.PI, MathF.PI);
float pitch = RandomRange(-MathF.PI, MathF.PI);
float cosPitch = MathF.Cos(pitch);
Vector3 c = new(
MathF.Cos(yaw) * localC.X * cosPitch,
MathF.Sin(yaw) * localC.Y * cosPitch,
MathF.Sin(pitch) * localC.Z);
return NormalizeCheckSmall(ref c) ? Vector3.Zero : c;
}
private int FindFreeSlot(ParticleEmitter em)
{
for (int i = 0; i < em.Particles.Length; i++)
{
if (!em.Particles[i].Alive)
return i;
}
return -1;
}
private static int FindOldestSlot(ParticleEmitter em)
{
int slot = -1;
float best = -1f;
for (int i = 0; i < em.Particles.Length; i++)
{
ref var p = ref em.Particles[i];
float r = p.Lifetime > 0f ? p.Age / p.Lifetime : 1f;
if (r > best)
{
best = r;
slot = i;
}
}
return slot;
}
private static int CountAlive(ParticleEmitter em)
{
int n = 0;
for (int i = 0; i < em.Particles.Length; i++)
if (em.Particles[i].Alive) n++;
{
if (em.Particles[i].Alive)
n++;
}
return n;
}
private float RandomLifespan(EmitterDesc desc)
{
float lifespan = desc.Lifespan > 0f ? desc.Lifespan : (desc.LifetimeMin + desc.LifetimeMax) * 0.5f;
float rand = desc.LifespanRand > 0f ? desc.LifespanRand : MathF.Abs(desc.LifetimeMax - desc.LifetimeMin) * 0.5f;
float value = lifespan + RandomCentered(rand);
if (value <= 0f && desc.LifetimeMax > 0f)
value = Lerp(desc.LifetimeMin, desc.LifetimeMax, (float)_rng.NextDouble());
return MathF.Max(0f, value);
}
private Vector3 RandomOffset(EmitterDesc desc)
{
float min = MathF.Min(desc.MinOffset, desc.MaxOffset);
float max = MathF.Max(desc.MinOffset, desc.MaxOffset);
if (max <= 0f)
return Vector3.Zero;
Vector3 axis = NormalizeOrZero(desc.OffsetDir);
Vector3 v = new(
RandomCentered(1f),
RandomCentered(1f),
RandomCentered(1f));
if (axis != Vector3.Zero)
v -= axis * Vector3.Dot(v, axis);
if (v.LengthSquared() < 1e-8f)
v = axis != Vector3.Zero ? Perpendicular(axis) : Vector3.UnitX;
else
v = Vector3.Normalize(v);
return v * Lerp(min, max, (float)_rng.NextDouble());
}
private Vector3 RandomVector(Vector3 direction, float min, float max)
{
if (direction == Vector3.Zero)
return Vector3.Zero;
if (max < min)
(min, max) = (max, min);
return direction * Lerp(min, max, (float)_rng.NextDouble());
}
private float RandomScale(float baseValue, float rand)
=> Math.Clamp(baseValue + RandomCentered(rand), 0.1f, 10f);
private float RandomTrans(float baseValue, float rand)
=> Math.Clamp(baseValue + RandomCentered(rand), 0f, 1f);
private float RandomCentered(float halfWidth)
=> ((float)_rng.NextDouble() - 0.5f) * 2f * halfWidth;
private float RandomRange(float min, float max)
=> Lerp(min, max, (float)_rng.NextDouble());
private static float Lerp(float a, float b, float t) => a + (b - a) * t;
private static Vector3 NormalizeOrZero(Vector3 v)
=> v.LengthSquared() > 1e-8f ? Vector3.Normalize(v) : Vector3.Zero;
private static bool NormalizeCheckSmall(ref Vector3 v)
{
float length = v.Length();
if (length < 1e-8f)
return true;
v /= length;
return false;
}
private static Vector3 Perpendicular(Vector3 v)
{
Vector3 basis = MathF.Abs(v.X) < 0.9f ? Vector3.UnitX : Vector3.UnitY;
return Vector3.Normalize(Vector3.Cross(v, basis));
}
private static uint Color32(float alpha, uint startArgb, uint endArgb, float t)
{
// Blend RGB channels linearly; apply alpha override from fade.
byte sa = (byte)((startArgb >> 24) & 0xFF);
byte sr = (byte)((startArgb >> 16) & 0xFF);
byte sg = (byte)((startArgb >> 8) & 0xFF);
byte sb = (byte)( startArgb & 0xFF);
byte ea = (byte)((endArgb >> 24) & 0xFF);
byte sg = (byte)((startArgb >> 8) & 0xFF);
byte sb = (byte)(startArgb & 0xFF);
byte er = (byte)((endArgb >> 16) & 0xFF);
byte eg = (byte)((endArgb >> 8) & 0xFF);
byte eb = (byte)( endArgb & 0xFF);
byte eg = (byte)((endArgb >> 8) & 0xFF);
byte eb = (byte)(endArgb & 0xFF);
byte r = (byte)Math.Clamp(sr + (er - sr) * t, 0f, 255f);
byte g = (byte)Math.Clamp(sg + (eg - sg) * t, 0f, 255f);
byte b = (byte)Math.Clamp(sb + (eb - sb) * t, 0f, 255f);
byte a = (byte)Math.Clamp(alpha * 255f, 0f, 255f);
return ((uint)a << 24) | ((uint)r << 16) | ((uint)g << 8) | b;
}
private Vector3 RandomDiskVector(Vector3 axis, float maxRadius)
{
if (maxRadius <= 0f) return Vector3.Zero;
// Two perpendicular vectors to axis.
Vector3 n = Vector3.Normalize(axis == Vector3.Zero ? Vector3.UnitZ : axis);
Vector3 t1 = Math.Abs(n.X) < 0.9f
? Vector3.Normalize(Vector3.Cross(n, Vector3.UnitX))
: Vector3.Normalize(Vector3.Cross(n, Vector3.UnitY));
Vector3 t2 = Vector3.Normalize(Vector3.Cross(n, t1));
float theta = (float)(_rng.NextDouble() * Math.PI * 2.0);
float r = maxRadius * MathF.Sqrt((float)_rng.NextDouble());
return (t1 * MathF.Cos(theta) + t2 * MathF.Sin(theta)) * r;
}
private float RandomCentered(float halfWidth)
{
return ((float)_rng.NextDouble() - 0.5f) * 2f * halfWidth;
}
}

View file

@ -139,15 +139,7 @@ public sealed class PhysicsScriptRunner
_active.RemoveAt(i);
}
_active.Add(new ActiveScript
{
Script = script,
ScriptId = scriptId,
EntityId = entityId,
AnchorWorld = anchorWorldPos,
StartTimeAbs = _now,
NextHookIndex = 0,
});
AddActiveScript(script, scriptId, entityId, anchorWorldPos, delaySeconds: 0);
if (DiagEnabled)
{
@ -159,6 +151,24 @@ public sealed class PhysicsScriptRunner
return true;
}
private void AddActiveScript(
DatPhysicsScript script,
uint scriptId,
uint entityId,
Vector3 anchorWorldPos,
float delaySeconds)
{
_active.Add(new ActiveScript
{
Script = script,
ScriptId = scriptId,
EntityId = entityId,
AnchorWorld = anchorWorldPos,
StartTimeAbs = _now + Math.Max(0f, delaySeconds),
NextHookIndex = 0,
});
}
/// <summary>
/// Advance every active script by <paramref name="dtSeconds"/>.
/// Fires each hook whose <see cref="PhysicsScriptData.StartTime"/>
@ -233,18 +243,18 @@ public sealed class PhysicsScriptRunner
if (hook is CallPESHook call)
{
// CallPESHook.PES = sub-script id; Pause = delay before the
// sub-script starts (retail's ScriptManager links it into
// the list with StartTime = now + Pause). For our flat-list
// design we just recurse Play() — the sub-script schedules
// its own hooks from its own time zero. If Pause > 0 we
// delay by baking it into the sub-script's StartTimeAbs.
Play(call.PES, a.EntityId, a.AnchorWorld);
if (call.Pause > 0f && _active.Count > 0)
// sub-script starts. Retail links it into the active script
// list with StartTime = now + Pause; our flat list preserves
// that timing without replacing the currently running script.
var subScript = ResolveScript(call.PES);
if (subScript is null || subScript.ScriptData.Count == 0)
{
var sub = _active[^1];
sub.StartTimeAbs = _now + call.Pause;
_active[^1] = sub;
if (DiagEnabled)
Console.WriteLine($"[pes] CallPES: script 0x{call.PES:X8} not found / empty");
return;
}
AddActiveScript(subScript, call.PES, a.EntityId, a.AnchorWorld, call.Pause);
return;
}

View file

@ -4,90 +4,123 @@ using System.Numerics;
namespace AcDream.Core.Vfx;
// ─────────────────────────────────────────────────────────────────────
// Scaffold for R4 — VFX / particle system data model.
// Full research: docs/research/deepdives/r04-vfx-particles.md
// Runtime GPU batching lives in AcDream.App/Rendering/Vfx (Silk.NET GL).
// ─────────────────────────────────────────────────────────────────────
/// <summary>
/// 13 retail particle motion integrators. See r04 §1.
/// Parabolic variants apply gravity with different orientation/decay rules.
/// Retail particle motion integrators from <c>ParticleType</c> in
/// <c>acclient.h</c>. Values are the retail dat values.
/// </summary>
public enum ParticleType
{
Still = 0, // static, fades out in place
LocalVelocity = 1, // moves at its spawn velocity
Parabolic = 2, // gravity arc
ParabolicLVGV = 3, // local+global velocity parabolic
ParabolicLVGA = 4,
ParabolicLVLA = 5,
ParabolicGVGA = 6,
ParabolicGVLA = 7,
ParabolicLALV = 8,
Swarm = 9, // orbits spawn point with randomness
Explode = 10, // all particles push outward
Implode = 11, // all particles pull inward
GlobalVelocity = 12,
Unknown = 0,
Still = 1,
LocalVelocity = 2,
ParabolicLVGA = 3,
ParabolicLVGAGR = 4,
Swarm = 5,
Explode = 6,
Implode = 7,
ParabolicLVLA = 8,
ParabolicLVLALR = 9,
ParabolicGVGA = 10,
ParabolicGVGAGR = 11,
GlobalVelocity = 12,
NumParticleType = 13,
}
/// <summary>
/// Retail <c>EmitterType</c> from <c>acclient.h</c>.
/// </summary>
public enum ParticleEmitterKind
{
Unknown = 0,
BirthratePerSec = 1,
BirthratePerMeter = 2,
}
/// <summary>
/// Render stage for an active particle emitter.
/// </summary>
public enum ParticleRenderPass
{
Scene = 0,
SkyPreScene = 1,
SkyPostScene = 2,
}
[Flags]
public enum EmitterFlags : uint
{
None = 0,
Additive = 0x01, // blend mode: SrcAlpha / One (vs default SrcAlpha / InvSrcAlpha)
Billboard = 0x02,
None = 0,
Additive = 0x01,
Billboard = 0x02,
FaceCamera = 0x04,
AttachLocal= 0x08, // particles follow parent anchor frame
AttachLocal = 0x08,
}
/// <summary>
/// Per-emitter configuration from the <c>ParticleEmitterInfo</c> dat.
/// See r04 §1 + DatReaderWriter.ParticleEmitterInfo.
/// Per-emitter configuration from the retail <c>ParticleEmitterInfo</c>
/// dat object.
/// </summary>
public sealed class EmitterDesc
{
public uint DatId { get; init; }
public ParticleType Type { get; init; }
public EmitterFlags Flags { get; init; }
public uint TextureSurfaceId { get; init; } // 0x06xxxxxx
public uint SoundOnSpawn { get; init; }
public uint DatId { get; init; }
public ParticleType Type { get; init; }
public ParticleEmitterKind EmitterKind { get; init; } = ParticleEmitterKind.BirthratePerSec;
public EmitterFlags Flags { get; init; }
public uint TextureSurfaceId { get; init; }
public uint GfxObjId { get; init; }
public uint HwGfxObjId { get; init; }
public uint SoundOnSpawn { get; init; }
// Emission behavior
public float EmitRate { get; init; } // particles / sec
public int MaxParticles { get; init; }
public float LifetimeMin { get; init; }
public float LifetimeMax { get; init; }
public float StartDelay { get; init; }
public float TotalDuration { get; init; } // 0 = infinite
// Emission behavior.
public float Birthrate { get; init; }
public float EmitRate { get; init; }
public int MaxParticles { get; init; }
public int InitialParticles { get; init; }
public int TotalParticles { get; init; }
public float LifetimeMin { get; init; }
public float LifetimeMax { get; init; }
public float Lifespan { get; init; }
public float LifespanRand { get; init; }
public float StartDelay { get; init; }
public float TotalDuration { get; init; }
// Spawn geometry (disk annulus perpendicular to OffsetDir)
public Vector3 OffsetDir { get; init; } = new(0, 0, 1);
public float MinOffset { get; init; }
public float MaxOffset { get; init; }
public float SpawnDiskRadius { get; init; }
// Spawn geometry.
public Vector3 OffsetDir { get; init; } = new(0, 0, 1);
public float MinOffset { get; init; }
public float MaxOffset { get; init; }
public float SpawnDiskRadius { get; init; }
// Initial kinematics
public Vector3 InitialVelocity { get; init; }
public float VelocityJitter { get; init; }
public Vector3 Gravity { get; init; } = new(0, 0, -9.8f);
// Kinematics. A/B/C are the retail vector coefficients.
public Vector3 InitialVelocity { get; init; }
public float VelocityJitter { get; init; }
public Vector3 Gravity { get; init; } = new(0, 0, -9.8f);
public Vector3 A { get; init; }
public float MinA { get; init; } = 1f;
public float MaxA { get; init; } = 1f;
public Vector3 B { get; init; }
public float MinB { get; init; } = 1f;
public float MaxB { get; init; } = 1f;
public Vector3 C { get; init; }
public float MinC { get; init; } = 1f;
public float MaxC { get; init; } = 1f;
// Appearance over lifetime (retail: start + end, linearly interpolated)
public uint StartColorArgb { get; init; } = 0xFFFFFFFF;
public uint EndColorArgb { get; init; } = 0xFFFFFFFF;
public float StartAlpha { get; init; } = 1f;
public float EndAlpha { get; init; } = 0f;
public float StartSize { get; init; } = 0.5f;
public float EndSize { get; init; } = 0.5f;
public float StartRotation { get; init; }
public float EndRotation { get; init; }
// Appearance over lifetime.
public uint StartColorArgb { get; init; } = 0xFFFFFFFF;
public uint EndColorArgb { get; init; } = 0xFFFFFFFF;
public float StartAlpha { get; init; } = 1f;
public float EndAlpha { get; init; } = 0f;
public float StartSize { get; init; } = 0.5f;
public float EndSize { get; init; } = 0.5f;
public float ScaleRand { get; init; }
public float TransRand { get; init; }
public float StartRotation { get; init; }
public float EndRotation { get; init; }
}
/// <summary>
/// A PhysicsScript (0x3Axxxxxx range in retail) is a list of hooks to
/// fire at specific start-times. Each hook creates an emitter or plays
/// a sound. Chaining hooks at different times gives "animation".
/// See r04 §6.
/// </summary>
public sealed class PhysicsScript
{
@ -98,34 +131,43 @@ public sealed class PhysicsScript
public sealed record PhysicsScriptHook(
float StartTime,
PhysicsScriptHookType Type,
uint RefDataId, // EmitterInfo / Sound / PartTransform
int PartIndex, // attach to this part
uint RefDataId,
int PartIndex,
Vector3 Offset,
bool IsParentLocal);
public enum PhysicsScriptHookType
{
CreateParticle = 18, // matches retail animation-hook type
DestroyParticle= 19,
PlaySound = 1,
AnimationDone = 2,
CreateParticle = 18,
DestroyParticle = 19,
PlaySound = 1,
AnimationDone = 2,
}
/// <summary>
/// Individual runtime particle. Owned by the <c>ParticleSystem</c>;
/// advanced per-frame.
/// Individual runtime particle. Owned by the <c>ParticleSystem</c>.
/// </summary>
public struct Particle
{
public Vector3 Position;
public Vector3 Velocity;
public float SpawnedAt;
public float Lifetime; // seconds
public float Age;
public uint ColorArgb; // current
public float Size;
public float Rotation;
public bool Alive;
public Vector3 EmissionOrigin;
public Quaternion SpawnRotation;
public Vector3 Position;
public Vector3 Velocity;
public Vector3 Offset;
public Vector3 A;
public Vector3 B;
public Vector3 C;
public float SpawnedAt;
public float Lifetime;
public float Age;
public float StartSize;
public float EndSize;
public float StartAlpha;
public float EndAlpha;
public uint ColorArgb;
public float Size;
public float Rotation;
public bool Alive;
}
/// <summary>
@ -134,16 +176,20 @@ public struct Particle
/// </summary>
public sealed class ParticleEmitter
{
public EmitterDesc Desc { get; init; } = null!;
public Vector3 AnchorPos { get; set; }
public Quaternion AnchorRot { get; set; } = Quaternion.Identity;
public uint AttachedObjectId { get; set; } // 0 = world-space only
public int AttachedPartIndex { get; set; } = -1;
public Particle[] Particles { get; init; } = null!;
public int ActiveCount;
public float EmittedAccumulator; // fractional particles pending
public float StartedAt; // game-time seconds
public bool Finished;
public EmitterDesc Desc { get; init; } = null!;
public Vector3 AnchorPos { get; set; }
public Quaternion AnchorRot { get; set; } = Quaternion.Identity;
public uint AttachedObjectId { get; set; }
public int AttachedPartIndex { get; set; } = -1;
public Particle[] Particles { get; init; } = null!;
public ParticleRenderPass RenderPass { get; init; }
public int ActiveCount;
public float EmittedAccumulator;
public float StartedAt;
public float LastEmitTime;
public Vector3 LastEmitOffset;
public int TotalEmitted;
public bool Finished;
}
/// <summary>
@ -151,20 +197,25 @@ public sealed class ParticleEmitter
/// </summary>
public interface IParticleSystem
{
/// <summary>Spawn an emitter attached to a world position (or entity).</summary>
int SpawnEmitter(EmitterDesc desc, Vector3 anchor, Quaternion? rot = null,
uint attachedObjectId = 0, int attachedPartIndex = -1);
/// <summary>Spawn an emitter attached to a world position or entity.</summary>
int SpawnEmitter(
EmitterDesc desc,
Vector3 anchor,
Quaternion? rot = null,
uint attachedObjectId = 0,
int attachedPartIndex = -1,
ParticleRenderPass renderPass = ParticleRenderPass.Scene);
/// <summary>Fire a full PhysicsScript at a target (the retail PlayScript dispatch).</summary>
/// <summary>Fire a full PhysicsScript at a target.</summary>
void PlayScript(uint scriptId, uint targetObjectId, float modifier = 1f);
/// <summary>Advance all active emitters by dt seconds.</summary>
void Tick(float dt);
/// <summary>Stop an emitter early (e.g. cast interrupted).</summary>
/// <summary>Stop an emitter early.</summary>
void StopEmitter(int handle, bool fadeOut);
/// <summary>Current active particle count (for HUD stats).</summary>
/// <summary>Current active particle count.</summary>
int ActiveParticleCount { get; }
int ActiveEmitterCount { get; }
int ActiveEmitterCount { get; }
}

View file

@ -34,6 +34,7 @@ public sealed class SkyObjectData
public float TexVelocityX;
public float TexVelocityY;
public uint GfxObjId;
public uint PesObjectId;
public uint Properties;
/// <summary>
@ -531,6 +532,7 @@ public static class SkyDescLoader
TexVelocityX = s.TexVelocityX,
TexVelocityY = s.TexVelocityY,
GfxObjId = s.DefaultGfxObjectId?.DataId ?? 0u,
PesObjectId = s.DefaultPesObjectId?.DataId ?? 0u,
Properties = s.Properties,
};