VirtualController: Architecture and Cycle
Use this skill as an architectural playbook for VirtualController :)
Keep your focus on fresh code and check its relevance through git log/blame (cutoff: 2024-02-20).
What to download first
references/fresh-pattern-catalog.md- patterns with an obvious freshness status (Use/Limited) ✅references/rejected-snippets.md- zones that cannot be taken as a standard ⚠️references/docs-context.md- how to use docs safely
Source of truth
- The codebase is the primary source of truth.
- Documentation - secondary layer (terms, intent, diagnostics).
- Any site older than two years or with a TODO/problematic comment on the topic should not be included in the reference rules.
VirtualController mental model
VirtualControllerisEntitySystemwhich subscribes toPhysicsUpdateBeforeSolveEventandPhysicsUpdateAfterSolveEvent.- The order of calling the controller is specified via
UpdatesBefore/UpdatesAfter. - Hooks
UpdateBeforeSolveandUpdateAfterSolveare called on each physics substep. - The
predictionparameter tells whether predict simulation is running on the client. frameTime— time of one substep, not the entire tick.- The performance of controllers is monitored separately through built-in histograms (
BeforeMonitor/AfterMonitor).
Layer scheme
- Engine layer:
VirtualController, SharedPhysicsSystem, before/after solve events, solver/contact pipeline, special-casing KinematicController.
- Shared layer:
SharedMoverController, TileFrictionController, SharedConveyorController, ClimbSystem.
- Server layer:
PullController, RandomWalkController, ChasingWalkSystem, ChaoticJumpSystem, MoverController, ConveyorController.
- Client layer:
MoverController, ConveyorController-stub for prediction/network presence, prediction hooks via UpdateIsPredictedEvent.
Patterns
- Add
UpdatesBefore/UpdatesAfterbeforebase.Initialize()- otherwise the order hook will be fixed incorrectly. - In
UpdateBeforeSolvedo earlycontinuebyprediction/body.Predictso as not to break the predict. - Use
AwakeBodiesas the main set for per-step physical logic. - For
KinematicController, use manual damping via helper movement methods and thenSetLinearVelocity/SetAngularVelocity. - For heavy calculations inside the controller, separate the calculation phase (parallel job) from the phase of applying the results (main thread).
- For relay management, use the
SetRelay/RemoveRelayAPI methods, rather than manually adding/removing components. - For container-eject scenarios, where the entity must immediately appear “outside”, use
ForciblySetClimbingas a safe post-eject transition. - Keep
UpdateBeforeSolvedeterministic: minimum hidden state, minimum nondeterministic sources. - To control regressions, check the physics monitors of the controllers before/after the change.
- For movement systems, maintain an invariant: mob movement and tile friction must occur in a consistent order.
Anti-patterns
- Configure
UpdatesBefore/UpdatesAfterafterbase.Initialize(). - Copy TODO-heavy sections as an architectural standard.
- Write a controller that depends on “one call per tick” and ignores substeps.
- Perform expensive lookup/alloc operations without cache-query in a hot physics loop.
- Bypass the relay API using direct
RemComp/EnsureCompin the gameplay code. - Consider the empty client
ConveyorController“superfluous” and remove it from the predictor scheme. - Try to use old pre-cutoff fragments as a basis for new solutions.
- Treat mispredict with “magic guards” instead of correcting the source of desync.
- Interfere with transform movement and physical impulses without a clear cause-and-effect model.
- Ignore warning comments about fragile logic (
slop,hack,temporary).
Low-level Box2D/Physics Internals
- The simulation goes through
SimulateWorld: each substep raises before/after events, then broadphase/contact/solve. - Controllers are executed before the solver (
UpdateBeforeSolve) and after the solver (UpdateAfterSolve) on each substep. AwakeBodies- a key runtime set of bodies participating in the active simulation and controllers.- Generation and recalculation of contacts are based on broadphase overlap + narrowphase manifold update.
- For
KinematicControllerthere are separate branches in solver/contact logic, so it cannot be treated as a regularDynamic. - Any logic that changes speeds/pulses in controllers must take into account prediction and body mode.
Code examples
1) Subscribe VirtualController to before/after solve
public override void Initialize()
{
base.Initialize();
var updatesBefore = UpdatesBefore.ToArray();
var updatesAfter = UpdatesAfter.ToArray();
// The controller receives both physics hooks in one order graph.
SubscribeLocalEvent<PhysicsUpdateBeforeSolveEvent>(OnBeforeSolve, updatesBefore, updatesAfter);
SubscribeLocalEvent<PhysicsUpdateAfterSolveEvent>(OnAfterSolve, updatesBefore, updatesAfter);
}
2) Physics substeps with calling controllers
for (int i = 0; i < _substeps; i++)
{
var before = new PhysicsUpdateBeforeSolveEvent(prediction, frameTime);
RaiseLocalEvent(ref before);
_broadphase.FindNewContacts();
CollideContacts();
Step(frameTime, prediction);
var after = new PhysicsUpdateAfterSolveEvent(prediction, frameTime);
RaiseLocalEvent(ref after);
}
3) Explicit order between mover/friction/conveyor
public override void Initialize()
{
UpdatesBefore.Add(typeof(TileFrictionController));
base.Initialize();
}
public override void Initialize()
{
UpdatesAfter.Add(typeof(SharedMoverController));
base.Initialize();
}
4) Manual damping for KinematicController
if (body.BodyType == BodyType.KinematicController)
{
var velocity = body.LinearVelocity;
var angVelocity = body.AngularVelocity;
// For this type of body, the friction/solver path is different, so we dampen it manually.
_mover.Friction(0f, frameTime, friction, ref velocity);
_mover.Friction(0f, frameTime, friction, ref angVelocity);
PhysicsSystem.SetLinearVelocity(uid, velocity, body: body);
PhysicsSystem.SetAngularVelocity(uid, angVelocity, body: body);
}
5) Pull controller with reverse pulse in special mode
var impulse = accel * physics.Mass * frameTime;
PhysicsSystem.ApplyLinearImpulse(pullableEnt, impulse, body: physics);
// In weightless/blocked scenarios we add a pair impulse so as not to lose physical balance.
if (_gravity.IsWeightless(puller) && pullerXform.Comp.GridUid == null || !_actionBlockerSystem.CanMove(puller))
{
PhysicsSystem.WakeBody(puller);
PhysicsSystem.ApplyLinearImpulse(puller, -impulse);
}
6) Chasing controller forcibly keeps the body “in the air”
var delta = targetPos - selfPos;
var speed = delta.Length() > 0 ? delta.Normalized() * component.Speed : Vector2.Zero;
_physics.SetLinearVelocity(uid, speed);
// Special mode for entity behavior (for example, tesla-like objects).
_physics.SetBodyStatus(uid, physics, BodyStatus.InAir);
7) Chaotic jump with raycast-safe offset
var ray = new CollisionRay(startPos, direction.ToVec(), component.CollisionMask);
var hit = _physics.IntersectRay(mapId, ray, range, uid, returnOnFirstHit: false).FirstOrNull();
if (hit != null)
{
// Shift away from the collision point to avoid teleporting directly into the collision.
targetPos = hit.Value.HitPos - new Vector2((float)Math.Cos(direction), (float)Math.Sin(direction));
}
_transform.SetWorldPosition(uid, targetPos);
Extension rule
- Design new controllers as deterministic substep passes with explicit prediction-gating.
- Fix the order of controllers in
Initialize()tobase.Initialize(). - First check any borrowed fragment with
rejected-snippets. - Confirm any performance change by profiling controller histograms.
Think of VirtualController as a physics orchestration layer, not as “another Update()” 😅