Run body and fire phases during scripted control locks

This commit is contained in:
UnixNight committed 2026-10-26 12:21:25 -04:00
1 parent 5876da112c
commit c285b57091
35 files changed
+1503 -45

No files matched your search

+99
View File
@@ -139,6 +139,96 @@ Check(carlBytes.AsSpan(0x3159e, 15).SequenceEqual(Convert.FromHexString("8B0D489
"Source MCA clears game controlled pointer before playback");
Console.WriteLine("PASS end-of-lab Carl cutscene input lock and natural/skip control restoration");
foreach (var kind in new[] { "3CAM", "3MCA", "3AIT" })
{
var jim = Entity("3JIM", "JIM1", ("RotationX", 12f), ("RotationZ", 22f));
var command = Entity(kind, "command", ("PlayerControlled", "NULL"),
("CameraTarget", "JIM1"), ("CameraTarget0", "JIM1"), ("CameraTarget1", "JIM1"),
("SoundIndex", 1), ("SoundIndex0", 1), ("SoundIndex1", 1), ("SoundDatabase", "voice"),
("NextTrigger", "default"));
var scene = new SceneDirector(new("LV1B", [jim, command]), new TaskStates([]), (_, _) => .1);
var body = ControlBody();
var bag = new SceneInventory(new int[19]); bag.SetState(0, 3, 1); bag.SelectGadget(3);
using var binding = new PlayerSceneBinding(scene, body, bag, "JIM1");
for (var tick = 0; tick < 5; tick++) binding.Step(new(true, false, false, false, false));
var callbacks = new List<ScriptPreparation>();
scene.ActorPreparing += (actor, action) =>
{
Check(actor.Tag == "JIM1" && scene.AuthoredControlledTag == "JIM1", "Preparation observes the prior raw owner");
callbacks.Add(action);
};
var stopObserved = false;
scene.ActorChanged += actor =>
{
if (actor.Tag == "JIM1" && actor.Animation == "STOP")
{
Check(body.Velocity == Vector3.Zero && body.Speed == 0, "Body preparation precedes derived STOP notification");
stopObserved = true;
}
};
scene.Trigger("command");
var expected = kind switch
{
"3CAM" => new[] { ScriptPreparation.ReleaseGadget, ScriptPreparation.StopMotion, ScriptPreparation.FlattenOrientation },
"3MCA" => new[] { ScriptPreparation.StopMotion, ScriptPreparation.FlattenOrientation, ScriptPreparation.ReleaseGadget },
_ => new[] { ScriptPreparation.StopMotion }
};
Check(stopObserved && callbacks.SequenceEqual(expected) && body.Speed == 0 && body.Velocity == Vector3.Zero,
"CAM/MCA/AI retain their own ordered preparation boundaries");
Check(bag.SelectedGadget == (kind == "3AIT" ? 3 : -1), "AI control loss does not imply camera gadget cleanup");
Check(scene.FindActor("JIM1")!.Rotation.X == (kind == "3AIT" ? 12 : 0), "Only camera preparation flattens pitch/roll");
if (kind == "3AIT") continue; // Its DEFAULT next trigger has already restored control.
var controllers = body.ControllerSteps;
binding.Step(new(true, false, true, false, true));
Check(body.ControllerSteps == controllers && body.Jumps == 0 && body.PhysicsSteps > controllers,
"Input lock leaves body/effect callbacks running");
scene.DebugForceControl = true;
binding.Step(new(true, false, false, false, false));
var speed = body.Speed;
scene.Step(.11f);
Check(callbacks.SequenceEqual(expected), "Later MCA shots/CAM completion do not replay initial preparations");
Check(body.Speed == speed && scene.Controlled, "Force control does not become the raw preparation owner");
scene.DebugForceControl = false;
scene.Trigger("default");
var jumps = body.Jumps;
binding.Step(new(false, false, false, false, true));
Check(body.Jumps == jumps + 1, "DEFAULT restores held jump without an invented fresh-key boundary");
}
Console.WriteLine("PASS ordered CAM/MCA/AI preparations, body continuation, raw-owner force override and held-input restoration");
{
var jim = Entity("3JIM", "JIM1");
var command = Entity("3AIT", "move", ("PlayerControlled", "NULL"), ("AITarget", "JIM1"),
("AINewPos", "marker"), ("AINewRotY", 75f));
var marker = Entity("DUMY", "marker", ("PositionX", 200f), ("PositionY", 500f), ("PositionZ", 300f));
var scene = new SceneDirector(new("LV1B", [jim, command, marker]), new TaskStates([]), (_, _) => 1);
var body = ControlBody();
using var binding = new PlayerSceneBinding(scene, body, new SceneInventory(new int[19]), "JIM1");
scene.Trigger("move");
Near(body.ActorRoot, marker.Position, "Authored AI position is applied to the actual player body");
Check(body.Yaw == 75 && !scene.Controlled, "Authored AI yaw follows the logical setter during control loss");
binding.Step(new(true, false, true, false, true));
Check(body.ActorRoot.Y < marker.Position.Y && body.ActorRoot.X == marker.Position.X && body.ControllerSteps == 0,
"Body settles at the scripted location without accepting movement input");
Near(scene.FindActor("JIM1")!.Position, body.ActorRoot, "Physics publishes the new logical player root");
}
Console.WriteLine("PASS authored player teleport/yaw survives uncontrolled body synchronization");
{
var jim = Entity("3JIM", "JIM1");
var empty = Entity("3MCA", "empty", ("CameraTarget0", "none"), ("PlayerControlled", "NULL"), ("NextTrigger", "default"));
var missing = Entity("3CAM", "missing", ("CameraTarget", "absent"), ("SoundIndex", 1), ("PlayerControlled", "NULL"));
var scene = new SceneDirector(new("LV1B", [jim, empty, missing]), new TaskStates([]), (_, _) => 1);
var callbacks = new List<ScriptPreparation>(); scene.ActorPreparing += (_, action) => callbacks.Add(action);
scene.Trigger("empty");
Check(callbacks.Count == 0 && scene.AuthoredControlledTag == "JIM1" && !scene.Playing,
"Initial MCA none target returns without preparation or invoking completion ownership");
scene.Trigger("missing");
Check(callbacks.Count == 3 && scene.AuthoredControlledTag == null && scene.Blocked,
"CAM preparation precedes target-lookup failure");
}
Console.WriteLine("PASS first-MCA none return and CAM failure preparation boundaries");
foreach(var type in new[]{0,1,2,3,4})
{
var camera=Entity("3MCA","camera",("CameraTarget0","actor"),("SoundDatabase","voice"),("SoundIndex0",1),("CameraType0",type),("LookatVOffset0",100f),("NextTrigger","default"));
@@ -268,6 +358,15 @@ var returnGate=vr.Entities.First(e=>e.Kind=="LOAD");interactions.Update(returnGa
Check(transitions==1 && returned!.Returning && returned.LevelFile==save.ReturnLevel && returned.StartPoint==save.ReturnStart,"RETURN uses stored destination, restore flag and contact-enter gating");
Console.WriteLine("PASS original VR01 star/trophy score, strict contact entry, acquired-state save/reload and RETURN request");
static LabSimulation ControlBody()
{
var points = new[] { new Vector3(-10000, 0, -10000), new Vector3(-10000, 0, 10000),
new Vector3(10000, 0, 10000), new Vector3(10000, 0, -10000) };
var floor = new Mesh(points.Select(p => new MeshVertex(p, Vector2.Zero, Vector3.One)).ToArray(), [0, 1, 2, 0, 2, 3]);
var standing = new Mesh([new(new(-20, -20, -20), Vector2.Zero, Vector3.One), new(new(20, 80, 20), Vector2.Zero, Vector3.One)], []);
return new(new SceneCollision(floor), standing, new(0, 25, 0), 0);
}
static GamEntity Entity(string kind,string tag,params (string Name,object Value)[] values)
{
var properties=new Dictionary<string,GamProperty>();
+13 -6
View File
@@ -41,6 +41,7 @@ interactions.PracticeRequested += practice.Show;
var prompts = 0;
LevelTransition? destination = null;
interactions.Transition += request => destination ??= request;
using var playerBinding = new PlayerSceneBinding(director, simulation, interactions.Inventory, level.Player!.Tag!);
director.Begin(start);
interactions.Reset(); mechanisms.Reset(); director.Skip();
@@ -70,12 +71,18 @@ for (var leg = 0; leg < route.Length && destination == null; leg++)
if (difference.Length() < 90) { arrived = true; break; }
var desiredYaw = MathF.Atan2(-difference.X, difference.Y) * 180 / MathF.PI;
var error = MathF.IEEERemainder(desiredYaw - simulation.Yaw, 360);
if (director.Controlled)
var previous = simulation.ActorRoot;
// This is a modern input driver, not original navigation. Brake before
//large heading changes; coasting turns can miss the narrow exit opening
//when the recovered cutscene preparation changes the arrival speed.
var brake = MathF.Abs(error) > 15 && simulation.Speed > 0;
var input = brake ? new PlayerInput(false, true, false, false, false)
: new PlayerInput(MathF.Abs(error) < 10, false, error > 1, error < -1, false);
var acceptsInput = playerBinding.Step(input);
Require(Vector3.Distance(previous, simulation.ActorRoot) < 100, "Player warped during input replay");
interactions.UpdateEnergy(simulation.Energy);
if (acceptsInput)
{
var previous = simulation.ActorRoot;
simulation.Step(new(MathF.Abs(error) < 30, false, error > 1, error < -1, false));
Require(Vector3.Distance(previous, simulation.ActorRoot) < 100, "Player warped during input replay");
director.SyncActor(level.Player!.Tag!, simulation.ActorRoot, new(0, simulation.Yaw, 0));
director.Touch(level.Player!.Tag!, simulation.ActorRoot);
interactions.Update(simulation.ActorRoot, simulation.InteractionRadius);
if (practice.Active) continue; // Same modal activation boundary as Program.
@@ -86,7 +93,7 @@ for (var leg = 0; leg < route.Length && destination == null; leg++)
director.Step(FixedStepClock.Step);
if (destination != null) break;
}
Require(arrived || destination != null, $"Input route blocked at leg{leg}: {simulation.ActorRoot}");
Require(arrived || destination != null, $"Input route blocked at leg{leg}: {simulation.Report}; yaw={simulation.Yaw}, control={director.AuthoredControlledTag}, shot={director.CurrentTag}, blocked={director.Blocked}, goal={route[leg]}");
Require(tasks.Get("SCENE") == sceneStates[leg], $"Wrong task state after walking leg{leg}");
Console.WriteLine($"PASS walked leg{leg}: SCENE={tasks.Get("SCENE")}, root={simulation.ActorRoot}");
}
+56
View File
@@ -10,6 +10,8 @@ var tests = new (string Name, Action Check)[]
("clock remainder, stall bound, reset and invalid intervals", ClockBoundaries),
("physics consumes prior motion; fresh versus retained input order", FrameOrdering),
("ordinary route load retains scalars independently of body/jump reset", RetainedLevelState),
("script preparation preserves queued work and uncontrolled physics consumes it", UncontrolledPhysics),
("uncontrolled fire ticks while movement and grounded-release reset are gated", UncontrolledFire),
("source camera query origin, hit adjustment, gain and one query per input", CameraQueryConsumer),
("debug noclip bypasses walls/gravity/camera and exits without queued motion", Noclip),
("turn-only speed, forward acceleration/cap and release", SpeedLimits),
@@ -103,6 +105,60 @@ static void FrameOrdering()
Check(jump.MovementMode == 0, "reset restores stored walking input mode");
}
static void UncontrolledPhysics()
{
var cameraQueries = 0;
var simulation = FlatSimulation(cameraRay: (_, _) => { cameraQueries++; return null; });
simulation.Step(new(true, false, false, false, true));
var pending = simulation.PendingImpulse;
var mode = simulation.MovementMode; var jump = simulation.JumpState;
var hold = simulation.JumpHoldSeconds; var fire = simulation.JetpackRemaining;
var before = simulation.Position;
simulation.PrepareForScript();
Check(simulation.Speed == 0 && simulation.Velocity == Vector3.Zero && simulation.PendingImpulse == pending,
"43A750 zeros speed/velocity while queued impulse survives");
Check(simulation.MovementMode == mode && simulation.JumpState == jump && simulation.JumpHoldSeconds == hold
&& simulation.JetpackRemaining == fire, "Preparation does not invent a mode/jump/hold/fire reset");
var queries = cameraQueries;
for (var tick = 0; tick < 8; tick++) simulation.Step(new(true, false, true, false, true), controlled: false);
Check(simulation.Position.Y > before.Y && simulation.PendingImpulse == Vector3.Zero,
"Uncontrolled body consumes the queued impulse once and keeps integrating");
Check(simulation.Jumps == 1 && simulation.ControllerSteps == 1 && simulation.Speed == 0 && simulation.TurnRate == 0
&& simulation.JumpState == jump && simulation.MovementMode == mode && simulation.JumpHoldSeconds == hold,
"Held movement/turn/jump cannot enter the uncontrolled controller");
Check(simulation.PhysicsSteps == 9 && simulation.EffectSteps == 9 && simulation.Steps == 9,
"Body and fire callbacks remain distinct from controlled movement count");
Check(cameraQueries == queries, "Uncontrolled input does not advance the follow-camera query");
simulation.ApplyAuthoredTransform(simulation.ActorRoot + new Vector3(25, 0, 30), 85);
Check(simulation.Velocity.Y > 0 && simulation.Jumps == 1,
"Authored transform write is separate from body preparation");
}
static void UncontrolledFire()
{
foreach (var code in new[] { "LV1B", "VR04" })
{
var simulation = FlatSimulation(); simulation.LevelCode = code;
simulation.ApplyRetainedLevelState(new("LV1B", 3, 1, .625f, 6.125f));
simulation.RestoreReturnRoot(simulation.ActorRoot + Vector3.UnitY * 500);
var energy = simulation.Energy;
simulation.PrepareForScript();
simulation.Step(new(true, false, true, false, true), controlled: false);
Near(simulation.JetpackRemaining, 6.125f - FixedStepClock.Step, .00001f, "Owned fire time continues during control lock");
Near(simulation.Energy, code == "VR04" ? energy : energy - FixedStepClock.Step * .5f, .00001f,
"Fire drain and tutorial immunity do not depend on raw control");
Check(simulation.ControllerSteps == 0 && simulation.JumpState == 0 && simulation.MovementMode == 1
&& simulation.JumpHoldSeconds == .625f && simulation.JetpackEffectVisible, "Controller scalars untouched while fire remains visible");
}
var grounded = FlatSimulation();
grounded.ApplyRetainedLevelState(new("LV1B", 3, 1, .625f, 6.125f));
grounded.Step(default, controlled: false);
Check(grounded.Grounded && grounded.MovementMode == 1 && grounded.JetpackRemaining < 0
&& grounded.Energy == 20, "Grounded fire clears independently of the gated grounded-release controller");
grounded.Step(default);
Check(grounded.MovementMode == 0 && grounded.ControllerSteps == 1, "Normal grounded-release reset resumes with control");
}
static void RetainedLevelState()
{
var state = new PlayerLevelState("LV1B", 3, 1, .625f, 6.125f);
+36
View File
@@ -0,0 +1,36 @@
from dataclasses import replace
from pathlib import Path
import sys
import unittest
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tools/binary'))
from cutscene_preparation import collect, preparation_events, JetpackPreparationState, project_jetpack_preparation
class CutscenePreparationTests(unittest.TestCase):
def test_source_bytes_and_virtual_targets(self):
self.assertEqual(collect(ROOT.parent / 'Original')['sha256'],
'f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8')
def test_distinct_preparation_order_and_later_shot_boundary(self):
self.assertEqual(preparation_events('cam_null', 'JIM1'),
['JIM1:438', 'JIM1:410', 'JIM1:flatten_euler', 'control:NULL'])
self.assertEqual(preparation_events('mca_activation', 'JIM1'),
['JIM1:410', 'JIM1:flatten_euler', 'JIM1:438', 'control:NULL'])
self.assertEqual(preparation_events('ai_null', 'JIM1'), ['JIM1:410', 'control:NULL'])
self.assertEqual(preparation_events('mca_next_shot', 'JIM1'), [])
self.assertEqual(preparation_events('default_restore', 'JIM1'), [])
self.assertEqual(preparation_events('mca_activation', None), [])
def test_bounded_jetpack_state_does_not_become_blanket_reset(self):
before = JetpackPreparationState()
self.assertEqual(project_jetpack_preparation(before, 'cam_null'),
replace(before, speed=0, velocity=(0, 0, 0), selected_gadget=-1, euler=(0, 150, 0)))
self.assertEqual(project_jetpack_preparation(before, 'ai_null'), replace(before, speed=0, velocity=(0, 0, 0)))
with self.assertRaises(ValueError):
project_jetpack_preparation(replace(before, selected_gadget=0), 'cam_null')
if __name__ == '__main__':
unittest.main()
+25
View File
@@ -0,0 +1,25 @@
from pathlib import Path
import sys
import unittest
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tools/binary'))
from uncontrolled_physics import collect, eligible
class UncontrolledPhysicsTests(unittest.TestCase):
def test_source_field_and_virtual_gate_provenance(self):
self.assertEqual(len(collect(ROOT.parent / 'Original')['tables']), 6)
def test_raw_control_does_not_replace_frame_and_body_flags(self):
for control in (None, 0x1000, 0x2000):
self.assertTrue(eligible(raw_control=control))
for gate in ('frame_valid', 'supervisor', 'bodies_enabled', 'registered', 'body_integration'):
self.assertFalse(eligible(raw_control=control, **{gate: False}), gate)
self.assertFalse(eligible(raw_control=control, editor=True))
self.assertFalse(eligible(raw_control=control, flag5099ab=True))
self.assertTrue(eligible(raw_control=control, flag5099ab=True, override4f641c=True))
if __name__ == '__main__':
unittest.main()
+53
View File
@@ -0,0 +1,53 @@
"""Original ownership-gate evidence and independent controller/effect boundaries."""
from pathlib import Path
import sys
import unittest
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tools/binary'))
from uncontrolled_player import collect, controller_phases, fire_projection
class UncontrolledPlayerTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.report = collect(ROOT.parent / 'Original')
def test_source_instruction_virtual_and_whole_body_provenance(self):
self.assertEqual(len(self.report['sites']), 47)
bodies = {x['name']: x for x in self.report['bodies']}
self.assertFalse(bodies['complete_fire_callback']['raw_control_reference'])
self.assertTrue(bodies['complete_movement_callback']['raw_control_reference'])
def test_null_and_other_control_skip_only_gated_controller_tail(self):
for raw in (None, 0, 0x2000):
phases = controller_phases(raw)
self.assertIn('base40E050', phases)
self.assertIn('conditional_timer7A8', phases)
self.assertNotIn('controller_modes', phases)
self.assertNotIn('jump_ground_air', phases)
self.assertIn('jump_ground_air', controller_phases(0x1000))
self.assertNotIn('controller_modes', controller_phases(0x1000, status83e0=True))
self.assertNotIn('controller_modes', controller_phases(0x1000, modal8181=True))
self.assertEqual(controller_phases(0x1000, game_enabled=False), ['game_gate'])
def test_fire_timer_is_not_controller_or_cutscene_ownership_state(self):
# The exact same owned-fire tick can follow any controller ownership
# projection: raw control is not an input to the original fire callback.
for raw in (None, 0x1000, 0x2000):
controller_phases(raw)
self.assertEqual(fire_projection(2, .25, 20, 0x4C563142), (1.75, 19.875, True, True))
self.assertEqual(fire_projection(.25, .25, 20, 0x4C563142), (0, 20, False, True))
self.assertEqual(fire_projection(2, .25, 20, 0x4C563142, grounded=True), (-.25, 20, False, True))
self.assertEqual(fire_projection(-1, .25, 20, 0x4C563142), (-1.25, 20, False, True))
def test_fire_gate_owner_and_tutorial_energy_are_independent_boundaries(self):
self.assertEqual(fire_projection(2, .25, 20, 0x4C563142, owner=False), (2, 20, False, False))
self.assertEqual(fire_projection(2, .25, 20, 0x4C563142, game_enabled=False), (2, 20, False, False))
for code in range(0x56523031, 0x56523039):
self.assertEqual(fire_projection(2, .25, 20, code), (1.75, 20, True, True))
self.assertEqual(fire_projection(2, .25, .01, 0x4C563142), (1.75, 0, True, True))
if __name__ == '__main__':
unittest.main()