feat(runtime): C3c - production placement cutover: both hosts on the residence conductors (routes 1+8)

Campaign P remaining-physics-divergence, placement cutover slice C3c
(docs/plans/2026-08-02-placement-cutover.md). Both production hosts now
register every initial Create through the residence + continuation-
executor + first-entry-conductor machinery (C0-C3b):

- Graphical (route 1): RegisterEntityWithInitialResidence at Create; the
  shared RuntimeFirstEntryDriveController pumps both conductors from the
  placement-receipt flow; MaterializeProjection and RebucketLiveEntity
  are presentation-only while a residence is ACTIVE (ExecutorCompleted is
  the presentation-binding receipt); post-residence entities take the
  full legacy path including the prepare_to_enter_world clock edges.
  PlayerModeController attaches presentation to the Runtime-published
  controller; its legacy resolve/step-heights/host-construction path is
  deleted; presentation-only rollback (retail has no entry-flow rollback).
- Headless (route 8): OnSpawned registers with residence when a drive
  exists; content-less sessions keep the pre-flip direct registration;
  SynchronizeLocalPlayer/CreateController/ApplySetupStepHeights deleted;
  prepared-collision read failure is a typed AwaitingCollisionSource
  retry; far remotes outside the service window complete celless.
- RuntimeLocalPlayerMovementState.Controller setter sealed internal; all
  controller mutation flows through the publication lifecycle.

Fix slices landed within this cutover, each dual-gated:
- F1: live movement-stat/server-physics application routed through the
  Runtime ownership seam (post-logout ingest crash on the retired
  controller eliminated; RuntimeMovementSkillProjection deleted).
- F2: login activation wedge - collision-admission prefix gate factored
  out of the seal (reentrant-commit RejectedAuthority), rearm generation
  identity corrected, PlayerModeAutoEntry requires the Runtime-published
  controller (world reveal can no longer seal unmaterialized).
- F3: landblock-prefix 0-sentinel replaced by explicit absent-id guards;
  map-corner landblocks (grid row/col 0) fully legal through admission,
  park/rearm/retire, quiescence, and outdoor shadow seeds.
- F5: local-player first-entry ground contact seeded by the shared
  SpawnPlacementSettler (moved App->Core) at FinalizeActivation - the
  retail first-gravity-frame touch (enter_world 0x00516170 carries no
  seed); the legacy unconditional force-seed is overwritten by a real
  floor-found contact; airborne spawns stay airborne; outbound contact
  bit verified end-to-end. Fixes the standing-cast 'You can't do that
  while in the air!' rejections.
- R1 (dual-review round): login constraint leash armed at the committed
  placement (HandleReceivedPosition 0x00453FD0 analog); register rows
  AD-61 (settle-timing compression now covering the local player) and
  AD-42 (repointed off the deleted resolve split) in this commit;
  residence-conversion owner API; wire-landblock guards; drive-pending
  ledger in IsConverged; route attach/detach latch; executor-drain drift
  model documented + source-pinned.

Gates: Runtime 1,003, App 4,039/3 skips, Headless 79, complete solution
10,816/0 failed/4 skips (Release, -m:1); connected lifecycle/reconnect
gate PASS (logs/connected-world-gate-20260802-175401; graceful exits,
world-visible, zero airborne rejections). The nine-stop soak remains red
for the pre-existing 6b28ff99 whole-world collision-clone throughput
regression (attributed with evidence; scheduled as its own slice before
C5). Dual Opus reviews (retail-conformance + adversarial): delta PASS.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Erik 2026-08-02 18:10:33 +02:00
parent 78f1eb1896
commit 529e0e9d88
68 changed files with 5977 additions and 831 deletions

View file

@ -500,6 +500,79 @@ internal sealed class SessionPlayerCompositionPhase
d.PlayerIdentity,
dormantLiveEntities,
d.Options.DumpLiveSpawns ? d.Log : null);
// C3c: the graphical first-entry drive controller — walks every
// initial-Create residence through its Runtime conductor with the
// production prepared-collision source, the live movement-skill
// options, and the truthful local-player activation preparation
// (authored-cylinder radius/height with the legacy fallbacks, and
// the shadow disposition read from the exact shadow registry the
// activation commit validates against).
IPreparedCollisionSource firstEntryCollision =
content.PreparedAssets as IPreparedCollisionSource
?? throw new NotSupportedException(
"Production prepared assets must expose the matching "
+ "prepared-collision catalog.");
// C3c-R1 review F9: the provider runs on EVERY drive pump while the
// entity's conductor is still yielding, and the Setup cylinder per
// incarnation is immutable (SourceGfxObjOrSetupId and the spawn
// record's ObjScale are fixed at Create) — cache the resolved
// world-entity lookup + GetSetupCylinder per pending incarnation
// (keyed by the incarnation-unique local id; an unresolved/default
// result is NOT cached so late hydration still upgrades it). The
// shadow disposition deliberately stays live: shadow registration
// can land between pumps and the activation commit validates the
// disposition against the exact registry.
uint firstEntryCylinderLocalId = 0u;
float firstEntryCylinderRadius = 0f;
float firstEntryCylinderHeight = 0f;
var firstEntryDrive = new RuntimeFirstEntryDriveController(
d.EntityObjects,
d.Runtime.Clock,
firstEntryCollision,
() => PlayerMovementConstructionOptions.From(
d.Runtime.CharacterOwner.MovementSkills.Snapshot),
record =>
{
float radius = 0.48f;
float height = 1.835f;
uint localId = record.Key?.LocalEntityId ?? 0u;
if (localId != 0u && localId == firstEntryCylinderLocalId)
{
radius = firstEntryCylinderRadius;
height = firstEntryCylinderHeight;
}
else if (live.LiveEntities.TryGetWorldEntity(
record.ServerGuid,
out WorldEntity? playerEntity)
&& playerEntity is not null)
{
(float setupRadius, float setupHeight) =
d.MotionBindings.GetSetupCylinder(
record.ServerGuid,
playerEntity);
if (setupRadius >= 0.05f)
{
radius = setupRadius;
height = setupHeight;
if (localId != 0u)
{
firstEntryCylinderLocalId = localId;
firstEntryCylinderRadius = radius;
firstEntryCylinderHeight = height;
}
}
}
bool hasAuthoredShadow = record.Key is { } key
&& d.PhysicsEngine.ShadowObjects.HasLogicalOwner(
key.LocalEntityId);
return new RuntimeLocalPlayerPhysicsActivationPreparation(
radius,
height,
hasAuthoredShadow
? RuntimeLocalPlayerShadowDisposition
.RegisteredAuthoredPayload
: RuntimeLocalPlayerShadowDisposition.ProvenShapeless);
});
var hydration = new LiveEntityHydrationController(
live.LiveEntities,
d.EntityObjects,
@ -517,7 +590,8 @@ internal sealed class SessionPlayerCompositionPhase
d.PlayerIdentity,
deletion,
dormantLiveEntities,
d.Options.DumpLiveSpawns ? d.Log : null);
d.Options.DumpLiveSpawns ? d.Log : null,
firstEntryDrive);
bindings.Adopt(
"landblock-loaded hydration",
live.LandblockLoaded.Bind(hydration));
@ -884,7 +958,8 @@ internal sealed class SessionPlayerCompositionPhase
d.RemoteMovementObservations,
live.RenderSceneShadow,
live.PlacementProjection,
placementProjectionRetry),
placementProjectionRetry,
firstEntryDrive),
liveSessionCommands,
d.Log);
LiveSessionHost sessionHost = sessionRuntimeFactory.Create(

View file

@ -2,6 +2,7 @@ using System;
using AcDream.App.Net;
using AcDream.App.Streaming;
using AcDream.App.World;
using AcDream.Runtime.Physics;
namespace AcDream.App.Input;
@ -83,7 +84,24 @@ internal sealed class LivePlayerModeAutoEntryContext
public bool IsPlayerEntityPresent =>
_liveEntities.ContainsWorldEntity(_identity.ServerGuid);
public bool IsPlayerControllerReady => true;
/// <summary>
/// C3c-F2: post-flip the movement controller is Runtime-owned, so this
/// precondition has to report the Runtime first-entry conductor's commit
/// — exactly what <c>PlayerModeController.TryEnter</c> requires. It was
/// the constant <c>true</c>, which was harmless only while entry itself
/// CONSTRUCTED the controller and therefore could not fail on it. After
/// the flip a not-yet-committed conductor made entry return false, and
/// because this guard is a one-shot that disarms before invoking (and
/// <see cref="EnterPlayerMode"/> completes the world reveal
/// unconditionally), a single early attempt permanently sealed the reveal
/// with the player never in world.
/// </summary>
public bool IsPlayerControllerReady =>
_playerMode.Controller is { IsRuntimePublished: true }
&& _liveEntities.TryGetRecord(
_identity.ServerGuid,
out LiveEntityRecord record)
&& record.PhysicsHost is EntityPhysicsHost;
public bool IsWorldReady =>
_liveEntities.TryGetSnapshot(

View file

@ -164,7 +164,9 @@ internal sealed class PlayerModeController :
try { RetireApproachLifetime(); }
catch (Exception error) { failures.Add(error); }
_mode.IsPlayerMode = false;
_controllerSlot.Controller = null;
// C3c: the movement controller is Runtime-owned — player-mode exit
// detaches presentation only; the publication lifecycle (generation
// reset/teardown) owns the controller's retirement.
_hostSlot.Host = null;
_chase.Legacy = null;
_chase.Retail = null;
@ -201,7 +203,9 @@ internal sealed class PlayerModeController :
try { RetireApproachLifetime(); }
catch (Exception error) { failures.Add(error); }
_mode.ResetSession();
_controllerSlot.Controller = null;
// C3c: the Runtime generation reset retires the controller through
// RuntimeLocalPlayerMovementState.ResetSession; App detaches
// presentation only.
_hostSlot.Host = null;
_chase.Legacy = null;
_chase.Retail = null;
@ -233,6 +237,19 @@ internal sealed class PlayerModeController :
return false;
}
// C3c: player mode attaches presentation to the Runtime-published
// controller/host; until the first-entry conductor commits them,
// entry simply retries on a later frame.
if (_controllerSlot.Controller is not { } publishedController
|| !publishedController.IsRuntimePublished
|| playerRecord.PhysicsHost is not EntityPhysicsHost)
{
Console.WriteLine(
$"live: {loggingTag} — Runtime first-entry controller for "
+ $"0x{playerGuid:X8} not committed yet");
return false;
}
BuildControllerAndCamera(
loggingTag,
playerGuid,
@ -247,6 +264,32 @@ internal sealed class PlayerModeController :
WorldEntity playerEntity,
LiveEntityRecord playerRecord)
{
// C3c route-1 flip: the movement controller, physics body, host, and
// committed placement are Runtime-owned — constructed and activated
// by the first-entry conductor's publication chain before player
// mode can enter. This method attaches only App presentation
// (approach lifetime, animation bindings, camera, shadow, host
// slot). A failure here rolls back camera/shadow ONLY and never
// touches Runtime. C3c-R1 review F8: auto-entry does NOT retry a
// throw from this attach — PlayerModeAutoEntry.TryEnter disarms its
// one-shot BEFORE invoking EnterPlayerMode, so an exception here
// burns the shot; recovery is the manual Tab entry (or a session
// reset re-arming the trigger).
if (_controllerSlot.Controller is not { } controller
|| !controller.IsRuntimePublished)
{
throw new InvalidOperationException(
$"Player mode ({loggingTag}) requires the Runtime-published "
+ "local movement controller; the first-entry conductor has "
+ "not committed it yet.");
}
if (playerRecord.PhysicsHost is not EntityPhysicsHost playerHost)
{
throw new InvalidOperationException(
$"Player mode ({loggingTag}) requires the Runtime-committed "
+ "local physics host.");
}
IPlayerApproachCompletionSink approachLifetime =
_approachCompletions.BeginControllerLifetime();
bool lifetimeCommitted = false;
@ -256,46 +299,11 @@ internal sealed class PlayerModeController :
LocalPlayerShadowState.Snapshot? priorShadow = _shadow.Capture();
try
{
var controller = new PlayerMovementController(
_physics,
playerRecord.ObjectClock,
PlayerMovementConstructionOptions.From(_skills.Snapshot));
controller.ApplyPhysicsState(playerRecord.FinalPhysicsState);
// Retail MovementManager::MakeMoveToManager @ 0x00524000 creates one
// MoveToManager facade over the local CPhysicsObj seams.
PlayerMovementController capturedController = controller;
EntityPhysicsHost playerHost = null!;
controller.Movement.MoveToFactory = () =>
// Approach-completion presentation rides the Runtime-owned
// MoveToManager (created by the publication chain's own
// MakeMoveToManager).
if (controller.MoveTo is { } moveTo)
{
var moveTo = new MoveToManager(
capturedController.Motion,
stopCompletely: () =>
capturedController.StopCompletelyAtPhysicsObjectBoundary(),
getPosition: () => new Position(
capturedController.CellId,
capturedController.Position,
capturedController.BodyOrientation),
getHeading: () => MoveToMath.HeadingFromYaw(capturedController.Yaw),
setHeading: (heading, _) => capturedController.Yaw =
MoveToMath.YawFromHeading(heading),
getOwnRadius: () => _motionBindings.GetSetupCylinder(
playerGuid,
playerEntity).Radius,
getOwnHeight: () => _motionBindings.GetSetupCylinder(
playerGuid,
playerEntity).Height,
contact: () => capturedController.BodyInContact,
isInterpolating: () => false,
getVelocity: () => capturedController.BodyVelocity,
getSelfId: () => playerGuid,
setTarget: (context, target, radius, quantum) =>
playerHost.SetTarget(context, target, radius, quantum),
clearTarget: playerHost.ClearTarget,
getTargetQuantum: () => playerHost.TargetManager.GetTargetQuantum(),
setTargetQuantum: playerHost.TargetManager.SetTargetQuantum,
curTime: () => capturedController.SimTimeSeconds);
moveTo.MoveToComplete = error =>
{
if (PhysicsDiagnostics.ProbeAutoWalkEnabled)
@ -307,75 +315,8 @@ internal sealed class PlayerModeController :
};
moveTo.MoveToCancelled = error =>
approachLifetime.PublishCancellation(error);
moveTo.StickTo = (target, radius, height) =>
playerHost.PositionManager.StickTo(target, radius, height);
moveTo.Unstick = () => playerHost.PositionManager.UnStick();
return moveTo;
};
MovementManager exactMovement = controller.Movement;
var configuredHost = new EntityPhysicsHost(
playerGuid,
getPosition: () => new Position(
playerRecord.FullCellId,
playerRecord.WorldEntity?.Position ?? capturedController.Position,
capturedController.BodyOrientation),
getVelocity: () => capturedController.BodyVelocity,
getRadius: () => _motionBindings.GetSetupCylinder(
playerGuid,
playerEntity).Radius,
inContact: () => capturedController.BodyInContact,
minterpMaxSpeed: () => capturedController.Motion.GetAdjustedMaxSpeed(),
curTime: () => capturedController.SimTimeSeconds,
physicsTimerTime: () => capturedController.SimTimeSeconds,
getObjectA: _motionBindings.ResolvePhysicsHost,
handleUpdateTarget: info =>
{
if (PhysicsDiagnostics.ProbeAutoWalkEnabled)
{
Console.WriteLine(
$"[autowalk-target] object=0x{info.ObjectId:X8} "
+ $"status={info.Status} context={info.ContextId} "
+ $"target=({info.TargetPosition.Frame.Origin.X:F2},"
+ $"{info.TargetPosition.Frame.Origin.Y:F2},"
+ $"{info.TargetPosition.Frame.Origin.Z:F2})");
}
exactMovement.HandleUpdateTarget(info);
},
interruptCurrentMovement: () => exactMovement.CancelMoveTo(
WeenieError.ActionCancelled));
playerHost = EntityPhysicsHostComposition.SelectStableHostWithoutRebind(
_liveEntities,
playerRecord,
configuredHost);
exactMovement.MakeMoveToManager();
controller.Motion.UnstickFromObject = () =>
playerHost.PositionManager.UnStick();
controller.PositionManager = playerHost.PositionManager;
controller.Motion.InterruptCurrentMovement = () =>
{
if (PhysicsDiagnostics.ProbeAutoWalkEnabled
&& exactMovement.IsMovingTo())
{
Console.WriteLine("[autowalk-end] reason=interrupt");
}
exactMovement.CancelMoveTo(WeenieError.ActionCancelled);
};
if (RuntimeMovementSkillProjection.ApplyTo(
_skills,
controller))
{
Console.WriteLine(
$"live: {loggingTag} — applied server skills "
+ $"run={_skills.RunSkill} jump={_skills.JumpSkill}");
}
ApplyStepHeights(controller, playerEntity, playerGuid);
uint initialCellId = ResolveInitialCell(playerGuid, playerEntity);
Action? drainPriorAnimationQueue = null;
if (_animations.TryGetValue(playerEntity.Id, out LiveEntityAnimationState? animation)
&& animation.Sequencer is { } sequencer)
{
@ -392,51 +333,9 @@ internal sealed class PlayerModeController :
sequencer.Manager.CheckForCompletedMotions;
controller.Motion.DefaultSink =
new MotionTableDispatchSink(sequencer);
drainPriorAnimationQueue = sequencer.Manager.HandleEnterWorld;
sequencer.Manager.HandleEnterWorld();
}
// Retail CPhysicsObj owns CMotionInterp and CPartArray throughout
// construction. Our split owners preserve that lifetime with a
// narrow preparation lease: SetPosition's synchronous type-5
// completion reaches this candidate MotionInterpreter, while the
// public controller slot remains unpublished until every other
// player-mode edge has prepared successfully.
using IDisposable motionPreparation =
_controllerSlot.BeginMotionPreparation(
controller,
drainPriorAnimationQueue);
ResolveResult initial = _physics.Resolve(
playerEntity.Position,
initialCellId,
Vector3.Zero,
100f);
var (placementRadius, placementHeight) =
_motionBindings.GetSetupCylinder(playerGuid, playerEntity);
if (placementRadius < 0.05f)
{
placementRadius = 0.48f;
placementHeight = 1.835f;
}
ResolveResult placement = _physics.ResolvePlacement(
initial.Position,
initial.CellId,
placementRadius,
placementHeight,
controller.StepUpHeight,
controller.StepDownHeight,
ObjectInfoState.IsPlayer | ObjectInfoState.EdgeSlide,
playerEntity.Id);
if (placement.Ok)
initial = placement;
controller.PreparePositionForCommit(
initial.Position,
initial.CellId,
CellLocalForSeed(initial.Position, initial.CellId));
controller.SetBodyOrientation(playerEntity.Rotation);
var legacyCamera = new ChaseCamera { Aspect = _viewport.Aspect };
var retailCamera = new RetailChaseCamera
{
@ -446,44 +345,15 @@ internal sealed class PlayerModeController :
cameraAttempted = true;
_camera.EnterChaseMode(legacyCamera, retailCamera);
EntityPhysicsHost stableAfterCamera =
EntityPhysicsHostComposition.SelectStableHostWithoutRebind(
_liveEntities,
playerRecord,
configuredHost);
if (!ReferenceEquals(stableAfterCamera, playerHost))
{
throw new InvalidOperationException(
"The local physics host changed during chase-camera activation.");
}
shadowAttempted = true;
_shadow.SyncPose(
playerEntity,
initial.Position,
controller.Position,
playerEntity.Rotation,
initial.CellId,
controller.CellId,
force: true);
// Publish the incarnation-stable CPhysicsObj delegates only after all
// DAT, placement, shadow, and camera preparation has succeeded. A
// late preparation failure therefore cannot expose an abandoned
// controller through LiveEntityRecord.PhysicsHost.
EntityPhysicsHost publishedHost = EntityPhysicsHostComposition.InstallOrRebind(
_liveEntities,
playerRecord,
configuredHost);
if (!ReferenceEquals(publishedHost, playerHost))
{
throw new InvalidOperationException(
"The local physics host changed between preparation and commit.");
}
playerEntity.SetPosition(initial.Position);
playerEntity.ParentCellId = initial.CellId;
controller.CommitPreparedPosition();
_hostSlot.Host = publishedHost;
_controllerSlot.Controller = controller;
_hostSlot.Host = playerHost;
_chase.Legacy = legacyCamera;
_chase.Retail = retailCamera;
_mode.IsPlayerMode = true;
@ -505,8 +375,16 @@ internal sealed class PlayerModeController :
catch (Exception cleanupError) { failures.Add(cleanupError); }
}
// C3c: presentation-only rollback. The Runtime-published
// controller/body/host stay live — retail has no entry-flow
// rollback. C3c-R1 review F8: this rethrow is NOT retried by
// auto-entry — the one-shot trigger disarms before invoking
// (PlayerModeAutoEntry.TryEnter), and the throw also propagates
// out of the auto-entry context before its world-reveal
// Complete() call. After a failed attach the player re-enters
// via the manual Tab path (or a session reset re-arms the
// trigger).
_mode.IsPlayerMode = false;
_controllerSlot.Controller = null;
_hostSlot.Host = null;
_chase.Legacy = null;
_chase.Retail = null;
@ -532,92 +410,4 @@ internal sealed class PlayerModeController :
_approachCompletions.RetireControllerLifetime(lifetime);
}
private void ApplyStepHeights(
PlayerMovementController controller,
WorldEntity playerEntity,
uint playerGuid)
{
if ((playerEntity.SourceGfxObjOrSetupId & 0xFF000000u) == 0x02000000u)
{
DatReaderWriter.DBObjs.Setup? setup;
lock (_datLock)
setup = _dats.Get<DatReaderWriter.DBObjs.Setup>(
playerEntity.SourceGfxObjOrSetupId);
if (setup is not null)
_collisionAssets.CacheSetup(
playerEntity.SourceGfxObjOrSetupId,
setup);
// TS-46 (2026-07-30): CPartArray::GetStepUpHeight/GetStepDownHeight
// (0x005180d0/0x005180f0) return setup->step_up_height * this->scale
// — apply the same ObjScale multiply the remote/ordinary paths now
// use (LiveEntityMotionRuntimeController.GetSetupMoverShape), for
// parity on a non-1.0-scale player (a rare but real case — e.g. a
// disguise/size-changing effect). Human ObjScale is 1.0 in the
// overwhelming common case, so this is a no-op there.
float scale =
_liveEntities.Snapshots.TryGetValue(playerGuid, out var sp)
&& sp.ObjScale is { } objScale && objScale > 0f
? objScale
: (playerEntity.Scale > 0f ? playerEntity.Scale : 1f);
controller.StepUpHeight = setup is { StepUpHeight: > 0f }
? setup.StepUpHeight * scale
: 0.4f;
controller.StepDownHeight = setup is { StepDownHeight: > 0f }
? setup.StepDownHeight * scale
: 0.4f;
// TS-46 (2026-07-30): the Setup's own ≤2-sphere list, verbatim —
// retail CPhysicsObj::transition (0x00512dc0) seeds the sweep
// from CPartArray::GetSphere, not a (radius, height) capsule
// reconstruction. Empty (no Setup, or a Setup with no sphere
// rows) leaves SphereList at its default empty value, which
// ResolveWithTransition treats as "use the legacy scalar
// reconstruction."
controller.SphereList = setup?.Spheres is { Count: > 0 } spheres
? spheres
.Select(s => new FlatCollisionSphere(s.Origin, s.Radius))
.ToImmutableArray()
: ImmutableArray<FlatCollisionSphere>.Empty;
Console.WriteLine(
$"physics: player step heights — StepUp={controller.StepUpHeight:F3} m "
+ $"(Setup.StepUpHeight={(setup?.StepUpHeight ?? 0f):F3}), "
+ $"StepDown={controller.StepDownHeight:F3} m "
+ $"(Setup.StepDownHeight={(setup?.StepDownHeight ?? 0f):F3}), "
+ $"Spheres={controller.SphereList.Length}");
return;
}
controller.StepUpHeight = 0.4f;
controller.StepDownHeight = 0.4f;
controller.SphereList = ImmutableArray<FlatCollisionSphere>.Empty;
Console.WriteLine(
"physics: player step heights — defaulting to 0.4 m (no setup dat)");
}
private uint ResolveInitialCell(uint playerGuid, WorldEntity playerEntity)
{
if (_liveEntities.Snapshots.TryGetValue(playerGuid, out var spawn)
&& spawn.Position is { LandblockId: not 0u } position)
{
return position.LandblockId;
}
int landblockX = _origin.CenterX
+ (int)MathF.Floor(playerEntity.Position.X / 192f);
int landblockY = _origin.CenterY
+ (int)MathF.Floor(playerEntity.Position.Y / 192f);
return ((uint)landblockX << 24)
| ((uint)landblockY << 16)
| 0x0001u;
}
private Vector3 CellLocalForSeed(Vector3 worldPosition, uint cellId)
{
int landblockX = (int)((cellId >> 24) & 0xFFu);
int landblockY = (int)((cellId >> 16) & 0xFFu);
var origin = new Vector3(
(landblockX - _origin.CenterX) * 192f,
(landblockY - _origin.CenterY) * 192f,
0f);
return worldPosition - origin;
}
}

View file

@ -15,6 +15,7 @@ internal sealed class GraphicalSessionEventRoute : ILiveSessionEventRouting
_createSubscription;
private readonly Func<RuntimeGenerationToken> _generation;
private readonly RuntimePlacementProjectionRetrySlot _retries;
private readonly RuntimeFirstEntryDriveController? _firstEntry;
private RuntimePlacementProjectionSubscription? _subscription;
private IDisposable? _retryLease;
private bool _attachStarted;
@ -25,7 +26,8 @@ internal sealed class GraphicalSessionEventRoute : ILiveSessionEventRouting
ILiveSessionEventRouting events,
GameRuntime runtime,
IRuntimePlacementProjectionSink placements,
RuntimePlacementProjectionRetrySlot retries)
RuntimePlacementProjectionRetrySlot retries,
RuntimeFirstEntryDriveController? firstEntry = null)
: this(
events,
() => new RuntimePlacementProjectionSubscription(
@ -33,7 +35,8 @@ internal sealed class GraphicalSessionEventRoute : ILiveSessionEventRouting
placements,
retryPendingOnSubscribe: false),
() => runtime.Generation,
retries)
retries,
firstEntry)
{
ArgumentNullException.ThrowIfNull(runtime);
ArgumentNullException.ThrowIfNull(placements);
@ -43,7 +46,8 @@ internal sealed class GraphicalSessionEventRoute : ILiveSessionEventRouting
ILiveSessionEventRouting events,
Func<RuntimePlacementProjectionSubscription> createSubscription,
Func<RuntimeGenerationToken> generation,
RuntimePlacementProjectionRetrySlot retries)
RuntimePlacementProjectionRetrySlot retries,
RuntimeFirstEntryDriveController? firstEntry = null)
{
_events = events ?? throw new ArgumentNullException(nameof(events));
_createSubscription = createSubscription
@ -51,6 +55,7 @@ internal sealed class GraphicalSessionEventRoute : ILiveSessionEventRouting
_generation = generation
?? throw new ArgumentNullException(nameof(generation));
_retries = retries ?? throw new ArgumentNullException(nameof(retries));
_firstEntry = firstEntry;
}
public void Attach()
@ -60,6 +65,10 @@ internal sealed class GraphicalSessionEventRoute : ILiveSessionEventRouting
return;
_attachStarted = true;
// C3c-R1 review F6: assert (not assume) that the prior route
// detached — session reset precedes a new route — before this route
// takes ownership of the shared drive controller's tracked entries.
_firstEntry?.AttachRoute(this);
_events.Attach();
RuntimePlacementProjectionSubscription? subscription = null;
@ -67,9 +76,20 @@ internal sealed class GraphicalSessionEventRoute : ILiveSessionEventRouting
try
{
subscription = _createSubscription();
RuntimePlacementProjectionSubscription boundSubscription =
subscription;
retryLease = _retries.BindOwned(
_generation(),
subscription.RetryPending);
// C3c: drive pending first-entry sequences before
// republishing the pending FIFO head — a conductor's own
// Advance is what consumes conductor-owned receipts, and the
// subsequent RetryPending lets the presentation sink apply
// whatever new head the drive surfaced.
() =>
{
_firstEntry?.DriveAll();
return boundSubscription.RetryPending();
});
_subscription = subscription;
_retryLease = retryLease;
_ = subscription.RetryPending();
@ -91,6 +111,12 @@ internal sealed class GraphicalSessionEventRoute : ILiveSessionEventRouting
// can therefore never retry a retired generation or disposed route.
Interlocked.Exchange(ref _retryLease, null)?.Dispose();
Interlocked.Exchange(ref _subscription, null)?.Dispose();
// C3c: the drive controller's tracked entries die with this exact
// session route; Runtime's own retirement/session-clear fan-out owns
// conductor/residence convergence independently. C3c-R1 review F6:
// route-scoped — a route that never attached cannot clear a live
// route's entries.
_firstEntry?.DetachRoute(this);
if (!_eventsDisposed)
{
_events.Dispose();

View file

@ -0,0 +1,86 @@
using AcDream.Runtime.Gameplay;
namespace AcDream.App.Net;
/// <summary>
/// C3c-F1 (2026-08-02): the App half of the movement-stats application
/// seam. Every server stat recompute (skills, burden, stamina, PK status —
/// the character-bindings <c>OnSkillsUpdated</c>/<c>OnMovementStatsUpdated</c>
/// callbacks) routes through
/// <see cref="RuntimeLocalPlayerMovementState.ApplyCharacterMovementStats"/>;
/// App holds no controller reference and performs no direct configuration
/// mutation. A recompute displaced past session teardown (the post-logout
/// inbound-Create ingest chain that crashed the connected lifecycle gate)
/// observes a typed dropped outcome and is logged under the existing
/// player diagnostics instead of faulting the session.
/// </summary>
/// <remarks>
/// Stuck-cast fix (2026-07-30): retail fires
/// <c>CPhysicsObj::report_exhaustion</c> from exactly ONE site —
/// <c>CommandInterpreter::HandleExhaustion</c> (0x006b3c70), a
/// notification-handler vtable slot invoked on the stamina-exhaustion
/// EVENT — not on every vitals refresh. The P1 wiring called
/// <c>ReportExhaustion()</c> on EVERY movement-stats application
/// (every stamina regen/drain tick), and each call re-dispatches the
/// current movement state through the animation sink — truncating any
/// in-flight action animation (cast gestures wedged mid-play; the
/// diagnostic session showed 490 spurious stance re-queues). The
/// re-apply fires only when the exhausted state (stamina == 0)
/// actually TRANSITIONS, matching retail's event semantics. Skill/
/// burden changes still reach <c>PlayerWeenie</c> immediately through
/// the owner seam — the next natural dispatch picks up the new rates,
/// exactly as retail. The edge is observed for dormant applications too
/// (the event fired; a player not yet in world has no movement to
/// re-dispatch, and activation starts movement from the already-current
/// stamina gate), but dispatched only on a live controller.
/// </remarks>
internal sealed class LiveMovementStatsApplier(
RuntimeLocalPlayerMovementState movement,
RuntimeMovementSkillState skills,
Action<string> log)
{
private readonly RuntimeLocalPlayerMovementState _movement = movement
?? throw new ArgumentNullException(nameof(movement));
private readonly RuntimeMovementSkillState _skills = skills
?? throw new ArgumentNullException(nameof(skills));
private readonly Action<string> _log = log
?? throw new ArgumentNullException(nameof(log));
private readonly StaminaExhaustionEdgeTracker _staminaExhaustion = new();
/// <summary>
/// Forgets the retiring character/session exhaustion baseline; the next
/// generation's first sample must not synthesize an edge.
/// </summary>
public void Reset() => _staminaExhaustion.Reset();
public RuntimeMovementStatsApplication Apply(string reason)
{
RuntimeMovementStatsApplication outcome =
_movement.ApplyCharacterMovementStats(_skills);
switch (outcome)
{
case RuntimeMovementStatsApplication.DroppedNoController:
case RuntimeMovementStatsApplication.DroppedIncompleteSnapshot:
// Byte-identical to the pre-F1 ApplyTo=false silent skip.
return outcome;
case RuntimeMovementStatsApplication.DroppedDisplacedController:
_log(
$"player: dropped displaced movement {reason} — the "
+ "Runtime movement controller is terminal");
return outcome;
}
RuntimeMovementSkillSnapshot snapshot = _skills.Snapshot;
if (_staminaExhaustion.Observe(snapshot.CurrentStamina)
&& outcome is RuntimeMovementStatsApplication.AppliedLive)
{
_movement.ReportExhaustion();
}
_log(
$"player: applied server movement {reason} "
+ $"run={snapshot.RunSkill} jump={snapshot.JumpSkill} "
+ $"burden={snapshot.Burden:F2} stamina={snapshot.CurrentStamina}");
return outcome;
}
}

View file

@ -85,7 +85,8 @@ internal sealed record LiveSessionWorldRuntime(
RemoteMovementObservationTracker RemoteMovementObservations,
RenderSceneShadowRuntime? RenderSceneShadow,
RuntimePlacementPresentationSink PlacementProjection,
RuntimePlacementProjectionRetrySlot PlacementRetries);
RuntimePlacementProjectionRetrySlot PlacementRetries,
RuntimeFirstEntryDriveController FirstEntryDrive);
/// <summary>
/// Builds the exact per-generation route/reset graph for the canonical live
@ -100,7 +101,7 @@ internal sealed class LiveSessionRuntimeFactory
private readonly LiveSessionWorldRuntime _world;
private readonly LiveSessionCommandSurface _commands;
private readonly Action<string> _log;
private readonly StaminaExhaustionEdgeTracker _staminaExhaustion = new();
private readonly LiveMovementStatsApplier _movementStats;
public LiveSessionRuntimeFactory(
LiveSessionPlayerRuntime player,
@ -119,6 +120,12 @@ internal sealed class LiveSessionRuntimeFactory
_world = world ?? throw new ArgumentNullException(nameof(world));
_commands = commands ?? throw new ArgumentNullException(nameof(commands));
_log = log ?? throw new ArgumentNullException(nameof(log));
// C3c-F1: stat recomputes route through the Runtime movement owner's
// typed application seam; App keeps zero direct controller mutations.
_movementStats = new LiveMovementStatsApplier(
_player.Controller,
_domain.Character.MovementSkills,
_log);
}
public LiveSessionHost Create(
@ -192,7 +199,7 @@ internal sealed class LiveSessionRuntimeFactory
private void ResetPlayerPresentation()
{
_staminaExhaustion.Reset();
_movementStats.Reset();
_interaction.PlayerMode.ResetSession();
_world.SpawnClaims.Reset();
}
@ -254,7 +261,8 @@ internal sealed class LiveSessionRuntimeFactory
route,
_domain.Runtime,
_world.PlacementProjection,
_world.PlacementRetries);
_world.PlacementRetries,
_world.FirstEntryDrive);
}
private LiveInventorySessionBindings CreateInventoryBindings() => new(
@ -284,59 +292,19 @@ internal sealed class LiveSessionRuntimeFactory
_domain.Actions.Combat,
_domain.Character,
ResolveSkillFormulaBonus: skillCreditResolver.Resolve,
OnSkillsUpdated: (runSkill, jumpSkill) => ApplyMovementStats("skills"),
OnSkillsUpdated: (runSkill, jumpSkill) =>
_movementStats.Apply("skills"),
OnConfirmationRequest: request =>
_ui.RetailUi?.HandleConfirmationRequest(request),
OnConfirmationDone: done =>
_ui.RetailUi?.HandleConfirmationDone(done),
ClientTime: ClientTimerNow,
// Campaign P Slice P1 (2026-07-30): burden/stamina/vitae changes
// reactively re-apply to the live controller through the SAME
// seam skills already used, then wire the previously-dead
// ReportExhaustion() R3-W4 seam so movement re-evaluates
// immediately (pseudocode doc §8/§9).
OnMovementStatsUpdated: () => ApplyMovementStats("stats"));
}
/// <summary>
/// Re-applies the current <see cref="RuntimeMovementSkillState"/>
/// snapshot (skills/burden/stamina) to the live player controller.
/// </summary>
/// <remarks>
/// Stuck-cast fix (2026-07-30): retail fires
/// <c>CPhysicsObj::report_exhaustion</c> from exactly ONE site —
/// <c>CommandInterpreter::HandleExhaustion</c> (0x006b3c70), a
/// notification-handler vtable slot invoked on the stamina-exhaustion
/// EVENT — not on every vitals refresh. The P1 wiring called
/// <c>ReportExhaustion()</c> on EVERY movement-stats application
/// (every stamina regen/drain tick), and each call re-dispatches the
/// current movement state through the animation sink — truncating any
/// in-flight action animation (cast gestures wedged mid-play; the
/// diagnostic session showed 490 spurious stance re-queues). The
/// re-apply now fires only when the exhausted state (stamina == 0)
/// actually TRANSITIONS, matching retail's event semantics. Skill/
/// burden changes still reach <see cref="PlayerWeenie"/> immediately
/// via <see cref="RuntimeMovementSkillProjection.ApplyTo"/> — the next
/// natural dispatch picks up the new rates, exactly as retail.
/// </remarks>
private void ApplyMovementStats(string reason)
{
PlayerMovementController? controller = _player.Controller.Controller;
if (!RuntimeMovementSkillProjection.ApplyTo(
_domain.Character.MovementSkills,
controller))
{
return;
}
RuntimeMovementSkillSnapshot snapshot = _domain.Character.MovementSkills.Snapshot;
if (_staminaExhaustion.Observe(snapshot.CurrentStamina))
controller!.Motion.ReportExhaustion();
_log(
$"player: applied server movement {reason} "
+ $"run={snapshot.RunSkill} jump={snapshot.JumpSkill} "
+ $"burden={snapshot.Burden:F2} stamina={snapshot.CurrentStamina}");
// reactively re-apply through the SAME seam skills already used
// (pseudocode doc §8/§9). C3c-F1: that seam is now the Runtime
// movement owner's typed application entry — see
// LiveMovementStatsApplier.
OnMovementStatsUpdated: () => _movementStats.Apply("stats"));
}
private LiveSessionCommandBindings CreateCommandBindings(

View file

@ -190,7 +190,7 @@ internal sealed class LiveEntityNetworkUpdateController
// retail's first frame would (position snapped onto the floor,
// contact plane + CONTACT/ON_WALKABLE committed below). A sweep that
// finds no floor (true airborne spawn) leaves the body airborne.
if (!RemoteSpawnPlacementSettler.TrySettle(
if (!AcDream.Core.Physics.SpawnPlacementSettler.TrySettle(
_physicsEngine,
remote.Body,
worldPos,
@ -1003,7 +1003,20 @@ internal sealed class LiveEntityNetworkUpdateController
return;
}
if (parsed.Guid == _playerServerGuid)
_playerController?.ApplyPhysicsState(record.FinalPhysicsState);
{
// C3c-F1 (2026-08-02): route through the owner's
// lifecycle-deciding typed entry. The publication lifecycle —
// not this inbound handler — decides whether the push lands:
// a dormant first-entry controller drops it (the activation
// transaction re-reads the same canonical FinalPhysicsState
// itself; the accepted SetState is queued behind the initial
// residence so this value is unchanged), and a terminal
// controller treats it as a displaced push instead of faulting
// the session (the second connected-gate crash chain,
// logs/connected-world-gate-20260802-125907).
_ = _playerController?.ApplyServerPhysicsState(
record.FinalPhysicsState);
}
if (!_liveEntities.TryGetWorldEntity(parsed.Guid, out var entity)) return;

View file

@ -1,62 +0,0 @@
using System.Numerics;
using AcDream.Core.Physics;
namespace AcDream.App.Physics;
/// <summary>
/// Performs the compressed first-gravity-frame settle used to establish
/// retail Contact/OnWalkable state for a newly materialized remote body.
/// </summary>
internal static class RemoteSpawnPlacementSettler
{
internal const float SettleDistance = 0.5f;
public static bool TrySettle(
PhysicsEngine physicsEngine,
PhysicsBody body,
Vector3 worldPosition,
uint cellId,
float sphereRadius,
float sphereHeight,
ObjectInfoState moverFlags,
uint movingEntityId,
Action hitGround,
Action leaveGround)
{
ArgumentNullException.ThrowIfNull(physicsEngine);
ArgumentNullException.ThrowIfNull(body);
ArgumentNullException.ThrowIfNull(hitGround);
ArgumentNullException.ThrowIfNull(leaveGround);
if (cellId == 0)
return false;
ResolveResult settle = physicsEngine.ResolveWithTransition(
worldPosition,
worldPosition - new Vector3(0f, 0f, SettleDistance),
cellId,
sphereRadius,
sphereHeight,
stepUpHeight: 0.4f,
stepDownHeight: 0.4f,
isOnGround: false,
body,
moverFlags,
movingEntityId);
if (!settle.Ok || !settle.InContact)
return false;
body.Position = settle.Position;
PhysicsObjUpdate.CommitSetPositionTransition(
body,
settle.InContact,
settle.OnWalkable,
settle.CollisionNormalValid,
settle.CollisionNormal,
previousContact: false,
previousOnWalkable: false,
hitGround,
leaveGround);
return true;
}
}

View file

@ -709,6 +709,17 @@ internal sealed class DatLiveEntityProjectionMaterializer
}
bool createdProjection = false;
// C3c route-1 flip: a fresh world Create materializes presentation-
// only — the sidecar exists but stays non-spatial until the
// residence-driven Runtime placement's completion receipt (or, for a
// record whose residence already completed before its sidecar could
// exist, the self-projection below). An already-materialized record
// keeps its sticky residence so unflipped same-incarnation
// transitions (an equipped child dropping to world) stay on their
// legacy path by construction.
LiveEntityMaterializationResidence residence =
retainedRecord?.MaterializationResidence
?? LiveEntityMaterializationResidence.AwaitRuntimePlacement;
WorldEntity? entity = _runtime.MaterializeLiveEntity(
expectedCanonical,
spawn.Position!.Value.LandblockId,
@ -734,7 +745,8 @@ internal sealed class DatLiveEntityProjectionMaterializer
},
LiveEntityProjectionKind.World,
initializeProjection: record => record.EffectProfile = profile,
out LiveEntityRecord? expectedRecord);
out LiveEntityRecord? expectedRecord,
residence);
if (entity is null
|| expectedRecord is null
|| !_runtime.IsCurrentCreateIntegration(
@ -744,6 +756,27 @@ internal sealed class DatLiveEntityProjectionMaterializer
{
return false;
}
if (residence is LiveEntityMaterializationResidence.AwaitRuntimePlacement
&& expectedCanonical.FullCellId != 0u
&& !_runtime.HasActiveInitialCreateResidence(expectedCanonical))
{
// The residence-driven placement already committed before this
// sidecar existed (a deferred-parent child replayed during its
// parent's drain, or a recovery re-materialization) — its
// completion receipt is gone, so presentation self-projects from
// the committed canonical state through the presentation-only
// bucket path.
if (!_runtime.RebucketLiveEntity(
spawn.Guid,
expectedCanonical.FullCellId)
|| !_runtime.IsCurrentCreateIntegration(
expectedRecord,
expectedCreateIntegrationVersion)
|| !ReferenceEquals(expectedRecord.WorldEntity, entity))
{
return false;
}
}
if (!createdProjection)
{

View file

@ -524,6 +524,22 @@ public sealed class EquippedChildRenderController : IDisposable
{
return false;
}
// C3c: a world-created (residence-managed) child converting to an
// attached projection exits the residence-managed presentation path
// at this same-incarnation kind transition. Attached children have
// no Runtime placement, and the flip's sticky-residence rule expects
// equipped children to carry LegacyImmediate so a later drop back to
// world stays on the legacy path by construction
// (DatLiveEntityProjectionMaterializer.MaterializeProjection's
// retained-residence comment). C3c-R1 review F1: the conversion is
// the owner's explicit API, which asserts no initial-create
// residence is still active, rather than a direct field write here.
if (retainedChild is not null
&& _liveEntities.IsCurrentRecord(retainedChild))
{
_liveEntities.ConvertMaterializationResidenceToLegacyImmediate(
retainedChild);
}
WorldEntity? entity = _liveEntities.MaterializeLiveEntity(
childCanonical,
parentCellId,

View file

@ -4,6 +4,7 @@ using AcDream.Core.Net;
using AcDream.Core.Net.Messages;
using AcDream.Core.World;
using AcDream.Runtime.Entities;
using AcDream.Runtime.Session;
namespace AcDream.App.World;
@ -180,6 +181,14 @@ internal sealed class LiveEntityHydrationController : ILiveEntityLandblockLoaded
private readonly LiveEntityDeletionController _deletion;
private readonly DormantLiveEntityStore _dormant;
private readonly Action<string>? _diagnostic;
/// <summary>
/// C3c: the graphical first-entry drive pump — pumped at the end of each
/// Create transaction so a fresh residence drives its conductor
/// synchronously (retail HandleCreateObject runs enter_world inline).
/// Optional so presentation-free hydration tests keep constructing this
/// controller without one.
/// </summary>
private readonly RuntimeFirstEntryDriveController? _firstEntry;
private readonly Dictionary<RuntimeEntityRecord, CanonicalProjectionOperation>
_projectionOperations =
new(ReferenceEqualityComparer.Instance);
@ -203,7 +212,8 @@ internal sealed class LiveEntityHydrationController : ILiveEntityLandblockLoaded
ILocalPlayerIdentitySource identity,
LiveEntityDeletionController deletion,
DormantLiveEntityStore? dormant = null,
Action<string>? diagnostic = null)
Action<string>? diagnostic = null,
RuntimeFirstEntryDriveController? firstEntry = null)
{
_runtime = runtime ?? throw new ArgumentNullException(nameof(runtime));
_entityObjects = entityObjects
@ -219,6 +229,7 @@ internal sealed class LiveEntityHydrationController : ILiveEntityLandblockLoaded
_deletion = deletion ?? throw new ArgumentNullException(nameof(deletion));
_dormant = dormant ?? new DormantLiveEntityStore();
_diagnostic = diagnostic;
_firstEntry = firstEntry;
}
internal event Action<uint>? AppearanceApplied;
@ -259,7 +270,9 @@ internal sealed class LiveEntityHydrationController : ILiveEntityLandblockLoaded
lock (_datLock)
{
LiveEntityRegistrationResult registration =
_runtime.RegisterLiveEntity(spawn);
_runtime.RegisterLiveEntity(
spawn,
isLocalPlayer: spawn.Guid == _identity.ServerGuid);
InboundCreateResult result = registration.Inbound;
if (result.Disposition is
AcDream.Core.Physics.CreateObjectTimestampDisposition.StaleGeneration)
@ -380,6 +393,16 @@ AppearanceSynchronization:
$"Prior incarnation of live entity 0x{spawn.Guid:X8} failed teardown after its replacement was installed.",
cleanupFailure);
}
// C3c: pump the first-entry drive after the complete Create
// hydration transaction — the sidecar exists, so this entity's
// conductor can run mover-prep -> placement -> drain and its
// completion receipt can bind presentation synchronously,
// matching retail HandleCreateObject's inline enter_world. Any
// still-yielding sequence (missing prepared Setup, deferred
// destination cell, FIFO ahead of us) is retried by the
// per-frame placement retry phase.
_firstEntry?.DriveAll();
}
}

View file

@ -523,7 +523,9 @@ public sealed class LiveEntityRuntime : ILiveEntityRadarSource
/// </summary>
public event Action<LiveEntityRecord, bool>? ProjectionVisibilityChanged;
public LiveEntityRegistrationResult RegisterLiveEntity(WorldSession.EntitySpawn incoming)
public LiveEntityRegistrationResult RegisterLiveEntity(
WorldSession.EntitySpawn incoming,
bool isLocalPlayer = false)
{
if (_isClearing || _sessionClearPendingFinalization || _isRegisteringResources)
{
@ -533,9 +535,16 @@ public sealed class LiveEntityRuntime : ILiveEntityRadarSource
: "A live entity cannot register from inside atomic resource registration.");
}
// C3c route-1 flip: every graphical initial Create enters the
// canonical initial-residence lease. The accepted wire frame stays on
// the canonical record with FullCell 0 until the authored Runtime
// SetPosition operation commits; the host's first-entry drive
// controller walks the conductors from the residence-begin
// notification.
RuntimeEntityRegistrationResult registration =
_entityObjects.RegisterEntity(
_entityObjects.RegisterEntityWithInitialResidence(
incoming,
isLocalPlayer,
RetirePriorProjection);
RuntimeEntityRecord? canonical = registration.Canonical;
LiveEntityRecord? projection = canonical is null
@ -795,11 +804,32 @@ public sealed class LiveEntityRuntime : ILiveEntityRadarSource
|| record.WorldEntity is not { } entity)
return false;
if (record.MaterializationResidence is
LiveEntityMaterializationResidence.AwaitRuntimePlacement)
LiveEntityMaterializationResidence.AwaitRuntimePlacement
&& HasActiveInitialCreateResidence(record.Canonical))
{
// The private Runtime Place path below performs a presentation-
// only bucket update. This legacy API also commits canonical
// Runtime residence and cannot touch a cut-over incarnation.
// C3c: while the initial-create residence is ACTIVE, Runtime's
// SetPosition owner is the sole canonical position/cell/
// object-clock authority and even the graphical bucket stays
// suppressed: the conductor's completion receipt (which reaches
// presentation through
// TryApplyInitialCreateCompletionPresentation, not this API) is
// the entity's first world-visible moment. Without this gate a
// re-entrant caller (e.g. a resource-registration observer)
// could install a bucket for a suppressed record before its
// placement ever committed. A STALE residence is lazily retired
// by this same query, after which legacy moves flow.
//
// C3c-R1 review R2: the gate is the EXACT-token residence
// activity view, never the sticky MaterializationResidence enum
// alone. Post-residence (the lease completed and was consumed)
// this method falls through to the FULL legacy branch below:
// the unflipped update routes (network position/state, remote
// and local teleports, streaming reprojection, hydration
// recovery) are the position authority again, and retail's
// prepare_to_enter_world (0x00511FA0) clock rebase must run on
// every root-workset membership edge — the earlier
// presentation-only shortcut skipped CommitRebucket and that
// clock edge for the entity's whole post-residence lifetime.
return false;
}
@ -930,6 +960,197 @@ public sealed class LiveEntityRuntime : ILiveEntityRadarSource
return true;
}
/// <summary>
/// C3c: the graphical-bucket-only projection of a conductor-owned
/// initial placement — called ONLY from
/// <see cref="TryApplyInitialCreateCompletionPresentation"/> (the
/// completion receipt at the initial-create residence boundary), never
/// from the public <see cref="RebucketLiveEntity"/> (C3c-R1 review R2:
/// post-residence moves take the full legacy branch there).
/// Deliberately never calls <c>CommitRebucket</c>,
/// <c>SuspendObjectClock</c>, or <c>ResetObjectClockForEnterWorld</c> —
/// Runtime's SetPosition commit already owns all of those for the
/// residence-driven placement this receipt projects. May place into a
/// pending (not-yet-loaded) bucket exactly like the legacy Create path
/// did; the pending drain publishes visibility when the landblock loads.
/// </summary>
private bool RebucketLiveEntityPresentationOnly(
uint serverGuid,
LiveEntityRecord record,
WorldEntity entity,
uint spatialCellOrLandblockId)
{
RuntimeEntityKey key = RequireProjectionKey(record);
bool wasProjected = record.IsSpatiallyProjected;
bool wasVisible = record.IsSpatiallyVisible;
ulong projectionOperation = ++record.ProjectionMutationVersion;
record.IsSpatiallyProjected = true;
Exception? spatialNotificationFailure = null;
uint priorRebucketingGuid = _rebucketingGuid;
_rebucketingGuid = serverGuid;
BeginPresentationOnlySpatialMutation(key);
try
{
try
{
_spatial.RebucketLiveEntity(
key,
entity,
spatialCellOrLandblockId);
}
catch (AggregateException error)
{
spatialNotificationFailure = error;
}
}
finally
{
EndPresentationOnlySpatialMutation(key);
_rebucketingGuid = priorRebucketingGuid;
}
if (!IsCurrentProjectionOperation(serverGuid, record, projectionOperation))
{
ThrowAfterCommittedProjectionChange(
serverGuid,
spatialNotificationFailure,
runtimeNotificationFailure: null);
return false;
}
bool visible = _spatial.IsLiveEntityProjectionResident(key);
record.IsSpatiallyVisible = visible;
RefreshSpatialPresentationIndexes(record);
RefreshPresentation(record);
RefreshSpatialRuntimeIndexes(record);
Exception? runtimeNotificationFailure = null;
if (!wasProjected || wasVisible != visible)
{
try
{
PublishProjectionVisibilityChanged(record, visible);
}
catch (Exception error)
{
runtimeNotificationFailure = error;
}
}
if (!IsCurrentProjectionOperation(serverGuid, record, projectionOperation))
{
ThrowAfterCommittedProjectionChange(
serverGuid,
spatialNotificationFailure,
runtimeNotificationFailure);
return false;
}
ThrowAfterCommittedProjectionChange(
serverGuid,
spatialNotificationFailure,
runtimeNotificationFailure);
return true;
}
/// <summary>
/// C3c: applies one initial-Create ExecutorCompleted receipt's
/// presentation — the graphical binding point for a residence-driven
/// initial placement. Runtime committed position, cell, body, clocks,
/// and worksets during the conductor's drain; this installs the
/// committed frame on the sidecar and moves its graphical bucket
/// (pending buckets allowed — the legacy Create path's own semantics).
/// Superseded facts (a later legacy-path move already advanced the
/// record past the receipt) are treated as already-projected: the
/// receipt is stale for presentation and must not snap the entity back.
/// </summary>
internal bool TryApplyInitialCreateCompletionPresentation(
in RuntimePlacementProjectionSnapshot projection)
{
RuntimePlacementProjectionToken token = projection.Token;
if (!token.IsValid
|| token.SessionLifetimeVersion != _directory.SessionLifetimeVersion
|| !_projections.TryGet(token.Entity, out LiveEntityRecord? record)
|| !_directory.IsCurrent(record.Canonical)
|| record.Canonical.Key != token.Entity
|| record.WorldEntity is not { } entity)
{
// No sidecar (a deferred-child replay materializes later and
// self-projects from canonical state) or a displaced identity —
// acknowledge-only.
return true;
}
if (record.FullCellId != token.ExactCellId
|| record.Canonical.PlacementCommitVersion
!= token.PlacementCommitVersion)
{
// A newer move superseded this receipt's facts after the drain.
return true;
}
entity.SetPosition(projection.WorldPosition);
entity.Rotation = projection.Orientation;
entity.ParentCellId = token.ExactCellId;
entity.EffectCellId = token.ExactCellId;
return RebucketLiveEntityPresentationOnly(
record.ServerGuid,
record,
entity,
token.ExactCellId);
}
/// <summary>
/// C3c: true while the exact incarnation behind <paramref name="key"/>
/// holds an initial-create residence lease — the discriminator the
/// placement sink uses to leave conductor-owned Place/Withdraw receipts
/// at the FIFO head for the drive controller to consume.
/// </summary>
internal bool HasActiveInitialCreateResidence(RuntimeEntityKey key) =>
_directory.TryGetByLocalId(
key.LocalEntityId,
out RuntimeEntityRecord canonical)
&& _directory.IsCurrent(canonical)
&& canonical.Key == key
&& _entityObjects.TryGetInitialCreateResidence(canonical, out _);
/// <summary>
/// C3c: true when the exact incarnation behind <paramref name="canonical"/>
/// holds an initial-create residence lease. Used by materialization to
/// decide whether presentation must await the conductor's completion
/// receipt or may self-project from already-committed canonical state.
/// </summary>
internal bool HasActiveInitialCreateResidence(
RuntimeEntityRecord canonical) =>
_entityObjects.TryGetInitialCreateResidence(canonical, out _);
/// <summary>
/// C3c-R1 review F1: the ONLY sanctioned mutation of the otherwise
/// sticky <see cref="LiveEntityRecord.MaterializationResidence"/> — a
/// world-created (residence-managed) entity converting to an attached
/// projection at a same-incarnation kind transition (the equipped-child
/// world→attached path). Attached children have no Runtime placement,
/// so the sticky-residence rule expects them to carry
/// <see cref="LiveEntityMaterializationResidence.LegacyImmediate"/>.
/// Owned here so the invariant is asserted at the owner: converting
/// while the initial-create residence is still ACTIVE would let an
/// attached materialization race the conductor's pending placement.
/// </summary>
internal void ConvertMaterializationResidenceToLegacyImmediate(
LiveEntityRecord record)
{
ArgumentNullException.ThrowIfNull(record);
if (record.MaterializationResidence is not
LiveEntityMaterializationResidence.AwaitRuntimePlacement)
{
return;
}
if (HasActiveInitialCreateResidence(record.Canonical))
{
throw new InvalidOperationException(
$"Live entity 0x{record.ServerGuid:X8}/"
+ $"{record.Canonical.Incarnation} cannot convert to "
+ "LegacyImmediate residence while its initial-create "
+ "residence lease is still active.");
}
record.MaterializationResidence =
LiveEntityMaterializationResidence.LegacyImmediate;
}
/// <summary>
/// Applies one canonical Runtime placement receipt to the graphical
/// sidecar only. Runtime has already committed identity, position,

View file

@ -66,6 +66,29 @@ internal sealed class RuntimePlacementPresentationSink
public bool TryApply(in RuntimePlacementProjectionSnapshot projection)
{
if (projection.Kind is RuntimePlacementProjectionKind.ExecutorCompleted)
{
// C3c: the initial-Create completion receipt is the graphical
// binding point for a residence-driven placement (the F1
// acknowledge-and-ignore behavior applied only while
// PublishExecutorCompletion had zero production callers).
return TryApplyInitialCreateCompletion(in projection);
}
if (projection.Kind is RuntimePlacementProjectionKind.Place
or RuntimePlacementProjectionKind.Withdraw
&& _liveEntities.HasActiveInitialCreateResidence(
projection.Token.Entity))
{
// C3c: a Place/Withdraw for an entity still holding its
// initial-create residence belongs to the first-entry conductor
// machinery, which acknowledges its own receipts at the exact
// FIFO head. Leave it there — the drive controller's pump
// consumes it; applying or acknowledging here would starve the
// conductor's own acknowledgement stage forever.
return false;
}
if (projection.Kind is RuntimePlacementProjectionKind.Place
&& !_transit.IsCurrentPlacementAuthority(
projection.Token.Portal,
@ -76,19 +99,15 @@ internal sealed class RuntimePlacementPresentationSink
if (!_liveEntities.TryApplyRuntimePlacementProjection(in projection))
return false;
if (projection.Kind is RuntimePlacementProjectionKind.Discard
or RuntimePlacementProjectionKind.ExecutorCompleted)
if (projection.Kind is RuntimePlacementProjectionKind.Discard)
{
// F1: ExecutorCompleted is acknowledge-and-ignore like Discard -
// no world/presentation mutation by definition. Must NOT fall
// through to the record-lookup gate below (that gate legitimately
// rejects for OTHER reasons, and this sink's caller
// Discard cancels only an unacknowledged observation - no
// world/presentation mutation. Must NOT fall through to the
// record-lookup gate below (that gate legitimately rejects for
// OTHER reasons, and this sink's caller
// (RuntimePlacementProjectionSubscription) treats a false return
// as "leave at the FIFO head" - a rejected ExecutorCompleted
// would permanently wedge the whole ordered stream). Provably
// inert today: PublishExecutorCompletion has zero production
// callers - see
// RuntimePlacementPresentationSinkTests.ExecutorCompleted_IsAckOnlyNoOpEvenWhenTokenIsStaleOrSidecarIsGone.
// as "leave at the FIFO head" - a rejected Discard would
// permanently wedge the whole ordered stream).
return true;
}
if (!_liveEntities.TryGetRecord(
@ -109,6 +128,37 @@ internal sealed class RuntimePlacementPresentationSink
};
}
/// <summary>
/// C3c: binds one completed initial-Create drain's presentation. A
/// celless completion (a route that performed no SetPosition — a
/// deferred-parent child staying invisible until its parent replay, or a
/// positionless create) and a missing/superseded sidecar are
/// acknowledge-only; the sidecar's own materialization self-projects
/// from canonical state in those cases. Pending (not-yet-loaded)
/// destination buckets are allowed — the legacy Create path's own
/// semantics — so this receipt can never wedge the ordered stream behind
/// an unloaded graphical backend.
/// </summary>
private bool TryApplyInitialCreateCompletion(
in RuntimePlacementProjectionSnapshot projection)
{
if (projection.Token.ExactCellId == 0u)
return true;
if (!_liveEntities.TryApplyInitialCreateCompletionPresentation(
in projection))
{
return false;
}
if (!_liveEntities.TryGetRecord(
projection.Token.Entity,
out LiveEntityRecord record)
|| record.WorldEntity is not { } entity)
{
return true;
}
return TryPublishPlace(record, entity);
}
private bool TryPublishPlace(LiveEntityRecord record, WorldEntity entity)
{
if (!IsCurrent(record, entity))