Files
Neutron/src/GamePort/Game/LabSimulation.cs
T

695 lines
35 KiB
C#

using System.Numerics;
using GamePort.Assets;
namespace GamePort.Game;
public readonly record struct PlayerInput(bool Forward, bool Backward, bool Left, bool Right, bool Jump,
bool Rise = false, bool Descend = false, bool StrafeLeft = false, bool StrafeRight = false, bool Fast = false, bool Fire = false,
bool RocketTurn = false, bool RocketRoll = false, bool RocketMouseRise = false,bool GrapplerEnter=false);
public enum PlayerPose { Idle, Run, Backpedal, Jump, Fall, Fly, Shoot, Swing, TurnLeft, TurnRight }
/// <summary>
/// Walking, airborne steering and jetpack checkpoint. Recovered arithmetic is described in
/// jimmy-movement-stabilization.md. Legacy capsule, floor-derived pivot and60Hz are port policies;
/// original collision, intro, object interactions and animation timing remain open.
/// </summary>
public sealed class LabSimulation
{
public const float BodyRadius = 24; // Provisional, not a recovered collider dimension.
private readonly SceneCollision collision;
private readonly Func<Vector3, Vector3, SupportHit?>? cameraRay;
private readonly Func<Vector3, Vector3, SupportHit?>? ceilingRay;
private readonly OriginalBodyPhysics? originalBody;
private readonly PlayerEnergy energy;
private readonly Vector3 sourceStart, sourceRotation;
private readonly float modelMinimumY, rootHeight, startFloor;
private float targetYaw, extraAirAcceleration, shadowDistance, lateralContribution;
private float targetPitch, targetRoll;
private float forwardAirPitch, backwardAirPitch;
private bool facingDirty;
private int? retainedSupportMaterial;
private bool bubbleLoop;
private PlayerPose bubblePose;
private Vector3 pendingImpulse;
private int movementMode;
private JetpackBurstState jumpState;
private bool forceFall;
private bool keyboardTurn, hasSupportPolygon;
private sbyte groundTurnDirection;
private bool primaryHeld;
private Vector3 noclipEntry;
private float noclipEntryYaw;
private int gadgetMode = -1;
private Vector3? grapplerCameraTarget;
public GrapplerGadget? Grappler {get;private set;}
public bool Noclip { get; private set; }
public bool HasNoclipEntry { get; private set; }
public float NoclipSpeed { get; set; } = 600;
public Func<int>? JetpackInventoryState { get; set; }
public string LevelCode { get; set; } = "LV1B";
public InvisibleGadget Invisible { get; } = new();
public BubbleEffect Bubble { get; } = new();
public BaseballGadget Baseball { get; } = new();
public PlayerAppearance Appearance { get; } = new();
public Vr01FloorState FloorState { get; } = new();
public Vector3 BubbleRoot { get; private set; }
public float BodyFactor { get; private set; } = OriginalBodySupport.JimmyFactor;
public float MaximumSpeed { get; private set; } = RecoveredMotion.MaximumSpeed;
public float Pitch { get; private set; }
public float Roll { get; private set; }
public Vector3 Rotation => new(Pitch,Yaw,Roll);
public Vector3 FacingTarget => new(targetPitch,targetYaw,targetRoll);
public bool FacingDirty => facingDirty;
public float ForwardAirPitch => forwardAirPitch;
public float BackwardAirPitch => backwardAirPitch;
public int BubbleBounces { get; private set; }
public int GadgetMode
{
get => gadgetMode;
set
{
var previousPose=Pose;
if (gadgetMode == 0) ReleaseBubble();
if (gadgetMode == 2) Invisible.Release();
if (gadgetMode == 6) Baseball.Release();
if (gadgetMode == 7) Grappler?.Release();
gadgetMode = -1;
if (value == 0)
{
if (Energy <= 0 && !IgnoresGadgetEnergy || Bubble.Active || Bubble.Expanding || Bubble.Collapsing) return;
InteractionRadius=160; BodyFactor=.415f; movementMode=2; MaximumSpeed=1350;
bubblePose=previousPose;
gadgetMode=0; Bubble.Start();
if (!bubbleLoop) { GadgetSound?.Invoke(2,true); bubbleLoop=true; }
return;
}
if (value == 2 && !Invisible.Equip(Energy, IgnoresGadgetEnergy)) return;
if (value == 6) Baseball.Equip();
if(value==7)
{
if(Grappler==null)return;
Grappler.Equip();
}
gadgetMode = value;
}
}
public bool IgnoresGadgetEnergy => PlayerEnergy.IsTutorial(LevelCode);
public float Energy { get => energy.Value; set => energy.Value = value; }
public bool LowEnergyWarning => energy.LowWarning;
public event Action<int>? EnergySound;
public event Action<int,bool>? GadgetSound;
public event Action? BubbleSoundStopped;
public event Action<int>? ScoreChanged;
public event Action? DefaultGadgetRequested;
//Source260/live15C serves both body collision and contact tests. The name
//predates source-body integration; burst100 is not an interaction-only size.
public float InteractionRadius { get; private set; } = 60;
public bool JetpackEffectVisible { get; private set; }
public Action<PlayerInput>? InputActions { get; set; }
public bool Shooting { get; private set; }
public float JetpackRemaining => jumpState.EffectRemaining;
public int JumpState => jumpState.JumpState;
public float JumpHoldSeconds => jumpState.HoldSeconds;
public int Bursts { get; private set; }
public float BodyHeight { get; }
public Vector3 Position { get; private set; } // Feet, not original actor root.
public Vector3 Velocity { get; private set; }
public Vector3 PendingImpulse => pendingImpulse;
public int MovementMode => movementMode;
// Fresh game registers before Jimmy. A retained Jimmy precedes the newly
// appended destination game, whose input callback therefore runs later.
public bool InputAfterPlayerUpdate { get; set; }
public float Yaw { get; private set; }
public float Speed { get; private set; }
public float PublishedSpeed { get; private set; }
public bool UsesOriginalBody => originalBody != null;
public float TurnRate { get; private set; }
public bool Grounded { get; private set; }
public PlayerPose Pose => Noclip ? Velocity.LengthSquared() > 0 ? PlayerPose.Fly : PlayerPose.Idle
: Grappler?.SwingPose==true ? PlayerPose.Swing
: GadgetMode == 0 ? bubblePose
: pendingImpulse.Y > 0 ? PlayerPose.Jump
: Grounded ? Shooting ? PlayerPose.Shoot : Speed < -1 ? PlayerPose.Backpedal : Speed > 10 ? PlayerPose.Run
: Speed>=0&&!primaryHeld&&groundTurnDirection<0 ? PlayerPose.TurnLeft
: Speed>=0&&!primaryHeld&&groundTurnDirection>0 ? PlayerPose.TurnRight : PlayerPose.Idle
: jumpState.JumpState == 3 && jumpState.EffectRemaining > 0 ? PlayerPose.Fly
: !forceFall && Velocity.Y > 0 ? PlayerPose.Jump : PlayerPose.Fall;
public int Steps { get; private set; }
public int PhysicsSteps { get; private set; }
public int ControllerSteps { get; private set; }
public int EffectSteps { get; private set; }
public int CeilingHits { get; private set; }
public int Jumps { get; private set; }
public int Landings { get; private set; }
public int WallHits { get; private set; }
public float Travel { get; private set; }
public float MaximumRise { get; private set; }
public Func<Vector3, Vector3, float, Vector3>? DynamicRootResolver { get; set; }
public Vector3 ActorRoot => Position + Vector3.UnitY * rootHeight;
public Vector3 CameraEye { get; private set; }
public Vector3 CameraTarget => grapplerCameraTarget??ActorRoot + new Vector3(0, 80 + 1.9f * Baseball.CameraPitch, 0);
//Preserve upright sole placement as a modern local correction, while the
//recovered full-axis rotation and unrotated translation use the actor root.
public Matrix4x4 Model => JimmyRenderTransform.Aligned(ActorRoot,Rotation,-modelMinimumY-rootHeight);
public LabSimulation(SceneCollision collision, Mesh standingPose, Vector3 start, float yaw,
Func<Vector3, Vector3, SupportHit?>? cameraRay = null,
Func<Vector3, Vector3, SupportHit?>? ceilingRay = null,
OriginalStaticCollision? originalCollision = null, PlayerEnergy? energy = null)
: this(collision,standingPose,start,new Vector3(0,yaw,0),cameraRay,ceilingRay,originalCollision,energy) { }
public LabSimulation(SceneCollision collision, Mesh standingPose, Vector3 start, Vector3 rotation,
Func<Vector3, Vector3, SupportHit?>? cameraRay = null,
Func<Vector3, Vector3, SupportHit?>? ceilingRay = null,
OriginalStaticCollision? originalCollision = null, PlayerEnergy? energy = null)
{
if(!float.IsFinite(rotation.X)||!float.IsFinite(rotation.Y)||!float.IsFinite(rotation.Z))
throw new ArgumentOutOfRangeException(nameof(rotation));
this.collision = collision;
this.cameraRay = cameraRay;
this.ceilingRay = ceilingRay;
originalBody = originalCollision == null ? null : new OriginalBodyPhysics(originalCollision);
this.energy = energy ?? new PlayerEnergy();
Invisible.AlphaRequested += Appearance.SetAlpha;
Invisible.BlendRequested += Appearance.SetBlend;
Baseball.Thrown += () => GadgetSound?.Invoke(10,false);
sourceStart = start;
sourceRotation = rotation;
var bounds = standingPose.Bounds();
modelMinimumY = bounds.Min.Y;
BodyHeight = bounds.Max.Y - bounds.Min.Y;
var floor = collision.GroundHeight(start, 2500)
?? throw new InvalidDataException("No support below GAM startpoint");
startFloor = floor;
// Normal Jimmy PostLoad4236A3..BA and support47BAE1 place the actor
// root at floor+60*1.265. Serialized spawnY is settled by physics.
// Feet collision and sole-based visual placement remain provisional.
rootHeight = OriginalBodySupport.JimmyRadius * OriginalBodySupport.JimmyFactor;
Reset();
}
public void Reset()
{
if(gadgetMode==7){GadgetMode=-1;DefaultGadgetRequested?.Invoke();}
Grappler?.Reset();grapplerCameraTarget=null;
if (gadgetMode == 0) { GadgetMode=-1; DefaultGadgetRequested?.Invoke(); }
if (gadgetMode == 2) gadgetMode = -1;
Invisible.Reset();
Baseball.Reset();
if (gadgetMode == 6) gadgetMode = -1;
Bubble.Reset(); FloorState.Reset(); Appearance.Reset(); retainedSupportMaterial=null;
Pitch=sourceRotation.X;Roll=sourceRotation.Z;
targetPitch=targetYaw=targetRoll=0;facingDirty=false;BubbleBounces=0;
forwardAirPitch=JimmyAirMotion.ForwardPitch;backwardAirPitch=JimmyAirMotion.BackwardPitch;
MaximumSpeed=RecoveredMotion.MaximumSpeed; BodyFactor=OriginalBodySupport.JimmyFactor;
var floor = collision.GroundHeight(sourceStart, 2500)!.Value;
Position = new(sourceStart.X, floor + (UsesOriginalBody ? 0 : SceneCollision.Skin), sourceStart.Z);
Velocity = Vector3.Zero;
Yaw = sourceRotation.Y;
Speed = PublishedSpeed = TurnRate = extraAirAcceleration = shadowDistance = 0;
lateralContribution = 0; pendingImpulse = Vector3.Zero; movementMode = 0;
keyboardTurn=false;hasSupportPolygon=false;
groundTurnDirection=0;primaryHeld=false;
jumpState = default;
forceFall = JetpackEffectVisible = false;
Shooting = false;
InteractionRadius = 60; Bursts = 0;
Grounded = true;
Noclip = HasNoclipEntry = false;
Steps = Jumps = Landings = WallHits = 0;
PhysicsSteps = ControllerSteps = EffectSteps = CeilingHits = 0;
Travel = MaximumRise = 0;
CameraEye = DesiredEye().Eye;
}
/// <summary>Jimmy PostLoad423A90..423ABF restores the saved RETURN root.
/// Yaw remains the authored STRT yaw; the source stores only XYZ here.</summary>
public void RestoreReturnRoot(Vector3 root)
{
if (!float.IsFinite(root.X) || !float.IsFinite(root.Y) || !float.IsFinite(root.Z))
throw new ArgumentOutOfRangeException(nameof(root));
Position = root - Vector3.UnitY * rootHeight;
CameraEye = DesiredEye().Eye;
}
public PlayerLevelState? CaptureLevelState(int selectedGadget) => Noclip ? null
: new(LevelCode, selectedGadget, movementMode, jumpState.HoldSeconds, jumpState.EffectRemaining,
forwardAirPitch,backwardAirPitch);
/// <summary>Apply after destination construction. Init re-applies authored
/// body vectors and clears speed/turn; PostLoad resets jump, not these scalars.
/// Grounding and the next controller/fire tick may change them independently.</summary>
public bool ApplyRetainedLevelState(PlayerLevelState state)
{
ArgumentNullException.ThrowIfNull(state);
if (!state.SupportsDestination(LevelCode)) return false;
if (state.MovementMode is < 0 or > 1 || !float.IsFinite(state.HoldSeconds)
|| state.HoldSeconds < 0 || !float.IsFinite(state.EffectRemaining)
|| !float.IsFinite(state.ForwardPitch)||!float.IsFinite(state.BackwardPitch))
throw new ArgumentOutOfRangeException(nameof(state));
movementMode = state.MovementMode;
jumpState = new(0, state.HoldSeconds, state.EffectRemaining);
forwardAirPitch=state.ForwardPitch;backwardAirPitch=state.BackwardPitch;
return true;
}
// EXE 0x47F940 truncates, then degree lookup masks to the 16384-entry table.
// Table generated with modern trig; x87 bit-identical table recovery is pending.
public static (float Sin, float Cos) Trig(float degrees)
{
var index = (int)(degrees * 45.5111122f) & 0x3fff;
var radians = index * (Math.Tau / 16384);
return ((float)Math.Sin(radians), (float)Math.Cos(radians));
}
public void Step(PlayerInput input, bool controlled = true, bool? anyControlled = null, Action? afterPhysics = null,Func<bool>? controlledAfterPhysics=null)
{
if (Noclip)
{
StepNoclip(input);
Bubble.Step(FixedStepClock.Step); //Modern flight skips body/input, not the released owned sprite's fade.
return;
}
//47E554 global body integration precedes473740 registry callbacks.
// This reconstructs the player/input/fire partial order, not the full
// scene registry, original cadence or original collision response.
StepPhysics();
afterPhysics?.Invoke();
if(controlledAfterPhysics!=null)controlled=controlledAfterPhysics();
if (controlled && !InputAfterPlayerUpdate) StepInput(input);
//42469F..4246DC runs independently of raw ownership.
if (Grounded)
{
InteractionRadius = GadgetMode == 0 ? 160 : 60;
if (GadgetMode==0) bubblePose=PlayerPose.Idle;
}
//424BE0..424C34 runs this wrapper before437940's ownership gate.
StepCeiling();
StepFloorPolicy(); //437940's base40E050, before the input-identity gate.
StepFacing(); //40E050→473240→43A420 also runs without input ownership.
if (controlled) StepPlayer(input);
Invisible.Step(FixedStepClock.Step, anyControlled ?? controlled, input.Fire, input.Jump,
Energy, IgnoresGadgetEnergy, AdjustEnergy);
if (LevelCode == "VR01") FloorState.Step(FixedStepClock.Step,Appearance.SetColor);
var effect = JetpackBurst.StepEffect(jumpState, Grounded, FixedStepClock.Step, Energy, LevelCode);
jumpState = effect.State; JetpackEffectVisible = effect.Visible;
if (effect.Visible) AdjustEnergy(-FixedStepClock.Step * JetpackBurst.EnergyPerSecond);
EffectSteps++;
Bubble.Step(FixedStepClock.Step); //Owned effect clock is not Jimmy input ownership.
if (controlled && InputAfterPlayerUpdate) StepInput(input);
Steps++;
}
/// <summary>43A750 preparation clears speed and velocity XYZ only. Queued
/// impulse, acceleration, mode, jump/hold and owned fire timer survive.</summary>
public void PrepareForScript()
{
Speed = 0; Velocity = Vector3.Zero;
}
public void LeaveRocketship(Vector3 sharedEye)
{
//4285..4286 cleanup leaves the last copied root and enters air/FALL.
Velocity=Vector3.Zero;extraAirAcceleration=0;Speed=0;movementMode=1;
forceFall=true;CameraEye=sharedEye;
}
public void EnterScooter()
{
CancelPoweredFlight(); //425120 only cancels mode1 jump/effect.
}
public void ApplyScooterTransform(Vector3 root,Vector3 rotation)
{ApplyAuthoredTransform(root,rotation);SetFacingDestination(rotation);}
public void LeaveScooter(Vector3 root,Vector3 rotation,Vector3 eye)
{
ApplyScooterTransform(root+Vector3.UnitY*40,rotation);
Velocity=Vector3.Zero;extraAirAcceleration=0;CameraEye=eye;
}
public void RocketImpact()
{
AdjustEnergy(-1);ScoreChanged?.Invoke(-1);CancelPoweredFlight();
}
public void EnableGrappler(Mesh world,GrapplerMemory memory)
{
if(LevelCode!="VR08"||originalBody==null)throw new NotSupportedException("Live Grappler requires the VR08 source body");
Grappler=new(world,LevelCode,memory);
Grappler.Detached+=()=>{Velocity=Vector3.Zero;forceFall=true;};
}
private GrapplerMove MoveGrappler(Vector3 desired)
{
var moved=originalBody!.MoveAttached(ActorRoot,desired,InteractionRadius);
if(moved.CallbackPolygon is{} contact)
{
if(contact.StoredNormal.Y<=-.7f)
{if(Velocity.Y>0)Velocity=Velocity with{Y=0};if(extraAirAcceleration>0)extraAirAcceleration=0;}
else {WallHits++;Grappler!.Contact();}
}
return new(moved.Position,Velocity);
}
public void StopForPrimaryFire() => Speed = 0;
public void SetShooting(bool shooting) => Shooting = shooting;
public void AdjustEnergy(float delta) => energy.Adjust(delta, LevelCode, id => EnergySound?.Invoke(id));
private void ReleaseBubble()
{
movementMode=0; MaximumSpeed=650;
Bubble.Stop(); Bubble.ClearExpansion();
if (bubbleLoop) BubbleSoundStopped?.Invoke();
bubbleLoop=false; InteractionRadius=60; BodyFactor=OriginalBodySupport.JimmyFactor;
}
public void FlattenOrientation()
{
//CAM4166A0..4166E5 / MCA431565..43158D copy (0,currentYaw,0)
//to both live Euler and destination274. This is a direct destination
//write: unlike36C, it preserves the existing facing-dirty byte.
Pitch=Roll=targetPitch=targetRoll=0;
targetYaw=Yaw;
}
private void StepFloorPolicy()
{
if (LevelCode!="VR01" || originalBody==null) return;
var effect=FloorState.Visit(retainedSupportMaterial,GadgetMode);
if (effect.Entered)
{ GadgetSound?.Invoke(39,false); if (GadgetMode!=0) GadgetSound?.Invoke(190,false); }
if (!effect.Damaged) return;
AdjustEnergy(-5); ScoreChanged?.Invoke(-5); CancelPoweredFlight();
}
private void CancelPoweredFlight()
{
if (movementMode!=1) return;
jumpState=jumpState with {JumpState=0,EffectRemaining=0}; forceFall=true;
}
private void StepCeiling()
{
if (Velocity.Y <= 0 || ceilingRay == null
|| ceilingRay(ActorRoot, ActorRoot + Vector3.UnitY * 150) == null) return;
Velocity = Velocity with { Y = (float)Math.Min(-Velocity.Y * .6, -85) };
CeilingHits++;
//425120 leaves hold, mode, pending impulse and acceleration intact.
//Full sound/selected-gadget cleanup callbacks remain a separate gap.
CancelPoweredFlight();
}
/// <summary>Authored AI root/Euler writes. They do not reset body motion or
/// destination yaw61C; the full logical/render Euler model remains separate.</summary>
public void ApplyAuthoredTransform(Vector3 root, float yaw)
{
if (!float.IsFinite(root.X) || !float.IsFinite(root.Y) || !float.IsFinite(root.Z) || !float.IsFinite(yaw))
throw new ArgumentOutOfRangeException(nameof(root));
Position = root - Vector3.UnitY * rootHeight; Yaw = yaw;
}
public void ApplyAuthoredTransform(Vector3 root,Vector3 rotation)
{
if(!float.IsFinite(rotation.X)||!float.IsFinite(rotation.Y)||!float.IsFinite(rotation.Z))
throw new ArgumentOutOfRangeException(nameof(rotation));
ApplyAuthoredTransform(root,rotation.Y);Pitch=rotation.X;Roll=rotation.Z;
}
/// <summary>Modern debug movement; never serialized into original save state.</summary>
public bool SetNoclip(bool enabled)
{
if (enabled == Noclip) return false;
if (enabled)
{
if(gadgetMode==7){GadgetMode=-1;DefaultGadgetRequested?.Invoke();}
if (gadgetMode==0) { GadgetMode=-1; DefaultGadgetRequested?.Invoke(); }
noclipEntry = Position; noclipEntryYaw = Yaw; HasNoclipEntry = true;
}
var returned = !enabled && !collision.CanOccupy(Position, BodyRadius, BodyHeight);
if (returned) { Position = noclipEntry; Yaw = targetYaw = noclipEntryYaw; }
Noclip = enabled;
StopDebugMotion();
Grounded = false;
CameraEye = DesiredEye().Eye;
return returned;
}
public void StopDebugMotion()
{
if (gadgetMode==0) { GadgetMode=-1; DefaultGadgetRequested?.Invoke(); }
Shooting = false;
Velocity = pendingImpulse = Vector3.Zero;
groundTurnDirection=0;primaryHeld=false;
Speed = PublishedSpeed = TurnRate = extraAirAcceleration = lateralContribution = 0;
jumpState = default; movementMode = 0; forceFall = JetpackEffectVisible = false;
//Modern debug stop freezes the retained facing request as well as body
//motion. Otherwise entering noclip can leave a queued airborne lean.
targetPitch=Pitch;targetYaw=Yaw;targetRoll=Roll;facingDirty=false;
}
public bool ReturnToNoclipEntry()
{
if (!HasNoclipEntry) return false;
Position = noclipEntry; Yaw = targetYaw = noclipEntryYaw;
StopDebugMotion(); Grounded = false; CameraEye = DesiredEye().Eye;
return true;
}
private void StepNoclip(PlayerInput input)
{
if (!float.IsFinite(NoclipSpeed) || NoclipSpeed <= 0 || NoclipSpeed > 10000)
throw new ArgumentOutOfRangeException(nameof(NoclipSpeed));
const float dt = FixedStepClock.Step;
Yaw = targetYaw = (Yaw + ((input.Left ? 1 : 0) - (input.Right ? 1 : 0)) * 90 * dt) % 360;
var (sin, cos) = Trig(Yaw);
var direction = new Vector3(-sin, 0, cos) * ((input.Forward ? 1 : 0) - (input.Backward ? 1 : 0))
+ new Vector3(cos, 0, sin) * ((input.StrafeRight ? 1 : 0) - (input.StrafeLeft ? 1 : 0))
+ Vector3.UnitY * ((input.Rise ? 1 : 0) - (input.Descend ? 1 : 0));
if (direction.LengthSquared() > 1) direction = Vector3.Normalize(direction);
Velocity = direction * NoclipSpeed * (input.Fast ? 3 : 1);
var delta = Velocity * dt;
Position += delta; Travel += new Vector2(delta.X, delta.Z).Length();
MaximumRise = Math.Max(MaximumRise, Position.Y - startFloor);
Grounded = false; Steps++;
CameraEye = DesiredEye().Eye;
}
private void StepInput(PlayerInput input)
{
const float dt = FixedStepClock.Step;
lateralContribution = 0;
primaryHeld=input.Fire;
//438A60 dispatches by stored movement mode, not current support.
if (movementMode == 0)
{
groundTurnDirection=(sbyte)(input.Left?-1:input.Right?1:0); //complete82A: keyboard Left wins.
//The830 backward clock owner remains unresolved; ordinary state0
//does not invent a hold timer or admit its seeded auto-turn branch.
var ground=JimmyGroundMotion.Input(new(Speed,targetYaw),Yaw,input,MaximumSpeed,
blockBackward:(GadgetMode is -1 or 3)&&input.Fire);
Speed=ground.State.Speed;lateralContribution=ground.Lateral;
if(input.Left||input.Right)keyboardTurn=true;
if(ground.HeadingUpdated)SetFacingDestination(new(0,ground.State.TargetYaw,0));
}
else if (movementMode==2)
{
var steering=BubbleMotion.StepInput(Speed,TurnRate,input,Grounded,dt,MaximumSpeed,forwardAirPitch,backwardAirPitch);
Speed=steering.Speed; TurnRate=steering.TurnRate;
if(input.Left||input.Right)keyboardTurn=true;
SetFacingDestination(new(steering.TargetPitch,Yaw,steering.TargetRoll));
}
else
{
var steering = JimmyAirMotion.Input(new(Speed,TurnRate,keyboardTurn),input,Grounded,dt,MaximumSpeed);
Speed = steering.Speed; TurnRate = steering.TurnRate;
keyboardTurn=steering.KeyboardTurn;
//439E2B preserves current yaw as the destination; air apply then
//438011..43802B adds the independent turn rate directly to yaw.
SetFacingDestination(JimmyAirMotion.Destination(input,Yaw,TurnRate,forwardAirPitch,backwardAirPitch));
}
Baseball.StepCameraInput(input);
StepCamera(); //438BC0/439900 input path owns follow; still provisional geometry/state.
if(Grappler is{Equipped:true} grappler)
{
var state=grappler.StepInput(ActorRoot,new(Pitch,Yaw,Roll),Velocity,input,dt,MoveGrappler);
Position=state.Root-Vector3.UnitY*rootHeight;Pitch=state.Rotation.X;Yaw=state.Rotation.Y;Roll=state.Rotation.Z;Velocity=state.Velocity;
if(state.NewAttachment){jumpState=jumpState with{JumpState=0,EffectRemaining=0};JetpackEffectVisible=false;}
if(state.EndsActiveInput)return;
}
if (movementMode==2)
{
AdjustEnergy(-dt*.5f);
if (Energy<=0) { GadgetMode=-1; DefaultGadgetRequested?.Invoke(); }
//4262A5 continues placement even if depletion just cleaned the mode.
var direction=ActorRoot+Vector3.UnitY*100-CameraEye;
direction=direction.LengthSquared()>0 ? Vector3.Normalize(direction) : Vector3.Zero;
BubbleRoot=ActorRoot+Vector3.UnitY*50-direction*80;
}
InputActions?.Invoke(input);
Baseball.StepInput(input,ActorRoot,new(Pitch,Yaw,Roll),Grounded,Energy,IgnoresGadgetEnergy,
StopForPrimaryFire,SetShooting,AdjustEnergy);
}
private void StepFacing()
{
var before=Rotation;
var rotation=JimmyOrientation.Step(before,FacingTarget,FixedStepClock.Step,dirty:facingDirty);
if(facingDirty)facingDirty=before!=FacingTarget;
Pitch=rotation.X;Yaw=rotation.Y;Roll=rotation.Z;
}
private void SetFacingDestination(Vector3 target)
{targetPitch=target.X;targetYaw=target.Y;targetRoll=target.Z;facingDirty=true;}
private void StepPlayer(PlayerInput input)
{
ControllerSteps++;
const float dt = FixedStepClock.Step;
if (movementMode==2)
{
forwardAirPitch=-10;backwardAirPitch=10; //43880A/438814, after input when fresh.
var bubble=BubbleMotion.StepApply(Speed,TurnRate,Yaw,Pitch,Velocity,Grounded,input.Jump,dt);
Velocity=bubble.Velocity; Yaw=bubble.Yaw; Speed=bubble.Speed; PublishedSpeed=Speed;
if (Grounded) { BubbleBounces++; if (bubble.Boing) GadgetSound?.Invoke(106,false); }
return;
}
//437A96 selects air mode on held jump;437B9E..BAC resets jump/mode/turn
//only in the player's grounded/released update, after input when fresh.
if (input.Jump) movementMode = 1;
else if (Grounded)
{
movementMode = 0; TurnRate = 0;
}
Vector3 velocity;
if(movementMode==0)
{
var ground=JimmyGroundMotion.Apply(Speed,Velocity,new(Pitch,Yaw,Roll),TurnRate,
lateralContribution,Grounded,hasSupportPolygon,dt);
velocity=ground.Velocity;Pitch=ground.Rotation.X;Yaw=ground.Rotation.Y;Roll=ground.Rotation.Z;
}
else
{
forwardAirPitch=JimmyAirMotion.ForwardPitch;backwardAirPitch=JimmyAirMotion.BackwardPitch;
var airMotion=JimmyAirMotion.Apply(Speed,TurnRate,new(Pitch,Yaw,Roll),Velocity,dt);
velocity=airMotion.Velocity;Pitch=airMotion.Rotation.X;Yaw=airMotion.Rotation.Y;Roll=airMotion.Rotation.Z;
}
if (collision.GroundHeight(ActorRoot, 2500) is { } shadowFloor)
shadowDistance = MathF.Abs(ActorRoot.Y - shadowFloor - 13);
var air = JetpackBurst.Step(jumpState, new(Grounded, input.Jump, velocity.Y, shadowDistance,
JetpackInventoryState?.Invoke() ?? 0, Energy, LevelCode, GadgetMode, dt, extraAirAcceleration));
jumpState = air.State; extraAirAcceleration = air.ExtraAccelerationY;
pendingImpulse += new Vector3(0, air.ImpulseY, 0);
if (air.ImpulseY != 0) Jumps++;
if (air.MovementModeOverride is { } mode) movementMode = mode;
if (air.VelocityYOverride is { } vertical) velocity.Y = vertical;
if (air.RadiusOverride is { } radius) InteractionRadius = radius;
if (air.Pose == JetpackPose.Fall) forceFall = true;
else if (air.Pose is JetpackPose.Jump or JetpackPose.Fly) forceFall = false;
if (air.StartGadget) Bursts++;
Velocity = velocity; // Produced body state is consumed by the next physics pass.
PublishedSpeed = Speed; //437C22..437C2D: controller608 -> body160.
}
private void StepPhysics()
{
PhysicsSteps++;
const float dt = FixedStepClock.Step;
if (originalBody != null)
{
StepOriginalPhysics();
return;
}
var wasGrounded = Grounded;
var velocity = Velocity;
// Keep the existing capsule/gravity adapter until C4 recovers Jimmy's
// support/response. Source479DF7..479E54 cancels gravity and vertical
// velocity when global geometry4F69E5 is disabled, not when grounded.
// This adapter does not model that separate source debug/global gate.
var displacement = RecoveredMotion.Integrate(ref velocity, ref pendingImpulse,
Vector3.UnitY * extraAirAcceleration, RecoveredMotion.Gravity, dt);
var before = Position;
var result = collision.Move(Position, displacement, BodyRadius, BodyHeight);
Position = result.Position;
if (DynamicRootResolver != null)
{
var root = ActorRoot;
var resolved = DynamicRootResolver(before + Vector3.UnitY * rootHeight, root, InteractionRadius);
if (resolved != root)
{
// Original47A5E0 re-clips against static geometry before storing
// the new root. Here both kernels remain explicitly provisional.
result = collision.Move(Position, resolved - root, BodyRadius, BodyHeight);
Position = result.Position;
}
}
Grounded = result.Grounded && velocity.Y <= 0;
//The capsule has no original338 support polygon. Combining source
//downward pressure with its slide solver blocks the lab stair route.
//Keep that solver's baseline until the source body/contact bridge lands.
hasSupportPolygon=false;
if (Grounded && velocity.Y < 0 || result.HitCeiling && velocity.Y > 0 && ceilingRay == null) velocity.Y = 0;
if (Grounded) { extraAirAcceleration = 0; forceFall = false; }
Velocity = velocity;
if (!wasGrounded && Grounded) Landings++;
if (result.HitWall) WallHits++;
Travel += Vector2.Distance(new(before.X, before.Z), new(Position.X, Position.Z));
MaximumRise = Math.Max(MaximumRise, Position.Y - startFloor);
}
private void StepOriginalPhysics()
{
if (DynamicRootResolver != null)
throw new NotSupportedException("Original ordinary-body subset cannot use the provisional dynamic resolver");
var before = Position;
var result = originalBody!.Step(new(ActorRoot, Velocity, Vector3.UnitY * extraAirAcceleration,
pendingImpulse, Grounded, PublishedSpeed), FixedStepClock.Step, InteractionRadius,BodyFactor);
if (result.SupportHit is { } hit) retainedSupportMaterial=originalBody.MaterialFor(hit);
Position = result.Body.Position - Vector3.UnitY * rootHeight;
Velocity = result.Body.Velocity;
pendingImpulse = result.Body.Impulse;
extraAirAcceleration = result.Body.Acceleration.Y;
Grounded = result.Body.Supported;
hasSupportPolygon=result.SupportHit!=null;
if (Grounded) forceFall = false;
if (result.Landing != null) Landings++;
if (result.Contact is { StoredNormal.Y: > -.7f }) {WallHits++;Grappler?.Contact();}
Travel += Vector2.Distance(new(before.X, before.Z), new(Position.X, Position.Z));
MaximumRise = Math.Max(MaximumRise, Position.Y - startFloor);
}
private void StepCamera()
{
const float dt = FixedStepClock.Step;
if(Grappler is{} grappler&&movementMode!=2&&!Noclip)
{
var follow=GrapplerCamera.Follow(grappler.Camera,ActorRoot,new(Pitch,Yaw,Roll),TurnRate,movementMode,CameraEye,dt,cameraRay);
CameraEye=follow.Eye;grapplerCameraTarget=follow.Target;return;
}
grapplerCameraTarget=null;
var desired = DesiredEye();
var delta = (desired.Eye - CameraEye) * new Vector3(1.6f, 1.2f, 1.6f) * desired.Gain * dt;
CameraEye = cameraRay == null ? collision.ClipCamera(CameraTarget, CameraEye + delta) : CameraEye + delta;
}
private (Vector3 Eye, float Gain) DesiredEye()
{
var (sin, cos) = Trig(Yaw);
var eye = ActorRoot + new Vector3(sin * 350, Baseball.CameraHeight - 2 * Baseball.CameraPitch, -cos * 350);
if (Noclip) return (eye, 1); // Debug exploration also bypasses camera obstruction.
if (cameraRay == null) return (collision.ClipCamera(CameraTarget, eye), 1);
//43B820: query from the computed look target; first accepted static hit
//moves desired eye25% toward look and returns follow gain1.5. No radius
//or second sweep after interpolation occurs in that source callback.
return cameraRay(CameraTarget, eye) is { } hit
? (CameraTarget - (CameraTarget - hit.Position) * .75f, 1.5f) : (eye, 1);
}
public static PlayerInput SmokeInput(int step) => new(step < 120, false, false,
step >= 120 && step < 180, step >= 72 && step < 84);
public static PlayerInput JetpackSmokeInput(int step) => new(step is >= 45 and < 80,
step is >= 80 and < 120, step is >= 60 and < 95, false, step < 180);
public bool SmokePassed => Steps >= 240 && Travel > 50 && MaximumRise > 20 && Jumps > 0 && Landings > 0 && Grounded;
public string Report => $"Walk checkpoint: steps={Steps}, controller={ControllerSteps}, physics={PhysicsSteps}, effect={EffectSteps}, travel={Travel:F2}, jumps={Jumps}, landings={Landings}, max rise={MaximumRise:F2}, wall hits={WallHits}, ceiling hits={CeilingHits}, grounded={Grounded}, feet={Position}, body={(UsesOriginalBody ? "source ordinary" : "provisional capsule")}.";
}