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

@ -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))

View file

@ -643,12 +643,17 @@ public sealed class ShadowObjectRegistry
private static uint DeriveOutdoorSeed(
Vector3 worldPos, float worldOffsetX, float worldOffsetY, uint landblockId)
{
// C3c-F3: only a genuinely-absent landblock id (0) has no seed —
// prefix 0x00000000 is landblock (0,0), the map corner, whose
// outdoor cells 0x00000001..0x40 are as real as any other block's.
// The old prefix-0 sentinel silently dropped every landblock-baked
// static in the corner block.
if (landblockId == 0u) return 0u;
float localX = worldPos.X - worldOffsetX;
float localY = worldPos.Y - worldOffsetY;
int cx = (int)System.Math.Clamp(localX / 24f, 0f, 7f);
int cy = (int)System.Math.Clamp(localY / 24f, 0f, 7f);
uint lbPrefix = landblockId & 0xFFFF0000u;
if (lbPrefix == 0u) return 0u;
// The clamp only anchors the SEED id; AddAllOutsideCells re-seats the
// actual flood cells from the sphere centers via LandDefs.AdjustToOutside
// (block-crossing), so an out-of-block position still floods correctly.
@ -2120,7 +2125,16 @@ public sealed class ShadowObjectRegistry
return false;
}
internal bool HasLogicalOwner(uint entityId) =>
/// <summary>
/// True while <paramref name="entityId"/> owns a logical shadow
/// registration (suspended or live). Public since C3c: the graphical
/// host reports the truthful
/// local-player shadow disposition (authored payload vs proven
/// shapeless) into the Runtime first-entry activation, which
/// <see cref="TryPrepareSetPosition"/> validates against this exact
/// registry state.
/// </summary>
public bool HasLogicalOwner(uint entityId) =>
_entityReg.ContainsKey(entityId);
/// <summary>

View file

@ -1,15 +1,27 @@
using System.Numerics;
using AcDream.Core.Physics;
namespace AcDream.App.Physics;
namespace AcDream.Core.Physics;
/// <summary>
/// Performs the compressed first-gravity-frame settle used to establish
/// retail Contact/OnWalkable state for a newly materialized remote body.
/// retail Contact/OnWalkable state for a newly placed body.
///
/// Retail gains spawn contact from the FIRST GRAVITY FRAME, not the
/// placement itself: <c>CPhysicsObj::enter_world</c> (0x00516170) runs
/// <c>SetPosition</c> (find_placement validates the spot but records no
/// touch) and every retail CPhysicsObj then simulates, falls the few
/// centimetres onto the floor, and the transition's touch grants the
/// contact plane + CONTACT/ON_WALKABLE. Bodies that do not run that first
/// ordinary frame at placement (stationary remotes — #270 — and the local
/// player's Runtime first-entry activation — C3c-F5) compress the settle
/// here: a short downward sweep from the placed position whose touch
/// handler produces exactly the state retail's first frame would. A sweep
/// that finds no floor (true airborne spawn) leaves the body airborne,
/// exactly like retail's fall.
/// </summary>
internal static class RemoteSpawnPlacementSettler
public static class SpawnPlacementSettler
{
internal const float SettleDistance = 0.5f;
public const float SettleDistance = 0.5f;
public static bool TrySettle(
PhysicsEngine physicsEngine,

View file

@ -34,23 +34,39 @@ internal sealed class HeadlessRuntimePlacementProjectionSink
if (projection.Kind is RuntimePlacementProjectionKind.ExecutorCompleted)
{
// F1: acknowledge-and-ignore, same as Discard - ExecutorCompleted
// is not a placement to project (no world/presentation mutation
// by definition; the executor's own drain already committed
// every Place/Withdraw this receipt follows). It must NOT fall
// through to the record-lookup gate below: that gate can validly
// reject an unrelated entity/session mismatch, and this sink's
// caller (RuntimePlacementProjectionSubscription) treats a false
// return as "leave at the FIFO head" - a rejected ExecutorCompleted
// would permanently wedge the entire ordered placement stream
// behind it. Currently provably inert: PublishExecutorCompletion
// has zero production callers (Execute/RegisterEntityWithInitialResidence
// are both unreached in production) - see
// HeadlessSessionHostTests.ExecutorCompletedReceiptIsAcknowledgeOnlyRegardlessOfRecordValidity.
// is not a placement to project (a headless host has no
// presentation to bind off the completed initial drain; the
// executor's own drain already committed every canonical fact).
// It must NOT fall through to the record-lookup gate below: that
// gate can validly reject an unrelated entity/session mismatch,
// and this sink's caller (RuntimePlacementProjectionSubscription)
// treats a false return as "leave at the FIFO head" - a rejected
// ExecutorCompleted would permanently wedge the entire ordered
// placement stream behind it.
return true;
}
RuntimePlacementProjectionToken token = projection.Token;
RuntimeEntityDirectory directory = _runtime.EntityObjects.Entities;
if (projection.Kind is RuntimePlacementProjectionKind.Place
or RuntimePlacementProjectionKind.Withdraw
&& token.IsValid
&& directory.TryGetByLocalId(
token.Entity.LocalEntityId,
out RuntimeEntityRecord residenceCandidate)
&& directory.IsCurrent(residenceCandidate)
&& residenceCandidate.Key == token.Entity
&& _runtime.EntityObjects.TryGetInitialCreateResidence(
residenceCandidate,
out _))
{
// 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 for the drive pump; validating or
// acknowledging it here would starve the conductor forever.
return false;
}
if (!token.IsValid
|| token.SessionLifetimeVersion
!= directory.SessionLifetimeVersion

View file

@ -15,6 +15,7 @@ internal sealed class HeadlessSessionEventRoute : ILiveSessionEventRouting
private readonly ILiveSessionEventRouting _events;
private readonly GameRuntime _runtime;
private readonly IRuntimePlacementProjectionSink _placements;
private readonly RuntimeFirstEntryDriveController? _firstEntry;
private RuntimePlacementProjectionSubscription? _subscription;
private bool _attachStarted;
private bool _eventsDisposed;
@ -23,12 +24,14 @@ internal sealed class HeadlessSessionEventRoute : ILiveSessionEventRouting
internal HeadlessSessionEventRoute(
ILiveSessionEventRouting events,
GameRuntime runtime,
IRuntimePlacementProjectionSink placements)
IRuntimePlacementProjectionSink placements,
RuntimeFirstEntryDriveController? firstEntry = null)
{
_events = events ?? throw new ArgumentNullException(nameof(events));
_runtime = runtime ?? throw new ArgumentNullException(nameof(runtime));
_placements = placements
?? throw new ArgumentNullException(nameof(placements));
_firstEntry = firstEntry;
}
public void Attach()
@ -41,6 +44,10 @@ internal sealed class HeadlessSessionEventRoute : ILiveSessionEventRouting
// succeeds and throws, LiveSessionHost's retryable rollback still
// invokes Dispose on the underlying route.
_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();
_subscription = new RuntimePlacementProjectionSubscription(
_runtime,
@ -56,6 +63,12 @@ internal sealed class HeadlessSessionEventRoute : ILiveSessionEventRouting
// network route. A still-pending FIFO head remains Runtime-owned for
// the replacement route to drain.
Interlocked.Exchange(ref _subscription, null)?.Dispose();
// C3c: the drive controller's tracked entries die with this exact
// route; Runtime's 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

@ -120,6 +120,12 @@ internal sealed class HeadlessSessionHost : IDisposable
private readonly RuntimeLocalPlayerFrameController _localPlayerFrame;
private readonly HeadlessProcessContentOwner.HeadlessProcessContentLease?
_contentLease;
/// <summary>C3c: one per-host first-entry drive controller (lazy — its
/// residence-begin subscription binds once against the persistent
/// Runtime lifetime) plus the active world projection it pumps
/// through.</summary>
private RuntimeFirstEntryDriveController? _firstEntryDrive;
private HeadlessSessionWorldProjection? _worldProjection;
private int _disposeStage;
private long _reconnectDeadline;
private bool _reconnectPending;
@ -295,6 +301,10 @@ internal sealed class HeadlessSessionHost : IDisposable
_localPlayerFrame.AdvanceBeforeNetwork(
checked((float)deltaSeconds));
Runtime.Session.Tick();
// C3c: pump pending first-entry sequences after the network drain —
// collision-generation progress and freshly accepted Creates both
// surface here, mirroring the graphical per-frame retry phase.
_worldProjection?.PumpFirstEntry();
_localPlayerFrame.RunPostNetworkCommandPhase();
Runtime.ActionOwner.CombatAttack.Tick();
_policy.Tick(Runtime, Commands);
@ -525,10 +535,34 @@ internal sealed class HeadlessSessionHost : IDisposable
private ILiveSessionEventRouting CreateEventRoute(
AcDream.Core.Net.WorldSession session)
{
IRuntimeDirectWorldProjection? worldProjection =
_contentLease is { } content
? new HeadlessSessionWorldProjection(Runtime, content)
: null;
IRuntimeDirectWorldProjection? worldProjection = null;
if (_contentLease is { } content)
{
// C3c: one drive controller per host — the residence-begin
// notification binds once against the persistent Runtime
// lifetime; reconnects reuse it (its tracked entries are cleared
// with each retiring route).
_firstEntryDrive ??= new RuntimeFirstEntryDriveController(
Runtime.EntityObjects,
Runtime.Clock,
content.PreparedCollision,
() => PlayerMovementConstructionOptions.From(
Runtime.CharacterOwner.MovementSkills.Snapshot),
// A headless host registers no shadow payloads — the local
// player is provably shapeless in the shadow registry, with
// the same default approach cylinder the deleted
// hand-resolve used.
static _ => new RuntimeLocalPlayerPhysicsActivationPreparation(
Radius: 0.48f,
Height: 1.835f,
RuntimeLocalPlayerShadowDisposition.ProvenShapeless));
var projection = new HeadlessSessionWorldProjection(
Runtime,
content,
_firstEntryDrive);
_worldProjection = projection;
worldProjection = projection;
}
var entities = new RuntimeLiveEntitySessionController(
Runtime,
session,
@ -583,7 +617,8 @@ internal sealed class HeadlessSessionHost : IDisposable
return new HeadlessSessionEventRoute(
route,
Runtime,
new HeadlessRuntimePlacementProjectionSink(Runtime));
new HeadlessRuntimePlacementProjectionSink(Runtime),
_firstEntryDrive);
}
private static LiveSessionCharacterSelector MapCharacterSelector(

View file

@ -16,6 +16,15 @@ internal interface IHeadlessCollisionNeighborhood
void CenterOn(uint fullCellId);
bool IsReady(uint fullCellId);
/// <summary>
/// C3c-R1 review F7: true when <paramref name="fullCellId"/>'s landblock
/// is one this neighborhood can ever collision-publish — inside the 3x3
/// window around the requested center (or no center has been requested
/// yet). A remote Create outside the window must not open a deferred
/// placement: its collision-generation wake could never fire.
/// </summary>
bool IsWithinServiceWindow(uint fullCellId);
}
internal readonly record struct HeadlessCollisionGenerationAdvance(
@ -233,6 +242,20 @@ internal sealed class HeadlessCollisionNeighborhood
AdvanceWork();
}
public bool IsWithinServiceWindow(uint fullCellId)
{
if (_requestedCenterLandblock == 0u)
return true;
uint target = CanonicalLandblock(fullCellId);
int dx = Math.Abs(
(int)((target >> 24) & 0xFFu)
- (int)((_requestedCenterLandblock >> 24) & 0xFFu));
int dy = Math.Abs(
(int)((target >> 16) & 0xFFu)
- (int)((_requestedCenterLandblock >> 16) & 0xFFu));
return dx <= 1 && dy <= 1;
}
public bool IsReady(uint fullCellId)
{
uint center = CanonicalLandblock(fullCellId);
@ -480,36 +503,72 @@ internal sealed class HeadlessSessionWorldProjection
private readonly GameRuntime _runtime;
private readonly IHeadlessCollisionNeighborhood _collision;
private readonly IPreparedCollisionSource? _preparedCollision;
private readonly RuntimeFirstEntryDriveController? _firstEntry;
private uint _requestedLocalPlayerCell;
internal HeadlessSessionWorldProjection(
GameRuntime runtime,
HeadlessProcessContentOwner.HeadlessProcessContentLease content)
HeadlessProcessContentOwner.HeadlessProcessContentLease content,
RuntimeFirstEntryDriveController? firstEntry = null)
: this(
runtime,
new HeadlessCollisionNeighborhood(runtime, content),
content.PreparedCollision)
firstEntry)
{
}
internal HeadlessSessionWorldProjection(
GameRuntime runtime,
IHeadlessCollisionNeighborhood collision,
IPreparedCollisionSource? preparedCollision = null)
RuntimeFirstEntryDriveController? firstEntry = null)
{
_runtime = runtime
?? throw new ArgumentNullException(nameof(runtime));
_collision = collision
?? throw new ArgumentNullException(nameof(collision));
_preparedCollision = preparedCollision;
_firstEntry = firstEntry;
}
public void ProjectSpawn(
RuntimeEntityRecord record,
bool isLocalPlayer)
{
if (isLocalPlayer)
SynchronizeLocalPlayer(record);
// C3c route-8 flip: the first-entry conductors own mover
// preparation, body/controller construction, and placement for every
// Create. The host's spawn projection centers the collision
// neighborhood on the local player's wire cell (the activation
// defers until its collision generation commits) and pumps the
// drive; remote leases ride the same pump.
if (isLocalPlayer
&& record.ServerGuid == _runtime.PlayerIdentity.ServerGuid
// C3c-R1 review F4: LandblockId is the RAW wire value; 0 is the
// absent-id sentinel and the F3 admission guards
// (RuntimePhysicsState.BeginCollisionAdmission) now throw on it,
// which would make one absent-position Create session-fatal.
// Skip the centering; the conductor pumps regardless.
&& record.Snapshot.Position is { LandblockId: not 0u } position)
{
_requestedLocalPlayerCell = position.LandblockId;
_collision.CenterOn(position.LandblockId);
}
else if (!isLocalPlayer
&& record.Snapshot.Position is
{ LandblockId: not 0u } remotePosition
&& !_collision.IsWithinServiceWindow(remotePosition.LandblockId))
{
// C3c-R1 review F7: a remote/projectile Create outside the
// neighborhood's service window would submit a placement whose
// DeferredCell park can never wake (the far landblock is never
// collision-published here), pinning its residence and this
// pump's entry forever. Convert to the celless completion route
// BEFORE the pump: the conductor completes with FullCell 0 and
// the accepted wire frame stays on the canonical snapshot — the
// exact pre-flip accepted-frame behavior for far remotes. A
// later fresh Position event owns any subsequent placement.
_ = _runtime.EntityObjects
.TryConvertInitialResidenceToCellessRoute(record);
}
_firstEntry?.DriveAll();
}
public void ProjectPosition(
@ -522,7 +581,17 @@ internal sealed class HeadlessSessionWorldProjection
if (_runtime.MovementOwner.Controller is null)
{
SynchronizeLocalPlayer(record);
// C3c: the initial-resolve hand-copy is gone — a Position
// arriving before the conductor's publication commit only pumps
// the drive (the conductor re-reads the accepted snapshot
// itself). C3c-R1 review F4: guard the raw wire LandblockId —
// 0 is the absent-id sentinel the F3 admission guards throw on.
if (record.Snapshot.Position is { LandblockId: not 0u } position)
{
_requestedLocalPlayerCell = position.LandblockId;
_collision.CenterOn(position.LandblockId);
}
_firstEntry?.DriveAll();
return;
}
@ -530,6 +599,19 @@ internal sealed class HeadlessSessionWorldProjection
BlipLocalPlayer(record);
}
/// <summary>
/// C3c: the host tick's first-entry pump — advances the collision
/// neighborhood toward the requested local-player cell (its publication
/// work progresses on <c>IsReady</c> polls) and drives every pending
/// conductor sequence.
/// </summary>
internal void PumpFirstEntry()
{
if (_requestedLocalPlayerCell != 0u)
_ = _collision.IsReady(_requestedLocalPlayerCell);
_firstEntry?.DriveAll();
}
public void BeginTeleport()
{
if (_runtime.MovementOwner.Controller is { } controller)
@ -545,7 +627,7 @@ internal sealed class HeadlessSessionWorldProjection
destination.EntityGuid,
out RuntimeEntityRecord record))
{
SynchronizeLocalPlayer(record);
ResynchronizeLocalPlayerForPortalArrival(record);
}
if (_runtime.MovementOwner.Controller is { } controller)
controller.State = PlayerState.InWorld;
@ -563,19 +645,27 @@ internal sealed class HeadlessSessionWorldProjection
IsCollisionReady: ready);
}
private void SynchronizeLocalPlayer(RuntimeEntityRecord record)
/// <summary>
/// TODO-C4 (route 3): portal-arrival re-synchronization only. The
/// route-1/8 initial-entry hand-copy (controller construction + first
/// resolve/placement) was deleted at C3c — the first-entry conductor's
/// publication chain owns it — but the portal route is unflipped, so its
/// arrival re-resolve keeps today's exact behavior against the
/// already-published controller until C4 routes it through
/// RuntimePortalPlacementAuthority.
/// </summary>
private void ResynchronizeLocalPlayerForPortalArrival(
RuntimeEntityRecord record)
{
if (record.ServerGuid
!= _runtime.PlayerIdentity.ServerGuid
|| record.Snapshot.Position is not { } position)
|| record.Snapshot.Position is not { } position
|| _runtime.MovementOwner.Controller is not { } controller)
{
return;
}
_collision.CenterOn(position.LandblockId);
PlayerMovementController controller =
_runtime.MovementOwner.Controller
?? CreateController(record);
Vector3 wirePosition = new(
position.PositionX,
position.PositionY,
@ -636,57 +726,4 @@ internal sealed class HeadlessSessionWorldProjection
wirePosition);
}
private PlayerMovementController CreateController(
RuntimeEntityRecord record)
{
var controller = new PlayerMovementController(
_runtime.EntityObjects.Physics.Engine,
record.ObjectClock,
PlayerMovementConstructionOptions.From(
_runtime.CharacterOwner.MovementSkills.Snapshot));
controller.ApplyPhysicsState(record.FinalPhysicsState);
controller.LocalEntityId = record.LocalEntityId ?? 0u;
ApplySetupStepHeights(record, controller);
RuntimeMovementSkillProjection.ApplyTo(
_runtime.CharacterOwner.MovementSkills,
controller);
_runtime.MovementOwner.Controller = controller;
return controller;
}
private void ApplySetupStepHeights(
RuntimeEntityRecord record,
PlayerMovementController controller)
{
if (record.Snapshot.SetupTableId is not { } setupId
|| (setupId & 0xFF000000u) != 0x02000000u
|| _preparedCollision is null)
{
return;
}
PreparedCollisionReadResult<FlatSetupCollision> read =
_preparedCollision.ReadSetupCollision(setupId);
if (read.Status != PreparedAssetReadStatus.Loaded
|| read.Data is not { } setup)
{
throw new InvalidDataException(
$"Player Setup collision 0x{setupId:X8} is {read.Status}.");
}
_runtime.EntityObjects.Physics.DataCache.CacheSetup(
setupId,
setup);
controller.StepUpHeight = setup.StepUpHeight > 0f
? setup.StepUpHeight
: 0.4f;
controller.StepDownHeight = setup.StepDownHeight > 0f
? setup.StepDownHeight
: 0.4f;
// TS-46 (2026-07-30): the prepared package already carries the
// Setup's verbatim sphere list — no raw-DAT read needed here (unlike
// the graphical PlayerModeController.ApplyStepHeights, which reads
// DatReaderWriter.DBObjs.Setup directly). Empty falls back to
// ResolveWithTransition's legacy scalar reconstruction.
controller.SphereList = setup.Spheres;
}
}

View file

@ -70,7 +70,16 @@ public readonly record struct RuntimeEntityObjectOwnershipSnapshot(
/// keys - the remote/projectile Create-time body-construction conductor.
/// Dormant like its C3a sibling; converges to zero the same way.
/// </summary>
int RemoteFirstEntryActiveCount = 0)
int RemoteFirstEntryActiveCount = 0,
/// <summary>
/// C3c-R1 review F5: outstanding host first-entry drive entries
/// (<c>RuntimeFirstEntryDriveController</c> pending keys, summed over
/// every drive registered against this lifetime via
/// <see cref="RuntimeEntityObjectLifetime.RegisterFirstEntryDriveOwnership"/>).
/// Previously outside every ledger; gated by <see cref="IsConverged"/>
/// like the conductor counts it pumps.
/// </summary>
int FirstEntryDrivePendingCount = 0)
{
public bool IsConverged =>
IsDisposed
@ -94,6 +103,7 @@ public readonly record struct RuntimeEntityObjectOwnershipSnapshot(
&& PendingCompletionReceiptCount == 0
&& LocalPlayerFirstEntryActiveCount == 0
&& RemoteFirstEntryActiveCount == 0
&& FirstEntryDrivePendingCount == 0
&& StreamSubscriberCount == 0
&& PlacementStreamSubscriberCount == 0
&& PendingDispatchCount == 0
@ -137,6 +147,10 @@ public sealed class RuntimeEntityObjectLifetime : IDisposable
{
private bool _sessionClearInProgress;
private bool _disposed;
/// <summary>C3c: see <see cref="BindInitialResidenceBeginNotification"/>.</summary>
private Action<RuntimeEntityRecord>? _initialResidenceBegan;
/// <summary>C3c-R1 review F5: see <see cref="RegisterFirstEntryDriveOwnership"/>.</summary>
private readonly List<Func<int>> _firstEntryDriveOwnership = [];
public RuntimeEntityObjectLifetime(
uint firstLocalEntityId = RuntimeEntityDirectory.FirstLocalEntityId,
@ -437,7 +451,31 @@ public sealed class RuntimeEntityObjectLifetime : IDisposable
InitialCreateExecution.LastReplayFailure is not null,
InitialCreateExecution.PendingCompletionReceiptCount,
LocalPlayerFirstEntry.CaptureOwnership().ActiveCount,
RemoteFirstEntry.CaptureOwnership().ActiveCount);
RemoteFirstEntry.CaptureOwnership().ActiveCount,
CaptureFirstEntryDrivePendingCount());
}
private int CaptureFirstEntryDrivePendingCount()
{
int total = 0;
for (int i = 0; i < _firstEntryDriveOwnership.Count; i++)
total = checked(total + _firstEntryDriveOwnership[i]());
return total;
}
/// <summary>
/// C3c-R1 review F5: registers one host first-entry drive controller's
/// pending-count provider into this lifetime's ownership snapshot, so
/// tracked-but-undriven entries can never sit outside every ledger. The
/// drive controller registers itself at construction (it already binds
/// <see cref="BindInitialResidenceBeginNotification"/> there); multiple
/// registrations sum, mirroring the multicast notification shape.
/// </summary>
public void RegisterFirstEntryDriveOwnership(Func<int> pendingCount)
{
ArgumentNullException.ThrowIfNull(pendingCount);
EnsureNotDisposed();
_firstEntryDriveOwnership.Add(pendingCount);
}
public void BindEventContext(
@ -451,6 +489,22 @@ public sealed class RuntimeEntityObjectLifetime : IDisposable
InitialCreateExecution.BindGeneration(generation);
}
/// <summary>
/// C3c: registers one host callback fired for every FRESH initial-create
/// residence begin (never for a same-generation FIFO append). Multicast,
/// mirroring <see cref="RuntimeInitialCreateResidenceState.BindRetirementNotification"/>.
/// The callback runs synchronously inside the registration transaction —
/// subscribers must only record the entity for a later drive pump, never
/// call a conductor's Advance re-entrantly from it.
/// </summary>
public void BindInitialResidenceBeginNotification(
Action<RuntimeEntityRecord> began)
{
ArgumentNullException.ThrowIfNull(began);
EnsureNotDisposed();
_initialResidenceBegan += began;
}
/// <summary>
/// C0-2: forwards to <see cref="RuntimeInitialCreateContinuationExecutor.BindLiveInputs"/>,
/// the same fan-out shape <see cref="BindEventContext"/> already uses for
@ -2270,6 +2324,20 @@ public sealed class RuntimeEntityObjectLifetime : IDisposable
return InitialCreateResidences.TryGetCurrent(canonical, out lease);
}
/// <summary>
/// C3c-R1 review F7: host seam for a bounded-collision-neighborhood
/// host to convert a remote/projectile Create's active residence to the
/// celless completion route when its destination landblock will never
/// be collision-published (a headless far remote). See
/// <see cref="RuntimeInitialCreateResidenceState.TryConvertToCellessRoute"/>.
/// </summary>
public bool TryConvertInitialResidenceToCellessRoute(
RuntimeEntityRecord canonical)
{
EnsureNotDisposed();
return InitialCreateResidences.TryConvertToCellessRoute(canonical);
}
internal RuntimeInitialCreateResidenceCompletionStatus
CompleteInitialCreateResidence(
RuntimeEntityRecord canonical,
@ -2339,7 +2407,19 @@ public sealed class RuntimeEntityObjectLifetime : IDisposable
canonical,
accepted,
isLocalPlayer);
return lease.IsValid;
if (!lease.IsValid)
return false;
// C3c: host drive notification. Fires for EVERY fresh residence
// begin through this single choke point — wire-dispatch Creates AND
// the executor's deferred-child replays (which register through this
// class's own bound delegate, never through a host runtime). The
// subscriber must only RECORD the key for a later drive pump — this
// fires mid-registration, before Registered publishes, and a
// synchronous Advance here would interleave with the enclosing
// transaction (and, for a replayed child, with the parent's own
// in-flight Execute).
_initialResidenceBegan?.Invoke(canonical);
return true;
}
private Exception FailInitialResidenceRegistration(

View file

@ -1007,6 +1007,52 @@ internal sealed class RuntimeInitialCreateResidenceState
return _completed.Remove(token.Entity);
}
/// <summary>
/// C3c-R1 review F7: converts an ACTIVE, not-yet-placed
/// SetPosition-performing residence to the celless
/// (AwaitFreshPosition) route shape, forgetting its authored placement
/// operation. The residence entry itself stays active — the conductor's
/// next pump takes the existing celless skip-to-Execute path and
/// completes with FullCell 0, exactly like a Parented/PickedUp lease.
/// The retirement fan-out is fired to reset conductor/executor progress
/// for the key (its subscribers are pure progress reapers:
/// executor <c>DiscardProgress</c> + both conductors' <c>Forget</c>);
/// the entry itself is deliberately NOT retired. Refused once any
/// placement has committed (<c>FullCellId != 0</c>) — the entity is not
/// a far remote then.
/// </summary>
internal bool TryConvertToCellessRoute(RuntimeEntityRecord record)
{
ArgumentNullException.ThrowIfNull(record);
if (record.Key is not { } key
|| !_entries.TryGetValue(key, out Entry? entry)
|| !ReferenceEquals(entry.Record, record))
{
return false;
}
if (!IsCurrent(entry))
{
Retire(entry);
return false;
}
RuntimeInitialCreateResidenceLease lease = entry.Lease;
if (!lease.Route.PerformsSetPosition)
return true;
if (record.FullCellId != 0u)
return false;
RuntimePlacementCancellationReceipt cancellation =
_setPosition.ForgetExactPlacement(lease.Placement);
entry.Lease = lease with
{
Route = RuntimeAuthoritativePositionRouteClassifier
.ToCellessCreateRoute(lease.Route),
Placement = default,
};
_setPosition.PublishCancellation(cancellation);
NotifyRetirement(key);
return true;
}
internal bool Forget(
RuntimeEntityRecord record,
out RuntimeInitialCreateResidenceLease lease,

View file

@ -113,11 +113,13 @@ internal readonly record struct RuntimeRemoteFirstEntryOwnershipSnapshot(
/// <c>DormantLocalActivation</c> set, so the ordinary submission tail is the
/// correct — and only — commit route.
///
/// Dormant by design: <see cref="RuntimeEntityObjectLifetime"/> fully
/// constructs and wires this class (construction, retirement fan-out, bulk
/// session-clear cleanup, ownership fold) exactly like the C3a conductor,
/// but nothing calls <see cref="Advance"/> in production — C3c wires the
/// hosts.
/// PRODUCTION-DRIVEN since the C3c flip: <see cref="RuntimeEntityObjectLifetime"/>
/// fully constructs and wires this class (construction, retirement fan-out,
/// bulk session-clear cleanup, ownership fold) exactly like the C3a
/// conductor, and the host first-entry drive
/// (<c>RuntimeFirstEntryDriveController</c>) calls <see cref="Advance"/>
/// for every remote/projectile initial-create residence on both the
/// graphical and headless hosts.
/// </summary>
internal sealed class RuntimeRemoteFirstEntryState
{

View file

@ -263,6 +263,13 @@ public sealed class GameRuntime
context.EntityObjects.Physics,
context.Movement,
context.PlayerIdentity));
// C3c: the C3a conductor's "first act" — bind the publication
// owner the conductor was constructed without (it is built by
// RuntimeEntityObjectLifetime BEFORE
// RuntimeLocalPlayerPhysicsPublicationState exists; see the F2
// late-bind note on RuntimeLocalPlayerFirstEntryState's ctor).
context.EntityObjects.LocalPlayerFirstEntry.BindPublication(
context.Movement.PhysicsPublication);
context.EntityObjects.BindEventContext(
() => generationReset.ActiveRetiringGeneration

View file

@ -368,6 +368,38 @@ public sealed class PlayerMovementController
_body.calc_acceleration();
}
/// <summary>
/// C3c-F1 (2026-08-02): the lifecycle-deciding inbound-SetState entry
/// for the local player. Live states apply the exact
/// <see cref="ApplyPhysicsState"/> body; the dormant window drops the
/// push because the activation transaction owns the dormant body's
/// physics state exclusively (<see cref="RefreshDormantRuntimePhysicsState"/>
/// re-reads the canonical record's FinalPhysicsState at both activation
/// phases, and while the accepted SetState is queued behind the initial
/// residence the App-side push carries that same unchanged record value
/// — the drop is value-preserving by construction); terminal states are
/// displaced pushes (J3.6 displaced-callback-rejection), never a fault.
/// </summary>
internal RuntimeServerPhysicsStateApplication ApplyServerPhysicsState(
PhysicsStateFlags state)
{
switch (_publicationLifecycle)
{
case PlayerMovementControllerPublicationLifecycle.StandalonePublished:
case PlayerMovementControllerPublicationLifecycle.CandidatePreparing:
case PlayerMovementControllerPublicationLifecycle.RuntimePublished:
_body.State = state;
_body.calc_acceleration();
return RuntimeServerPhysicsStateApplication.AppliedLive;
case PlayerMovementControllerPublicationLifecycle.RuntimeOwnedDormant:
return RuntimeServerPhysicsStateApplication
.DroppedDormantActivationOwned;
default:
return RuntimeServerPhysicsStateApplication
.DroppedDisplacedController;
}
}
public bool IsAirborne => !_body.OnWalkable;
/// <summary>
@ -1292,6 +1324,114 @@ public sealed class PlayerMovementController
lastPkAttackTimestamp);
}
/// <summary>
/// C3c-F1 (2026-08-02): the lifecycle-deciding half of the Runtime
/// movement-stats application seam
/// (<see cref="RuntimeLocalPlayerMovementState.ApplyCharacterMovementStats"/>).
/// The publication owner — not any App caller — decides whether a
/// server stat recompute may land:
/// <list type="bullet">
/// <item><see cref="PlayerMovementControllerPublicationLifecycle.StandalonePublished"/>,
/// <see cref="PlayerMovementControllerPublicationLifecycle.CandidatePreparing"/>, and
/// <see cref="PlayerMovementControllerPublicationLifecycle.RuntimePublished"/>
/// apply immediately — byte-identical to the deleted
/// <c>RuntimeMovementSkillProjection.ApplyTo</c> direct path.</item>
/// <item><see cref="PlayerMovementControllerPublicationLifecycle.RuntimeOwnedDormant"/>
/// ALSO applies immediately: the dormant window (publication committed,
/// activation deferred on cell streaming —
/// <c>RuntimeLocalPlayerFirstEntryState.AdvanceCore</c>'s
/// AwaitingActivation loop) spans inbound pumps, and this exact instance
/// is the controller that <c>ActivateRuntimePublication</c> later makes
/// live, so the write must land here (same discipline as
/// <see cref="RefreshDormantRuntimePhysicsState"/> /
/// <see cref="RefreshDormantRuntimeVector"/>: accepted server facts
/// arriving mid-dormancy land on the dormant owner). These writes touch
/// only <see cref="PlayerWeenie"/> fields and the mover-flag latch —
/// no body/world/currency state the activation envelope validates.</item>
/// <item><see cref="PlayerMovementControllerPublicationLifecycle.CandidateSealed"/>,
/// <see cref="PlayerMovementControllerPublicationLifecycle.RuntimeRetired"/>, and
/// <see cref="PlayerMovementControllerPublicationLifecycle.Discarded"/>
/// report the typed displaced-write outcome (J3.6
/// displaced-callback-rejection): a stat write against a terminal
/// controller is meaningless by design — the next login re-derives from
/// PlayerDescription. A sealed candidate is additionally unreachable
/// through the seam in production: it is never installed into
/// <see cref="RuntimeLocalPlayerMovementState"/> (Prepare requires the
/// movement owner empty and Commit installs it already-dormant in the
/// same synchronous Advance step).</item>
/// </list>
/// </summary>
internal RuntimeMovementStatsApplication ApplyCharacterMovementStats(
in RuntimeMovementSkillSnapshot snapshot)
{
switch (_publicationLifecycle)
{
case PlayerMovementControllerPublicationLifecycle.StandalonePublished:
case PlayerMovementControllerPublicationLifecycle.CandidatePreparing:
case PlayerMovementControllerPublicationLifecycle.RuntimePublished:
ApplyCharacterMovementStatsCore(snapshot);
return RuntimeMovementStatsApplication.AppliedLive;
case PlayerMovementControllerPublicationLifecycle.RuntimeOwnedDormant:
ApplyCharacterMovementStatsCore(snapshot);
return RuntimeMovementStatsApplication.AppliedDormant;
default:
return RuntimeMovementStatsApplication.DroppedDisplacedController;
}
}
/// <summary>
/// The exact application body of the deleted
/// <c>RuntimeMovementSkillProjection.ApplyTo</c> (same fields, same
/// order, same conversions) — moved behind the lifecycle switch so the
/// dormant window can share it without routing through the
/// <see cref="EnsureConfigurationMutable"/>-gated public setters.
/// Campaign P Slice P1 (2026-07-30): burden/stamina ride the SAME seam
/// run/jump skill already used — see the pseudocode doc §9. TS-23
/// (Campaign P Slice P3, 2026-07-30): the player's own
/// PK/PKLite/Impenetrable collision-exemption bits and the
/// PlayerKillerStatus/LastPkAttackTimestamp pair the jump-cost PK-timer
/// bump reads — see <c>EntityCollisionFlagsExt.ToMoverState</c> and
/// <c>PlayerWeenie.JumpStaminaCost</c>.
/// </summary>
private void ApplyCharacterMovementStatsCore(
in RuntimeMovementSkillSnapshot snapshot)
{
_weenie.SetSkills(snapshot.RunSkill, snapshot.JumpSkill);
_weenie.SetBurden(snapshot.Burden);
_weenie.SetStamina(
snapshot.CurrentStamina < 0 ? null : (uint)snapshot.CurrentStamina);
_ownPvpFlags = EntityCollisionFlagsExt
.FromPwdBitfield(snapshot.OwnPwdBitfield)
.ToMoverState();
_weenie.SetPlayerKillerStatus(
snapshot.PlayerKillerStatus < 0 ? null : snapshot.PlayerKillerStatus,
snapshot.LastPkAttackTimestamp);
}
/// <summary>
/// C3c-F1: the stamina-exhaustion EVENT dispatch
/// (retail <c>CommandInterpreter::HandleExhaustion</c> @ 0x006b3c70 →
/// <c>CPhysicsObj::report_exhaustion</c>), routed through the owner so
/// App never touches the gated <see cref="Motion"/> surface. Fires only
/// on a live controller: a dormant owner has no in-flight movement to
/// re-dispatch (retail's handler is a no-op for a player not in world;
/// activation dispatches movement fresh from the already-current
/// <see cref="PlayerWeenie"/> stamina gate), and a terminal owner is a
/// displaced callback.
/// </summary>
internal bool ReportExhaustionAtMovementBoundary()
{
if (_publicationLifecycle
is PlayerMovementControllerPublicationLifecycle.StandalonePublished
or PlayerMovementControllerPublicationLifecycle.CandidatePreparing
or PlayerMovementControllerPublicationLifecycle.RuntimePublished)
{
_motion.ReportExhaustion();
return true;
}
return false;
}
/// <summary>
/// R3-W2 (r3-port-plan.md §4): the player's <see cref="MotionInterpreter"/>
/// — GameWindow binds the player sequencer's MotionDone seam to it so the
@ -1651,15 +1791,39 @@ public sealed class PlayerMovementController
RearmConstraintLeashAtCurrentPosition();
}
/// <summary>
/// C3c-R1: arms the login-entry constraint leash from the Runtime
/// publication chain. The flip deleted the only login-path caller of
/// <see cref="RearmConstraintLeashAtCurrentPosition"/> (the App-side
/// <see cref="CommitPreparedPosition"/> call in the old
/// player-mode-entry commit); the dormant activation's final commit
/// (<c>RuntimeSetPositionState.TryApplyDormantLocalActivationFinalCommit</c>)
/// is the accepted-position event that replaces it — retail arms at
/// every accepted-position event (<c>SmartBox::HandleReceivedPosition</c>
/// 0x00453FD0). The final commit has already activated this controller
/// (<c>ActivateRuntimePublication</c>), so the published guard doubles
/// as a stale-caller check. Like the pre-flip commit path, no
/// UnConstrain teardown is needed: nothing can have armed the leash on
/// a controller whose <see cref="PositionManager"/> was created by its
/// own publication candidate.
/// </summary>
internal void ArmConstraintLeashAtCommittedPlacement()
{
EnsurePublishedForRuntimeOperation();
RearmConstraintLeashAtCurrentPosition();
}
/// <summary>
/// #167 (Campaign P P5): retail <c>SmartBox::HandleReceivedPosition</c>
/// (0x00453fd0) "Player, teleport-newer" branch re-arms the leash
/// immediately after <c>TeleportPlayer</c>'s teardown, anchored to the
/// RECEIVED position (here, the body's just-snapped current position).
/// Shared by the teleport path (after UnConstrain) and the deferred
/// Shared by the teleport path (after UnConstrain), the deferred
/// player-mode-entry commit path (<see cref="CommitPreparedPosition"/>),
/// which never ran UnConstrain because nothing could have armed the
/// leash before the controller had a <see cref="PositionManager"/>.
/// leash before the controller had a <see cref="PositionManager"/>,
/// and the C3c first-entry placement commit
/// (<see cref="ArmConstraintLeashAtCommittedPlacement"/>).
/// docs/research/2026-07-30-constraint-leash-constants.md §2/§3.2.
/// </summary>
private void RearmConstraintLeashAtCurrentPosition()

View file

@ -131,12 +131,14 @@ internal readonly record struct RuntimeLocalPlayerFirstEntryOwnershipSnapshot(
/// <see cref="RuntimeSetPositionState.TryPrepareAuthoredMover"/> half instead
/// and never the fused method.
///
/// Dormant by design: <see cref="RuntimeEntityObjectLifetime"/> fully
/// constructs and wires this class (construction, publication binding,
/// PRODUCTION-DRIVEN since the C3c flip: <see cref="RuntimeEntityObjectLifetime"/>
/// fully constructs and wires this class (construction, publication binding,
/// retirement fan-out, bulk session-clear cleanup, ownership fold) exactly
/// like every other owner it builds, but nothing calls
/// <see cref="Advance"/> in production — a later slice wires a host to drive
/// it.
/// like every other owner it builds, and the host first-entry drive
/// (<c>RuntimeFirstEntryDriveController</c>, pumped by the graphical
/// hydration/frame-retry cadence and the headless spawn/position/tick
/// cadence) calls <see cref="Advance"/> for every local-player
/// initial-create residence.
/// </summary>
internal sealed class RuntimeLocalPlayerFirstEntryState
{

View file

@ -14,6 +14,70 @@ public interface IRuntimeLocalPlayerMotionSource
MotionInterpreter? Motion { get; }
}
/// <summary>
/// C3c-F1 (2026-08-02): typed outcome of routing a server movement-stat
/// recompute through the Runtime movement owner. The dropped outcomes are
/// the J3.6 displaced-callback-rejection pattern — never an exception and
/// never a silent void: the caller logs them under its existing
/// diagnostics. A skill write against a dead session is meaningless by
/// design; the next login re-derives everything from PlayerDescription.
/// </summary>
public enum RuntimeMovementStatsApplication
{
/// <summary>Applied to the live (published/standalone) controller —
/// byte-identical to the pre-F1 direct application path.</summary>
AppliedLive,
/// <summary>Applied to the Runtime-owned dormant controller during the
/// committed-but-not-yet-activated first-entry window. The same
/// instance goes live at activation, so the values are already current
/// when movement starts.</summary>
AppliedDormant,
/// <summary>No controller is installed (pre-first-entry, mid-candidate
/// construction, or after session teardown cleared the owner).</summary>
DroppedNoController,
/// <summary>The skill snapshot has no authoritative run/jump values yet
/// (PlayerDescription not processed) — same silent skip as the pre-F1
/// path.</summary>
DroppedIncompleteSnapshot,
/// <summary>The installed controller is terminal (sealed, retired, or
/// discarded): a displaced post-teardown write, reported instead of
/// faulting the session.</summary>
DroppedDisplacedController,
}
/// <summary>
/// C3c-F1 (2026-08-02): typed outcome of routing an inbound server
/// PhysicsState push through the local movement controller's publication
/// lifecycle. Same displaced-callback-rejection family as
/// <see cref="RuntimeMovementStatsApplication"/>, with one deliberate
/// difference: the dormant window DROPS the push rather than applying it,
/// because the activation transaction owns the dormant body's physics
/// state exclusively (it re-reads the canonical record's FinalPhysicsState
/// through <c>RefreshDormantRuntimePhysicsState</c> at both activation
/// phases), and the App-side push carries that exact same unchanged record
/// value while the accepted SetState itself is queued behind the initial
/// residence — dropping it is value-preserving by construction.
/// </summary>
public enum RuntimeServerPhysicsStateApplication
{
/// <summary>Applied to the live (published/standalone) controller —
/// byte-identical to the direct <c>ApplyPhysicsState</c> path.</summary>
AppliedLive,
/// <summary>The controller is Runtime-owned dormant: the activation
/// pipeline is the sole authority for the dormant body's physics state
/// and re-reads the canonical value itself.</summary>
DroppedDormantActivationOwned,
/// <summary>The installed controller is terminal — a displaced
/// post-teardown push.</summary>
DroppedDisplacedController,
}
/// <summary>
/// Canonical local movement lifetime and intent owner. Graphical input,
/// presentation, diagnostics, and future no-window hosts borrow this exact
@ -37,7 +101,13 @@ public sealed class RuntimeLocalPlayerMovementState
public PlayerMovementController? Controller
{
get => _controller;
set
// C3c seal: the public write escape hatch is closed. Production
// controller installation flows only through the publication
// lifecycle (CommitRuntimeOwnedController via
// RuntimeLocalPlayerPhysicsPublicationState.Commit) and teardown
// through ResetSession/Dispose/DiscardActivation. The setter stays
// reachable for tests via InternalsVisibleTo only.
internal set
{
ObjectDisposedException.ThrowIf(_disposed, this);
if (ReferenceEquals(_controller, value))
@ -189,6 +259,44 @@ public sealed class RuntimeLocalPlayerMovementState
return true;
}
/// <summary>
/// C3c-F1 (2026-08-02): the ONLY route by which server-authoritative
/// movement stats (run/jump skill, burden, stamina, PK status — the
/// exact field set of the deleted
/// <c>RuntimeMovementSkillProjection.ApplyTo</c>) reach the local
/// movement controller. App holds no controller reference for stat
/// application and performs no direct configuration mutation; the
/// owner's publication lifecycle decides whether the write lands
/// (live/dormant) or is reported as a typed displaced drop (terminal) —
/// the fix for the connected-gate post-logout ingest crash at
/// <c>PlayerMovementController.EnsureConfigurationMutable</c>.
/// Deliberately tolerant of a disposed owner: a recompute displaced
/// past teardown observes <see cref="RuntimeMovementStatsApplication.DroppedNoController"/>
/// instead of faulting the session.
/// </summary>
public RuntimeMovementStatsApplication ApplyCharacterMovementStats(
RuntimeMovementSkillState skills)
{
ArgumentNullException.ThrowIfNull(skills);
if (_controller is not { } controller)
return RuntimeMovementStatsApplication.DroppedNoController;
RuntimeMovementSkillSnapshot snapshot = skills.Snapshot;
if (!snapshot.IsComplete)
return RuntimeMovementStatsApplication.DroppedIncompleteSnapshot;
return controller.ApplyCharacterMovementStats(snapshot);
}
/// <summary>
/// C3c-F1: routes the stamina-exhaustion EVENT (retail
/// <c>CommandInterpreter::HandleExhaustion</c>) through the owner so the
/// App edge-tracker never touches the gated controller motion surface.
/// Returns false when no live controller can dispatch it (absent,
/// dormant, terminal, or disposed owner) — displaced-callback-tolerant
/// for the same reason as <see cref="ApplyCharacterMovementStats"/>.
/// </summary>
public bool ReportExhaustion() =>
_controller?.ReportExhaustionAtMovementBoundary() == true;
/// <summary>
/// Direct-host projection of the same combat readiness query used by the
/// graphical attack adapter. A host without a constructed local movement

View file

@ -278,13 +278,43 @@ internal sealed class RuntimeLocalPlayerPhysicsPublicationState : IDisposable
getObjectA: id => _physics.TryGetPhysicsHost(id, out var host)
? host
: null,
handleUpdateTarget: movement.HandleUpdateTarget,
// C3c: the [autowalk-target]/[autowalk-end] probes moved here
// with controller construction (previously App-side in
// PlayerModeController.BuildControllerAndCamera); they stay on
// the PhysicsDiagnostics owner exactly as before.
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})");
}
movement.HandleUpdateTarget(info);
},
interruptCurrentMovement: () =>
movement.CancelMoveTo(WeenieError.ActionCancelled));
{
if (PhysicsDiagnostics.ProbeAutoWalkEnabled
&& movement.IsMovingTo())
{
Console.WriteLine("[autowalk-end] reason=interrupt");
}
movement.CancelMoveTo(WeenieError.ActionCancelled);
});
movement.MakeMoveToManager();
motion.UnstickFromObject = physicsHost.PositionManager.UnStick;
motion.InterruptCurrentMovement = () =>
{
if (PhysicsDiagnostics.ProbeAutoWalkEnabled
&& movement.IsMovingTo())
{
Console.WriteLine("[autowalk-end] reason=interrupt");
}
movement.CancelMoveTo(WeenieError.ActionCancelled);
};
controller.PositionManager = physicsHost.PositionManager;
// This checkpoint publishes ownership only. The subsequent canonical
// SetPosition transaction is the sole authority which may enter the
@ -687,11 +717,106 @@ internal sealed class RuntimeLocalPlayerPhysicsPublicationState : IDisposable
_physics.SetPosition.DispatchDormantLocalActivationShadow(committed);
if (!IsCommittedActivationSuffixCurrent(activation, committed))
return committed.Status;
ArmFirstEntryConstraintLeash(activation);
SettleFirstEntryGroundContact(activation);
_physics.SetPosition.DispatchDormantLocalActivationPlacement(committed);
projection = committed.Projection.Token;
return committed.Status;
}
/// <summary>
/// C3c-R1: the login-entry constraint-leash arm the flip deleted with
/// the App-side <c>CommitPreparedPosition</c> caller. Ordering, with
/// file:line justification:
/// <list type="bullet">
/// <item>NOT at <c>Prepare</c> — <c>PreparePositionForCommit</c> (:219)
/// runs with <c>publishSharedState: false</c> and the controller's
/// <c>PositionManager</c> binds only later at :318, so the leash cannot
/// exist there (nor should it: the position is not accepted yet).</item>
/// <item>NOT at publication <c>Commit</c> — the activation's placement
/// evaluation (retail find-placement ring search) may still move or
/// reject the position.</item>
/// <item>HERE, after <c>TryApplyDormantLocalActivationFinalCommit</c>
/// (RuntimeSetPositionState.cs:2494-2516 commits the final cell,
/// activates the controller, and publishes the shared current cell) and
/// inside the same <c>IsCommittedActivationSuffixCurrent</c> gate the
/// settle uses — a stale suffix skips the arm exactly like the settle
/// (never armed on stale authority).</item>
/// <item>BEFORE <see cref="SettleFirstEntryGroundContact"/> — retail
/// arms anchored to the RECEIVED position
/// (<c>SmartBox::HandleReceivedPosition</c> 0x00453FD0) and only then
/// simulates the first gravity frame, which the settle compresses; the
/// anchor is therefore the committed placement, not the post-settle
/// pose.</item>
/// <item>Exactly once — <c>_activation</c> is nulled at :716 before
/// this suffix, so a resumed <c>AwaitingFinalShadowPreparation</c>
/// retry can never re-enter it after a successful final commit.</item>
/// </list>
/// </summary>
private void ArmFirstEntryConstraintLeash(Activation activation)
{
// Same containment as the settle below: the placement commit has
// already succeeded; a leash-arm failure must not unwind the suffix.
try
{
activation.Controller.ArmConstraintLeashAtCommittedPlacement();
}
catch
{
_activationDispatchFailureCount++;
}
}
/// <summary>
/// C3c-F5: retail seeds the LOCAL player's ground contact from the first
/// gravity frame after <c>enter_world</c>, never from the placement
/// itself — <c>SmartBox::HandleCreateObject</c> (0x00454C80) runs
/// <c>init_player</c> (0x00455010) then <c>CPhysicsObj::enter_world</c>
/// (0x00455095 → 0x00516170), whose <c>SetPosition</c> validates the
/// spot but records no touch and whose tail only sets ACTIVE (0x80).
/// Every retail CPhysicsObj then simulates, falls the few centimetres
/// onto the floor, and the transition's touch grants the contact plane
/// + CONTACT/ON_WALKABLE. The dormant activation's just-finished commit
/// is the faithful SetPosition port, so a fresh login body would start
/// airborne here; this compresses the settle exactly like the #270
/// remote-spawn seed (the shared <see cref="SpawnPlacementSettler"/>):
/// a short downward sweep whose real touch produces the state retail's
/// first frame would. No floor within reach (a genuine airborne spawn)
/// leaves the body airborne — the ordinary per-tick gravity fall owns
/// it from there. The body transients this commits ARE the controller's
/// grounded state (<c>PlayerMovementController.CanSendPositionEvent</c>
/// reads <c>InContact &amp;&amp; OnWalkable</c> off the same body) and
/// the outbound wire contact bit (<c>LocalPlayerOutboundController</c>
/// serializes that predicate) — the flag ACE's "You can't do that while
/// in the air!" gate reads.
/// </summary>
private void SettleFirstEntryGroundContact(Activation activation)
{
// Same post-commit callback-dispatch containment as the ground-edge
// dispatch in CommitActivation: the placement commit has already
// succeeded; a HitGround-side failure must not unwind the suffix.
try
{
_ = SpawnPlacementSettler.TrySettle(
_physics.Engine,
activation.Body,
activation.Body.Position,
activation.Body.CellPosition.ObjCellId,
activation.ActivationPreparation.Radius,
activation.ActivationPreparation.Height,
ObjectInfoState.IsPlayer
| ObjectInfoState.EdgeSlide
| activation.Controller.OwnPvpFlags,
activation.Controller.LocalEntityId,
activation.Movement.HitGround,
activation.Motion.LeaveGround);
}
catch
{
_activationDispatchFailureCount++;
}
}
private bool IsActivationPrephaseEnvelopeCurrent(
Activation activation,
in RuntimeDormantSetPositionCommitReceipt receipt) =>

View file

@ -1,41 +0,0 @@
using AcDream.Core.Physics;
namespace AcDream.Runtime.Gameplay;
/// <summary>
/// Applies the exact server-owned run/jump snapshot to either host's one local
/// movement controller. This lives beside the canonical skill owner so
/// graphical and no-window construction cannot drift.
/// </summary>
public static class RuntimeMovementSkillProjection
{
public static bool ApplyTo(
RuntimeMovementSkillState skills,
PlayerMovementController? controller)
{
ArgumentNullException.ThrowIfNull(skills);
RuntimeMovementSkillSnapshot snapshot = skills.Snapshot;
if (controller is null || !snapshot.IsComplete)
return false;
controller.SetCharacterSkills(
snapshot.RunSkill,
snapshot.JumpSkill);
// Campaign P Slice P1 (2026-07-30): burden/stamina ride the SAME
// seam run/jump skill already used — see the pseudocode doc §9.
controller.SetCharacterBurden(snapshot.Burden);
controller.SetCharacterStamina(snapshot.CurrentStamina);
// TS-23 (Campaign P Slice P3, 2026-07-30): the player's own
// PK/PKLite/Impenetrable collision-exemption bits and the
// PlayerKillerStatus/LastPkAttackTimestamp pair the jump-cost
// PK-timer bump reads — see EntityCollisionFlagsExt.ToMoverState
// and PlayerWeenie.JumpStaminaCost.
controller.OwnPvpFlags =
EntityCollisionFlagsExt.FromPwdBitfield(snapshot.OwnPwdBitfield)
.ToMoverState();
controller.SetCharacterPkStatus(
snapshot.PlayerKillerStatus,
snapshot.LastPkAttackTimestamp);
return true;
}
}

View file

@ -272,6 +272,39 @@ internal static class RuntimeAuthoritativePositionRouteClassifier
reporting);
}
/// <summary>
/// C3c-R1 review F7: converts an already-classified SetPosition-performing
/// initial-Create route into the EXACT celless (AwaitFreshPosition) shape
/// the Parented/PickedUp branch of <see cref="ClassifyCreate"/> produces,
/// preserving the route's authority, operation kind, and collision-batch
/// eligibility. A host with a bounded collision neighborhood (headless)
/// applies this to a remote/projectile Create whose destination landblock
/// that neighborhood will never publish — the parked placement's
/// collision-generation wake could otherwise never fire. The residence
/// then completes celless (FullCell stays 0, the accepted wire frame
/// stays on the canonical snapshot), mirroring the pre-flip direct-host
/// accepted-frame behavior for far remotes; a later fresh Position event
/// owns any subsequent placement.
/// </summary>
internal static RuntimeAuthoritativePositionRoute ToCellessCreateRoute(
in RuntimeAuthoritativePositionRoute route) =>
new(
route.Authority,
RuntimeAuthoritativePositionDisposition.AwaitFreshPosition,
route.OperationKind,
PhysicsSetPositionFlags.None,
0u,
UnparentBeforeRouting: false,
ApplyPlacementFrameBeforeRouting: false,
LeaveWorld: false,
TeleportHookPhase: RuntimeTeleportHookPhase.None,
StopInterpolating: false,
ConstrainPhase: RuntimePositionConstrainPhase.None,
PreserveHeading: false,
ZeroVelocity: false,
SendPositionImmediately: false,
route.CollisionBatchEligible);
internal static RuntimeAuthoritativePositionRoute ClassifyAcceptedPosition(
in RuntimeAcceptedPositionRouteRequest request)
{

View file

@ -1987,9 +1987,13 @@ public sealed class RuntimePhysicsState : IDisposable
{
EnsureNotDisposed();
EnsureCollisionMutationThread();
uint canonical = CanonicalLandblock(landblockId);
if (canonical == 0u)
// C3c-F3: the old `canonical == 0u` check was dead (CanonicalLandblock
// ORs in 0xFFFF, so it never returns 0) — the real absent-id guard is
// on the raw input. Landblock (0,0) canonicalizes to 0x0000FFFF and
// is fully legal here.
if (landblockId == 0u)
throw new ArgumentOutOfRangeException(nameof(landblockId));
uint canonical = CanonicalLandblock(landblockId);
return SetPosition.BeginCollisionPrefixQuiescence(
canonical,
collisionGeneration,
@ -2034,6 +2038,13 @@ public sealed class RuntimePhysicsState : IDisposable
{
EnsureNotDisposed();
EnsureCollisionMutationThread();
// C3c-F3: an absent landblock id (0) canonicalizes to 0x0000FFFF —
// the REAL map-corner landblock — so it must be rejected at the
// admission entrance. The prefix-0 sentinel used to (accidentally,
// and only at commit time) catch this caller bug; with prefix
// 0x00000000 now legal, the explicit guard is the only protection.
if (landblockId == 0u)
throw new ArgumentOutOfRangeException(nameof(landblockId));
uint canonical = CanonicalLandblock(landblockId);
if (_collisionPrefixMutations.ContainsKey(canonical))
{
@ -2622,9 +2633,13 @@ public sealed class RuntimePhysicsState : IDisposable
{
EnsureNotDisposed();
EnsureCollisionMutationThread();
uint canonical = CanonicalLandblock(landblockId);
if (canonical == 0u)
// C3c-F3: absent-id guard on the raw input — the old
// `canonical == 0u` test was dead (CanonicalLandblock never returns
// 0), and the corner landblock (canonical 0x0000FFFF) retires like
// any other.
if (landblockId == 0u)
throw new ArgumentOutOfRangeException(nameof(landblockId));
uint canonical = CanonicalLandblock(landblockId);
if (kind is RuntimeCollisionPrefixMutationKind.Activation)
throw new ArgumentOutOfRangeException(nameof(kind));
@ -2944,6 +2959,27 @@ public sealed class RuntimePhysicsState : IDisposable
: 1UL;
}
/// <summary>
/// True when a collision evaluation may read this cell's landblock right
/// now — no admission is in flight for it and its prefix is not quiescing.
/// <see cref="TrySealCollisionEvaluationAuthority"/> enforces exactly this
/// per queried prefix, so any owner that is about to DEPEND on a
/// successful seal must consult the same predicate first. C3c-F2: the
/// dormant local-player activation rearm did not, so a collision-generation
/// commit that reentered the first-entry pump before its own admission
/// retired rearmed the parked lease out of AwaitingCell, immediately failed
/// this seal, and — no longer being AwaitingCell — was reported as
/// RejectedAuthority (terminal) instead of "still waiting". That dropped
/// the login conductor for the whole session.
/// </summary>
internal bool IsCollisionEvaluationPrefixAdmissible(uint exactCellId)
{
uint landblockId = CanonicalLandblock(exactCellId);
return landblockId != 0u
&& !_collisionAdmissions.ContainsKey(landblockId)
&& !SetPosition.IsCollisionPrefixQuiescing(landblockId);
}
/// <summary>
/// Exact collision-prefix generation authority used by private
/// SetPosition evaluations. Beginning a replacement generation advances
@ -3021,8 +3057,7 @@ public sealed class RuntimePhysicsState : IDisposable
}
foreach (uint prefix in prefixes)
{
if (_collisionAdmissions.ContainsKey(prefix)
|| SetPosition.IsCollisionPrefixQuiescing(prefix))
if (!IsCollisionEvaluationPrefixAdmissible(prefix))
return false;
}

View file

@ -109,8 +109,14 @@ internal readonly record struct RuntimeCollisionPrefixQuiescenceToken(
ulong CollisionGeneration,
ulong OperationId)
{
internal bool IsValid => LandblockPrefix != 0u
&& (LandblockPrefix & 0xFFFFu) == 0u
// C3c-F3: presence is discriminated by OperationId (allocated from a
// monotonic counter starting at 1, so a default token always carries 0)
// and CollisionGeneration (generations also start at 1) — NOT by
// LandblockPrefix != 0. Prefix 0x00000000 is the legitimate prefix of
// landblock (0,0) (id 0x0000FFFF, Dereth's map corner); the old
// prefix-based term made every real corner-landblock token read as
// invalid, wedging TryGetCurrentQuiescence and every release path.
internal bool IsValid => (LandblockPrefix & 0xFFFFu) == 0u
&& CollisionGeneration != 0UL
&& OperationId != 0UL;
}
@ -778,9 +784,14 @@ internal sealed class RuntimeSetPositionState : IDisposable
EnsureNotDisposed();
if (collisionGeneration == 0UL)
throw new ArgumentOutOfRangeException(nameof(collisionGeneration));
uint prefix = landblockId & 0xFFFF0000u;
if (prefix == 0u)
// C3c-F3: reject only the genuinely-absent landblock id (0). Prefix
// 0x00000000 is landblock (0,0) — the map corner — so a prefix == 0
// test can no longer stand in for "no landblock"; that sentinel
// collision crashed every collision publication whose streaming
// window reached the corner (connected-gate 20260802-135444).
if (landblockId == 0u)
throw new ArgumentOutOfRangeException(nameof(landblockId));
uint prefix = landblockId & 0xFFFF0000u;
if (_collisionPrefixQuiescence.TryGetValue(
prefix,
@ -1848,6 +1859,45 @@ internal sealed class RuntimeSetPositionState : IDisposable
&& operation.WakeableLostCell;
}
/// <summary>
/// C3c-F2: the identity check below is against
/// <see cref="RuntimePhysicsState.CollisionGenerationAuthority"/> — the
/// generation the collision world currently HOLDS — not against
/// <c>ExpectedCollisionGeneration</c>, which means two different things
/// at the two ends of this wait. At park time (this class's own
/// <c>TryPrepareDormantLocalActivationCommit</c>) an admission for the
/// destination landblock is in flight, so Expected == that admission's
/// generation G and the lease correctly parks against G. The wake that
/// sets <c>CollisionGenerationReady</c> is
/// <c>CommitCollisionGeneration(lb, G, ready)</c>, and the very next
/// statement in RuntimePhysicsState retires the admission
/// (AdvanceCommittedActivation) while leaving the committed generation at
/// G — from that instant Expected returns G+1, a generation that does not
/// exist and may never be begun. Comparing the parked G against Expected
/// therefore refused every login rearm forever (the connected-gate
/// DeferredCell wedge: controller never published, world never visible).
/// The committed-authority comparison keeps every staleness guarantee: a
/// superseding BeginCollisionAdmission or a CancelCollisionGeneration
/// moves the authority off G and this lease still refuses to rearm.
///
/// <para>
/// The trailing
/// <see cref="RuntimePhysicsState.IsCollisionEvaluationPrefixAdmissible"/>
/// term is the second half of the same C3c-F2 defect and is what the live
/// probe caught: the collision-generation commit reenters the host's
/// first-entry pump BEFORE its own admission is retired
/// (RuntimePhysicsState.cs:2503 commits the generation, :2552-2558 retires
/// the admission). Rearming inside that window moves the lease out of
/// AwaitingCell and the very next evaluation fails
/// <c>TrySealCollisionEvaluationAuthority</c> on the still-registered
/// admission — at which point EvaluateActivation can no longer report
/// DeferredCell (the operation is no longer AwaitingCell) and returns
/// RejectedAuthority, which is TERMINAL for the conductor. Refusing the
/// rearm until the prefix is evaluable keeps the lease parked and
/// retryable, exactly as the remote wake path already does with
/// <c>TryGetBlockingQuiescence</c> (:4069-4095).
/// </para>
/// </summary>
private bool TryRearmDeferredDormantLocalActivation(
RuntimeEntityRecord record,
PhysicsBody body,
@ -1868,8 +1918,10 @@ internal sealed class RuntimeSetPositionState : IDisposable
|| !operation.CollisionGenerationReady
|| operation.ProjectionSequence != 0UL
|| operation.CollisionGeneration != _physics
.ExpectedCollisionGeneration(operation.ExactCellId)
|| !_physics.Engine.IsSpawnCellReady(operation.ExactCellId))
.CollisionGenerationAuthority(operation.ExactCellId)
|| !_physics.Engine.IsSpawnCellReady(operation.ExactCellId)
|| !_physics.IsCollisionEvaluationPrefixAdmissible(
operation.ExactCellId))
{
return false;
}
@ -3366,14 +3418,19 @@ internal sealed class RuntimeSetPositionState : IDisposable
command);
CollisionPrefixQuiescence? quiescence =
_collisionPrefixQuiescence.GetValueOrDefault(prefix);
// C3c-F3: pass the overrides through as genuinely optional —
// `quiescence?.` yields null (absent) with no quiescence and the
// token's exact values (present, prefix 0x00000000 included)
// with one. The old `?? 0u` collapse made a corner-landblock
// quiescence indistinguishable from "no quiescence".
RuntimeSetPositionOutcome parked = ParkDeferred(
operation,
result,
publishImmediately: false,
collisionGenerationOverride:
quiescence?.Token.CollisionGeneration ?? 0UL,
quiescence?.Token.CollisionGeneration,
collisionPrefixOverride:
quiescence?.Token.LandblockPrefix ?? 0u);
quiescence?.Token.LandblockPrefix);
if (_pendingProjection.TryGetValue(
parked.Projection.Sequence,
out RuntimePlacementProjectionSnapshot staged))
@ -3929,12 +3986,22 @@ internal sealed class RuntimeSetPositionState : IDisposable
_operationPool.Clear();
}
/// <summary>
/// C3c-F3: the quiescence-override pair is nullable — null means "no
/// quiescence holds this park", a present value means "parked under that
/// quiescence's exact prefix/generation". Nullable uint is the chosen
/// has-prefix representation for the whole chain because the previous
/// 0-sentinel collided with landblock (0,0)'s legitimate prefix
/// 0x00000000: a corner-landblock quiescence override read as "absent",
/// so <see cref="Operation.CollisionQuiescenceHeld"/> derived false and
/// the parked operation skipped the QuiescenceHeld stage entirely.
/// </summary>
private RuntimeSetPositionOutcome ParkDeferred(
Operation operation,
in PhysicsSetPositionResult result,
bool publishImmediately = true,
ulong collisionGenerationOverride = 0UL,
uint collisionPrefixOverride = 0u)
ulong? collisionGenerationOverride = null,
uint? collisionPrefixOverride = null)
{
PhysicsBody body = operation.Body!;
body.Orientation = result.Orientation;
@ -3969,13 +4036,11 @@ internal sealed class RuntimeSetPositionState : IDisposable
operation.WakeableLostCell = true;
operation.EnteringWorldFromCelllessResidence = true;
ArmLostFamilyDeadlines(operation);
operation.CollisionGeneration = collisionGenerationOverride != 0UL
? collisionGenerationOverride
: _physics.ExpectedCollisionGeneration(result.CellId);
operation.CollisionPrefix = collisionPrefixOverride != 0u
? collisionPrefixOverride
: result.CellId & 0xFFFF0000u;
operation.CollisionQuiescenceHeld = collisionPrefixOverride != 0u;
operation.CollisionGeneration = collisionGenerationOverride
?? _physics.ExpectedCollisionGeneration(result.CellId);
operation.CollisionPrefix = collisionPrefixOverride
?? result.CellId & 0xFFFF0000u;
operation.CollisionQuiescenceHeld = collisionPrefixOverride.HasValue;
operation.Command = operation.Command with
{
Physics = operation.Command.Physics with

View file

@ -0,0 +1,354 @@
using AcDream.Content;
using AcDream.Runtime.Entities;
using AcDream.Runtime.Gameplay;
using AcDream.Runtime.Physics;
namespace AcDream.Runtime.Session;
/// <summary>
/// C3c: the host-driven pump that walks every initial-Create residence
/// through its first-entry conductor. One instance per host session route;
/// graphical and no-window hosts construct it with their own prepared
/// collision source and local-player activation-preparation provider and
/// call <see cref="DriveAll"/> from their own cadence (post-Create
/// hydration and the per-frame placement retry phase for the graphical
/// host; spawn/position projection and the session tick for headless).
///
/// The controller owns NO placement state — it records which entities hold
/// a fresh residence lease (via
/// <see cref="RuntimeEntityObjectLifetime.BindInitialResidenceBeginNotification"/>)
/// and repeatedly calls the conductors, which re-validate all currency
/// themselves. Terminal yields (Completed/RejectedToken/RejectedAuthority)
/// drop the entry; every Awaiting*/Contention yield keeps it for the next
/// pump.
///
/// Continuation placements (the executor's AwaitingContinuationPlacement
/// yield) are completed here through the C0 fused
/// <see cref="RuntimeSetPositionState.TryPrepareAndSubmitAuthoredPlacement"/>
/// — legal for a continuation operation, which never has
/// DormantLocalActivation set — followed by head acknowledgement. The
/// production sink may consume the resulting Place first (the residence is
/// already consumed by then, so the sink's residence gate does not fire);
/// a failed acknowledgement after that is benign — the executor's
/// ResumePendingPlacement keys off the retained acknowledged completion,
/// not off who acknowledged.
/// </summary>
internal sealed class RuntimeFirstEntryDriveController
{
/// <summary>
/// Bounded chase of synchronous progress inside one entity's drive —
/// enough for mover-prep + placement + acknowledgement + a handful of
/// continuation placements in a single pump without risking an unbounded
/// loop against a livelocked yield.
/// </summary>
private const int MaxSynchronousStepsPerEntity = 16;
private sealed class Pending
{
internal required RuntimeEntityRecord Record { get; init; }
internal required RuntimeInitialCreateResidenceToken Token { get; init; }
internal required bool IsLocalPlayer { get; init; }
}
private readonly RuntimeEntityObjectLifetime _entityObjects;
private readonly IGameRuntimeClock _clock;
private readonly IPreparedCollisionSource _collisionSource;
private readonly Func<PlayerMovementConstructionOptions> _localOptions;
private readonly Func<RuntimeEntityRecord,
RuntimeLocalPlayerPhysicsActivationPreparation> _localActivation;
private readonly Dictionary<RuntimeEntityKey, Pending> _pending = [];
private readonly List<RuntimeEntityKey> _driveScratch = [];
private bool _driving;
/// <summary>C3c-R1 review F6: see <see cref="AttachRoute"/>.</summary>
private object? _routeOwner;
internal RuntimeFirstEntryDriveController(
RuntimeEntityObjectLifetime entityObjects,
IGameRuntimeClock clock,
IPreparedCollisionSource collisionSource,
Func<PlayerMovementConstructionOptions> localOptions,
Func<RuntimeEntityRecord,
RuntimeLocalPlayerPhysicsActivationPreparation> localActivation)
{
_entityObjects = entityObjects
?? throw new ArgumentNullException(nameof(entityObjects));
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
_collisionSource = collisionSource
?? throw new ArgumentNullException(nameof(collisionSource));
_localOptions = localOptions
?? throw new ArgumentNullException(nameof(localOptions));
_localActivation = localActivation
?? throw new ArgumentNullException(nameof(localActivation));
_entityObjects.BindInitialResidenceBeginNotification(
NoteResidenceBegan);
// C3c-R1 review F5: tracked-but-undriven entries fold into the
// entity-object ownership snapshot instead of sitting outside every
// ledger.
_entityObjects.RegisterFirstEntryDriveOwnership(() => _pending.Count);
}
internal int PendingCount => _pending.Count;
/// <summary>
/// Records a fresh residence for a later pump. Runs synchronously inside
/// the registration transaction (including the executor's deferred-child
/// replays, which re-enter registration mid-Execute), so it must never
/// call Advance here — only capture the exact key/token/dispatch facts.
/// </summary>
private void NoteResidenceBegan(RuntimeEntityRecord record)
{
if (record.Key is not { } key
|| !_entityObjects.TryGetInitialCreateResidence(
record,
out RuntimeInitialCreateResidenceLease lease))
{
return;
}
_pending[key] = new Pending
{
Record = record,
Token = lease.Token,
// Dispatch is decided ONCE from the lease's classified route —
// TryGetCurrent fails mid-drain (the residence moves to its
// completed table at Complete), so the lease cannot be
// re-fetched on a later pump.
IsLocalPlayer = lease.Route.OperationKind
is RuntimeSetPositionOperationKind.InitialLogin,
};
}
/// <summary>
/// Drives every tracked first-entry sequence one bounded step. Safe to
/// call from any host cadence point; re-entrant calls (a conductor's own
/// synchronous callbacks reaching a host pump) fail closed into the next
/// outer pump instead of interleaving.
/// </summary>
internal void DriveAll()
{
if (_driving || _pending.Count == 0)
return;
_driving = true;
try
{
_driveScratch.Clear();
foreach (RuntimeEntityKey key in _pending.Keys)
_driveScratch.Add(key);
foreach (RuntimeEntityKey key in _driveScratch)
{
if (_pending.TryGetValue(key, out Pending? pending))
DriveOne(key, pending);
}
}
finally
{
_driving = false;
}
}
/// <summary>
/// C3c-R1 review F6: the explicit one-route-at-a-time latch. A drive
/// controller outlives its session routes (hosts reuse it across
/// reconnects), and route teardown clears the tracked entries — so the
/// "session reset precedes a new route" ordering the hosts rely on is
/// asserted here instead of silently assumed: a second route attaching
/// before the prior route detached would otherwise let the OLD route's
/// dispose wipe the NEW route's tracked entries.
/// </summary>
internal void AttachRoute(object route)
{
ArgumentNullException.ThrowIfNull(route);
if (_routeOwner is not null && !ReferenceEquals(_routeOwner, route))
{
throw new InvalidOperationException(
"A first-entry drive controller serves one session route at "
+ "a time; the prior route must be disposed (session reset "
+ "precedes a new route) before a replacement attaches.");
}
_routeOwner = route;
}
/// <summary>
/// Route-scoped teardown: clears every tracked entry, but ONLY when
/// <paramref name="route"/> is the attached owner — a route that never
/// attached (construction rollback) or was displaced must not clear the
/// live route's entries. The conductors and residence own their own
/// convergence independently (retirement fan-out + session clear).
/// </summary>
internal void DetachRoute(object route)
{
ArgumentNullException.ThrowIfNull(route);
if (!ReferenceEquals(_routeOwner, route))
return;
_routeOwner = null;
_pending.Clear();
}
private void DriveOne(RuntimeEntityKey key, Pending pending)
{
for (int step = 0; step < MaxSynchronousStepsPerEntity; step++)
{
if (pending.Record.Key != key)
{
// Post-teardown key release; the retirement fan-out already
// reaped the conductors' own progress.
_pending.Remove(key);
return;
}
bool terminal;
bool awaitingContinuationPlacement;
if (pending.IsLocalPlayer)
{
RuntimeLocalPlayerFirstEntryStatus status =
_entityObjects.LocalPlayerFirstEntry.Advance(
pending.Record,
pending.Token,
_localOptions(),
_localActivation(pending.Record),
_collisionSource,
_clock.SimulationTimeSeconds,
inputs: default,
out _);
terminal = status
is RuntimeLocalPlayerFirstEntryStatus.Completed
or RuntimeLocalPlayerFirstEntryStatus.RejectedToken
or RuntimeLocalPlayerFirstEntryStatus.RejectedAuthority;
awaitingContinuationPlacement = status
is RuntimeLocalPlayerFirstEntryStatus
.AwaitingContinuationPlacement;
}
else
{
RuntimeRemoteFirstEntryStatus status =
_entityObjects.RemoteFirstEntry.Advance(
pending.Record,
pending.Token,
_collisionSource,
_clock.SimulationTimeSeconds,
inputs: default,
out _,
out _);
terminal = status
is RuntimeRemoteFirstEntryStatus.Completed
or RuntimeRemoteFirstEntryStatus.RejectedToken
or RuntimeRemoteFirstEntryStatus.RejectedAuthority;
awaitingContinuationPlacement = status
is RuntimeRemoteFirstEntryStatus
.AwaitingContinuationPlacement;
}
if (terminal)
{
_pending.Remove(key);
return;
}
if (!awaitingContinuationPlacement)
{
// AwaitingCollisionSource / AwaitingActivation /
// AwaitingPlacement / AwaitingReceiptAcknowledgement /
// Contention — nothing more this pump can do synchronously.
return;
}
if (!TryCompleteContinuationPlacement(key, pending.Record))
return;
// A continuation placement progressed — re-Advance so the
// executor can consume the acknowledged completion and keep
// draining.
}
}
/// <summary>
/// Completes (or makes bounded progress on) the executor's pending
/// continuation placement for <paramref name="key"/>. Returns true when
/// enough progress happened that re-calling Advance can observe it.
/// </summary>
private bool TryCompleteContinuationPlacement(
RuntimeEntityKey key,
RuntimeEntityRecord record)
{
RuntimeSetPositionState setPosition =
_entityObjects.Physics.SetPosition;
// A receipt of OURS already at the FIFO head (a Place from a prior
// submit attempt, or the Withdraw of a deferred park) is consumed
// first — acknowledgement is what re-arms a parked operation and what
// ResumePendingPlacement's retained-completion check requires.
bool acknowledgedSomething = false;
while (setPosition.TryPeekProjection(
out RuntimePlacementProjectionSnapshot head)
&& head.Token.Entity == key
&& head.Kind is RuntimePlacementProjectionKind.Place
or RuntimePlacementProjectionKind.Withdraw)
{
if (!setPosition.AcknowledgeProjection(head.Token))
break;
acknowledgedSomething = true;
}
if (!_entityObjects.InitialCreateExecution
.TryGetPendingContinuationPlacement(
key,
out RuntimeEntityPlacementToken placement))
{
// Flavor 2 (transient operation-slot contention): no token was
// ever begun; the only correct action is a later Execute retry.
return acknowledgedSomething;
}
if (!_entityObjects.InitialCreateExecution
.TryGetPendingContinuationRoute(
key,
out RuntimeAuthoritativePositionRoute route))
{
return acknowledgedSomething;
}
RuntimeSetPositionMoverPreparationStatus status =
setPosition.TryPrepareAndSubmitAuthoredPlacement(
record,
placement,
route.OperationKind,
route.SetPositionFlags,
_collisionSource,
_clock.SimulationTimeSeconds,
out RuntimeSetPositionOutcome outcome);
if (status != RuntimeSetPositionMoverPreparationStatus.Prepared)
{
// RetrySetupUnavailable retries on a later pump; a rejected
// preparation for an already-submitted-and-awaiting operation is
// driven purely by the head acknowledgements above.
return acknowledgedSomething;
}
switch (outcome.Status)
{
case RuntimeSetPositionStatus.CommittedHostAcknowledgementPending:
// The synchronous publish may already have let the production
// sink apply-and-acknowledge this exact receipt (the
// residence is consumed by drain time, so the sink's
// residence gate no longer declines it). A false return here
// is therefore benign; the retained acknowledged completion
// is what the executor consumes either way.
_ = setPosition.AcknowledgeProjection(outcome.Projection);
return true;
case RuntimeSetPositionStatus.DeferredCell:
// Parked with a published Withdraw; consume it if it is
// already the head so the collision-generation wake can
// resubmit.
while (setPosition.TryPeekProjection(
out RuntimePlacementProjectionSnapshot parked)
&& parked.Token.Entity == key
&& parked.Kind is RuntimePlacementProjectionKind.Withdraw)
{
if (!setPosition.AcknowledgeProjection(parked.Token))
break;
acknowledgedSomething = true;
}
return acknowledgedSomething;
default:
// Rejected/Cancelled — authority moved; the next Advance
// observes it and abandons through the conductor's own path.
return true;
}
}
}

View file

@ -72,8 +72,28 @@ public sealed class RuntimeLiveEntitySessionController
private void OnSpawned(WorldSession.EntitySpawn spawn)
{
RuntimeEntityRegistrationResult registration =
Entities.RegisterEntity(spawn);
// C3c route-8 flip: every direct-host Create enters the SAME initial
// residence lease graphical route 1 uses; the conductor drive (via
// IRuntimeDirectWorldProjection.ProjectSpawn and the host's pump)
// owns mover preparation, body/controller construction, placement,
// and the FIFO drain from here.
//
// C3c-R1 review R3: a CONTENT-LESS host (a validated-legal headless
// configuration — HeadlessConfigurationLoader.ValidateContent
// accepts a null process.content) constructs no world projection
// and therefore no first-entry drive; opening a residence with no
// drive to pump it would park every Create (and every position/
// state packet queued behind its pending residence) forever. That
// configuration keeps the exact pre-flip legacy registration:
// presentation-free RegisterEntity plus the direct accepted-frame
// commit below. C4/C5 revisit: unify once the direct-host conductor
// drive no longer requires prepared content.
RuntimeEntityRegistrationResult registration = _worldProjection is null
? Entities.RegisterEntity(spawn)
: Entities.RegisterEntityWithInitialResidence(
spawn,
isLocalPlayer: spawn.Guid
== _runtime.PlayerIdentity.ServerGuid);
if (registration.Canonical is not { } canonical)
return;