refactor(world): extract live entity teardown

This commit is contained in:
Erik 2026-07-21 18:25:59 +02:00
parent 4427cfb2c7
commit f38822c490
8 changed files with 565 additions and 159 deletions

View file

@ -0,0 +1,27 @@
using System.Numerics;
namespace AcDream.App.Physics;
/// <summary>
/// Session-scoped observation timestamps used to infer when a remote
/// locomotion cycle has stopped. Canonical live identity remains in
/// <c>LiveEntityRuntime</c>; this owner contains only derived observer state.
/// </summary>
internal sealed class RemoteMovementObservationTracker
{
private readonly Dictionary<uint, (Vector3 Pos, DateTime Time)> _lastMove = new();
internal (Vector3 Pos, DateTime Time) this[uint serverGuid]
{
set => _lastMove[serverGuid] = value;
}
internal bool TryGetValue(
uint serverGuid,
out (Vector3 Pos, DateTime Time) observation) =>
_lastMove.TryGetValue(serverGuid, out observation);
internal bool Remove(uint serverGuid) => _lastMove.Remove(serverGuid);
internal void Clear() => _lastMove.Clear();
}

View file

@ -372,8 +372,8 @@ public sealed class GameWindow : IDisposable, ILiveAnimationPresentationContext
// ACE Player_Tick.cs line 368: the client never sends "released forward"
// MoveToState, so the server never broadcasts an explicit stop. Observer
// must infer it from position deltas.
private readonly Dictionary<uint, (System.Numerics.Vector3 Pos, System.DateTime Time)>
_remoteLastMove = new();
private readonly AcDream.App.Physics.RemoteMovementObservationTracker
_remoteMovementObservations = new();
/// <summary>
/// Per-remote-entity movement state for smoothing between server
@ -397,8 +397,8 @@ public sealed class GameWindow : IDisposable, ILiveAnimationPresentationContext
/// keyed by server guid. Retail keeps these stamps on CPhysicsObj
/// (update_times); seeded from CreateObject's PhysicsDesc timestamp
/// block during <see cref="LiveEntityHydrationController.OnCreate"/>, consulted at the
/// top of <see cref="OnLiveMotionUpdated"/>, dropped with the entity in
/// <see cref="OnLiveEntityDeleted"/>.
/// top of <see cref="OnLiveMotionUpdated"/>, and dropped by the live
/// entity teardown owner.
/// </summary>
private AcDream.App.World.LiveEntityRuntime? _liveEntities;
private AcDream.App.World.LiveEntityLivenessController? _liveEntityLiveness;
@ -2064,6 +2064,8 @@ public sealed class GameWindow : IDisposable, ILiveAnimationPresentationContext
// N.5 mandatory path: spawn adapters + dispatcher always construct.
// _wbMeshAdapter, _meshShader, _textureCache, and _bindlessSupport are
// all guaranteed non-null here (startup throws above if any are missing).
var liveEntityComponentLifecycle =
new AcDream.App.World.DeferredLiveEntityRuntimeComponentLifecycle();
{
var wbSpawnAdapter = new AcDream.App.Rendering.Wb.LandblockSpawnAdapter(_wbMeshAdapter!);
// Sequencer factory: look up Setup + MotionTable from dats and build
@ -2212,8 +2214,6 @@ public sealed class GameWindow : IDisposable, ILiveAnimationPresentationContext
_worldState,
AdvanceLandblockPresentationRetirement);
var liveEntityComponentLifecycle =
new AcDream.App.World.DeferredLiveEntityRuntimeComponentLifecycle();
_liveEntities = new AcDream.App.World.LiveEntityRuntime(
_worldState,
new AcDream.App.World.CompositeLiveEntityResourceLifecycle(
@ -2224,9 +2224,6 @@ public sealed class GameWindow : IDisposable, ILiveAnimationPresentationContext
entityScriptActivator.OnCreate,
entityScriptActivator.OnRemove)),
liveEntityComponentLifecycle);
liveEntityComponentLifecycle.Bind(
new AcDream.App.World.DelegateLiveEntityRuntimeComponentLifecycle(
TearDownLiveEntityRuntimeComponents));
_liveEntities.ProjectionVisibilityChanged += (record, visible) =>
{
if (record.WorldEntity is { } entity)
@ -2237,10 +2234,6 @@ public sealed class GameWindow : IDisposable, ILiveAnimationPresentationContext
if (record.WorldEntity is { } entity)
_particleSink!.SetEntityPresentationVisible(entity.Id, visible);
};
_liveEntityLiveness = new AcDream.App.World.LiveEntityLivenessController(
_liveEntities,
() => _playerServerGuid,
OnLiveEntityPruned);
_projectileController = new AcDream.App.Physics.ProjectileController(
_liveEntities,
_physicsEngine,
@ -2566,6 +2559,24 @@ public sealed class GameWindow : IDisposable, ILiveAnimationPresentationContext
() => _playerServerGuid,
IsSealedDungeonCell,
Console.WriteLine);
var liveEntityTeardown =
new AcDream.App.World.LiveEntityRuntimeTeardownController(
_liveEntities,
_liveEntityPresentation!,
_entityEffects!,
_remoteTeleportController!,
_selectionInteractions,
_selection,
_animatedEntities,
_remoteMovementObservations,
_translucencyFades,
_liveEntityProjectionWithdrawal!,
_equippedChildRenderer!,
_physicsEngine.ShadowObjects,
_liveEntityLights!,
_classificationCache,
() => _playerServerGuid);
liveEntityComponentLifecycle.Bind(liveEntityTeardown);
_liveEntityHydration = new AcDream.App.World.LiveEntityHydrationController(
_liveEntities,
Objects,
@ -2579,9 +2590,14 @@ public sealed class GameWindow : IDisposable, ILiveAnimationPresentationContext
_liveEntityPresentation!),
originCoordinator,
networkUpdateBridge,
liveEntityTeardown,
PublishLocalPhysicsTimestamps,
() => _playerServerGuid,
_options.DumpLiveSpawns ? Console.WriteLine : null);
_liveEntityLiveness = new AcDream.App.World.LiveEntityLivenessController(
_liveEntities,
() => _playerServerGuid,
candidate => _liveEntityHydration.OnPrune(candidate));
parentAcceptance!.Bind(_liveEntityHydration.TryAcceptParentForProjection);
networkUpdateBridge.Bind(
new AcDream.App.World.DelegateLiveEntityNetworkUpdateSink(
@ -2691,7 +2707,7 @@ public sealed class GameWindow : IDisposable, ILiveAnimationPresentationContext
NetworkEffects = () => _entityEffects?.ClearNetworkState(),
AnimationHookFrames = () => _animationHookFrames?.Clear(),
LivePresentation = () => _liveEntityPresentation?.Clear(),
RemoteMovementDiagnostics = _remoteLastMove.Clear,
RemoteMovementDiagnostics = _remoteMovementObservations.Clear,
});
private void ResetSessionMouseCapture()
@ -2831,7 +2847,8 @@ public sealed class GameWindow : IDisposable, ILiveAnimationPresentationContext
spawn,
static (hydration, value) => hydration.OnCreate(value)),
Deleted: deletion => _inboundEntityEvents.Run(
this, deletion, static (window, value) => window.OnLiveEntityDeleted(value)),
_liveEntityHydration!, deletion,
static (hydration, value) => hydration.OnDelete(value)),
PickedUp: pickup => _inboundEntityEvents.Run(
_liveEntityHydration!, pickup,
static (hydration, value) => hydration.OnPickup(value)),
@ -3015,41 +3032,6 @@ public sealed class GameWindow : IDisposable, ILiveAnimationPresentationContext
block.Height, heightTable, landblockX, landblockY, localX, localY);
}
private void OnLiveEntityDeleted(AcDream.Core.Net.Messages.DeleteObject.Parsed delete)
{
// A Delete can arrive before CreateObject, in which case no instance
// timestamp owner exists and its mixed pending effect FIFO must be
// discarded directly. For a known record, cleanup belongs after the
// generation gate: a stale Delete must not cancel the current owner.
if (_liveEntities?.TryGetRecord(delete.Guid, out _) != true)
_entityEffects?.ForgetUnknownOwner(delete.Guid);
bool removed = _liveEntities!.UnregisterLiveEntity(
delete,
isLocalPlayer: delete.Guid == _playerServerGuid,
beforeTeardown: () =>
{
AcDream.Core.Net.ObjectTableWiring.ApplyEntityDelete(Objects, delete);
});
if (removed
&& Environment.GetEnvironmentVariable("ACDREAM_DUMP_MOTION") == "1")
{
Console.WriteLine(
$"live: delete guid=0x{delete.Guid:X8} instSeq={delete.InstanceSequence}");
}
}
private void OnLiveEntityPruned(AcDream.App.World.LiveEntityPruneCandidate candidate)
{
// ACE retains KnownObjects across normal teleports and consequently
// does not issue an F747 when an old region leaves client visibility.
// Route the 25-second client liveness expiry through the exact same
// generation gate and symmetric teardown as a wire ObjectDelete.
OnLiveEntityDeleted(new AcDream.Core.Net.Messages.DeleteObject.Parsed(
candidate.ServerGuid,
candidate.Generation));
}
/// <summary>
/// Rebuilds the paperdoll doll from the live player entity (retail makeObject(player) +
/// DoObjDescChangesFromDefault). Clones the player's already-resolved Setup / MeshRefs / palette /
@ -3556,105 +3538,6 @@ public sealed class GameWindow : IDisposable, ILiveAnimationPresentationContext
hiddenEntityHost.NotifyHidden();
}
private void TearDownLiveEntityRuntimeComponents(LiveEntityRecord record)
{
record.RuntimeComponentTeardownPlan ??= CreateLiveEntityRuntimeTeardownPlan(record);
record.RuntimeComponentTeardownPlan.Advance();
}
private AcDream.App.World.LiveEntityTeardownPlan CreateLiveEntityRuntimeTeardownPlan(
LiveEntityRecord record)
{
uint serverGuid = record.ServerGuid;
var incarnation = new AcDream.App.World.LiveEntityIncarnationCleanup(
record,
guid => _liveEntities?.TryGetRecord(guid, out LiveEntityRecord current) == true
? current
: null);
var cleanups = new List<Action>
{
() => _liveEntityPresentation?.Forget(record),
() => _entityEffects?.OnLiveEntityUnregistered(record),
() => _remoteTeleportController?.Forget(record),
() =>
{
bool replacementExists =
_liveEntities?.TryGetRecord(serverGuid, out LiveEntityRecord current) == true
&& !ReferenceEquals(current, record);
if (_selectionInteractions is { } interactions)
{
interactions.OnEntityRemoved(record, replacementExists);
}
else if (!replacementExists && _selection.SelectedObjectId == serverGuid)
{
_selection.Clear(
AcDream.Core.Selection.SelectionChangeSource.System,
AcDream.Core.Selection.SelectionChangeReason.SelectedObjectRemoved);
}
},
};
if (record.WorldEntity is not { } existingEntity)
{
return new AcDream.App.World.LiveEntityTeardownPlan(cleanups);
}
// R2-Q5 + R3-W2: retail runs BOTH layers' exit-world drains
// independently (r3-port-plan §4): the manager's (each pending
// animation fires MotionDone(success:false) → the bound interp pops
// in step) THEN the interp's own (flushes any remainder —
// MovementManager::HandleExitWorld 0x00524350, the R5-V5 facade
// relay: interp ONLY → CMotionInterp::HandleExitWorld 0x00527f30).
if (_animatedEntities.TryGetValue(existingEntity.Id, out var aeGone))
cleanups.Add(() => aeGone.Sequencer?.Manager.HandleExitWorld());
RemoteMotion? rmGone = record.RemoteMotionRuntime as RemoteMotion;
if (rmGone is not null)
cleanups.Add(rmGone.Movement.HandleExitWorld);
// R5-V2: retail CPhysicsObj::exit_world tells every voyeur of this
// entity that it left the world (TargetManager::NotifyVoyeurOfEvent
// ExitWorld) — a watcher moving-to/stuck-to this entity drops the
// moveto/stick. This is the ONLY clean-up for a watcher whose target
// already sent an Ok (once status != Undefined the 10 s staleness
// timeout never fires), so it must run before the host is pruned.
EntityPhysicsHost? ephGone = record.PhysicsHost as EntityPhysicsHost;
if (ephGone is not null)
{
// R5-V3 (#171): retail exit_world (0x00514e60) order — the
// departing entity first tears down its OWN stick
// (PositionManager::UnStick @0x00514e88 — drops its voyeur
// subscription on whatever it was stuck to) and its own target
// subscription (TargetManager::ClearTarget @0x00514e97 — same
// for a plain mid-chase moveto), THEN NotifyVoyeurOfEvent
// (ExitWorld) tells the entities watching IT. Without the first
// two, a despawning attacker leaves a dead voyeur entry on its
// target until send-failure pruning.
cleanups.Add(ephGone.PositionManager.UnStick);
cleanups.Add(ephGone.ClearTarget);
cleanups.Add(ephGone.NotifyExitWorld);
}
cleanups.Add(() => _animatedEntities.Remove(existingEntity.Id));
cleanups.Add(() => _classificationCache.InvalidateEntity(existingEntity.Id));
// Dead-reckon state is keyed by SERVER guid (not local id) so we
// clear using the same guid the next spawn/update would use.
// LiveEntityRuntime removes the canonical remote-motion index by
// captured reference after this App teardown plan converges. Never use
// the GUID-only dictionary view here: it may already expose a newer
// incarnation.
cleanups.Add(() => incarnation.RunIfNoReplacement(
() => _remoteLastMove.Remove(serverGuid)));
cleanups.Add(() => _translucencyFades.ClearEntity(existingEntity.Id)); // #188
cleanups.Add(() => _liveEntityProjectionWithdrawal!.LeaveWorld(
record,
_playerServerGuid));
cleanups.Add(() => _equippedChildRenderer?.OnLogicalTeardown(record));
// Logical teardown ends the retained shadow payload too. The weaker
// pickup/parent path stops after Suspend so re-entry can restore it.
cleanups.Add(() => _physicsEngine.ShadowObjects.Deregister(existingEntity.Id));
cleanups.Add(() => _liveEntityLights?.Forget(existingEntity.Id));
return new AcDream.App.World.LiveEntityTeardownPlan(cleanups);
}
/// <summary>
/// R4-V5: shared retail <c>unpack_movement</c> type-6..9 routing
/// (<c>0x00524440</c> cases 6/7/8/9, decomp §2f) — one body for remotes
@ -4149,9 +4032,9 @@ public sealed class GameWindow : IDisposable, ILiveAnimationPresentationContext
}
// CRITICAL: when we enter a locomotion cycle (Walk/Run/etc),
// stamp the _remoteLastMove timestamp to "now". Without this,
// stamp the remote observation timestamp to "now". Without this,
// the stop-detection loop in TickAnimations sees the previous
// _remoteLastMove timestamp (set by the last UpdatePosition,
// observation timestamp (set by the last UpdatePosition,
// often >300ms ago during idle) and fires the stop signal
// IMMEDIATELY — flipping the sequencer straight back to Ready.
// The visible symptom was "remote char never animates; just
@ -4172,8 +4055,8 @@ public sealed class GameWindow : IDisposable, ILiveAnimationPresentationContext
// window from this transition. Without this, the entity
// starts its run animation and is instantly interrupted.
var refreshedTime = System.DateTime.UtcNow;
if (_remoteLastMove.TryGetValue(update.Guid, out var prev))
_remoteLastMove[update.Guid] = (prev.Pos, refreshedTime);
if (_remoteMovementObservations.TryGetValue(update.Guid, out var prev))
_remoteMovementObservations[update.Guid] = (prev.Pos, refreshedTime);
if (_remoteDeadReckon.TryGetValue(update.Guid, out var dr))
dr.LastServerPosTime = (refreshedTime - System.DateTime.UnixEpoch).TotalSeconds;
}
@ -4936,16 +4819,16 @@ public sealed class GameWindow : IDisposable, ILiveAnimationPresentationContext
if (update.Guid != _playerServerGuid)
{
var now = System.DateTime.UtcNow;
if (_remoteLastMove.TryGetValue(update.Guid, out var prev))
if (_remoteMovementObservations.TryGetValue(update.Guid, out var prev))
{
float moveDist = System.Numerics.Vector3.Distance(prev.Pos, worldPos);
if (moveDist > 0.05f)
_remoteLastMove[update.Guid] = (worldPos, now);
_remoteMovementObservations[update.Guid] = (worldPos, now);
// else: leave old entry so "Time" = last real movement time
}
else
{
_remoteLastMove[update.Guid] = (worldPos, now);
_remoteMovementObservations[update.Guid] = (worldPos, now);
}
// Retail-faithful hard-snap on UpdatePosition.
@ -7519,7 +7402,7 @@ public sealed class GameWindow : IDisposable, ILiveAnimationPresentationContext
// after that callback stack has unwound on the same update thread.
try
{
_liveEntities?.RetryPendingTeardowns();
_liveEntityHydration?.RetryPendingTeardowns();
}
catch (AggregateException error)
{

View file

@ -146,6 +146,7 @@ internal sealed class LiveEntityHydrationController
private readonly ILiveEntityReadyPublisher _ready;
private readonly ILiveEntityWorldOriginCoordinator _origin;
private readonly ILiveEntityNetworkUpdateSink _networkUpdates;
private readonly ILiveEntityTeardownCoordinator _teardown;
private readonly Action<uint, AcceptedPhysicsTimestamps> _publishTimestamps;
private readonly Func<uint> _playerGuid;
private readonly Action<string>? _diagnostic;
@ -159,6 +160,7 @@ internal sealed class LiveEntityHydrationController
ILiveEntityReadyPublisher ready,
ILiveEntityWorldOriginCoordinator origin,
ILiveEntityNetworkUpdateSink networkUpdates,
ILiveEntityTeardownCoordinator teardown,
Action<uint, AcceptedPhysicsTimestamps> publishTimestamps,
Func<uint> playerGuid,
Action<string>? diagnostic = null)
@ -171,6 +173,7 @@ internal sealed class LiveEntityHydrationController
_ready = ready ?? throw new ArgumentNullException(nameof(ready));
_origin = origin ?? throw new ArgumentNullException(nameof(origin));
_networkUpdates = networkUpdates ?? throw new ArgumentNullException(nameof(networkUpdates));
_teardown = teardown ?? throw new ArgumentNullException(nameof(teardown));
_publishTimestamps = publishTimestamps
?? throw new ArgumentNullException(nameof(publishTimestamps));
_playerGuid = playerGuid ?? throw new ArgumentNullException(nameof(playerGuid));
@ -339,6 +342,47 @@ internal sealed class LiveEntityHydrationController
return accepted;
}
/// <summary>
/// Retail <c>SmartBox::HandleDeleteObject @ 0x00451EA0</c> rejects the
/// player, requires the exact Instance timestamp, then performs one
/// symmetric logical teardown. An unknown owner only loses queued
/// pre-create effect packets.
/// </summary>
public bool OnDelete(DeleteObject.Parsed delete)
{
// SmartBox::HandleDeleteObject rejects the player before resolving an
// object or touching any queued owner state. A pre-Create player
// Delete must therefore be side-effect-free too.
if (delete.Guid == _playerGuid())
return false;
if (!_runtime.TryGetRecord(delete.Guid, out _))
_teardown.ForgetUnknownOwner(delete.Guid);
bool removed = _runtime.UnregisterLiveEntity(
delete,
isLocalPlayer: false,
beforeTeardown: () =>
ObjectTableWiring.ApplyEntityDelete(_objects, delete));
if (removed)
{
_diagnostic?.Invoke(
$"live: delete guid=0x{delete.Guid:X8} instSeq={delete.InstanceSequence}");
}
return removed;
}
/// <summary>
/// Retail's 25-second visibility expiry converges through the same exact
/// generation gate and teardown transaction as an authoritative F747.
/// </summary>
public bool OnPrune(LiveEntityPruneCandidate candidate) =>
OnDelete(new DeleteObject.Parsed(
candidate.ServerGuid,
candidate.Generation));
public int RetryPendingTeardowns() => _runtime.RetryPendingTeardowns();
/// <summary>
/// Parent events may precede either CreateObject. The relationship owner
/// retains wire order and invokes <see cref="TryAcceptParentForProjection"/>

View file

@ -0,0 +1,167 @@
using AcDream.App.Interaction;
using AcDream.App.Physics;
using AcDream.App.Rendering;
using AcDream.App.Rendering.Vfx;
using AcDream.App.Rendering.Wb;
using AcDream.Core.Physics;
using AcDream.Core.Rendering;
using AcDream.Core.Selection;
namespace AcDream.App.World;
internal interface ILiveEntityTeardownCoordinator
: ILiveEntityRuntimeComponentLifecycle
{
void ForgetUnknownOwner(uint serverGuid);
}
/// <summary>
/// Owns the retryable App-component half of retail
/// <c>CObjectMaint::DeleteObject @ 0x00508460</c>. Each successful cleanup is
/// committed on the exact record tombstone, so a later retry never repeats an
/// ExitWorld notification or removes a same-GUID replacement.
/// </summary>
internal sealed class LiveEntityRuntimeTeardownController
: ILiveEntityTeardownCoordinator
{
private readonly LiveEntityRuntime? _runtime;
private readonly LiveEntityPresentationController? _presentation;
private readonly EntityEffectController? _effects;
private readonly RemoteTeleportController? _remoteTeleport;
private readonly SelectionInteractionController? _interactions;
private readonly SelectionState? _selection;
private readonly LiveEntityAnimationRuntimeView<LiveEntityAnimationState>? _animations;
private readonly RemoteMovementObservationTracker? _remoteMovementObservations;
private readonly TranslucencyFadeManager? _translucencyFades;
private readonly LiveEntityProjectionWithdrawalController? _projectionWithdrawal;
private readonly EquippedChildRenderController? _children;
private readonly ShadowObjectRegistry? _shadows;
private readonly LiveEntityLightController? _lights;
private readonly EntityClassificationCache? _classification;
private readonly Func<uint>? _playerGuid;
private readonly Func<LiveEntityRecord, LiveEntityTeardownPlan> _createPlan;
private readonly Action<uint> _forgetUnknownOwner;
public LiveEntityRuntimeTeardownController(
LiveEntityRuntime runtime,
LiveEntityPresentationController presentation,
EntityEffectController effects,
RemoteTeleportController remoteTeleport,
SelectionInteractionController? interactions,
SelectionState selection,
LiveEntityAnimationRuntimeView<LiveEntityAnimationState> animations,
RemoteMovementObservationTracker remoteMovementObservations,
TranslucencyFadeManager translucencyFades,
LiveEntityProjectionWithdrawalController projectionWithdrawal,
EquippedChildRenderController children,
ShadowObjectRegistry shadows,
LiveEntityLightController lights,
EntityClassificationCache classification,
Func<uint> playerGuid)
{
_runtime = runtime ?? throw new ArgumentNullException(nameof(runtime));
_presentation = presentation ?? throw new ArgumentNullException(nameof(presentation));
_effects = effects ?? throw new ArgumentNullException(nameof(effects));
_remoteTeleport = remoteTeleport ?? throw new ArgumentNullException(nameof(remoteTeleport));
_interactions = interactions;
_selection = selection ?? throw new ArgumentNullException(nameof(selection));
_animations = animations ?? throw new ArgumentNullException(nameof(animations));
_remoteMovementObservations = remoteMovementObservations
?? throw new ArgumentNullException(nameof(remoteMovementObservations));
_translucencyFades = translucencyFades
?? throw new ArgumentNullException(nameof(translucencyFades));
_projectionWithdrawal = projectionWithdrawal
?? throw new ArgumentNullException(nameof(projectionWithdrawal));
_children = children ?? throw new ArgumentNullException(nameof(children));
_shadows = shadows ?? throw new ArgumentNullException(nameof(shadows));
_lights = lights ?? throw new ArgumentNullException(nameof(lights));
_classification = classification
?? throw new ArgumentNullException(nameof(classification));
_playerGuid = playerGuid ?? throw new ArgumentNullException(nameof(playerGuid));
_createPlan = CreatePlan;
_forgetUnknownOwner = effects.ForgetUnknownOwner;
}
internal LiveEntityRuntimeTeardownController(
Func<LiveEntityRecord, LiveEntityTeardownPlan> createPlan,
Action<uint> forgetUnknownOwner)
{
_createPlan = createPlan ?? throw new ArgumentNullException(nameof(createPlan));
_forgetUnknownOwner = forgetUnknownOwner
?? throw new ArgumentNullException(nameof(forgetUnknownOwner));
}
public void TearDown(LiveEntityRecord record)
{
ArgumentNullException.ThrowIfNull(record);
record.RuntimeComponentTeardownPlan ??= _createPlan(record);
record.RuntimeComponentTeardownPlan.Advance();
}
public void ForgetUnknownOwner(uint serverGuid) =>
_forgetUnknownOwner(serverGuid);
private LiveEntityTeardownPlan CreatePlan(LiveEntityRecord record)
{
LiveEntityRuntime runtime = _runtime!;
uint serverGuid = record.ServerGuid;
var incarnation = new LiveEntityIncarnationCleanup(
record,
guid => runtime.TryGetRecord(guid, out LiveEntityRecord current)
? current
: null);
var cleanups = new List<Action>
{
() => _presentation!.Forget(record),
() => _effects!.OnLiveEntityUnregistered(record),
() => _remoteTeleport!.Forget(record),
() =>
{
bool replacementExists =
runtime.TryGetRecord(serverGuid, out LiveEntityRecord current)
&& !ReferenceEquals(current, record);
if (_interactions is { } interactions)
{
interactions.OnEntityRemoved(record, replacementExists);
}
else if (!replacementExists
&& _selection!.SelectedObjectId == serverGuid)
{
_selection.Clear(
SelectionChangeSource.System,
SelectionChangeReason.SelectedObjectRemoved);
}
},
};
if (record.WorldEntity is not { } existingEntity)
return new LiveEntityTeardownPlan(cleanups);
// CPhysicsObj::exit_world @ 0x00514E60 drains the PartArray and
// MovementManager before unsticking/clearing the object's target and
// notifying its voyeurs. Preserve the two independent motion drains.
if (_animations!.TryGetValue(existingEntity.Id, out LiveEntityAnimationState animation))
cleanups.Add(() => animation.Sequencer?.Manager.HandleExitWorld());
if (record.RemoteMotionRuntime is RemoteMotion remoteMotion)
cleanups.Add(remoteMotion.Movement.HandleExitWorld);
if (record.PhysicsHost is EntityPhysicsHost physicsHost)
{
cleanups.Add(physicsHost.PositionManager.UnStick);
cleanups.Add(physicsHost.ClearTarget);
cleanups.Add(physicsHost.NotifyExitWorld);
}
cleanups.Add(() => _animations.Remove(existingEntity.Id));
cleanups.Add(() => _classification!.InvalidateEntity(existingEntity.Id));
cleanups.Add(() => incarnation.RunIfNoReplacement(
() => _remoteMovementObservations!.Remove(serverGuid)));
cleanups.Add(() => _translucencyFades!.ClearEntity(existingEntity.Id));
cleanups.Add(() => _projectionWithdrawal!.LeaveWorld(
record,
_playerGuid!()));
cleanups.Add(() => _children!.OnLogicalTeardown(record));
cleanups.Add(() => _shadows!.Deregister(existingEntity.Id));
cleanups.Add(() => _lights!.Forget(existingEntity.Id));
return new LiveEntityTeardownPlan(cleanups);
}
}