perf(vfx): port retail particle visibility degradation

Resolve DAT-authored particle ranges from the hardware GfxObj, apply retail distance and completed-cell visibility gates, and preserve the exact finite/infinite off-view update semantics. This removes dense-world simulation work without shortening terrain, entity, fog, or streaming distance.

Publish doorway-clipped outdoor cells through a focused frame controller, retain effect cell identity for outdoor statics, reject hidden emitters before particle-slot scans, and offer an explicit opt-in Extended particle range.

Release build succeeds and all 5,857 tests pass with five intentional skips. Retail-conformance, architecture, and adversarial review cycles are clean; connected Aerlinthe visual/performance gate pending.

Co-authored-by: OpenAI Codex <codex@openai.com>
This commit is contained in:
Erik 2026-07-17 15:27:36 +02:00
parent 82789eea88
commit f1ba147ac5
29 changed files with 1810 additions and 125 deletions

View file

@ -361,6 +361,7 @@ public sealed class GameWindow : IDisposable
private AcDream.Core.Vfx.EmitterDescRegistry? _emitterRegistry;
private AcDream.Core.Vfx.ParticleSystem? _particleSystem;
private AcDream.Core.Vfx.ParticleHookSink? _particleSink;
private readonly AcDream.App.Rendering.Vfx.ParticleVisibilityController _particleVisibility = new();
private readonly AcDream.App.Rendering.Vfx.EntityEffectPoseRegistry _effectPoses = new();
private AcDream.App.Rendering.Vfx.AnimationHookFrameQueue? _animationHookFrames;
// Phase 6 — retail PhysicsScript runtime. Receives PlayScript (0xF754)
@ -2868,6 +2869,7 @@ public sealed class GameWindow : IDisposable
_itemInteractionController?.ClearBusy();
_selection.Reset();
_pendingPostArrivalAction = null;
_particleVisibility.Reset();
try
{
_liveEntities?.Clear();
@ -7544,6 +7546,7 @@ public sealed class GameWindow : IDisposable
Position = e.Position + worldOffset,
Rotation = e.Rotation,
MeshRefs = meshRefs,
EffectCellId = e.EffectCellId,
IsBuildingShell = e.IsBuildingShell, // Phase A8: preserve dat-level tag
BuildingShellAnchorCellId = e.BuildingShellAnchorCellId,
};
@ -7870,6 +7873,10 @@ public sealed class GameWindow : IDisposable
Rotation = spawn.Rotation,
MeshRefs = meshRefs,
Scale = spawn.Scale,
EffectCellId = AcDream.Core.Physics.TerrainSurface.ComputeOutdoorCellId(
lb.LandblockId,
localX,
localY),
};
if (sceneryBounds.TryGet(out var scbMin, out var scbMax))
hydrated.SetLocalBounds(scbMin, scbMax);
@ -9502,6 +9509,8 @@ public sealed class GameWindow : IDisposable
// normal SmartBox viewport and UIElement_Viewport's portal
// CreatureMode; it does not redraw the world behind portal space.
bool portalViewportVisible = _portalTunnel?.IsVisible == true;
if (portalViewportVisible)
_particleVisibility.Reset();
// Phase G.1: set the clear color from the current sky's fog
// tint so the horizon band continues naturally past the
@ -9623,6 +9632,10 @@ public sealed class GameWindow : IDisposable
// and by the sky renderer (for the camera-centered sky dome).
System.Numerics.Matrix4x4.Invert(camera.View, out var invView);
var camPos = new System.Numerics.Vector3(invView.M41, invView.M42, invView.M43);
_particleVisibility.BeginFrame(camPos);
_terrain?.BeginVisibilityFrame();
if (!IsLiveModeWaitingForLogin)
_particleVisibility.UseWorldView();
// L.0 Audio tab: push the SettingsVM's live AudioDraft into the
// engine each frame, so volume sliders preview audibly while
@ -10205,6 +10218,7 @@ public sealed class GameWindow : IDisposable
clipAssembly = pviewResult.ClipAssembly;
envCellShellFilter = pviewResult.DrawableCells;
_interiorPartition = pviewResult.Partition;
_particleVisibility.MarkVisibleCells(pviewResult.DrawableCells);
// A7.L1: snapshot this frame's drawn cell set for NEXT frame's light-
// pool scoping. DrawableCells is the renderer's own reused scratch set
@ -10517,7 +10531,10 @@ public sealed class GameWindow : IDisposable
// below. Sky has already drawn before this label so the
// pre-login screen shows a live, correctly-tinted sky and
// nothing else.
SkipWorldGeometry: ;
SkipWorldGeometry:
if (_terrain is not null)
_particleVisibility.MarkVisibleCells(_terrain.VisibleCellIds);
_particleVisibility.CompleteFrame();
}
// Retail gmSmartBoxUI swaps the world SmartBox viewport for a
@ -10734,6 +10751,17 @@ public sealed class GameWindow : IDisposable
_particleSink?.RefreshAttachedEmitters();
_liveEntityLights?.Refresh();
if (_particleSystem is not null)
{
var particleRange = _settingsVm?.DisplayDraft.ParticleRange
?? _persistedDisplay.ParticleRange;
float rangeMultiplier = particleRange
== AcDream.UI.Abstractions.Panels.Settings.ParticleRange.Extended
? AcDream.App.Rendering.Vfx.ParticleVisibilityController.ExtendedRangeMultiplier
: 1f;
_particleVisibility.Apply(_particleSystem, rangeMultiplier);
}
// Retail CPhysicsObj::UpdateObjectInternal (0x005156B0) advances
// ParticleManager before ScriptManager. A particle created by a PES
// hook therefore begins simulation on the following object frame.
@ -11527,7 +11555,12 @@ public sealed class GameWindow : IDisposable
EnableClipDistances();
_terrainCpuStopwatch.Restart();
_terrain?.Draw(camera, frustum, neverCullLandblockId: playerLb);
_terrain?.Draw(
camera,
frustum,
neverCullLandblockId: playerLb,
clipPlanes: slice.Planes,
ndcClipAabb: slice.NdcAabb);
_terrainCpuStopwatch.Stop();
_terrainCpuSamples[_terrainCpuSampleCursor] =
(long)(_terrainCpuStopwatch.Elapsed.TotalMicroseconds * 100.0);

View file

@ -395,61 +395,66 @@ public sealed unsafe class ParticleRenderer : IDisposable
_meshDrawListScratch.Clear();
_submissionScratch.Clear();
int sequence = 0;
foreach (var (em, idx) in _particles.EnumerateLive())
foreach (var em in _particles.EnumerateEmitters())
{
if (!em.PresentationVisible)
if (!em.PresentationVisible || !em.ViewEligible)
continue;
if (em.RenderPass != renderPass)
continue;
if (emitterFilter is not null && !emitterFilter(em))
continue;
ref var p = ref em.Particles[idx];
// `p.Position` is already in world coordinates: AttachLocal
// emitters get their AnchorPos refreshed each frame by the
// owning subsystem (sky-PES driver, animation tick, etc.) which
// mirrors retail's live-parent-frame read at
// ParticleEmitter::UpdateParticles 0x0051d2d4 for is_parent_local=1.
Vector3 pos = p.Position;
float distSq = Vector3.DistanceSquared(pos, cameraWorldPos);
uint gfxObjId = em.Desc.HwGfxObjId != 0 ? em.Desc.HwGfxObjId : em.Desc.GfxObjId;
if (gfxObjId != 0
&& ResolveGeometryKind(gfxObjId) == RetailParticleGeometryKind.FullMesh
&& TryAppendMeshDraws(em, p, gfxObjId, distSq, ref sequence))
for (int idx = 0; idx < em.Particles.Length; idx++)
{
continue;
}
ref var p = ref em.Particles[idx];
if (!p.Alive)
continue;
// `p.Position` is already in world coordinates: AttachLocal
// emitters get their AnchorPos refreshed each frame by the
// owning subsystem (sky-PES driver, animation tick, etc.) which
// mirrors retail's live-parent-frame read at
// ParticleEmitter::UpdateParticles 0x0051d2d4 for is_parent_local=1.
Vector3 pos = p.Position;
float distSq = Vector3.DistanceSquared(pos, cameraWorldPos);
uint gfxObjId = em.Desc.HwGfxObjId != 0 ? em.Desc.HwGfxObjId : em.Desc.GfxObjId;
if (gfxObjId != 0
&& ResolveGeometryKind(gfxObjId) == RetailParticleGeometryKind.FullMesh
&& TryAppendMeshDraws(em, p, gfxObjId, distSq, ref sequence))
{
continue;
}
var gfxInfo = ResolveParticleGfxInfo(em.Desc);
uint texture = gfxInfo.TextureHandle;
bool useTexture = texture != 0;
bool additive = gfxInfo.HasMaterial
? gfxInfo.Additive
: (em.Desc.Flags & EmitterFlags.Additive) != 0;
var key = new BatchKey(texture, useTexture, additive);
Vector3 axisX;
Vector3 axisY;
if (gfxInfo.IsBillboard)
{
pos += Vector3.UnitZ * (gfxInfo.CenterOffset.Z * p.Size);
axisX = cameraRight * (gfxInfo.Size.X * p.Size);
axisY = cameraUp * (gfxInfo.Size.Y * p.Size);
}
else
{
Quaternion orientation = ParticleOrientation(em, p);
pos += Vector3.Transform(gfxInfo.CenterOffset * p.Size, orientation);
axisX = Vector3.Transform(gfxInfo.AxisX, orientation) * (gfxInfo.Size.X * p.Size);
axisY = Vector3.Transform(gfxInfo.AxisY, orientation) * (gfxInfo.Size.Y * p.Size);
}
var gfxInfo = ResolveParticleGfxInfo(em.Desc);
uint texture = gfxInfo.TextureHandle;
bool useTexture = texture != 0;
bool additive = gfxInfo.HasMaterial
? gfxInfo.Additive
: (em.Desc.Flags & EmitterFlags.Additive) != 0;
var key = new BatchKey(texture, useTexture, additive);
Vector3 axisX;
Vector3 axisY;
if (gfxInfo.IsBillboard)
{
pos += Vector3.UnitZ * (gfxInfo.CenterOffset.Z * p.Size);
axisX = cameraRight * (gfxInfo.Size.X * p.Size);
axisY = cameraUp * (gfxInfo.Size.Y * p.Size);
}
else
{
Quaternion orientation = ParticleOrientation(em, p);
pos += Vector3.Transform(gfxInfo.CenterOffset * p.Size, orientation);
axisX = Vector3.Transform(gfxInfo.AxisX, orientation) * (gfxInfo.Size.X * p.Size);
axisY = Vector3.Transform(gfxInfo.AxisY, orientation) * (gfxInfo.Size.Y * p.Size);
}
int drawIndex = draws.Count;
draws.Add(new ParticleDraw(key, new ParticleInstance(pos, axisX, axisY, p.ColorArgb, distSq)));
_submissionScratch.Add(new ParticleSubmission(
ParticleSubmissionKind.Billboard,
drawIndex,
distSq,
sequence++));
int drawIndex = draws.Count;
draws.Add(new ParticleDraw(key, new ParticleInstance(pos, axisX, axisY, p.ColorArgb, distSq)));
_submissionScratch.Add(new ParticleSubmission(
ParticleSubmissionKind.Billboard,
drawIndex,
distSq,
sequence++));
}
}
}

View file

@ -69,12 +69,21 @@ public sealed unsafe class TerrainModernRenderer : IDisposable
// Reusable per-frame buffers.
private readonly List<int> _visibleSlots = new();
private readonly HashSet<uint> _visibleCellIds = new();
private DrawElementsIndirectCommand[] _deicScratch = Array.Empty<DrawElementsIndirectCommand>();
// Diag.
public int LoadedSlots => _alloc.LoadedCount;
public int VisibleSlots => _visibleSlots.Count;
public int CapacitySlots => _alloc.Capacity;
/// <summary>
/// Outdoor landcells admitted by the current landscape view. The set is
/// accumulated across doorway landscape slices and consumed after the
/// completed render frame by particle visibility.
/// </summary>
internal HashSet<uint> VisibleCellIds => _visibleCellIds;
public void BeginVisibilityFrame() => _visibleCellIds.Clear();
public TerrainModernRenderer(
GL gl,
@ -208,10 +217,17 @@ public sealed unsafe class TerrainModernRenderer : IDisposable
// No GPU clear: the per-frame DEIC array won't reference this slot.
}
public void Draw(ICamera camera, FrustumPlanes? frustum = null, uint? neverCullLandblockId = null)
public void Draw(
ICamera camera,
FrustumPlanes? frustum = null,
uint? neverCullLandblockId = null,
ReadOnlySpan<Vector4> clipPlanes = default,
Vector4? ndcClipAabb = null)
{
if (_alloc.LoadedCount == 0) return;
Matrix4x4 viewProjection = camera.View * camera.Projection;
// Build visible slot list with per-slot frustum cull.
_visibleSlots.Clear();
for (int slot = 0; slot < _slots.Length; slot++)
@ -224,6 +240,16 @@ public sealed unsafe class TerrainModernRenderer : IDisposable
continue;
}
_visibleSlots.Add(slot);
CollectVisibleCells(
_visibleCellIds,
data.LandblockId,
data.WorldOrigin,
data.AabbMin.Z,
data.AabbMax.Z,
frustum,
viewProjection,
clipPlanes,
ndcClipAabb);
}
if (_visibleSlots.Count == 0) return;
@ -436,6 +462,130 @@ public sealed unsafe class TerrainModernRenderer : IDisposable
_gl.BindVertexArray(0);
}
internal static void CollectVisibleCells(
HashSet<uint> destination,
uint landblockId,
Vector3 worldOrigin,
float zMin,
float zMax,
FrustumPlanes? frustum,
Matrix4x4 viewProjection,
ReadOnlySpan<Vector4> clipPlanes,
Vector4? ndcClipAabb = null)
{
ArgumentNullException.ThrowIfNull(destination);
const float cellSize = AcDream.Core.Physics.TerrainSurface.CellSize;
const int cellsPerSide = AcDream.Core.Physics.TerrainSurface.CellsPerSide;
uint prefix = landblockId & 0xFFFF0000u;
for (int cellX = 0; cellX < cellsPerSide; cellX++)
{
float minX = worldOrigin.X + cellX * cellSize;
float maxX = minX + cellSize;
for (int cellY = 0; cellY < cellsPerSide; cellY++)
{
float minY = worldOrigin.Y + cellY * cellSize;
float maxY = minY + cellSize;
var cellMin = new Vector3(minX, minY, zMin);
var cellMax = new Vector3(maxX, maxY, zMax);
if (frustum is not null
&& !FrustumCuller.IsAabbVisible(frustum.Value, cellMin, cellMax))
{
continue;
}
// Retail publishes landcell in_view from the clipped landscape
// view, not merely from the camera frustum. The modern renderer
// expresses each doorway slice as homogeneous clip-space planes
// plus its scissor AABB; use both products here so particle
// simulation follows the same visible terrain slice as the GPU.
if (!IsAabbVisibleThroughClipRegion(
cellMin,
cellMax,
viewProjection,
clipPlanes,
ndcClipAabb))
{
continue;
}
uint low = AcDream.Core.Physics.TerrainSurface.ComputeOutdoorCellLowId(
cellX * cellSize,
cellY * cellSize);
destination.Add(prefix | low);
}
}
}
private static bool IsAabbVisibleThroughClipRegion(
Vector3 min,
Vector3 max,
Matrix4x4 viewProjection,
ReadOnlySpan<Vector4> clipPlanes,
Vector4? ndcClipAabb)
{
Vector4 aabb = ndcClipAabb.GetValueOrDefault();
bool hasScissorConstraint = ndcClipAabb.HasValue
&& (aabb.X > -1f || aabb.Y > -1f || aabb.Z < 1f || aabb.W < 1f);
if (clipPlanes.IsEmpty && !hasScissorConstraint)
return true;
Span<Vector4> clipCorners = stackalloc Vector4[8];
for (int corner = 0; corner < clipCorners.Length; corner++)
{
var world = new Vector4(
(corner & 1) == 0 ? min.X : max.X,
(corner & 2) == 0 ? min.Y : max.Y,
(corner & 4) == 0 ? min.Z : max.Z,
1f);
clipCorners[corner] = Vector4.Transform(world, viewProjection);
}
for (int planeIndex = 0; planeIndex < clipPlanes.Length; planeIndex++)
{
if (IsAabbOutsideHomogeneousPlane(clipCorners, clipPlanes[planeIndex]))
{
return false;
}
}
if (!hasScissorConstraint)
return true;
Span<Vector4> scissorPlanes = stackalloc Vector4[4]
{
new( 1f, 0f, 0f, -aabb.X),
new(-1f, 0f, 0f, aabb.Z),
new( 0f, 1f, 0f, -aabb.Y),
new( 0f, -1f, 0f, aabb.W),
};
for (int planeIndex = 0; planeIndex < scissorPlanes.Length; planeIndex++)
{
if (IsAabbOutsideHomogeneousPlane(clipCorners, scissorPlanes[planeIndex]))
{
return false;
}
}
return true;
}
private static bool IsAabbOutsideHomogeneousPlane(
ReadOnlySpan<Vector4> clipCorners,
Vector4 plane)
{
// A linear half-space reaches its maximum over the transformed AABB at
// one of the eight corners. If every corner is negative, no point in
// the cell box can survive this GPU clip plane.
for (int corner = 0; corner < clipCorners.Length; corner++)
{
if (Vector4.Dot(plane, clipCorners[corner]) >= 0f)
return false;
}
return true;
}
private void EnsureCapacity(int newCapacity)
{
if (newCapacity <= _alloc.Capacity) return;

View file

@ -45,7 +45,7 @@ public sealed class EntityEffectPoseRegistry : IEntityEffectPoseSource, IEntityE
Matrix4x4.CreateFromQuaternion(entity.Rotation)
* Matrix4x4.CreateTranslation(entity.Position),
partLocal,
entity.ParentCellId ?? 0u,
entity.EffectCellId ?? entity.ParentCellId ?? 0u,
availability);
}
@ -67,7 +67,7 @@ public sealed class EntityEffectPoseRegistry : IEntityEffectPoseSource, IEntityE
}
record.RootWorld = rootWorld;
record.CellId = entity.ParentCellId ?? 0u;
record.CellId = entity.EffectCellId ?? entity.ParentCellId ?? 0u;
if (entity.IndexedPartTransforms.Count > 0)
{
CopyParts(
@ -119,7 +119,7 @@ public sealed class EntityEffectPoseRegistry : IEntityEffectPoseSource, IEntityE
return false;
record.RootWorld = Matrix4x4.CreateFromQuaternion(entity.Rotation)
* Matrix4x4.CreateTranslation(entity.Position);
record.CellId = entity.ParentCellId ?? 0u;
record.CellId = entity.EffectCellId ?? entity.ParentCellId ?? 0u;
return true;
}

View file

@ -0,0 +1,93 @@
using System.Numerics;
using AcDream.Core.Vfx;
namespace AcDream.App.Rendering.Vfx;
/// <summary>
/// Bridges the retained retail PView result into the next physics update's
/// <c>CObjCell::IsInView</c> particle gate. The controller owns only immutable
/// frame meaning: one completed viewer position plus the AC cells admitted by
/// that completed view. It neither creates emitters nor performs rendering.
/// </summary>
public sealed class ParticleVisibilityController
{
public const float ExtendedRangeMultiplier = 2f;
private readonly HashSet<uint> _buildingCellIds = new();
private readonly HashSet<uint> _completedCellIds = new();
private Vector3 _buildingViewerPosition;
private Vector3 _completedViewerPosition;
private bool _frameOpen;
private bool _frameUsesWorldView;
private bool _hasCompletedWorldView;
public void BeginFrame(Vector3 viewerPosition)
{
_buildingCellIds.Clear();
_buildingViewerPosition = viewerPosition;
_frameUsesWorldView = false;
_frameOpen = true;
}
/// <summary>
/// Declares that this frame has an authoritative world-visibility product.
/// That product can come from the unified retail PView or from the outdoor
/// landscape fallback. Login and portal-space frames deliberately omit it;
/// dedicated pass and examination emitters carry explicit bypass policies.
/// </summary>
public void UseWorldView()
{
if (_frameOpen)
_frameUsesWorldView = true;
}
public void MarkVisibleCells(HashSet<uint> cellIds)
{
ArgumentNullException.ThrowIfNull(cellIds);
if (!_frameOpen || !_frameUsesWorldView)
return;
_buildingCellIds.UnionWith(cellIds);
}
public void CompleteFrame()
{
if (!_frameOpen)
return;
_frameOpen = false;
if (!_frameUsesWorldView)
{
_completedCellIds.Clear();
_completedViewerPosition = _buildingViewerPosition;
_hasCompletedWorldView = false;
return;
}
_completedCellIds.Clear();
_completedCellIds.UnionWith(_buildingCellIds);
_completedViewerPosition = _buildingViewerPosition;
_hasCompletedWorldView = true;
}
public void Apply(ParticleSystem particles, float rangeMultiplier)
{
ArgumentNullException.ThrowIfNull(particles);
particles.ApplyRetailView(
_completedViewerPosition,
_completedCellIds,
_hasCompletedWorldView,
rangeMultiplier);
}
public void Reset()
{
_buildingCellIds.Clear();
_completedCellIds.Clear();
_frameOpen = false;
_frameUsesWorldView = false;
_hasCompletedWorldView = false;
_buildingViewerPosition = default;
_completedViewerPosition = default;
}
}