fix(rendering): bound portal resource lifetime
Separate logical ownership, render publication, and GPU retirement across live entities, landblocks, particles, textures, mesh arenas, portal/UI teardown, and per-frame scratch storage. Add bounded DAT/texture caches, upload budgets, three-frame fence retirement, exact-incarnation appearance reconciliation, frame pacing, and extensive lifetime conformance coverage.\n\nThe seven-destination connected route now cuts peak working/private memory roughly in half, returns Caul to 125-153 FPS locally, and produces no WER or AMD reset.\n\nCo-authored-by: OpenAI Codex <codex@openai.com>
This commit is contained in:
parent
3971997689
commit
749e8ceeb1
225 changed files with 29107 additions and 3914 deletions
|
|
@ -1,4 +1,5 @@
|
|||
using AcDream.Content.Vfx;
|
||||
using AcDream.Content;
|
||||
using AcDream.Core.Physics;
|
||||
using AcDream.Core.Tests.Conformance;
|
||||
using DatReaderWriter;
|
||||
|
|
@ -48,12 +49,13 @@ public sealed class HumanoidMotionTableRootMotionTests
|
|||
return;
|
||||
|
||||
using var dats = new DatCollection(datDir, DatAccessType.Read);
|
||||
using var boundedDats = new DatCollectionAdapter(dats);
|
||||
Setup setup = Assert.IsType<Setup>(dats.Get<Setup>(HumanoidSetup));
|
||||
MotionTable table = Assert.IsType<MotionTable>(dats.Get<MotionTable>(HumanoidMotionTable));
|
||||
var sequencer = new AnimationSequencer(
|
||||
setup,
|
||||
table,
|
||||
new RetailAnimationLoader(dats));
|
||||
new RetailAnimationLoader(boundedDats));
|
||||
|
||||
sequencer.SetCycle(NonCombatStyle, Ready);
|
||||
sequencer.SetCycle(NonCombatStyle, InterpretedWalkForward);
|
||||
|
|
|
|||
|
|
@ -84,4 +84,121 @@ public class WorldEventsTests
|
|||
Assert.Contains(1u, seen);
|
||||
Assert.Contains(3u, seen);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RehydratedEntity_ReplacesReplaySnapshotInsteadOfAppendingHistory()
|
||||
{
|
||||
var events = new WorldEvents();
|
||||
events.FireEntitySpawned(S(1));
|
||||
events.FireEntitySpawned(S(1) with { SourceId = 0x01000001u });
|
||||
|
||||
var seen = new List<WorldEntitySnapshot>();
|
||||
events.EntitySpawned += seen.Add;
|
||||
|
||||
WorldEntitySnapshot replay = Assert.Single(seen);
|
||||
Assert.Equal(0x01000001u, replay.SourceId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ForgottenEntity_IsNotReplayedToLateSubscriber()
|
||||
{
|
||||
var events = new WorldEvents();
|
||||
events.FireEntitySpawned(S(1));
|
||||
events.FireEntitySpawned(S(2));
|
||||
|
||||
Assert.True(events.ForgetEntity(1));
|
||||
|
||||
var seen = new List<uint>();
|
||||
events.EntitySpawned += e => seen.Add(e.Id);
|
||||
Assert.Equal(new uint[] { 2 }, seen);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ClearCurrent_LeavesNoReplayHistory()
|
||||
{
|
||||
var events = new WorldEvents();
|
||||
events.FireEntitySpawned(S(1));
|
||||
events.FireEntitySpawned(S(2));
|
||||
events.ClearCurrent();
|
||||
|
||||
var seen = new List<uint>();
|
||||
events.EntitySpawned += e => seen.Add(e.Id);
|
||||
Assert.Empty(seen);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task LiveEventDuringReplay_IsDeliveredAfterSnapshotWithoutStaleReordering()
|
||||
{
|
||||
var events = new WorldEvents();
|
||||
events.FireEntitySpawned(S(1));
|
||||
using var replayEntered = new ManualResetEventSlim();
|
||||
using var releaseReplay = new ManualResetEventSlim();
|
||||
var seen = new List<uint>();
|
||||
Action<WorldEntitySnapshot> handler = snapshot =>
|
||||
{
|
||||
lock (seen)
|
||||
seen.Add(snapshot.SourceId);
|
||||
if (snapshot.SourceId == 0x01000000u)
|
||||
{
|
||||
replayEntered.Set();
|
||||
releaseReplay.Wait();
|
||||
}
|
||||
};
|
||||
|
||||
Task subscribe = Task.Run(() => events.EntitySpawned += handler);
|
||||
Assert.True(replayEntered.Wait(5_000));
|
||||
events.FireEntitySpawned(S(1) with { SourceId = 0x01000001u });
|
||||
releaseReplay.Set();
|
||||
await subscribe;
|
||||
|
||||
lock (seen)
|
||||
Assert.Equal(new uint[] { 0x01000000u, 0x01000001u }, seen);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearCurrent_DropsLiveEventsQueuedBehindAnActiveReplay()
|
||||
{
|
||||
var events = new WorldEvents();
|
||||
events.FireEntitySpawned(S(1));
|
||||
using var replayEntered = new ManualResetEventSlim();
|
||||
using var releaseReplay = new ManualResetEventSlim();
|
||||
var seen = new List<uint>();
|
||||
Action<WorldEntitySnapshot> handler = snapshot =>
|
||||
{
|
||||
lock (seen)
|
||||
seen.Add(snapshot.Id);
|
||||
if (snapshot.Id == 1)
|
||||
{
|
||||
replayEntered.Set();
|
||||
releaseReplay.Wait();
|
||||
}
|
||||
};
|
||||
|
||||
Task subscribe = Task.Run(() => events.EntitySpawned += handler);
|
||||
Assert.True(replayEntered.Wait(5_000));
|
||||
events.FireEntitySpawned(S(2));
|
||||
events.ClearCurrent();
|
||||
releaseReplay.Set();
|
||||
await subscribe;
|
||||
|
||||
lock (seen)
|
||||
Assert.Equal(new uint[] { 1 }, seen);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UpsertCurrent_RestoresLateReplayWithoutNotifyingExistingSubscriber()
|
||||
{
|
||||
var events = new WorldEvents();
|
||||
var existing = new List<uint>();
|
||||
events.EntitySpawned += snapshot => existing.Add(snapshot.Id);
|
||||
events.FireEntitySpawned(S(1));
|
||||
events.ForgetEntity(1);
|
||||
|
||||
events.UpsertCurrent(S(1) with { SourceId = 0x01000001u });
|
||||
|
||||
Assert.Equal(new uint[] { 1 }, existing);
|
||||
var late = new List<WorldEntitySnapshot>();
|
||||
events.EntitySpawned += late.Add;
|
||||
Assert.Equal(0x01000001u, Assert.Single(late).SourceId);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
50
tests/AcDream.Core.Tests/Plugins/WorldGameStateTests.cs
Normal file
50
tests/AcDream.Core.Tests/Plugins/WorldGameStateTests.cs
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
using System.Numerics;
|
||||
using AcDream.Core.Plugins;
|
||||
using AcDream.Plugin.Abstractions;
|
||||
|
||||
namespace AcDream.Core.Tests.Plugins;
|
||||
|
||||
public sealed class WorldGameStateTests
|
||||
{
|
||||
private static WorldEntitySnapshot S(uint id, uint sourceId = 0x01000000u) =>
|
||||
new(id, sourceId, Vector3.Zero, Quaternion.Identity);
|
||||
|
||||
[Fact]
|
||||
public void Add_ReplacesExistingProjectionById()
|
||||
{
|
||||
var state = new WorldGameState();
|
||||
state.Add(S(1));
|
||||
state.Add(S(1, 0x01000001u));
|
||||
|
||||
WorldEntitySnapshot current = Assert.Single(state.Entities);
|
||||
Assert.Equal(0x01000001u, current.SourceId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RemoveById_CompactsIndexWithoutLosingOtherEntities()
|
||||
{
|
||||
var state = new WorldGameState();
|
||||
state.Add(S(1));
|
||||
state.Add(S(2));
|
||||
state.Add(S(3));
|
||||
|
||||
Assert.True(state.RemoveById(2));
|
||||
state.Add(S(3, 0x01000003u));
|
||||
|
||||
Assert.Equal(2, state.Entities.Count);
|
||||
Assert.DoesNotContain(state.Entities, entity => entity.Id == 2);
|
||||
Assert.Equal(0x01000003u, Assert.Single(state.Entities, entity => entity.Id == 3).SourceId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Clear_RemovesCurrentProjectionAndIndex()
|
||||
{
|
||||
var state = new WorldGameState();
|
||||
state.Add(S(1));
|
||||
state.Clear();
|
||||
state.Add(S(1, 0x01000001u));
|
||||
|
||||
WorldEntitySnapshot current = Assert.Single(state.Entities);
|
||||
Assert.Equal(0x01000001u, current.SourceId);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,5 +1,6 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using AcDream.Content;
|
||||
using DatReaderWriter;
|
||||
using DatReaderWriter.DBObjs;
|
||||
using DatReaderWriter.Options;
|
||||
|
|
@ -100,6 +101,7 @@ public class Issue93TownNetworkFountainRoomLightInspectionTests
|
|||
var datDir = ResolveDatDir();
|
||||
if (datDir is null) { _out.WriteLine("SKIP: no dat dir"); return; }
|
||||
using var dats = new DatCollection(datDir, DatAccessType.Read);
|
||||
using var boundedDats = new DatCollectionAdapter(dats);
|
||||
|
||||
const uint setupId = 0x02000365u;
|
||||
var setup = dats.Get<Setup>(setupId);
|
||||
|
|
@ -115,7 +117,7 @@ public class Issue93TownNetworkFountainRoomLightInspectionTests
|
|||
int survivors = 0, markerSkipped = 0, gfxNull = 0;
|
||||
foreach (var mr in flat)
|
||||
{
|
||||
if (AcDream.Core.Meshing.GfxObjDegradeResolver.IsRuntimeHiddenMarker(dats, mr.GfxObjId))
|
||||
if (AcDream.Core.Meshing.GfxObjDegradeResolver.IsRuntimeHiddenMarker(boundedDats, mr.GfxObjId))
|
||||
{
|
||||
markerSkipped++;
|
||||
_out.WriteLine($" part gfx=0x{mr.GfxObjId:X8} -> MARKER (skipped)");
|
||||
|
|
@ -164,6 +166,7 @@ public class Issue93TownNetworkFountainRoomLightInspectionTests
|
|||
var datDir = ResolveDatDir();
|
||||
if (datDir is null) { _out.WriteLine("SKIP: no dat dir"); return; }
|
||||
using var dats = new DatCollection(datDir, DatAccessType.Read);
|
||||
using var boundedDats = new DatCollectionAdapter(dats);
|
||||
|
||||
var setup = dats.Get<Setup>(setupId);
|
||||
Assert.NotNull(setup);
|
||||
|
|
@ -174,7 +177,7 @@ public class Issue93TownNetworkFountainRoomLightInspectionTests
|
|||
int survivors = 0;
|
||||
foreach (var mr in flat)
|
||||
{
|
||||
if (AcDream.Core.Meshing.GfxObjDegradeResolver.IsRuntimeHiddenMarker(dats, mr.GfxObjId)) continue;
|
||||
if (AcDream.Core.Meshing.GfxObjDegradeResolver.IsRuntimeHiddenMarker(boundedDats, mr.GfxObjId)) continue;
|
||||
if (dats.Get<GfxObj>(mr.GfxObjId) is null) continue;
|
||||
survivors++;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -331,7 +331,6 @@ public class EntityClassificationCacheTests
|
|||
uint ibo, uint firstIndex, int indexCount, ulong texHandle)
|
||||
{
|
||||
var key = new GroupKey(
|
||||
Ibo: ibo,
|
||||
FirstIndex: firstIndex,
|
||||
BaseVertex: 0,
|
||||
IndexCount: indexCount,
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Numerics;
|
||||
using AcDream.App.Rendering.Wb;
|
||||
using AcDream.Core.Physics;
|
||||
|
|
@ -16,8 +15,8 @@ public sealed class EntitySpawnAdapterTests
|
|||
[Fact]
|
||||
public void OnCreate_ServerSpawnedEntity_RegistersAnimatedEntityState()
|
||||
{
|
||||
var cache = new CapturingTextureCache();
|
||||
var adapter = MakeAdapter(cache);
|
||||
var lifetime = new RecordingTextureLifetime();
|
||||
var adapter = MakeAdapter(lifetime);
|
||||
var entity = MakeEntity(id: 1, serverGuid: 0xDEAD0001u);
|
||||
|
||||
var state = adapter.OnCreate(entity);
|
||||
|
|
@ -42,8 +41,8 @@ public sealed class EntitySpawnAdapterTests
|
|||
[Fact]
|
||||
public void OnCreate_ProceduralEntity_ReturnsNullAndRegistersNothing()
|
||||
{
|
||||
var cache = new CapturingTextureCache();
|
||||
var adapter = MakeAdapter(cache);
|
||||
var lifetime = new RecordingTextureLifetime();
|
||||
var adapter = MakeAdapter(lifetime);
|
||||
// ServerGuid == 0 → atlas-tier, must not be processed here.
|
||||
var entity = MakeEntity(id: 2, serverGuid: 0u);
|
||||
|
||||
|
|
@ -51,101 +50,19 @@ public sealed class EntitySpawnAdapterTests
|
|||
|
||||
Assert.Null(state);
|
||||
Assert.Null(adapter.GetState(0u));
|
||||
// No texture decode should have been triggered.
|
||||
Assert.Empty(cache.Calls);
|
||||
}
|
||||
|
||||
// ── Palette-override texture decode ───────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void OnCreate_WithPaletteOverrideAndSurfaceOverrides_TriggersTextureCacheDecode()
|
||||
{
|
||||
var cache = new CapturingTextureCache();
|
||||
var adapter = MakeAdapter(cache);
|
||||
|
||||
var palette = new PaletteOverride(
|
||||
BasePaletteId: 0x04001234u,
|
||||
SubPalettes: new[]
|
||||
{
|
||||
new PaletteOverride.SubPaletteRange(0x04002000u, 0, 2),
|
||||
});
|
||||
|
||||
// Entity carries two parts each with one surface override.
|
||||
var entity = new WorldEntity
|
||||
{
|
||||
Id = 10,
|
||||
ServerGuid = 0xBEEF0001u,
|
||||
SourceGfxObjOrSetupId = 0x02000001u,
|
||||
Position = Vector3.Zero,
|
||||
Rotation = Quaternion.Identity,
|
||||
PaletteOverride = palette,
|
||||
MeshRefs = new[]
|
||||
{
|
||||
new MeshRef(0x01000010u, Matrix4x4.Identity)
|
||||
{
|
||||
SurfaceOverrides = new Dictionary<uint, uint>
|
||||
{
|
||||
{ 0x08000100u, 0u }, // surfaceId → origTex (0 = none)
|
||||
},
|
||||
},
|
||||
new MeshRef(0x01000020u, Matrix4x4.Identity)
|
||||
{
|
||||
SurfaceOverrides = new Dictionary<uint, uint>
|
||||
{
|
||||
{ 0x08000200u, 0x05000300u }, // with origTex override
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
adapter.OnCreate(entity);
|
||||
|
||||
// One call per surface-with-override: (0x08000100, null) and (0x08000200, 0x05000300).
|
||||
Assert.Equal(2, cache.Calls.Count);
|
||||
|
||||
Assert.Contains(cache.Calls, c => c.SurfaceId == 0x08000100u
|
||||
&& c.OrigTexOverride == null
|
||||
&& c.Palette == palette);
|
||||
Assert.Contains(cache.Calls, c => c.SurfaceId == 0x08000200u
|
||||
&& c.OrigTexOverride == 0x05000300u
|
||||
&& c.Palette == palette);
|
||||
Assert.Empty(lifetime.ReleasedOwnerIds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OnCreate_WithPaletteOverrideButNoSurfaceOverrides_DoesNotCallCache()
|
||||
public void OnCreate_DoesNotAcquireTexturesBeforeTheSurfaceIsDrawn()
|
||||
{
|
||||
// Surfaces without SurfaceOverrides == null are decoded lazily at draw
|
||||
// time; the adapter only pre-warms what it knows at spawn time.
|
||||
var cache = new CapturingTextureCache();
|
||||
var adapter = MakeAdapter(cache);
|
||||
|
||||
var entity = new WorldEntity
|
||||
{
|
||||
Id = 11,
|
||||
ServerGuid = 0xBEEF0002u,
|
||||
SourceGfxObjOrSetupId = 0x02000002u,
|
||||
Position = Vector3.Zero,
|
||||
Rotation = Quaternion.Identity,
|
||||
PaletteOverride = new PaletteOverride(0x04001235u, Array.Empty<PaletteOverride.SubPaletteRange>()),
|
||||
// MeshRef with NO SurfaceOverrides.
|
||||
MeshRefs = new[] { new MeshRef(0x01000011u, Matrix4x4.Identity) },
|
||||
};
|
||||
var lifetime = new RecordingTextureLifetime();
|
||||
var adapter = MakeAdapter(lifetime);
|
||||
var entity = MakeEntity(id: 10, serverGuid: 0xBEEF0001u);
|
||||
|
||||
adapter.OnCreate(entity);
|
||||
|
||||
Assert.Empty(cache.Calls);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OnCreate_WithoutPaletteOverride_DoesNotCallCache()
|
||||
{
|
||||
var cache = new CapturingTextureCache();
|
||||
var adapter = MakeAdapter(cache);
|
||||
var entity = MakeEntity(id: 12, serverGuid: 0xBEEF0003u);
|
||||
|
||||
adapter.OnCreate(entity);
|
||||
|
||||
Assert.Empty(cache.Calls);
|
||||
Assert.Empty(lifetime.ReleasedOwnerIds);
|
||||
}
|
||||
|
||||
// ── OnRemove ─────────────────────────────────────────────────────────
|
||||
|
|
@ -153,14 +70,17 @@ public sealed class EntitySpawnAdapterTests
|
|||
[Fact]
|
||||
public void OnRemove_ReleasesPerEntityState()
|
||||
{
|
||||
var adapter = MakeAdapter();
|
||||
var lifetime = new RecordingTextureLifetime();
|
||||
var adapter = MakeAdapter(lifetime);
|
||||
var entity = MakeEntity(id: 20, serverGuid: 0xCAFE0001u);
|
||||
|
||||
adapter.OnCreate(entity);
|
||||
adapter.SetPresentationResident(entity, resident: true);
|
||||
Assert.NotNull(adapter.GetState(0xCAFE0001u));
|
||||
|
||||
adapter.OnRemove(0xCAFE0001u);
|
||||
Assert.Null(adapter.GetState(0xCAFE0001u));
|
||||
Assert.Equal([20u], lifetime.ReleasedOwnerIds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
|
@ -208,10 +128,10 @@ public sealed class EntitySpawnAdapterTests
|
|||
|
||||
// ── Helpers ───────────────────────────────────────────────────────────
|
||||
|
||||
private static EntitySpawnAdapter MakeAdapter(ITextureCachePerInstance? cache = null)
|
||||
private static EntitySpawnAdapter MakeAdapter(IEntityTextureLifetime? lifetime = null)
|
||||
{
|
||||
cache ??= new CapturingTextureCache();
|
||||
return new EntitySpawnAdapter(cache, _ => MakeSequencer());
|
||||
lifetime ??= new RecordingTextureLifetime();
|
||||
return new EntitySpawnAdapter(lifetime, _ => MakeSequencer());
|
||||
}
|
||||
|
||||
private static WorldEntity MakeEntity(uint id, uint serverGuid)
|
||||
|
|
@ -230,23 +150,11 @@ public sealed class EntitySpawnAdapterTests
|
|||
|
||||
// ── Mocks / stubs ─────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Capture every call to GetOrUploadWithPaletteOverride so tests can
|
||||
/// assert without a live GL context.
|
||||
/// </summary>
|
||||
private sealed class CapturingTextureCache : ITextureCachePerInstance
|
||||
private sealed class RecordingTextureLifetime : IEntityTextureLifetime
|
||||
{
|
||||
public readonly record struct Call(uint SurfaceId, uint? OrigTexOverride, PaletteOverride Palette);
|
||||
public List<Call> Calls { get; } = new();
|
||||
public List<uint> ReleasedOwnerIds { get; } = new();
|
||||
|
||||
public uint GetOrUploadWithPaletteOverride(
|
||||
uint surfaceId,
|
||||
uint? overrideOrigTextureId,
|
||||
PaletteOverride paletteOverride)
|
||||
{
|
||||
Calls.Add(new Call(surfaceId, overrideOrigTextureId, paletteOverride));
|
||||
return 1u; // Fake GL handle.
|
||||
}
|
||||
public void ReleaseOwner(uint localEntityId) => ReleasedOwnerIds.Add(localEntityId);
|
||||
}
|
||||
|
||||
private sealed class NullAnimationLoader : IAnimationLoader
|
||||
|
|
|
|||
|
|
@ -421,7 +421,6 @@ public sealed class WbDrawDispatcherBucketingTests
|
|||
Vector3? localSortCenter = null)
|
||||
{
|
||||
var key = new GroupKey(
|
||||
Ibo: ibo,
|
||||
FirstIndex: firstIndex,
|
||||
BaseVertex: 0,
|
||||
IndexCount: indexCount,
|
||||
|
|
|
|||
|
|
@ -307,6 +307,74 @@ public class LandblockStreamerTests
|
|||
Assert.NotEqual(testThreadId, loaderThreadId.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DisposeAndConcurrentDisposeWaitForInFlightLoad()
|
||||
{
|
||||
using var entered = new ManualResetEventSlim();
|
||||
using var release = new ManualResetEventSlim();
|
||||
var streamer = new LandblockStreamer(loadLandblock: _ =>
|
||||
{
|
||||
entered.Set();
|
||||
release.Wait();
|
||||
return null;
|
||||
});
|
||||
|
||||
try
|
||||
{
|
||||
streamer.Start();
|
||||
streamer.EnqueueLoad(0x12340000u);
|
||||
Assert.True(entered.Wait(TimeSpan.FromSeconds(2)));
|
||||
|
||||
Task firstDispose = Task.Run(streamer.Dispose);
|
||||
Task secondDispose = Task.Run(streamer.Dispose);
|
||||
await Task.Delay(50);
|
||||
Assert.False(firstDispose.IsCompleted);
|
||||
Assert.False(secondDispose.IsCompleted);
|
||||
|
||||
release.Set();
|
||||
await Task.WhenAll(firstDispose, secondDispose).WaitAsync(TimeSpan.FromSeconds(2));
|
||||
}
|
||||
finally
|
||||
{
|
||||
release.Set();
|
||||
streamer.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DisposeRejectsEveryEnqueueKind()
|
||||
{
|
||||
var streamer = new LandblockStreamer(loadLandblock: _ => null);
|
||||
streamer.Start();
|
||||
streamer.Dispose();
|
||||
|
||||
Assert.Throws<ObjectDisposedException>(() => streamer.EnqueueLoad(0x12340000u));
|
||||
Assert.Throws<ObjectDisposedException>(() => streamer.EnqueueUnload(0x12340000u));
|
||||
Assert.Throws<ObjectDisposedException>(streamer.ClearPendingLoads);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ConcurrentStartAndDisposeLeaveAClosedStreamer()
|
||||
{
|
||||
for (int iteration = 0; iteration < 20; iteration++)
|
||||
{
|
||||
var streamer = new LandblockStreamer(loadLandblock: _ => null);
|
||||
Exception? startFailure = null;
|
||||
|
||||
Task start = Task.Run(() =>
|
||||
{
|
||||
try { streamer.Start(); }
|
||||
catch (ObjectDisposedException ex) { startFailure = ex; }
|
||||
});
|
||||
Task dispose = Task.Run(streamer.Dispose);
|
||||
await Task.WhenAll(start, dispose).WaitAsync(TimeSpan.FromSeconds(2));
|
||||
|
||||
Assert.True(startFailure is null or ObjectDisposedException);
|
||||
Assert.Throws<ObjectDisposedException>(() => streamer.EnqueueLoad(0x12340000u));
|
||||
streamer.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<LandblockStreamResult> DrainFirstAsync(LandblockStreamer streamer)
|
||||
{
|
||||
for (int i = 0; i < SpinMaxIterations; i++)
|
||||
|
|
|
|||
|
|
@ -149,6 +149,58 @@ public class StreamingControllerPriorityApplyTests
|
|||
Assert.Equal(3, applied.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DeferredCompaction_ApplyFailureRetainsExactResultWithoutReplayingCommittedPrefix()
|
||||
{
|
||||
uint priority = StreamingRegion.EncodeLandblockIdForTest(169, 180);
|
||||
uint first = StreamingRegion.EncodeLandblockIdForTest(169, 182);
|
||||
uint retry = StreamingRegion.EncodeLandblockIdForTest(169, 183);
|
||||
uint last = StreamingRegion.EncodeLandblockIdForTest(169, 184);
|
||||
var outbox = new Queue<LandblockStreamResult>(
|
||||
[
|
||||
LoadedOf(first),
|
||||
LoadedOf(retry),
|
||||
LoadedOf(last),
|
||||
]);
|
||||
var applied = new List<uint>();
|
||||
bool failRetryOnce = true;
|
||||
var ctrl = new StreamingController(
|
||||
enqueueLoad: (_, _) => { },
|
||||
enqueueUnload: _ => { },
|
||||
drainCompletions: max =>
|
||||
{
|
||||
var batch = new List<LandblockStreamResult>();
|
||||
while (batch.Count < max && outbox.Count > 0)
|
||||
batch.Add(outbox.Dequeue());
|
||||
return batch;
|
||||
},
|
||||
applyTerrain: (build, _) =>
|
||||
{
|
||||
if (build.LandblockId == retry && failRetryOnce)
|
||||
{
|
||||
failRetryOnce = false;
|
||||
throw new InvalidOperationException("synthetic upload failure");
|
||||
}
|
||||
applied.Add(build.LandblockId);
|
||||
},
|
||||
state: new GpuWorldState(),
|
||||
nearRadius: 4,
|
||||
farRadius: 12)
|
||||
{
|
||||
MaxCompletionsPerFrame = 3,
|
||||
PriorityLandblockId = priority,
|
||||
};
|
||||
|
||||
Assert.Throws<InvalidOperationException>(() => ctrl.Tick(169, 180));
|
||||
Assert.Equal([first], applied);
|
||||
Assert.Equal(2, ctrl.DeferredApplyBacklog);
|
||||
|
||||
ctrl.Tick(169, 180);
|
||||
|
||||
Assert.Equal([first, retry, last], applied);
|
||||
Assert.Equal(0, ctrl.DeferredApplyBacklog);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ForceReloadWindow_DiscardsBufferedCompletionsFromOldWindow()
|
||||
{
|
||||
|
|
|
|||
|
|
@ -11,10 +11,15 @@ public class StreamingControllerTests
|
|||
private sealed class FakeStreamer
|
||||
{
|
||||
public List<uint> Loads { get; } = new();
|
||||
public List<(uint Id, LandblockStreamJobKind Kind)> LoadJobs { get; } = new();
|
||||
public List<uint> Unloads { get; } = new();
|
||||
public Queue<LandblockStreamResult> Pending { get; } = new();
|
||||
|
||||
public void EnqueueLoad(uint id, LandblockStreamJobKind _) => Loads.Add(id);
|
||||
public void EnqueueLoad(uint id, LandblockStreamJobKind kind)
|
||||
{
|
||||
Loads.Add(id);
|
||||
LoadJobs.Add((id, kind));
|
||||
}
|
||||
public void EnqueueUnload(uint id) => Unloads.Add(id);
|
||||
public IReadOnlyList<LandblockStreamResult> DrainCompletions(int max)
|
||||
{
|
||||
|
|
@ -65,6 +70,285 @@ public class StreamingControllerTests
|
|||
Assert.Empty(fake.Unloads);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ReconfigureRadii_SmallerWindowUnloadsOnlyOutsideResidents()
|
||||
{
|
||||
var state = new GpuWorldState();
|
||||
var fake = new FakeStreamer();
|
||||
int pendingClears = 0;
|
||||
var controller = new StreamingController(
|
||||
fake.EnqueueLoad,
|
||||
fake.EnqueueUnload,
|
||||
fake.DrainCompletions,
|
||||
(_, _) => { },
|
||||
state,
|
||||
nearRadius: 2,
|
||||
farRadius: 2,
|
||||
clearPendingLoads: () => pendingClears++);
|
||||
controller.Tick(50, 50);
|
||||
for (int dx = -2; dx <= 2; dx++)
|
||||
for (int dy = -2; dy <= 2; dy++)
|
||||
AddPublished(state, 50 + dx, 50 + dy, LandblockStreamTier.Near);
|
||||
fake.Loads.Clear();
|
||||
fake.LoadJobs.Clear();
|
||||
|
||||
controller.ReconfigureRadii(0, 0);
|
||||
|
||||
Assert.Equal(1, pendingClears);
|
||||
Assert.Empty(fake.Loads);
|
||||
Assert.Equal(24, fake.Unloads.Count);
|
||||
Assert.DoesNotContain(0x3232FFFFu, fake.Unloads);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ReconfigureRadii_LargerWindowLoadsOnlyMissingResidents()
|
||||
{
|
||||
var state = new GpuWorldState();
|
||||
var fake = new FakeStreamer();
|
||||
var controller = new StreamingController(
|
||||
fake.EnqueueLoad,
|
||||
fake.EnqueueUnload,
|
||||
fake.DrainCompletions,
|
||||
(_, _) => { },
|
||||
state,
|
||||
nearRadius: 0,
|
||||
farRadius: 0);
|
||||
controller.Tick(50, 50);
|
||||
AddPublished(state, 50, 50, LandblockStreamTier.Near);
|
||||
fake.Loads.Clear();
|
||||
fake.LoadJobs.Clear();
|
||||
|
||||
controller.ReconfigureRadii(1, 1);
|
||||
|
||||
Assert.Equal(8, fake.LoadJobs.Count);
|
||||
Assert.All(
|
||||
fake.LoadJobs,
|
||||
static job => Assert.Equal(LandblockStreamJobKind.LoadNear, job.Kind));
|
||||
Assert.DoesNotContain(fake.LoadJobs, static job => job.Id == 0x3232FFFFu);
|
||||
Assert.Empty(fake.Unloads);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ReconfigureRadii_UnchangedWindowDoesNotClearOrRebootstrap()
|
||||
{
|
||||
var state = new GpuWorldState();
|
||||
var fake = new FakeStreamer();
|
||||
int pendingClears = 0;
|
||||
var controller = new StreamingController(
|
||||
fake.EnqueueLoad,
|
||||
fake.EnqueueUnload,
|
||||
fake.DrainCompletions,
|
||||
(_, _) => { },
|
||||
state,
|
||||
nearRadius: 1,
|
||||
farRadius: 2,
|
||||
clearPendingLoads: () => pendingClears++);
|
||||
controller.Tick(50, 50);
|
||||
fake.Loads.Clear();
|
||||
fake.LoadJobs.Clear();
|
||||
|
||||
controller.ReconfigureRadii(1, 2);
|
||||
|
||||
Assert.Equal(0, pendingClears);
|
||||
Assert.Empty(fake.Loads);
|
||||
Assert.Empty(fake.Unloads);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ReconfigureRadii_ClearFailureRetainsOldWindowAndResumesWithoutDuplicateLoads()
|
||||
{
|
||||
var state = new GpuWorldState();
|
||||
var fake = new FakeStreamer();
|
||||
int clearAttempts = 0;
|
||||
var controller = new StreamingController(
|
||||
fake.EnqueueLoad,
|
||||
fake.EnqueueUnload,
|
||||
fake.DrainCompletions,
|
||||
(_, _) => { },
|
||||
state,
|
||||
nearRadius: 0,
|
||||
farRadius: 0,
|
||||
clearPendingLoads: () =>
|
||||
{
|
||||
clearAttempts++;
|
||||
if (clearAttempts == 1)
|
||||
throw new InvalidOperationException("clear not admitted");
|
||||
});
|
||||
controller.Tick(50, 50);
|
||||
AddPublished(state, 50, 50, LandblockStreamTier.Near);
|
||||
fake.LoadJobs.Clear();
|
||||
|
||||
Assert.Throws<AggregateException>(() => controller.ReconfigureRadii(1, 1));
|
||||
Assert.Equal(0, controller.NearRadius);
|
||||
Assert.Equal(0, controller.FarRadius);
|
||||
Assert.Empty(fake.LoadJobs);
|
||||
|
||||
controller.ReconfigureRadii(1, 1);
|
||||
|
||||
Assert.Equal(2, clearAttempts);
|
||||
Assert.Equal(8, fake.LoadJobs.Count);
|
||||
Assert.Equal(8, fake.LoadJobs.Select(static job => job.Id).Distinct().Count());
|
||||
Assert.Equal(1, controller.NearRadius);
|
||||
Assert.Equal(1, controller.FarRadius);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ReconfigureRadii_QueueFailureRetriesOnlyUncommittedAdmission()
|
||||
{
|
||||
var state = new GpuWorldState();
|
||||
var fake = new FakeStreamer();
|
||||
int loadAttempts = 0;
|
||||
bool failNext = false;
|
||||
void EnqueueLoad(uint id, LandblockStreamJobKind kind)
|
||||
{
|
||||
loadAttempts++;
|
||||
if (failNext)
|
||||
{
|
||||
failNext = false;
|
||||
throw new InvalidOperationException("load not admitted");
|
||||
}
|
||||
fake.EnqueueLoad(id, kind);
|
||||
}
|
||||
var controller = new StreamingController(
|
||||
EnqueueLoad,
|
||||
fake.EnqueueUnload,
|
||||
fake.DrainCompletions,
|
||||
(_, _) => { },
|
||||
state,
|
||||
nearRadius: 0,
|
||||
farRadius: 0);
|
||||
controller.Tick(50, 50);
|
||||
AddPublished(state, 50, 50, LandblockStreamTier.Near);
|
||||
fake.LoadJobs.Clear();
|
||||
loadAttempts = 0;
|
||||
failNext = true;
|
||||
|
||||
Assert.Throws<AggregateException>(() => controller.ReconfigureRadii(1, 1));
|
||||
Assert.Equal(8, loadAttempts);
|
||||
Assert.Equal(7, fake.LoadJobs.Count);
|
||||
Assert.Equal(0, controller.NearRadius);
|
||||
|
||||
controller.ReconfigureRadii(1, 1);
|
||||
|
||||
Assert.Equal(9, loadAttempts);
|
||||
Assert.Equal(8, fake.LoadJobs.Count);
|
||||
Assert.Equal(8, fake.LoadJobs.Select(static job => job.Id).Distinct().Count());
|
||||
Assert.Equal(1, controller.NearRadius);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ReconfigureRadii_CommittedQueueFailureIsReportedButNeverReplayed()
|
||||
{
|
||||
var state = new GpuWorldState();
|
||||
var fake = new FakeStreamer();
|
||||
bool throwCommitted = false;
|
||||
int loadAttempts = 0;
|
||||
void EnqueueLoad(uint id, LandblockStreamJobKind kind)
|
||||
{
|
||||
loadAttempts++;
|
||||
fake.EnqueueLoad(id, kind);
|
||||
if (throwCommitted)
|
||||
{
|
||||
throwCommitted = false;
|
||||
throw new StreamingMutationException(
|
||||
"post-admission diagnostic failed",
|
||||
mutationCommitted: true);
|
||||
}
|
||||
}
|
||||
var controller = new StreamingController(
|
||||
EnqueueLoad,
|
||||
fake.EnqueueUnload,
|
||||
fake.DrainCompletions,
|
||||
(_, _) => { },
|
||||
state,
|
||||
nearRadius: 0,
|
||||
farRadius: 0);
|
||||
controller.Tick(50, 50);
|
||||
AddPublished(state, 50, 50, LandblockStreamTier.Near);
|
||||
fake.LoadJobs.Clear();
|
||||
loadAttempts = 0;
|
||||
throwCommitted = true;
|
||||
|
||||
Assert.Throws<AggregateException>(() => controller.ReconfigureRadii(1, 1));
|
||||
|
||||
Assert.Equal(8, loadAttempts);
|
||||
Assert.Equal(8, fake.LoadJobs.Count);
|
||||
Assert.Equal(1, controller.NearRadius);
|
||||
controller.ReconfigureRadii(1, 1);
|
||||
Assert.Equal(8, loadAttempts);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ReconfigureRadii_ClearCallbackReentryDefersWithoutRecursiveClear()
|
||||
{
|
||||
var state = new GpuWorldState();
|
||||
var fake = new FakeStreamer();
|
||||
StreamingController? controller = null;
|
||||
int clearCalls = 0;
|
||||
controller = new StreamingController(
|
||||
fake.EnqueueLoad,
|
||||
fake.EnqueueUnload,
|
||||
fake.DrainCompletions,
|
||||
(_, _) => { },
|
||||
state,
|
||||
nearRadius: 0,
|
||||
farRadius: 0,
|
||||
clearPendingLoads: () =>
|
||||
{
|
||||
clearCalls++;
|
||||
controller!.ReconfigureRadii(1, 1);
|
||||
});
|
||||
controller.Tick(50, 50);
|
||||
AddPublished(state, 50, 50, LandblockStreamTier.Near);
|
||||
fake.LoadJobs.Clear();
|
||||
|
||||
controller.ReconfigureRadii(1, 1);
|
||||
|
||||
Assert.Equal(1, clearCalls);
|
||||
Assert.Equal(8, fake.LoadJobs.Count);
|
||||
Assert.Equal(1, controller.NearRadius);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ReconfigureRadii_QueueCallbackReentryDefersWithoutDuplicateAdmission()
|
||||
{
|
||||
var state = new GpuWorldState();
|
||||
var fake = new FakeStreamer();
|
||||
StreamingController? controller = null;
|
||||
bool reenter = false;
|
||||
int loadCalls = 0;
|
||||
void EnqueueLoad(uint id, LandblockStreamJobKind kind)
|
||||
{
|
||||
loadCalls++;
|
||||
fake.EnqueueLoad(id, kind);
|
||||
if (reenter)
|
||||
{
|
||||
reenter = false;
|
||||
controller!.ReconfigureRadii(1, 1);
|
||||
}
|
||||
}
|
||||
controller = new StreamingController(
|
||||
EnqueueLoad,
|
||||
fake.EnqueueUnload,
|
||||
fake.DrainCompletions,
|
||||
(_, _) => { },
|
||||
state,
|
||||
nearRadius: 0,
|
||||
farRadius: 0);
|
||||
controller.Tick(50, 50);
|
||||
AddPublished(state, 50, 50, LandblockStreamTier.Near);
|
||||
fake.LoadJobs.Clear();
|
||||
loadCalls = 0;
|
||||
reenter = true;
|
||||
|
||||
controller.ReconfigureRadii(1, 1);
|
||||
|
||||
Assert.Equal(8, loadCalls);
|
||||
Assert.Equal(8, fake.LoadJobs.Count);
|
||||
Assert.Equal(8, fake.LoadJobs.Select(static job => job.Id).Distinct().Count());
|
||||
Assert.Equal(1, controller.NearRadius);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DrainingLoadedResult_AddsToState()
|
||||
{
|
||||
|
|
@ -115,4 +399,59 @@ public class StreamingControllerTests
|
|||
|
||||
Assert.False(state.IsLoaded(landblockId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DrainingUnloadedResult_CommitsStateBeforePresentationTeardown()
|
||||
{
|
||||
var state = new GpuWorldState();
|
||||
var fake = new FakeStreamer();
|
||||
const uint landblockId = 0x2020FFFFu;
|
||||
var lb = new LoadedLandblock(
|
||||
landblockId,
|
||||
new LandBlock(),
|
||||
new[]
|
||||
{
|
||||
new WorldEntity
|
||||
{
|
||||
Id = 1,
|
||||
SourceGfxObjOrSetupId = 0x01000000u,
|
||||
Position = System.Numerics.Vector3.Zero,
|
||||
Rotation = System.Numerics.Quaternion.Identity,
|
||||
MeshRefs = Array.Empty<MeshRef>(),
|
||||
},
|
||||
});
|
||||
state.AddLandblock(lb);
|
||||
bool callbackSawDetachedState = false;
|
||||
var controller = new StreamingController(
|
||||
fake.EnqueueLoad,
|
||||
fake.EnqueueUnload,
|
||||
fake.DrainCompletions,
|
||||
(_, _) => { },
|
||||
state,
|
||||
nearRadius: 2,
|
||||
farRadius: 2,
|
||||
removeTerrain: id =>
|
||||
{
|
||||
callbackSawDetachedState = id == landblockId
|
||||
&& !state.TryGetLandblock(id, out _);
|
||||
});
|
||||
fake.Pending.Enqueue(new LandblockStreamResult.Unloaded(landblockId));
|
||||
|
||||
controller.Tick(50, 50);
|
||||
|
||||
Assert.True(callbackSawDetachedState);
|
||||
Assert.False(state.IsLoaded(landblockId));
|
||||
}
|
||||
|
||||
private static void AddPublished(
|
||||
GpuWorldState state,
|
||||
int x,
|
||||
int y,
|
||||
LandblockStreamTier tier)
|
||||
{
|
||||
uint id = ((uint)x << 24) | ((uint)y << 16) | 0xFFFFu;
|
||||
state.AddLandblock(
|
||||
new LoadedLandblock(id, new LandBlock(), Array.Empty<WorldEntity>()),
|
||||
tier: tier);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -338,6 +338,58 @@ public sealed class ParticleHookSinkTests
|
|||
Assert.Equal(1, deathNotices);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LogicalTeardown_AttemptsEveryEmitterWhenDeathSubscriberThrows()
|
||||
{
|
||||
const uint emitterId = 0x3200005Bu;
|
||||
var (system, sink, _) = Harness(emitterId);
|
||||
sink.OnHook(Owner, Vector3.Zero, Create(emitterId, logicalId: 31u));
|
||||
sink.OnHook(Owner, Vector3.Zero, Create(emitterId, logicalId: 32u));
|
||||
int deathAttempts = 0;
|
||||
system.EmitterDied += _ =>
|
||||
{
|
||||
deathAttempts++;
|
||||
throw new InvalidOperationException("observer failed after emitter removal");
|
||||
};
|
||||
|
||||
AggregateException error = Assert.Throws<AggregateException>(
|
||||
() => sink.StopAllForEntity(Owner, fadeOut: false));
|
||||
|
||||
Assert.Equal(2, error.InnerExceptions.Count);
|
||||
Assert.Equal(2, deathAttempts);
|
||||
Assert.Equal(0, system.ActiveEmitterCount);
|
||||
Assert.Equal(0, sink.ActiveBindingCount);
|
||||
Assert.Equal(0, sink.LogicalEmitterCount);
|
||||
Assert.Equal(0, sink.TrackedOwnerCount);
|
||||
|
||||
// Every physical stop committed despite observer failures, so a retry
|
||||
// is a clean no-op rather than replaying dead handles.
|
||||
sink.StopAllForEntity(Owner, fadeOut: false);
|
||||
Assert.Equal(2, deathAttempts);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LogicalTeardown_DeathCallbackCannotResurrectSameOwnerEmitter()
|
||||
{
|
||||
const uint emitterId = 0x3200005Cu;
|
||||
var (system, sink, _) = Harness(emitterId);
|
||||
sink.OnHook(Owner, Vector3.Zero, Create(emitterId, logicalId: 41u));
|
||||
int resurrectionAttempts = 0;
|
||||
system.EmitterDied += _ =>
|
||||
{
|
||||
resurrectionAttempts++;
|
||||
sink.OnHook(Owner, Vector3.Zero, Create(emitterId, logicalId: 42u));
|
||||
};
|
||||
|
||||
sink.StopAllForEntity(Owner, fadeOut: false);
|
||||
|
||||
Assert.Equal(1, resurrectionAttempts);
|
||||
Assert.Equal(0, system.ActiveEmitterCount);
|
||||
Assert.Equal(0, sink.ActiveBindingCount);
|
||||
Assert.Equal(0, sink.LogicalEmitterCount);
|
||||
Assert.Equal(0, sink.TrackedOwnerCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ExaminationObjectPolicyAppliesToExistingAndFutureEmittersAndTearsDown()
|
||||
{
|
||||
|
|
@ -362,17 +414,115 @@ public sealed class ParticleHookSinkTests
|
|||
Assert.Equal(0, sink.ExaminationOwnerCount);
|
||||
}
|
||||
|
||||
private sealed class MutablePoseSource : IEntityEffectPoseSource
|
||||
[Fact]
|
||||
public void PoseChangeWorkset_RefreshesOnlyChangedOwnersAndVisibilityEdges()
|
||||
{
|
||||
const uint emitterId = 0x32000059u;
|
||||
const int ownerCount = 2_000;
|
||||
var registry = new EmitterDescRegistry();
|
||||
registry.Register(MakeDesc(emitterId, attachLocal: true));
|
||||
var system = new ParticleSystem(registry, new Random(42));
|
||||
var poses = new MutablePoseSource();
|
||||
var sink = new ParticleHookSink(system, poses);
|
||||
|
||||
for (uint owner = 1; owner <= ownerCount; owner++)
|
||||
{
|
||||
poses.Publish(owner, Matrix4x4.Identity, Matrix4x4.Identity);
|
||||
sink.OnHook(owner, Vector3.Zero, Create(emitterId, logicalId: 0));
|
||||
}
|
||||
|
||||
// Spawn resolves the current pose directly; unchanged static owners
|
||||
// create no recurring frame work.
|
||||
sink.RefreshAttachedEmitters();
|
||||
Assert.Equal(0, sink.LastRefreshOwnerVisitCount);
|
||||
Assert.Equal(0, sink.LastRefreshBindingVisitCount);
|
||||
|
||||
poses.Publish(777u, Matrix4x4.CreateTranslation(1, 2, 3), Matrix4x4.Identity);
|
||||
poses.Publish(777u, Matrix4x4.CreateTranslation(7, 8, 9), Matrix4x4.Identity);
|
||||
sink.RefreshAttachedEmitters();
|
||||
Assert.Equal(1, sink.LastRefreshOwnerVisitCount);
|
||||
Assert.Equal(1, sink.LastRefreshBindingVisitCount);
|
||||
Assert.Equal(new Vector3(7, 8, 9),
|
||||
system.EnumerateEmitters().Single(emitter => emitter.AttachedObjectId == 777u).AnchorPos);
|
||||
|
||||
sink.RefreshAttachedEmitters();
|
||||
Assert.Equal(0, sink.LastRefreshOwnerVisitCount);
|
||||
|
||||
sink.SetEntityPresentationVisible(777u, false);
|
||||
sink.SetEntityPresentationVisible(777u, true);
|
||||
sink.RefreshAttachedEmitters();
|
||||
Assert.Equal(1, sink.LastRefreshOwnerVisitCount);
|
||||
Assert.True(system.EnumerateEmitters()
|
||||
.Single(emitter => emitter.AttachedObjectId == 777u)
|
||||
.PresentationVisible);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PoseChangeRaisedDuringRefresh_IsRetainedForNextRefresh()
|
||||
{
|
||||
const uint emitterId = 0x3200005Au;
|
||||
const uint firstOwner = 1u;
|
||||
const uint secondOwner = 2u;
|
||||
var registry = new EmitterDescRegistry();
|
||||
registry.Register(MakeDesc(emitterId, attachLocal: true));
|
||||
var system = new ParticleSystem(registry, new Random(42));
|
||||
var poses = new MutablePoseSource();
|
||||
poses.Publish(firstOwner, Matrix4x4.Identity, Matrix4x4.Identity);
|
||||
poses.Publish(secondOwner, Matrix4x4.Identity, Matrix4x4.Identity);
|
||||
var sink = new ParticleHookSink(system, poses);
|
||||
sink.OnHook(firstOwner, Vector3.Zero, Create(emitterId, logicalId: 0));
|
||||
sink.OnHook(secondOwner, Vector3.Zero, Create(emitterId, logicalId: 0));
|
||||
|
||||
bool raised = false;
|
||||
poses.RootRead = owner =>
|
||||
{
|
||||
if (owner != firstOwner || raised)
|
||||
return;
|
||||
raised = true;
|
||||
poses.Publish(
|
||||
secondOwner,
|
||||
Matrix4x4.CreateTranslation(20, 0, 0),
|
||||
Matrix4x4.Identity);
|
||||
};
|
||||
poses.Publish(
|
||||
firstOwner,
|
||||
Matrix4x4.CreateTranslation(10, 0, 0),
|
||||
Matrix4x4.Identity);
|
||||
|
||||
sink.RefreshAttachedEmitters();
|
||||
Assert.Equal(1, sink.LastRefreshOwnerVisitCount);
|
||||
sink.RefreshAttachedEmitters();
|
||||
Assert.Equal(1, sink.LastRefreshOwnerVisitCount);
|
||||
Assert.Equal(new Vector3(20, 0, 0),
|
||||
system.EnumerateEmitters()
|
||||
.Single(emitter => emitter.AttachedObjectId == secondOwner)
|
||||
.AnchorPos);
|
||||
}
|
||||
|
||||
private sealed class MutablePoseSource :
|
||||
IEntityEffectPoseSource,
|
||||
IEntityEffectPoseChangeSource
|
||||
{
|
||||
private readonly Dictionary<uint, (Matrix4x4 Root, Matrix4x4[] Parts)> _poses = new();
|
||||
|
||||
public void Publish(uint id, Matrix4x4 root, params Matrix4x4[] parts) =>
|
||||
_poses[id] = (root, parts);
|
||||
public event Action<uint>? EffectPoseChanged;
|
||||
public Action<uint>? RootRead { get; set; }
|
||||
|
||||
public void Remove(uint id) => _poses.Remove(id);
|
||||
public void Publish(uint id, Matrix4x4 root, params Matrix4x4[] parts)
|
||||
{
|
||||
_poses[id] = (root, parts);
|
||||
EffectPoseChanged?.Invoke(id);
|
||||
}
|
||||
|
||||
public void Remove(uint id)
|
||||
{
|
||||
_poses.Remove(id);
|
||||
EffectPoseChanged?.Invoke(id);
|
||||
}
|
||||
|
||||
public bool TryGetRootPose(uint localEntityId, out Matrix4x4 rootWorld)
|
||||
{
|
||||
RootRead?.Invoke(localEntityId);
|
||||
if (_poses.TryGetValue(localEntityId, out var pose))
|
||||
{
|
||||
rootWorld = pose.Root;
|
||||
|
|
|
|||
|
|
@ -607,6 +607,196 @@ public sealed class ParticleSystemTests
|
|||
Assert.All(sys.EnumerateEmitters(), emitter => Assert.True(emitter.ViewEligible));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DenseSuspendedSet_IsExcludedFromSimulationViewAndRenderWorksets()
|
||||
{
|
||||
var sys = MakeSystem();
|
||||
var desc = new EmitterDesc
|
||||
{
|
||||
DatId = 0x32000080u,
|
||||
Type = ParticleType.Still,
|
||||
MaxDegradeDistance = 100f,
|
||||
MaxParticles = 1,
|
||||
InitialParticles = 1,
|
||||
LifetimeMin = 100f,
|
||||
LifetimeMax = 100f,
|
||||
};
|
||||
var visibleCells = new HashSet<uint> { 0x01010001u };
|
||||
|
||||
for (int i = 0; i < 2_000; i++)
|
||||
{
|
||||
int handle = sys.SpawnEmitter(desc, Vector3.Zero, attachedObjectId: (uint)(i + 1));
|
||||
sys.UpdateEmitterOwnerCell(handle, 0x01010001u);
|
||||
if (i >= 3)
|
||||
{
|
||||
sys.SetEmitterPresentationVisible(handle, false);
|
||||
sys.SetEmitterSimulationEnabled(handle, false);
|
||||
}
|
||||
}
|
||||
|
||||
sys.ApplyRetailView(Vector3.Zero, visibleCells, hasCompletedView: true);
|
||||
sys.Tick(0.01f);
|
||||
|
||||
Assert.Equal(3, sys.LastRetailViewEmitterVisitCount);
|
||||
Assert.Equal(3, sys.LastTickEmitterVisitCount);
|
||||
Assert.Equal(3, sys.EnumerateRenderableEmitters(ParticleRenderPass.Scene).Count());
|
||||
Assert.Equal(2_000, sys.ActiveEmitterCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OwnerRenderScope_VisitsOnlyRequestedOwnersAndUnattachedEmittersInSpawnOrder()
|
||||
{
|
||||
var sys = MakeSystem();
|
||||
var desc = new EmitterDesc
|
||||
{
|
||||
DatId = 0x32000083u,
|
||||
Type = ParticleType.Still,
|
||||
MaxParticles = 1,
|
||||
};
|
||||
int unattached = sys.SpawnEmitter(desc, Vector3.Zero);
|
||||
int ownerSeven = 0;
|
||||
int ownerNine = 0;
|
||||
for (uint owner = 1; owner <= 2_000; owner++)
|
||||
{
|
||||
int handle = sys.SpawnEmitter(desc, Vector3.Zero, attachedObjectId: owner);
|
||||
if (owner == 7u)
|
||||
ownerSeven = handle;
|
||||
if (owner == 9u)
|
||||
ownerNine = handle;
|
||||
}
|
||||
|
||||
var destination = new List<ParticleEmitter>();
|
||||
sys.CopyRenderableEmittersForOwners(
|
||||
ParticleRenderPass.Scene,
|
||||
new HashSet<uint> { 9u, 7u, 4_000u },
|
||||
includeUnattached: true,
|
||||
destination);
|
||||
|
||||
Assert.Equal(3, sys.LastRenderScopeEmitterVisitCount);
|
||||
Assert.Equal(new[] { unattached, ownerSeven, ownerNine },
|
||||
destination.Select(emitter => emitter.Handle));
|
||||
|
||||
sys.CopyRenderableEmittersForOwners(
|
||||
ParticleRenderPass.Scene,
|
||||
new HashSet<uint> { 7u, 9u },
|
||||
includeUnattached: false,
|
||||
destination,
|
||||
excludedAttachedOwnerIds: new HashSet<uint> { 7u });
|
||||
Assert.Equal(1, sys.LastRenderScopeEmitterVisitCount);
|
||||
Assert.Equal(new[] { ownerNine }, destination.Select(emitter => emitter.Handle));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SpatialReentryWaitsForFreshRetailViewBeforeBecomingRenderable()
|
||||
{
|
||||
var sys = MakeSystem();
|
||||
int handle = sys.SpawnEmitter(
|
||||
new EmitterDesc
|
||||
{
|
||||
DatId = 0x32000084u,
|
||||
Type = ParticleType.Still,
|
||||
MaxDegradeDistance = 100f,
|
||||
MaxParticles = 1,
|
||||
},
|
||||
Vector3.Zero,
|
||||
attachedObjectId: 84u);
|
||||
sys.UpdateEmitterOwnerCell(handle, 0x01010001u);
|
||||
var visible = new HashSet<uint> { 0x01010001u };
|
||||
var destination = new List<ParticleEmitter>();
|
||||
|
||||
sys.ApplyRetailView(Vector3.Zero, visible, hasCompletedView: true);
|
||||
Assert.Single(sys.EnumerateRenderableEmitters(ParticleRenderPass.Scene));
|
||||
|
||||
sys.SetEmitterPresentationVisible(handle, false);
|
||||
sys.SetEmitterSimulationEnabled(handle, false);
|
||||
Assert.False(Assert.Single(sys.EnumerateEmitters()).ViewEligible);
|
||||
|
||||
sys.SetEmitterPresentationVisible(handle, true);
|
||||
sys.SetEmitterSimulationEnabled(handle, true);
|
||||
sys.CopyRenderableEmittersForOwners(
|
||||
ParticleRenderPass.Scene,
|
||||
new HashSet<uint> { 84u },
|
||||
includeUnattached: false,
|
||||
destination);
|
||||
Assert.Empty(destination);
|
||||
|
||||
sys.ApplyRetailView(Vector3.Zero, visible, hasCompletedView: true);
|
||||
sys.CopyRenderableEmittersForOwners(
|
||||
ParticleRenderPass.Scene,
|
||||
new HashSet<uint> { 84u },
|
||||
includeUnattached: false,
|
||||
destination);
|
||||
Assert.Single(destination);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OrderedIndexes_PreserveSpawnOrderAcrossHardRemovalAndPassFiltering()
|
||||
{
|
||||
var sys = MakeSystem();
|
||||
var desc = new EmitterDesc
|
||||
{
|
||||
DatId = 0x32000081u,
|
||||
Type = ParticleType.Still,
|
||||
MaxParticles = 1,
|
||||
};
|
||||
int first = sys.SpawnEmitter(desc, Vector3.Zero);
|
||||
int removedScene = sys.SpawnEmitter(desc, Vector3.Zero);
|
||||
int sky = sys.SpawnEmitter(
|
||||
desc,
|
||||
Vector3.Zero,
|
||||
renderPass: ParticleRenderPass.SkyPreScene,
|
||||
visibilityPolicy: ParticleVisibilityPolicy.PassOwned);
|
||||
int removedSky = sys.SpawnEmitter(
|
||||
desc,
|
||||
Vector3.Zero,
|
||||
renderPass: ParticleRenderPass.SkyPreScene,
|
||||
visibilityPolicy: ParticleVisibilityPolicy.PassOwned);
|
||||
int last = sys.SpawnEmitter(desc, Vector3.Zero);
|
||||
|
||||
sys.StopEmitter(removedScene, fadeOut: false);
|
||||
sys.StopEmitter(removedSky, fadeOut: false);
|
||||
|
||||
Assert.Equal(new[] { first, sky, last },
|
||||
sys.EnumerateEmitters().Select(emitter => emitter.Handle));
|
||||
Assert.Equal(new[] { first, last },
|
||||
sys.EnumerateRenderableEmitters(ParticleRenderPass.Scene)
|
||||
.Select(emitter => emitter.Handle));
|
||||
Assert.Equal(new[] { sky },
|
||||
sys.EnumerateRenderableEmitters(ParticleRenderPass.SkyPreScene)
|
||||
.Select(emitter => emitter.Handle));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TickSnapshot_ToleratesNestedEmitterRemovalFromDeathCallback()
|
||||
{
|
||||
var sys = MakeSystem();
|
||||
var desc = new EmitterDesc
|
||||
{
|
||||
DatId = 0x32000082u,
|
||||
Type = ParticleType.Still,
|
||||
MaxParticles = 1,
|
||||
InitialParticles = 1,
|
||||
TotalParticles = 1,
|
||||
LifetimeMin = 0.01f,
|
||||
LifetimeMax = 0.01f,
|
||||
Lifespan = 0.01f,
|
||||
};
|
||||
int first = sys.SpawnEmitter(desc, Vector3.Zero);
|
||||
int second = sys.SpawnEmitter(desc, Vector3.Zero);
|
||||
sys.EmitterDied += handle =>
|
||||
{
|
||||
if (handle == first)
|
||||
sys.StopEmitter(second, fadeOut: false);
|
||||
};
|
||||
|
||||
sys.Tick(0.02f);
|
||||
sys.Tick(0.01f);
|
||||
|
||||
Assert.Equal(1, sys.LastTickEmitterVisitCount);
|
||||
Assert.Equal(0, sys.ActiveEmitterCount);
|
||||
Assert.Empty(sys.EnumerateEmitters());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FiniteEmitter_DegradedBranchExpiresAndRemovesIt()
|
||||
{
|
||||
|
|
@ -849,6 +1039,26 @@ public sealed class ParticleSystemTests
|
|||
Assert.False(sys.IsEmitterAlive(handle));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EmitterDied_AttemptsEverySubscriberWhenOneThrows()
|
||||
{
|
||||
var sys = MakeSystem();
|
||||
var delivered = new List<int>();
|
||||
sys.EmitterDied += _ => throw new InvalidOperationException("first subscriber failed");
|
||||
sys.EmitterDied += delivered.Add;
|
||||
|
||||
int handle = sys.SpawnEmitter(
|
||||
MakeDesc(emitRate: 5f, lifetime: 0.2f, maxParticles: 4),
|
||||
Vector3.Zero);
|
||||
|
||||
AggregateException failure = Assert.Throws<AggregateException>(
|
||||
() => sys.StopEmitter(handle, fadeOut: false));
|
||||
|
||||
Assert.Contains("first subscriber failed", failure.ToString());
|
||||
Assert.Equal([handle], delivered);
|
||||
Assert.False(sys.IsEmitterAlive(handle));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Birthrate_PerSec_EmitsOnePerTickWhenIntervalElapsed()
|
||||
{
|
||||
|
|
|
|||
|
|
@ -141,10 +141,10 @@ public class LandblockLoaderTests
|
|||
var idsB = entitiesLbB.Select(e => e.Id).ToArray();
|
||||
Assert.Empty(idsA.Intersect(idsB));
|
||||
|
||||
// The namespace top byte is 0xC0 for stabs (distinct from 0x80 scenery,
|
||||
// 0x40 interior, low-range live entities).
|
||||
Assert.All(idsA, id => Assert.Equal(0xC0u, (id >> 24) & 0xFFu));
|
||||
Assert.All(idsB, id => Assert.Equal(0xC0u, (id >> 24) & 0xFFu));
|
||||
// The namespace top nibble is 0xC for stabs (distinct from 0x8
|
||||
// scenery, 0x4 interior, and low-range live entities).
|
||||
Assert.All(idsA, id => Assert.True(LandblockStaticEntityIdAllocator.IsInNamespace(id)));
|
||||
Assert.All(idsB, id => Assert.True(LandblockStaticEntityIdAllocator.IsInNamespace(id)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
|
@ -186,17 +186,34 @@ public class LandblockLoaderTests
|
|||
Assert.Equal(1u, entities[0].Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BuildEntitiesFromInfo_MoreThan255EntriesStayInTheOwningLandblockRange()
|
||||
{
|
||||
var info = new LandBlockInfo();
|
||||
for (uint i = 0; i < 300u; i++)
|
||||
info.Objects.Add(new Stab { Id = 0x01000001u, Frame = new Frame() });
|
||||
|
||||
IReadOnlyList<WorldEntity> entities =
|
||||
LandblockLoader.BuildEntitiesFromInfo(info, landblockId: 0xA9B40000u);
|
||||
|
||||
Assert.Equal(300, entities.Count);
|
||||
Assert.Equal(300, entities.Select(entity => entity.Id).Distinct().Count());
|
||||
Assert.All(entities, entity =>
|
||||
Assert.True(LandblockStaticEntityIdAllocator.IsInNamespace(entity.Id)));
|
||||
Assert.True(entities[^1].Id < LandblockStaticEntityIdAllocator.Base(0xA9u, 0xB5u));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BuildEntitiesFromInfo_NamespacedIdOverflowFailsBeforeCrossLandblockAlias()
|
||||
{
|
||||
var info = new LandBlockInfo();
|
||||
for (uint i = 0; i < 256u; i++)
|
||||
for (uint i = 0; i <= LandblockStaticEntityIdAllocator.MaxCounter + 1u; i++)
|
||||
info.Objects.Add(new Stab { Id = 0x01000001u, Frame = new Frame() });
|
||||
|
||||
InvalidDataException error = Assert.Throws<InvalidDataException>(
|
||||
() => LandblockLoader.BuildEntitiesFromInfo(info, landblockId: 0xA9B40000u));
|
||||
|
||||
Assert.Contains("255-entry", error.Message, StringComparison.Ordinal);
|
||||
Assert.Contains("4096-entry", error.Message, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
|
|
|||
|
|
@ -0,0 +1,46 @@
|
|||
using AcDream.Core.World;
|
||||
|
||||
namespace AcDream.Core.Tests.World;
|
||||
|
||||
public sealed class LandblockStaticEntityIdAllocatorTests
|
||||
{
|
||||
[Fact]
|
||||
public void Base_PreservesFullCoordinatesAndStabNamespace()
|
||||
{
|
||||
var bases = new HashSet<uint>();
|
||||
for (uint y = 0; y <= 255; y++)
|
||||
for (uint x = 0; x <= 255; x++)
|
||||
{
|
||||
uint value = LandblockStaticEntityIdAllocator.Base(x, y);
|
||||
Assert.True(LandblockStaticEntityIdAllocator.IsInNamespace(value));
|
||||
Assert.True(bases.Add(value), $"duplicate base for ({x},{y})");
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MaximumCounterDoesNotAliasAdjacentLandblock()
|
||||
{
|
||||
for (uint y = 0; y < 255; y++)
|
||||
{
|
||||
uint current = LandblockStaticEntityIdAllocator.Base(0, y);
|
||||
uint next = LandblockStaticEntityIdAllocator.Base(0, y + 1);
|
||||
Assert.True(current + LandblockStaticEntityIdAllocator.MaxCounter < next);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Allocate_AcceptsLastCounterThenFailsBeforeNamespaceWrap()
|
||||
{
|
||||
uint counter = LandblockStaticEntityIdAllocator.MaxCounter;
|
||||
|
||||
uint last = LandblockStaticEntityIdAllocator.Allocate(0xA9u, 0xB4u, ref counter);
|
||||
|
||||
Assert.Equal(
|
||||
LandblockStaticEntityIdAllocator.Base(0xA9u, 0xB4u)
|
||||
+ LandblockStaticEntityIdAllocator.MaxCounter,
|
||||
last);
|
||||
InvalidDataException error = Assert.Throws<InvalidDataException>(
|
||||
() => LandblockStaticEntityIdAllocator.Allocate(0xA9u, 0xB4u, ref counter));
|
||||
Assert.Contains("4096-entry", error.Message, StringComparison.Ordinal);
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue