Implement Bubble controller, sprite and VR01 body behavior

This commit is contained in:
UnixNight committed 2026-11-02 16:57:54 -05:00
1 parent 9ea578492d
commit 1ae5f4251c
51 files changed
+2811 -54

No files matched your search

+131
View File
@@ -0,0 +1,131 @@
using GamePort.Game;
namespace GamePort.Application;
/// <summary>Eight rendered port-verification phases, with accelerated full
/// player ticks between them. This is an input fixture, not original cadence.</summary>
public sealed class BubbleSmoke
{
private readonly LabSimulation player;
private readonly SceneInventory inventory;
private readonly bool[] checks = new bool[8];
private readonly float initialEnergy;
private float? supportedRootY;
private int acceleratedTicks, boingSounds, bouncesBeforeHeld, soundsBeforeHeld;
public BubbleSmoke(LabSimulation player, SceneInventory inventory)
{
this.player = player;
this.inventory = inventory;
initialEnergy = player.Energy;
player.GadgetSound += (id, _) => { if (id == 106) boingSounds++; };
inventory.SetState(0, 0, 1);
inventory.SelectGadget(0);
if (player.GadgetMode != 0 || player.MovementMode != 2 || player.InteractionRadius != 160
|| MathF.Abs(player.BodyFactor - .415f) > .00001f || player.MaximumSpeed != 1350
|| !player.Bubble.Expanding)
throw new InvalidOperationException("Bubble fixture requires a connected, eligible mode0/movement2 player binding with radius160/factor.415/max1350");
}
public void BeforeFrame(int count, Action<uint, bool> injectKey, bool headless)
{
if (count == 1) Advance(80);
if (count == 2 && !headless)
{
injectKey(224, true); //Left Ctrl: shared primary-fire throttle.
injectKey(80, true); //Left arrow: airborne steering.
}
if (count == 3)
{
PrepareLanding();
bouncesBeforeHeld = player.BubbleBounces;
soundsBeforeHeld = boingSounds;
//The next ordinary application tick consumes this SDL event.
//Never advance the jump helper before actual input processing.
if (!headless) injectKey(225, true);
}
if (count == 4 && !headless)
{
injectKey(224, false);
injectKey(80, false);
injectKey(225, false);
}
if (count == 5)
{
//Release near the next support contact so the fixed captured
//sprite remains in view while its source-owned fade runs.
PrepareLanding();
if (headless) inventory.SelectGadget(-1);
else injectKey(43, true);
}
if (count == 6)
{
if (!headless) injectKey(43, false);
Advance(40);
}
if (count == 7) Advance(40);
}
private void Advance(int count)
{
for (var i = 0; i < count; i++) Tick();
}
private void Tick()
{
player.Step(default);
acceleratedTicks++;
ObserveSupport();
}
private void ObserveSupport()
{
//Read the actual supported root; initial placement's Grounded flag is
//not an observed floor height until at least one real player tick.
if (player.Grounded) supportedRootY = player.ActorRoot.Y;
}
private void PrepareLanding()
{
for (var i = 0; i < 600; i++)
{
var predictedY = player.ActorRoot.Y
+ (player.Velocity.Y - 800 * FixedStepClock.Step) * FixedStepClock.Step;
if (supportedRootY is { } floor && player.Velocity.Y < 0 && predictedY <= floor) return;
Tick();
}
throw new InvalidOperationException($"Bubble fixture could not find an imminent supported landing within600 full player ticks: rootY={player.ActorRoot.Y:F4}, velocityY={player.Velocity.Y:F4}, last supported rootY={supportedRootY?.ToString("F4") ?? "unobserved"}");
}
public void AfterFrame(int count)
{
ObserveSupport();
var effect = player.Bubble;
if (count == 0) checks[0] = effect.Expanding && effect.Visible && !effect.Active
&& effect.Color.X > 0 && effect.Color.X < 1;
if (count == 1) checks[1] = effect.Active && !effect.Expanding && effect.Visible
&& effect.Width == 240 && effect.Height >= 210 && effect.Height <= 270;
if (count == 2) checks[2] = player.GadgetMode == 0 && player.MovementMode == 2
&& player.Speed > 0 && player.TurnRate > 0 && player.Pitch < 0 && !player.Shooting;
if (count == 3) checks[3] = player.BubbleBounces > bouncesBeforeHeld
&& MathF.Abs(player.Velocity.Y - 900) < .001f && boingSounds > soundsBeforeHeld;
if (count == 4) checks[4] = player.GadgetMode == 0 && effect.Active && !player.Shooting;
if (count == 5) checks[5] = player.GadgetMode == -1 && player.MaximumSpeed == 650
&& player.InteractionRadius == 60 && MathF.Abs(player.BodyFactor - 1.265f) < .00001f
&& effect.Collapsing && !effect.Active && !effect.Expanding;
if (count == 6) checks[6] = effect.Visible && effect.Collapsing && effect.Color.X > 0
&& effect.Color.X < 1 && effect.Color.X == effect.Color.Y && effect.Color.X == effect.Color.Z
&& effect.Color.X == effect.Color.W;
if (count == 7) checks[7] = !effect.Visible && !effect.Collapsing && effect.Color == System.Numerics.Vector4.Zero;
}
private bool EnergyPreserved => !player.IgnoresGadgetEnergy || player.Energy == initialEnergy;
public bool Passed => checks.All(value => value) && EnergyPreserved;
public string Report => $"Bubble fixture: expanding={checks[0]}, active={checks[1]}, fire/left throttle={checks[2]}, held support900/SFX106={checks[3]}, input release={checks[4]}, cleanup650={checks[5]}, fullRGBA fade={checks[6]}, hidden={checks[7]}, accelerated player ticks={acceleratedTicks}, boing sounds={boingSounds}, level={player.LevelCode}, energy={player.Energy:F3}/{initialEnergy:F3}, tutorial energy preserved={EnergyPreserved}.";
public static string? StageName(int count) => count switch
{ 0 => "expand", 1 => "active", 2 => "steer", 3 => "high-bounce", 5 => "release", 6 => "fade", 7 => "hidden", _ => null };
public static PlayerInput Input(int count) => new(false, false, count is 2 or 3, false,
count == 3, Fire: count is 2 or 3);
}
+86
View File
@@ -0,0 +1,86 @@
using System.Numerics;
using System.Security.Cryptography;
using System.Text.Json;
using GamePort.Assets;
using GamePort.Game;
namespace GamePort.Application;
/// <summary>Original Canv1 world quad with full RGBA fade. Camera-facing basis
/// and center alignment are declared port policies pending original render recovery.</summary>
public sealed class BubbleVisuals
{
private const string PixelHash = "a3a678c47c1ce94946b1136560a84f3ef86c6884b981256a9fbff62fe8a988e4";
private readonly int offset;
private readonly uint firstIndex;
public Mesh Mesh { get; }
public BubbleVisuals(Mesh combined, string preparedRoot)
{
var manifest = Path.GetFullPath(Path.Combine(preparedRoot, "bubble/bubble.json"));
if (new FileInfo(manifest).Length > 16 * 1024) throw new InvalidDataException("Bubble manifest exceeds limit");
using var document = JsonDocument.Parse(File.ReadAllBytes(manifest), new JsonDocumentOptions { MaxDepth = 10 });
var root = document.RootElement;
if (root.GetProperty("schema").GetInt32() != 1 || root.GetProperty("textures").GetArrayLength() != 1)
throw new InvalidDataException("Unsupported Bubble resource format");
var entry = root.GetProperty("textures")[0];
if (entry.GetProperty("id").GetInt32() != 1 || entry.GetProperty("name").GetString() != "orangebubble"
|| entry.GetProperty("width").GetInt32() != 146 || entry.GetProperty("height").GetInt32() != 146
|| entry.GetProperty("rgbaSha256").GetString() != PixelHash)
throw new InvalidDataException("Invalid source Bubble canvas");
var directory = Path.GetDirectoryName(manifest)!;
var path = Path.GetFullPath(Path.Combine(directory, entry.GetProperty("path").GetString()!));
if (!path.StartsWith(directory + Path.DirectorySeparatorChar, StringComparison.Ordinal)
|| new FileInfo(path).Length != 146 * 146 * 4)
throw new InvalidDataException("Invalid Bubble pixel path/length");
var rgba = File.ReadAllBytes(path);
if (!Convert.ToHexStringLower(SHA256.HashData(rgba)).Equals(PixelHash, StringComparison.Ordinal))
throw new InvalidDataException("Bubble decoded pixels differ from the original canvas");
offset = combined.Vertices.Length;
firstIndex = (uint)combined.Indices.Length;
var textures = new Dictionary<int, PngImage>(combined.Textures);
var textureId = int.MinValue + 16000;
while (textures.ContainsKey(textureId)) textureId++;
textures.Add(textureId, new(146, 146, rgba));
var vertices = combined.Vertices.ToList();
vertices.AddRange([new(Vector3.Zero, new(0, 1), Vector3.One), new(Vector3.Zero, new(1, 1), Vector3.One),
new(Vector3.Zero, new(1, 0), Vector3.One), new(Vector3.Zero, new(0, 0), Vector3.One)]);
var first = (uint)offset;
var indices = combined.Indices.ToList();
indices.AddRange([first, first + 1, first + 2, first, first + 2, first + 3]);
var draws = combined.Draws.ToList();
if (!combined.HasExplicitDraws && firstIndex != 0) draws.Add(new(0, firstIndex, -1));
draws.Add(new(firstIndex, 6, textureId) { Visible = false, Blend = MeshBlend.Additive });
Mesh = new(vertices.ToArray(), indices.ToArray()) { HasExplicitDraws = true, Draws = draws.ToArray(),
Textures = textures, CollisionPolygons = combined.CollisionPolygons,
HasCollisionMaterialIds = combined.HasCollisionMaterialIds };
}
public void Update(Mesh destination, BubbleEffect effect, Vector3 root, Vector3 eye, Vector3 target)
{
if (destination.Vertices.Length < offset + 4)
throw new ArgumentException("Destination omits Bubble vertices", nameof(destination));
var draw = destination.Draws.First(d => !d.ScreenSpace && d.FirstIndex == firstIndex && d.IndexCount == 6);
draw.Visible = effect.Visible;
draw.Blend = effect.ConventionalBlend ? MeshBlend.Alpha : MeshBlend.Additive;
draw.Opacity = effect.Color.W;
if (!draw.Visible) return;
if (!Finite(root) || !Finite(eye) || !Finite(target))
throw new ArgumentException("Bubble root and camera must be finite");
var direction = target - eye;
if (direction.LengthSquared() < .000001f) direction = Vector3.UnitZ;
direction = Vector3.Normalize(direction);
var right = Vector3.Cross(Vector3.UnitY, direction);
right = right.LengthSquared() < .000001f ? Vector3.UnitX : Vector3.Normalize(right);
var up = Vector3.Normalize(Vector3.Cross(direction, right));
var x = right * (effect.Width * .5f);
var y = up * (effect.Height * .5f);
var color = new Vector3(effect.Color.X, effect.Color.Y, effect.Color.Z);
destination.Vertices[offset] = new(root - x - y, new(0, 1), color);
destination.Vertices[offset + 1] = new(root + x - y, new(1, 1), color);
destination.Vertices[offset + 2] = new(root + x + y, new(1, 0), color);
destination.Vertices[offset + 3] = new(root - x + y, new(0, 0), color);
}
private static bool Finite(Vector3 value) => float.IsFinite(value.X) && float.IsFinite(value.Y) && float.IsFinite(value.Z);
}
+9 -5
View File
@@ -8,7 +8,7 @@ public sealed record DebugScene(string LevelFile, string Code, string[] Starts);
public enum DebugAction { None, Resume, Camera, SkipCutscene, RefillEnergy, GiveJetpack, ApplySceneTask, LoadScene, Reset, ForceControl, ToggleOverlay,
Noclip, NoclipSpeed, StopMotion, ShowObjective, ReturnNoclipEntry, LevelAvailability, InputOrder, ApplyJetpackState,
CameraObstruction, MuteMusic, MuteSpeech, MuteEffects, RestartMusic, StopEffects, SaveCheckpoint, LoadCheckpoint, Practice,
GiveInvisible, UnequipGadget }
GiveInvisible, UnequipGadget, GiveBubble }
public sealed record DebugMenuView(string[] Lines, int SelectedLine);
public sealed record DebugStatus(string Level, string Start, Vector3 Root, float Yaw, float Speed,
bool Grounded, float Energy, int Score, int SceneTask, string Cutscene, bool Controlled,
@@ -29,6 +29,9 @@ public sealed record DebugSystems
public float InvisibleRemaining { get; init; }
public float InvisibleRecharge { get; init; }
public bool Targetable { get; init; } = true;
public string BubblePhase { get; init; } = "OFF";
public float BodyRadius { get; init; } = 60;
public float BodyFactor { get; init; } = 1.265f;
public int Objective { get; init; }
public float ObjectiveTime { get; init; }
public bool? CameraObstruction { get; init; }
@@ -52,7 +55,7 @@ public sealed class DebugMenu
public const int ItemCount = 12;
public const int PageCount = 3;
public int Page { get; private set; }
public int PageItems => Page switch { 1 => 12, 2 => 9, _ => ItemCount };
public int PageItems => Page switch { 1 => 13, 2 => 9, _ => ItemCount };
private static readonly float[] FlySpeeds = [300, 600, 1200, 2400];
private int flySpeedIndex = 1, jetpackStateIndex = 1;
private static readonly int[] JetpackStates = [0, 1, 4];
@@ -115,7 +118,7 @@ public sealed class DebugMenu
3 => DebugAction.ShowObjective, 4 => DebugAction.ReturnNoclipEntry,
5 => DebugAction.LevelAvailability, 6 => DebugAction.InputOrder,
8 => DebugAction.ApplyJetpackState, 9 => DebugAction.RefillEnergy,
10 => DebugAction.GiveInvisible, 11 => DebugAction.UnequipGadget, _ => DebugAction.None
10 => DebugAction.GiveInvisible, 11 => DebugAction.UnequipGadget, 12 => DebugAction.GiveBubble, _ => DebugAction.None
};
if (Page == 2) return Selected switch
{
@@ -153,14 +156,15 @@ public sealed class DebugMenu
Page == 1 ? $"JUMP {system.JumpState} HOLD {F(system.JumpHold)} BURN {F(system.BurnRemaining)}"
: $"EFFECT BYTES {system.EffectBytes} AUDIO AVAILABLE {system.AudioAvailable}",
$"OBJECTIVE {system.Objective} TIME {F(system.ObjectiveTime)} GADGET STATE {system.JetpackAvailability}",
$"INVISIBLE {F(system.InvisibleRemaining)} RECHARGE {F(system.InvisibleRecharge)}/7 TARGETABLE {system.Targetable}", ""];
$"INVISIBLE {F(system.InvisibleRemaining)} RECHARGE {F(system.InvisibleRecharge)}/7 TARGETABLE {system.Targetable}",
$"BUBBLE {system.BubblePhase} BODY R {F(system.BodyRadius)} FACTOR {system.BodyFactor.ToString("0.000",c)}", ""];
string[] items = Page == 1 ? [
$"NOCLIP (F3): {system.Noclip} (ENTER TOGGLE)",
$"FLY SPEED: {F(FlySpeed)} LIVE {F(system.NoclipSpeed)} (ENTER APPLIES)", "STOP MOTION / CLEAR QUEUED JUMP", "SHOW CURRENT OBJECTIVE",
"RETURN TO NOCLIP ENTRY POSITION", "APPLY THIS LEVEL'S GADGET AVAILABILITY",
$"INPUT AFTER PLAYER: {system.InputAfterPlayer} (TOGGLE)",
$"JET PACK STATE: {JetpackState} (0 NONE / 1 OWNED / 4 DISABLED)", "APPLY JET PACK STATE", "REFILL ENERGY TO 100",
"GIVE / SELECT INVISIBLE", "UNEQUIP CURRENT GADGET"] : [
"GIVE / SELECT INVISIBLE", "UNEQUIP CURRENT GADGET", "GIVE / SELECT BUBBLE"] : [
$"STATIC CAMERA OBSTRUCTION: {(system.CameraObstruction?.ToString() ?? "UNAVAILABLE")}",
$"MUTE MUSIC: {system.MusicMuted}", $"MUTE SPEECH: {system.SpeechMuted}", $"MUTE EFFECTS: {system.EffectsMuted}",
"RESTART SELECTED MUSIC", "STOP ALL EFFECTS / LOOPS", "SAVE DEBUG CHECKPOINT", "LOAD DEBUG CHECKPOINT", "SHOW JET PACK PRACTICE PROMPT"];
@@ -7,6 +7,8 @@ namespace GamePort.Application;
/// indexed0 FC blend changes affect that draw without changing pose/visibility.</summary>
public static class PlayerGadgetMaterial
{
public static void Apply(MeshDraw draw, PlayerAppearance appearance)
{ draw.Opacity=appearance.Color.W; draw.Blend=appearance.Blend; }
public static void Apply(MeshDraw draw, InvisibleGadget invisible)
{
draw.Opacity = invisible.Opacity;
+6 -4
View File
@@ -11,9 +11,11 @@ public static class AirSteering
public const float TurnLimit = 30; //439D81..439DB7, ordinary mode1.
public const float CoastThreshold = 0.9090909361839294f; //49D5DC.
public static AirSteeringResult Step(float speed, float turnRate, PlayerInput input, float seconds)
public static AirSteeringResult Step(float speed, float turnRate, PlayerInput input, float seconds,
float maximumSpeed = RecoveredMotion.MaximumSpeed)
{
if (!float.IsFinite(speed) || !float.IsFinite(turnRate) || !float.IsFinite(seconds) || seconds < 0 || seconds >= 1)
if (!float.IsFinite(speed) || !float.IsFinite(turnRate) || !float.IsFinite(seconds)
|| !float.IsFinite(maximumSpeed) || maximumSpeed<=0 || seconds < 0 || seconds >= 1)
throw new ArgumentOutOfRangeException(nameof(seconds));
var turnStep = TurnAcceleration * seconds;
if (input.Left) turnRate += turnStep;
@@ -22,8 +24,8 @@ public static class AirSteering
else if (turnRate > 0) turnRate = MathF.Max(0, turnRate - turnStep);
turnRate = Math.Clamp(turnRate, -TurnLimit, TurnLimit);
if (input.Forward) speed = RecoveredMotion.AddSpeed(speed);
else if (speed > RecoveredMotion.MaximumSpeed * CoastThreshold)
if (input.Forward) speed = RecoveredMotion.AddSpeed(speed,maximumSpeed);
else if (speed > maximumSpeed * CoastThreshold)
speed -= RecoveredMotion.SpeedDecay * .5f;
//439C1D..439CB2 brakes to0, without starting reverse flight.
if (input.Backward)
+73
View File
@@ -0,0 +1,73 @@
using System.Numerics;
namespace GamePort.Game;
/// <summary>Owned C3DBubble sprite transitions (410AE0/410CA0/410D00).
/// The caller owns equip, cleanup, placement and callback scheduling.</summary>
public sealed class BubbleEffect(bool conventionalBlend = false)
{
public bool Visible { get; private set; }
public bool Active { get; private set; }
public bool Expanding { get; private set; }
public bool Collapsing { get; private set; }
public float Timer { get; private set; }
public Vector4 Color { get; private set; } = conventionalBlend ? new(.9f, .9f, .9f, 1) : Vector4.One;
public float Width { get; private set; } = 200;
public float Height { get; private set; } = 200;
public bool ConventionalBlend { get; } = conventionalBlend;
public void Start()
{
// Source equip rejects all three flags before calling this leaf.
Expanding = true;
Timer = 0;
Visible = true;
}
public void Stop()
{
// Source410D00 leaves expansion alone. Jimmy cleanup clears it separately.
Collapsing = true;
Active = false;
Timer = 0;
}
public void ClearExpansion() => Expanding = false;
public void Step(float seconds)
{
if (!float.IsFinite(seconds) || seconds < 0 || seconds >= 1)
throw new ArgumentOutOfRangeException(nameof(seconds));
//410AF2 stores float timer but retains the addition on the x87 stack
//for the fade comparisons. Preserve that distinction at strict boundaries.
var sum = (double)Timer + seconds;
Timer = (float)sum;
if (Active)
{
Width = 240;
Height = (float)(240 + Math.Sin((double)Timer * 10) * 30);
if (ConventionalBlend) Color = new(1, 1, 1, .5f);
}
else if (Expanding)
{
var scalar = (float)sum;
if (sum > 1) { scalar = 1; Active = true; Expanding = false; }
Color = new(scalar);
}
else if (Collapsing)
{
var fade = 1 - sum;
var scalar = (float)fade;
if (fade < 0) { scalar = 0; Collapsing = false; Visible = false; }
Color = new(scalar);
}
}
public void Reset()
{
Visible = Active = Expanding = Collapsing = false;
Timer = 0;
Color = ConventionalBlend ? new(.9f, .9f, .9f, 1) : Vector4.One;
Width = Height = 200;
}
}
+91
View File
@@ -0,0 +1,91 @@
using System.Numerics;
namespace GamePort.Game;
public readonly record struct BubbleSteering(float Speed, float TurnRate, float TargetPitch, float TargetRoll);
public readonly record struct BubbleApply(Vector3 Velocity, float Yaw, float Speed, bool Boing);
/// <summary>
/// Keyboard subset of mode2 input439900 and apply4387E0. Body integration,
/// impulses, acceleration and gadget lifetime belong to their existing phases.
/// Source ownership and precision limits: docs/gameplay/bubble-motion.md.
/// </summary>
public static class BubbleMotion
{
public const float MaximumSpeed = 1350;
public const float TurnLimit = 50;
public const float ReleasedBounceSpeed = 300;
public const float HeldBounceSpeed = 900;
public static BubbleSteering StepInput(float speed, float turn, PlayerInput input,
bool supported, float seconds, float maximumSpeed = MaximumSpeed)
{
Validate(speed, turn, seconds);
if (!float.IsFinite(maximumSpeed) || maximumSpeed <= 0)
throw new ArgumentOutOfRangeException(nameof(maximumSpeed));
var turnStep = AirSteering.TurnAcceleration * seconds;
if (input.Left) turn += turnStep;
else if (input.Right) turn -= turnStep;
else if (turn < 0) turn = MathF.Min(0, turn + turnStep);
else if (turn > 0) turn = MathF.Max(0, turn - turnStep);
//439ABB..439AE6: mode2 also uses the shared fire predicate as throttle.
var forward = input.Forward || input.Fire;
if (forward && speed < maximumSpeed)
speed = MathF.Min(maximumSpeed, speed + RecoveredMotion.SpeedIncrement);
if (!forward && speed > maximumSpeed * AirSteering.CoastThreshold)
speed -= RecoveredMotion.SpeedDecay * .5f;
//439BA2..439BED: this subtraction deliberately has no crossing clamp.
if (supported) speed = speed > 0 ? speed - RecoveredMotion.SpeedDecay * .5f : 0;
if (input.Backward)
{
if (speed > 0)
speed = MathF.Max(0, speed - RecoveredMotion.SpeedDecay * (supported ? 1 : .5f));
else if (speed < 0)
speed = MathF.Min(0, speed + RecoveredMotion.SpeedDecay);
}
turn = Math.Clamp(turn, -TurnLimit, TurnLimit);
return new(speed, turn, forward ? -10 : input.Backward ? 10 : 0, -.25f * turn);
}
public static BubbleApply StepApply(float speed, float turn, float yaw, float pitch,
Vector3 velocity, bool supported, bool jump, float seconds)
{
Validate(speed, turn, seconds);
if (!float.IsFinite(yaw) || !float.IsFinite(pitch)
|| !float.IsFinite(velocity.X) || !float.IsFinite(velocity.Y) || !float.IsFinite(velocity.Z))
throw new ArgumentOutOfRangeException(nameof(velocity));
float sideSpeed = 0;
//43884E..4388AE: test incoming velocity before replacing its X/Z.
if (velocity != Vector3.Zero)
{
yaw += turn * seconds;
const float friction = .8f;
sideSpeed = turn * .0181818176060915f * (1 - friction) * speed;
}
var (sin, cos) = LabSimulation.Trig(yaw);
var forwardSpeed = LabSimulation.Trig(pitch).Cos * speed;
velocity = new(-sin * forwardSpeed + cos * sideSpeed, velocity.Y,
cos * forwardSpeed + sin * sideSpeed);
//43899A..438A50: direct liveY assignment, after composing current X/Z.
//Only the published scalar halves; current velocity keeps pre-half X/Z.
if (supported)
{
velocity.Y = jump ? HeldBounceSpeed : ReleasedBounceSpeed;
if (!jump) speed *= .5f;
}
return new(velocity, yaw, speed, supported && jump);
}
private static void Validate(float speed, float turn, float seconds)
{
if (!float.IsFinite(speed) || !float.IsFinite(turn) || !float.IsFinite(seconds)
|| seconds < 0 || seconds >= 1)
throw new ArgumentOutOfRangeException(nameof(seconds));
}
}
+4 -3
View File
@@ -5,7 +5,7 @@ namespace GamePort.Game;
public readonly record struct GadgetCanvas(int Id, Vector2 Position);
/// <summary>Bounded group0 gadget panel; source425870/425EF0/425B20/427370.</summary>
public sealed class GadgetScreen(SceneInventory inventory)
public sealed class GadgetScreen(SceneInventory inventory, Func<int>? rawMode = null)
{
public static IReadOnlyList<Vector2> Positions { get; } = Array.AsReadOnly<Vector2>([new(12,182), new(158,182), new(12,327), new(157,327),
new(342,182), new(487,182), new(342,327), new(487,327)]);
@@ -24,7 +24,7 @@ public sealed class GadgetScreen(SceneInventory inventory)
{
if (Open) { Close(); return true; }
if (!permitted) return false;
if (EquippedMode(inventory.SelectedGadget) != -1)
if ((rawMode?.Invoke() ?? EquippedMode(inventory.SelectedGadget)) != -1)
{
inventory.SelectGadget(-1); Changed?.Invoke(); return true;
}
@@ -72,7 +72,8 @@ public sealed class GadgetScreen(SceneInventory inventory)
var item = Hovered;
var practice = PracticeArmed;
Close();
inventory.SelectGadget(item);
//428F61 loads Bubble practice BEFORE live radius/mode/effect setup.
inventory.SelectGadget(item,equip:!(practice && item==0));
if (practice) PracticeRequested?.Invoke(item);
return true;
}
+9
View File
@@ -17,6 +17,8 @@ public sealed class InvisibleGadget
public int Activations { get; private set; }
public bool Active => Equipped && !Targetable;
public event Action<bool>? EquippedChanged;
public event Action<float>? AlphaRequested;
public event Action<bool>? BlendRequested;
public bool Equip(float energy, bool energyOverride)
{
@@ -30,6 +32,8 @@ public sealed class InvisibleGadget
public void Release()
{
BlendRequested?.Invoke(true);
AlphaRequested?.Invoke(0);
Equipped = false; Remaining = Duration; Recharge = 0;
Targetable = true; Opacity = 1; ConventionalBlend = false;
MeterVisible = false; MeterReady = false;
@@ -62,6 +66,7 @@ public sealed class InvisibleGadget
adjustEnergy(-2);
Remaining = Duration; Recharge = 0; Activations++;
ConventionalBlend = false; Opacity = .7f; Targetable = false;
BlendRequested?.Invoke(false); AlphaRequested?.Invoke(.7f);
}
}
if (Remaining == 0 && (energy > 0 || energyOverride))
@@ -79,9 +84,13 @@ public sealed class InvisibleGadget
{
Remaining = 0; Opacity = 1; Targetable = true;
ConventionalBlend = false; MeterReady = false;
BlendRequested?.Invoke(true); AlphaRequested?.Invoke(0);
return;
}
if (Remaining <= 3)
{
ConventionalBlend = ((int)((double)Remaining * 5) & 1) != 0;
BlendRequested?.Invoke(ConventionalBlend);
}
}
}
+125 -13
View File
@@ -23,6 +23,10 @@ public sealed class LabSimulation
private readonly Vector3 sourceStart;
private readonly float startYaw, modelMinimumY, rootHeight, startFloor;
private float targetYaw, extraAirAcceleration, shadowDistance, lateralContribution;
private float targetPitch, targetRoll;
private int? retainedSupportMaterial;
private bool bubbleLoop;
private PlayerPose bubblePose;
private Vector3 pendingImpulse;
private int movementMode;
private JetpackBurstState jumpState;
@@ -36,13 +40,35 @@ public sealed class LabSimulation
public Func<int>? JetpackInventoryState { get; set; }
public string LevelCode { get; set; } = "LV1B";
public InvisibleGadget Invisible { get; } = new();
public BubbleEffect Bubble { 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 bool TracksBubbleOrientation { get; private set; }
public int BubbleBounces { get; private set; }
public int GadgetMode
{
get => gadgetMode;
set
{
var previousPose=Pose;
if (gadgetMode == 0) ReleaseBubble();
if (gadgetMode == 2) Invisible.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;
TracksBubbleOrientation=true;
gadgetMode=0; Bubble.Start();
if (!bubbleLoop) { GadgetSound?.Invoke(2,true); bubbleLoop=true; }
return;
}
if (value == 2 && !Invisible.Equip(Energy, IgnoresGadgetEnergy)) return;
gadgetMode = value;
}
@@ -51,6 +77,10 @@ public sealed class LabSimulation
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;
@@ -76,6 +106,7 @@ public sealed class LabSimulation
public float TurnRate { get; private set; }
public bool Grounded { get; private set; }
public PlayerPose Pose => Noclip ? Velocity.LengthSquared() > 0 ? PlayerPose.Fly : PlayerPose.Idle
: GadgetMode == 0 ? bubblePose
: pendingImpulse.Y > 0 ? PlayerPose.Jump
: Grounded ? Shooting ? PlayerPose.Shoot : Speed < -1 ? PlayerPose.Backpedal : Speed > 1 ? PlayerPose.Run : PlayerPose.Idle
: jumpState.JumpState == 3 && jumpState.EffectRemaining > 0 ? PlayerPose.Fly
@@ -94,7 +125,8 @@ public sealed class LabSimulation
public Vector3 ActorRoot => Position + Vector3.UnitY * rootHeight;
public Vector3 CameraEye { get; private set; }
public Vector3 CameraTarget => ActorRoot + new Vector3(0, 99, 0);
public Matrix4x4 Model => Matrix4x4.CreateRotationY(-Yaw * MathF.PI / 180)
public Matrix4x4 Model => Matrix4x4.CreateRotationZ(-(TracksBubbleOrientation?Roll:0) * MathF.PI / 180)
* Matrix4x4.CreateRotationX(-(TracksBubbleOrientation?Pitch:0) * MathF.PI / 180) * Matrix4x4.CreateRotationY(-Yaw * MathF.PI / 180)
* Matrix4x4.CreateTranslation(Position - new Vector3(0, modelMinimumY, 0));
public LabSimulation(SceneCollision collision, Mesh standingPose, Vector3 start, float yaw,
@@ -107,6 +139,8 @@ public sealed class LabSimulation
this.ceilingRay = ceilingRay;
originalBody = originalCollision == null ? null : new OriginalBodyPhysics(originalCollision);
this.energy = energy ?? new PlayerEnergy();
Invisible.AlphaRequested += Appearance.SetAlpha;
Invisible.BlendRequested += Appearance.SetBlend;
sourceStart = start;
startYaw = yaw;
var bounds = standingPose.Bounds();
@@ -124,8 +158,13 @@ public sealed class LabSimulation
public void Reset()
{
if (gadgetMode == 0) { GadgetMode=-1; DefaultGadgetRequested?.Invoke(); }
if (gadgetMode == 2) gadgetMode = -1;
Invisible.Reset();
Bubble.Reset(); FloorState.Reset(); Appearance.Reset(); retainedSupportMaterial=null;
Pitch=Roll=targetPitch=targetRoll=0; BubbleBounces=0;
TracksBubbleOrientation=false;
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;
@@ -183,24 +222,35 @@ public sealed class LabSimulation
public void Step(PlayerInput input, bool controlled = true, bool? anyControlled = null)
{
if (Noclip) { StepNoclip(input); return; }
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();
if (controlled && !InputAfterPlayerUpdate) StepInput(input);
//42469F..4246DC reasserts ordinary grounded radius before ownership
//checks. Bubble mode0's separate radius160 policy remains unimplemented.
if (Grounded) InteractionRadius = 60;
//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.
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++;
}
@@ -216,6 +266,37 @@ public sealed class LabSimulation
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() { Pitch=Roll=0; }
public void SeedBubbleTilt(Vector3 euler)
{
if (TracksBubbleOrientation) return;
Pitch=targetPitch=euler.X; Roll=targetRoll=euler.Z;
}
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
@@ -224,9 +305,7 @@ public sealed class LabSimulation
CeilingHits++;
//425120 leaves hold, mode, pending impulse and acceleration intact.
//Full sound/selected-gadget cleanup callbacks remain a separate gap.
if (movementMode != 1) return;
jumpState = jumpState with { JumpState = 0, EffectRemaining = 0 };
forceFall = true;
CancelPoweredFlight();
}
/// <summary>Authored AI root/Euler writes. They do not reset body motion or
@@ -244,6 +323,7 @@ public sealed class LabSimulation
if (enabled == Noclip) return false;
if (enabled)
{
if (gadgetMode==0) { GadgetMode=-1; DefaultGadgetRequested?.Invoke(); }
noclipEntry = Position; noclipEntryYaw = Yaw; HasNoclipEntry = true;
}
var returned = !enabled && !collision.CanOccupy(Position, BodyRadius, BodyHeight);
@@ -257,6 +337,7 @@ public sealed class LabSimulation
public void StopDebugMotion()
{
if (gadgetMode==0) { GadgetMode=-1; DefaultGadgetRequested?.Invoke(); }
Shooting = false;
Velocity = pendingImpulse = Vector3.Zero;
Speed = PublishedSpeed = TurnRate = extraAirAcceleration = lateralContribution = 0;
@@ -298,23 +379,41 @@ public sealed class LabSimulation
//438A60 dispatches by stored movement mode, not current support.
if (movementMode == 0)
{
if (TracksBubbleOrientation && (input.Forward || input.Left || input.Right
|| input.Backward && !(GadgetMode is -1 or 3 && input.Fire))) targetPitch=targetRoll=0;
float yawDelta = 0;
if (input.Left) { yawDelta += 20; lateralContribution = -1000; Speed = RecoveredMotion.AddSpeed(Speed); }
else if (input.Right) { yawDelta -= 20; lateralContribution = 1000; Speed = RecoveredMotion.AddSpeed(Speed); }
if (input.Forward) { yawDelta *= 0.5f; Speed = RecoveredMotion.AddSpeed(Speed); }
if (input.Left) { yawDelta += 20; lateralContribution = -1000; Speed = RecoveredMotion.AddSpeed(Speed,MaximumSpeed); }
else if (input.Right) { yawDelta -= 20; lateralContribution = 1000; Speed = RecoveredMotion.AddSpeed(Speed,MaximumSpeed); }
if (input.Forward) { yawDelta *= 0.5f; Speed = RecoveredMotion.AddSpeed(Speed,MaximumSpeed); }
if (yawDelta != 0) targetYaw = Yaw + yawDelta;
if (input.Backward) Speed = MathF.Max(Speed - 52.5f, -300);
else if (!input.Forward) Speed = RecoveredMotion.ReleaseSpeed(Speed);
}
else if (movementMode==2)
{
var steering=BubbleMotion.StepInput(Speed,TurnRate,input,Grounded,dt,MaximumSpeed);
Speed=steering.Speed; TurnRate=steering.TurnRate;
targetPitch=steering.TargetPitch; targetRoll=steering.TargetRoll; targetYaw=Yaw;
}
else
{
var steering = AirSteering.Step(Speed, TurnRate, input, dt);
var steering = AirSteering.Step(Speed, TurnRate, input, dt,MaximumSpeed);
Speed = steering.Speed; TurnRate = steering.TurnRate;
if (TracksBubbleOrientation) { targetPitch=0; targetRoll=-TurnRate; }
//439E2B preserves current yaw as the destination; air apply then
//438011..43802B adds the independent turn rate directly to yaw.
targetYaw = Yaw;
}
StepCamera(); //438BC0/439900 input path owns follow; still provisional geometry/state.
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);
}
@@ -322,6 +421,18 @@ public sealed class LabSimulation
{
ControllerSteps++;
const float dt = FixedStepClock.Step;
if (TracksBubbleOrientation)
{
Pitch+=(targetPitch-Pitch)*dt*4.5f;
Roll+=(targetRoll-Roll)*dt*4.5f;
}
if (movementMode==2)
{
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;
}
var yawError = MathF.IEEERemainder(targetYaw - Yaw, 360);
Yaw = (Yaw + yawError * dt * 3.7f) % 360;
//437A96 selects air mode on held jump;437B9E..BAC resets jump/mode/turn
@@ -405,7 +516,8 @@ public sealed class LabSimulation
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);
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;
+2
View File
@@ -34,6 +34,8 @@ public sealed class OriginalBodyPhysics
this.collision = collision;
}
public int? MaterialFor(SupportHit hit) => collision.MaterialFor(hit);
public OrdinaryBodyStep Step(OrdinaryBodyState body, float seconds,
float radius = OriginalBodySupport.JimmyRadius, float factor = OriginalBodySupport.JimmyFactor,
float friction = .8f, float suppressionScale = .5f, bool geometryEnabled = true)
+3 -3
View File
@@ -58,15 +58,15 @@ public sealed class OriginalCameraRay
}
/// <summary>
/// LV1B/VR04/LEV1 complete game slot134 is475CD0 (false), so only the proven
/// LV1B/VR01/VR04/LEV1 complete game slot134 is475CD0 (false), so only the proven
/// NC/checkpoint gates apply. Reject other levels rather than inventing masks.
/// Prepared source metadata is required; raw render visibility is irrelevant.
/// </summary>
public static OriginalCameraRay FromRouteScene(Mesh mesh, string levelCode)
{
ArgumentNullException.ThrowIfNull(mesh);
if (levelCode is not ("LV1B" or "VR04" or "LEV1"))
throw new NotSupportedException("Static camera game-filter recovery currently covers LV1B, VR04 and LEV1");
if (levelCode is not ("LV1B" or "VR01" or "VR04" or "LEV1"))
throw new NotSupportedException("Static camera game-filter recovery covers the route and VR01");
if (mesh.Indices.Length % 3 != 0 || mesh.CollisionPolygons.Length != mesh.Indices.Length / 3)
throw new InvalidDataException("Original camera query requires source polygon metadata");
var polygons = new CameraRayPolygon[mesh.CollisionPolygons.Length];
+6 -2
View File
@@ -23,6 +23,7 @@ public sealed class OriginalStaticCollision
{
private readonly Dictionary<int, List<CameraRayPolygon>> walls = [];
private readonly Dictionary<int, List<SupportTriangle>> all = [];
private readonly Dictionary<(int Shape,int Polygon),int?> materialIds = [];
public int PolygonCount { get; }
public int WallPolygonCount { get; }
public bool HasSpecialPlayerContacts { get; }
@@ -38,6 +39,7 @@ public sealed class OriginalStaticCollision
Finite(t.A); Finite(t.B); Finite(t.C); Finite(polygon.StoredNormal);
if (!identities.Add((t.ShapeId, t.PolygonId)))
throw new InvalidDataException("Source static collision needs one triangle per polygon");
materialIds.Add((t.ShapeId,t.PolygonId),polygon.MaterialId);
var min = Vector3.Min(t.A, Vector3.Min(t.B, t.C));
var max = Vector3.Max(t.A, Vector3.Max(t.B, t.C));
foreach (var cell in Rectangle(new(Cell(min.X), Cell(max.X), Cell(min.Z), Cell(max.Z))))
@@ -59,8 +61,8 @@ public sealed class OriginalStaticCollision
public static OriginalStaticCollision FromRouteScene(Mesh mesh, string level)
{
ArgumentNullException.ThrowIfNull(mesh);
if (level is not ("LV1B" or "VR04" or "LEV1"))
throw new NotSupportedException("Original static game-filter recovery covers only the three route scenes");
if (level is not ("LV1B" or "VR01" or "VR04" or "LEV1"))
throw new NotSupportedException("Original static game-filter recovery covers the route and VR01");
if (mesh.Indices.Length % 3 != 0 || mesh.CollisionPolygons.Length != mesh.Indices.Length / 3)
throw new InvalidDataException("Source static collision requires original polygon metadata");
if (!mesh.HasCollisionMaterialIds)
@@ -76,6 +78,8 @@ public sealed class OriginalStaticCollision
}));
}
public int? MaterialFor(SupportHit hit) => materialIds.GetValueOrDefault((hit.ShapeId,hit.PolygonId));
public StaticCollisionMove Move(Vector3 previous, Vector3 delta, float radius,
StaticCollisionContext context, bool edges = true, bool lowerEdges = false, bool geometryEnabled = true)
{
+31
View File
@@ -0,0 +1,31 @@
using System.Numerics;
using GamePort.Assets;
namespace GamePort.Game;
/// <summary>Stored current-atlas material state. Source alpha/FC requests and
/// late direct RGBA writes have different owners and must retain their order.</summary>
public sealed class PlayerAppearance
{
public Vector4 Color { get; private set; } = Vector4.One;
public bool BlendEnabled { get; private set; }
public bool Conventional { get; private set; }
public MeshBlend Blend => !BlendEnabled ? MeshBlend.Opaque : Conventional ? MeshBlend.Alpha : MeshBlend.Additive;
public void SetAlpha(float alpha)
{
if (!float.IsFinite(alpha) || alpha > 1) throw new ArgumentOutOfRangeException(nameof(alpha));
BlendEnabled = alpha > 0;
Color = alpha > 0 ? new(1,1,1,alpha) : Vector4.One;
Conventional = alpha <= 0;
}
public void SetBlend(bool conventional) => Conventional = conventional;
public void SetColor(Vector4 color)
{
if (!float.IsFinite(color.X+color.Y+color.Z+color.W)
|| color.X<0 || color.Y<0 || color.Z<0 || color.W<0 || color.W>1)
throw new ArgumentOutOfRangeException(nameof(color));
Color = color;
}
public void Reset() { Color=Vector4.One; BlendEnabled=false; Conventional=false; }
}
+14 -4
View File
@@ -20,6 +20,7 @@ public sealed class PlayerSceneBinding : IDisposable
director.GadgetReleaseRequested += Release;
inventory.GadgetSelected += Selected;
player.Invisible.EquippedChanged += InvisibleEquipped;
player.DefaultGadgetRequested += DefaultGadget;
Selected(inventory.SelectedGadget);
}
@@ -27,8 +28,10 @@ public sealed class PlayerSceneBinding : IDisposable
{
var acceptsInput = director.Controlled || player.Noclip;
player.Step(input, acceptsInput, director.ControlledTag != null);
var rotation = director.FindActor(tag)?.Rotation ?? Vector3.Zero;
director.SyncActor(tag, player.ActorRoot, rotation with { Y = player.Yaw });
if (player.GadgetMode==0 && player.Grounded && director.FindActor(tag) is{} actor) actor.Animation="STOP";
var rotation=director.FindActor(tag)?.Rotation ?? Vector3.Zero;
director.SyncActor(tag,player.ActorRoot,player.TracksBubbleOrientation
? new(player.Pitch,player.Yaw,player.Roll) : rotation with{Y=player.Yaw});
return acceptsInput;
}
@@ -36,6 +39,7 @@ public sealed class PlayerSceneBinding : IDisposable
{
if (!string.Equals(actor.Tag, tag, StringComparison.OrdinalIgnoreCase)) return;
if (action == ScriptPreparation.StopMotion) player.PrepareForScript();
else if (action == ScriptPreparation.FlattenOrientation) player.FlattenOrientation();
else if (action == ScriptPreparation.ReleaseGadget)
Release(actor);
}
@@ -45,12 +49,17 @@ public sealed class PlayerSceneBinding : IDisposable
if (!string.Equals(actor.Tag, tag, StringComparison.OrdinalIgnoreCase)) return;
//427FF0 switches raw mode, not display selection. A rejected Invisible
//equip can leave display2 with raw mode-1; cleanup does not equip it.
if (player.GadgetMode == 2 || inventory.SelectedGadget is -1 or 3)
if (player.GadgetMode is 0 or 2 || inventory.SelectedGadget is -1 or 3)
{ inventory.SelectGadget(-1); player.GadgetMode = -1; }
else if (player.GadgetMode != -1) UnsupportedGadgetCleanups++;
}
private void Selected(int item) => player.GadgetMode = GadgetScreen.EquippedMode(item);
private void Selected(int item)
{
if (item==0 && director.FindActor(tag) is{} actor) player.SeedBubbleTilt(actor.Rotation);
player.GadgetMode=GadgetScreen.EquippedMode(item);
}
private void DefaultGadget() => inventory.SelectGadget(-1);
private void InvisibleEquipped(bool equipped)
{
@@ -74,5 +83,6 @@ public sealed class PlayerSceneBinding : IDisposable
director.GadgetReleaseRequested -= Release;
inventory.GadgetSelected -= Selected;
player.Invisible.EquippedChanged -= InvisibleEquipped;
player.DefaultGadgetRequested -= DefaultGadget;
}
}
+1 -1
View File
@@ -18,7 +18,7 @@ public static class RecoveredMotion
// Deliberately per invocation: original increments omit dt. Call cadence is
// not yet verified. Rendering must not directly choose simulation cadence.
public static float AddSpeed(float speed) => MathF.Min(speed + SpeedIncrement, MaximumSpeed);
public static float AddSpeed(float speed, float maximumSpeed = MaximumSpeed) => MathF.Min(speed + SpeedIncrement, maximumSpeed);
public static float ReleaseSpeed(float speed) => speed > 0
? MathF.Max(0, speed - SpeedDecay) : MathF.Min(0, speed + SpeedDecay);
+2 -2
View File
@@ -54,12 +54,12 @@ public sealed class SceneInventory
}
}
public void SelectGadget(int item)
public void SelectGadget(int item, bool equip = true)
{
if (item != -1 && (item is < 0 or >= 9 || State(0, item) == 0))
throw new ArgumentOutOfRangeException(nameof(item), "Gadget is outside the recovered group or unavailable");
SelectedGadget = item;
GadgetSelected?.Invoke(item);
if (equip) GadgetSelected?.Invoke(item);
}
public int[] Snapshot() => states.ToArray();
+41
View File
@@ -0,0 +1,41 @@
using System.Numerics;
namespace GamePort.Game;
public readonly record struct Vr01FloorEffect(bool Entered, bool Damaged);
/// <summary>Textured retained-support callback for actual VR01 IDs0..4/111.
/// Other damage flags, floor classes and footstep-loop playback remain outside.</summary>
public sealed class Vr01FloorState
{
public bool InLava { get; private set; }
public bool Flashing { get; private set; }
public float Timer { get; private set; }
public int SoundSelector { get; private set; } = 5;
public Vr01FloorEffect Visit(int? material, int rawMode)
{
//Null means no eligible textured support. The actual VR01 profile's
//used material IDs all have source-verified texture links.
if (material == null) return default;
if (material is not (0 or 1 or 2 or 3 or 4 or 111))
throw new NotSupportedException("Outside the recovered VR01 floor profile");
var lava = material == 111;
var entered = lava && !InLava;
var damaged = lava && !Flashing && rawMode != 0;
InLava = lava; SoundSelector = lava ? 35 : 5;
if (damaged) { Flashing=true; Timer=0; }
return new(entered,damaged);
}
public void Step(float seconds, Action<Vector4> color)
{
if (!float.IsFinite(seconds) || seconds<0 || seconds>=1) throw new ArgumentOutOfRangeException(nameof(seconds));
ArgumentNullException.ThrowIfNull(color);
if (!Flashing) return;
var sum = (double)Timer + seconds;
Timer = (float)sum;
if (sum>4) { Flashing=false; color(Vector4.One); return; }
var pulse = (float)((Math.Sin(sum*20)+1)*.5);
color(new(pulse,1,pulse,1));
}
public void Reset() { InLava=Flashing=false; Timer=0; SoundSelector=5; }
}
+59 -9
View File
@@ -88,6 +88,7 @@ internal static class Program
--smoke-jetpack 300-step powered steering/jump check in VR04
--smoke-shrink-ray Fire at an actual VR04 soldier; explicit player-placement fixture
--smoke-invisible Accelerated recharge/activation/flash/expiry/unequip fixture in VR03
--smoke-bubble VR01 expand/throttle/bounce/cleanup/fade input fixture
--gadget-menu Render original gadget panel (--skip-intro); fixture owns item3
--smoke-gadget-menu SDL menu input/pause/selection/practice/Return check (24 frames)
--smoke-jump-key NAME Replay using shift/right-shift/insert/keypad0/right-mouse
@@ -258,6 +259,7 @@ internal static class Program
var jetpackSmoke = args.Contains("--smoke-jetpack");
var shrinkSmoke = args.Contains("--smoke-shrink-ray");
var invisibleSmoke = args.Contains("--smoke-invisible");
var bubbleSmoke = args.Contains("--smoke-bubble");
var carlSmoke = args.Contains("--smoke-carl-cutscene");
var controlPhaseSmoke = args.Contains("--smoke-control-phases");
var objectiveWindowSmoke = args.Contains("--smoke-objective-window");
@@ -278,7 +280,7 @@ internal static class Program
var defaultStory = (defaultScene || args.Contains("--walk")) && !args.Contains("--inspect") && !walkSmoke && !args.Contains("--smoke-window")
&& animationPath == null && !args.Contains("--time");
var story = defaultStory || loadedSave != null || saveOutput != null || args.Contains("--story") || args.Contains("--story-time")
|| args.Contains("--skip-intro") || jetpackSmoke || shrinkSmoke || invisibleSmoke || gadgetWindowSmoke || practiceWindowSmoke || practiceReturnSmoke || carlSmoke || controlPhaseSmoke || objectiveSmoke;
|| args.Contains("--skip-intro") || jetpackSmoke || shrinkSmoke || invisibleSmoke || bubbleSmoke || gadgetWindowSmoke || practiceWindowSmoke || practiceReturnSmoke || carlSmoke || controlPhaseSmoke || objectiveSmoke;
if (story && (args.Contains("--inspect") || walkSmoke || args.Contains("--smoke-window")))
throw new ArgumentException("Story playback requires its own simulation mode.");
if (walkSmoke && args.Contains("--inspect")) throw new ArgumentException("Walk smoke cannot run in inspection mode.");
@@ -307,6 +309,7 @@ internal static class Program
ShrinkRayVisuals? rayVisuals = null;
ShrinkSoldierVisuals? soldierVisuals = null;
JetpackVisuals? jetpackVisuals = null;
BubbleVisuals? bubbleVisuals = null;
var practice = new PracticePrompt();
ObjectivePanel? objectivePanel = null;
var patrols = new Dictionary<string, ActorPatrol>(StringComparer.OrdinalIgnoreCase);
@@ -335,13 +338,13 @@ internal static class Program
var standingPose = AseMesh.Load(AssetPath.Resolve(root, "ASE/jimstop.ase"));
if (walking)
{
var cameraRay = level!.Code is "LV1B" or "VR04" or "LEV1"
var cameraRay = level!.Code is "LV1B" or "VR01" or "VR04" or "LEV1"
? OriginalCameraRay.FromRouteScene(world, level.Code) : null;
debugCameraRay = cameraRay;
simulation = new LabSimulation(new SceneCollision(world), standingPose, originalStart.Position, originalStart.Rotation.Y,
cameraRay == null ? null : (look, eye) => cameraRay.Trace(look, eye),
cameraRay == null ? null : (start, end) => cameraRay.TraceGeometry(start, end),
level.Code == "VR04" ? OriginalStaticCollision.FromRouteScene(world,level.Code) : null, energy)
level.Code is "VR01" or "VR04" ? OriginalStaticCollision.FromRouteScene(world,level.Code) : null, energy)
{ LevelCode = level.Code, InputAfterPlayerUpdate = carriedSave != null };
if (carriedPlayer != null)
{
@@ -374,12 +377,13 @@ internal static class Program
storyTasks = tasks;
director = new SceneDirector(level!, tasks, resources.Duration);
interactions = new SceneInteractions(director, tasks, save);
gadgetScreen = new GadgetScreen(interactions.Inventory);
gadgetScreen = new GadgetScreen(interactions.Inventory,()=>simulation!.GadgetMode);
interactions.Inventory.ApplyLevelAvailability(level!.Code);
objectivePanel = new ObjectivePanel(interactions.CurrentObjective);
interactions.ObjectiveChanged += objectivePanel.Select;
simulation!.Energy = interactions.Energy;
simulation.JetpackInventoryState = () => interactions.Inventory.State(0, 3);
simulation.ScoreChanged += interactions.ChangeScore;
if (level.Code is "LV1B" or "VR04" or "LEV1")
{
gadgets = new SceneGadgets(director,interactions.Inventory,simulation,world);
@@ -439,6 +443,8 @@ internal static class Program
DynamicBodyResponse.Resolve(staticVisuals.DoorColliders(), previous, position, radius);
jetpackVisuals = new JetpackVisuals(mesh, Path.GetFullPath(Path.Combine(Path.GetDirectoryName(scene!)!, "..")));
mesh = jetpackVisuals.Mesh;
bubbleVisuals = new(mesh,Path.GetFullPath(Path.Combine(Path.GetDirectoryName(scene!)!,"..")));
mesh = bubbleVisuals.Mesh;
if (gadgets != null)
{
rayVisuals = new ShrinkRayVisuals(mesh,Path.GetFullPath(Path.Combine(Path.GetDirectoryName(scene!)!, "..")),root);
@@ -480,13 +486,15 @@ internal static class Program
var storyTime = double.Parse(Option(args, "--story-time") ?? "0", System.Globalization.CultureInfo.InvariantCulture);
if (!double.IsFinite(storyTime) || storyTime < 0 || storyTime > 3600 || storyTime > 0 && !headless)
throw new ArgumentException("Story time must be0..3600 seconds in headless mode.");
var frames = int.Parse(Option(args, "--frames") ?? (walkSmoke ? "240" : jetpackSmoke ? "300" : shrinkSmoke ? "90" : invisibleSmoke ? "8" : gadgetWindowSmoke ? "24" : objectiveWindowSmoke ? "180" : carlSmoke ? "60" : controlPhaseSmoke ? "32" : toolsSmoke ? "20" : debugSmoke ? "16" : diagnosticsSmoke ? "24" : headless ? "1" : "0"));
var frames = int.Parse(Option(args, "--frames") ?? (walkSmoke ? "240" : jetpackSmoke ? "300" : shrinkSmoke ? "90" : invisibleSmoke || bubbleSmoke ? "8" : gadgetWindowSmoke ? "24" : objectiveWindowSmoke ? "180" : carlSmoke ? "60" : controlPhaseSmoke ? "32" : toolsSmoke ? "20" : debugSmoke ? "16" : diagnosticsSmoke ? "24" : headless ? "1" : "0"));
if (gadgetWindowSmoke && (headless || level?.Code != "LV1B" || loadedSave != null || frames < 24))
throw new ArgumentException("Gadget menu SDL fixture requires a fresh windowed lab and24 frames");
if (shrinkSmoke && (level?.Code != "VR04" || gadgets == null || frames < 60))
throw new ArgumentException("Shrink-ray smoke requires actual VR04 and at least60 frames");
if (invisibleSmoke && (level?.Code != "VR03" || frames < 8 || loadedSave != null))
throw new ArgumentException("Invisible smoke requires a fresh VR03 and at least8 frames");
if (bubbleSmoke && (level?.Code!="VR01" || frames<8 || loadedSave!=null))
throw new ArgumentException("Bubble smoke requires a fresh VR01 and at least8 frames");
if (controlPhaseSmoke && (level?.Code != "LV1B" || loadedSave != null || frames < 32 || director == null))
throw new ArgumentException("Control-phase fixture needs a fresh lab and at least32 frames");
if (toolsSmoke && (headless || frames < 16 || director == null || level?.Code != "LV1B" || loadedSave != null || debugMenu.Open))
@@ -520,12 +528,19 @@ internal static class Program
var shrinkPhaseMask = 0;
var sawShrinkKey = false;
InvisibleSmoke? invisibleFixture = null;
BubbleSmoke? bubbleFixture = null;
var sawBubbleKeys=0;
Console.WriteLine($"Scene presentation: revision={renderer.SceneRevision}, windows={presentation.WindowCreationCount}, renderers={presentation.RendererCreationCount}, window ID={(window == 0 ? 0 : Sdl.SDL_GetWindowID(window))}, size={renderer.Width}x{renderer.Height}.");
{
using var audio = Option(args, "--audio") is { } audioFile
? new SdlAudio(audioFile, args.Contains("--loop-audio"), debugMenu.Open) : null;
using var sceneAudio = resources != null && !headless && !args.Contains("--mute") ? new SceneAudio(resources) : null;
sceneAudio?.SetPaused(debugMenu.Open);
if (simulation!=null)
{
simulation.GadgetSound += (id,loop) => sceneAudio?.Effect(id,loop?"bubble":null);
simulation.BubbleSoundStopped += () => sceneAudio?.StopLoop("bubble");
}
if (gadgets != null)
{
gadgets.Sound += (id,loop) => sceneAudio?.Effect(id,loop ? "shrink-ray" : null);
@@ -568,7 +583,7 @@ internal static class Program
Console.WriteLine($"Practice RETURN: exact saved root={restored}, root={simulation.ActorRoot}, STRT yaw={simulation.Yaw}, intro suppressed={!director.Playing}, companion restored={companionRestored}, retained player input order={simulation.InputAfterPlayerUpdate}, gadget availability={interactions.Inventory.State(0, 3)}.");
if (!restored) throw new InvalidOperationException("RETURN did not restore the live departure root without replaying STRT actions");
}
if (args.Contains("--skip-intro") || jetpackSmoke || shrinkSmoke || invisibleSmoke || gadgetWindowSmoke || debugSmoke || diagnosticsSmoke || toolsSmoke || controlPhaseSmoke) { sceneAudio?.StopSpeech(); director.Skip(); }
if (args.Contains("--skip-intro") || jetpackSmoke || shrinkSmoke || invisibleSmoke || bubbleSmoke || gadgetWindowSmoke || debugSmoke || diagnosticsSmoke || toolsSmoke || controlPhaseSmoke) { sceneAudio?.StopSpeech(); director.Skip(); }
if (gadgetWindowSmoke) { interactions!.Inventory.SetState(0,3,1); interactions.Inventory.SelectGadget(3); }
if (controlPhaseSmoke)
{
@@ -649,6 +664,7 @@ internal static class Program
gadgetScreen.Point(new(200,380), level!.Code, storyTasks!.Get("SCENE"));
}
if (invisibleSmoke) invisibleFixture = new(simulation!,interactions!.Inventory);
if (bubbleSmoke) bubbleFixture = new(simulation!,interactions!.Inventory);
if (shrinkSmoke)
{
//Explicit test placement near an ACTUAL authored soldier.
@@ -822,6 +838,11 @@ internal static class Program
: "INVISIBLE OWNED - ENERGY REQUIRED TO EQUIP"; break;
case DebugAction.UnequipGadget when interactions != null:
interactions.Inventory.SelectGadget(-1); debugMenu.Message = "GADGET UNEQUIPPED"; break;
case DebugAction.GiveBubble when interactions != null:
interactions.Inventory.SetState(0,0,1); interactions.Inventory.SelectGadget(0);
debugMenu.Message = simulation?.GadgetMode==0 ? "BUBBLE EQUIPPED - FIRE/UP ACCELERATES, JUMP BOUNCES HIGH"
: simulation?.Bubble.Collapsing==true ? "WAIT FOR THE BUBBLE TO FADE BEFORE REEQUIPPING" : "ENERGY REQUIRED TO EQUIP";
break;
case DebugAction.CameraObstruction when debugCameraRay != null:
debugCameraRay.Enabled = !debugCameraRay.Enabled; debugMenu.Message = "STATIC CAMERA QUERY TOGGLED"; break;
case DebugAction.MuteMusic or DebugAction.MuteSpeech or DebugAction.MuteEffects when sceneAudio != null:
@@ -887,6 +908,11 @@ internal static class Program
}
while (running)
{
bubbleFixture?.BeforeFrame(count,(key,down)=>
{
var e=new Sdl.Event{Type=down?Sdl.KeyDown:Sdl.KeyUp,Scancode=key,Down=down?(byte)1:(byte)0};
if(!Sdl.SDL_PushEvent(ref e))throw new InvalidOperationException(Sdl.Error);
},headless);
invisibleFixture?.BeforeFrame(count,(key,down)=>
{
var e = new Sdl.Event {Type=down?Sdl.KeyDown:Sdl.KeyUp,Scancode=key,Down=down?(byte)1:(byte)0};
@@ -938,6 +964,8 @@ internal static class Program
}
while (!headless && Sdl.SDL_PollEvent(out var e))
{
if (bubbleSmoke && e.Type==Sdl.KeyDown)
sawBubbleKeys |= e.Scancode switch {224=>1,80=>2,225=>4,43=>8,_=>0};
if (e.Type is Sdl.Quit or 0x210) running = false;
if (e.Type is Sdl.WindowResized or Sdl.WindowPixelSizeChanged) renderer.Resize();
if (e.Type is Sdl.WindowFocusLost or Sdl.WindowMinimized)
@@ -1062,12 +1090,13 @@ internal static class Program
}
}
if (debugMenu.Open) animationStarted += elapsed;
if (simulation != null && !debugMenu.Open && !inspecting && !practice.Active && gadgetScreen?.Open != true && (active || headless || walkSmoke || jetpackSmoke || shrinkSmoke || invisibleSmoke || gadgetWindowSmoke || objectiveWindowSmoke || debugSmoke || diagnosticsSmoke || toolsSmoke))
if (simulation != null && !debugMenu.Open && !inspecting && !practice.Active && gadgetScreen?.Open != true && (active || headless || walkSmoke || jetpackSmoke || shrinkSmoke || invisibleSmoke || bubbleSmoke || gadgetWindowSmoke || objectiveWindowSmoke || debugSmoke || diagnosticsSmoke || toolsSmoke))
{
var steps = headless || walkSmoke || jetpackSmoke || shrinkSmoke || invisibleSmoke || gadgetWindowSmoke || practiceWindowSmoke || carlSmoke || controlPhaseSmoke || objectiveWindowSmoke || debugSmoke || diagnosticsSmoke || toolsSmoke ? 1 : stepClock.Advance(elapsed);
var steps = headless || walkSmoke || jetpackSmoke || shrinkSmoke || invisibleSmoke || bubbleSmoke || gadgetWindowSmoke || practiceWindowSmoke || carlSmoke || controlPhaseSmoke || objectiveWindowSmoke || debugSmoke || diagnosticsSmoke || toolsSmoke ? 1 : stepClock.Advance(elapsed);
for (var step = 0; step < steps; step++)
{
var input = carlSmoke || controlPhaseSmoke ? new PlayerInput(true, false, true, false, true)
: bubbleSmoke && headless ? BubbleSmoke.Input(count)
: invisibleSmoke && headless ? new PlayerInput(false,false,false,false,false,Fire:count==1)
: shrinkSmoke && headless ? new PlayerInput(false,false,false,false,false,Fire:true)
: jetpackSmoke && headless ? LabSimulation.JetpackSmokeInput(simulation.Steps)
@@ -1149,6 +1178,7 @@ internal static class Program
if (gadgets != null) rayVisuals!.Update(mesh,gadgets.Ray,simulation!.Steps / 60d);
if (shrinkSmoke && gadgets!.Ray.Visible) shrinkPhaseMask |= 1 << gadgets.Ray.TexturePhase;
jetpackVisuals?.Update(mesh, simulation!);
bubbleVisuals?.Update(mesh,simulation!.Bubble,simulation.BubbleRoot,renderEye,renderTarget);
spriteVisuals?.FaceCamera(renderEye, renderTarget, mesh);
objectivePanel?.Key(keys.Contains(18) && !debugMenu.Open && !inspecting && !practice.Active && gadgetScreen?.Open != true
&& director is { Controlled: true, InventoryEnabled: true });
@@ -1179,6 +1209,9 @@ internal static class Program
BurnRemaining = simulation?.JetpackRemaining ?? 0, JetpackAvailability = interactions?.Inventory.State(0, 3) ?? 0,
InvisibleRemaining = simulation?.Invisible.Remaining ?? 0, InvisibleRecharge = simulation?.Invisible.Recharge ?? 0,
Targetable = simulation?.Invisible.Targetable ?? true,
BubblePhase = simulation?.Bubble.Active==true ? "ACTIVE" : simulation?.Bubble.Expanding==true ? "EXPAND"
: simulation?.Bubble.Collapsing==true ? "FADE" : "OFF",
BodyRadius = simulation?.InteractionRadius ?? 60, BodyFactor=simulation?.BodyFactor ?? 1.265f,
Objective = interactions?.CurrentObjective ?? 0, ObjectiveTime = objectivePanel?.Elapsed ?? 0,
CameraObstruction = debugCameraRay?.Enabled, CameraPolygons = debugCameraRay?.PolygonCount ?? 0,
CameraWallPolygons = debugCameraRay?.WallPolygonCount ?? 0, CameraTests = debugCameraRay?.LastTriangleTests ?? 0,
@@ -1208,9 +1241,20 @@ internal static class Program
mesh.Vertices.AsSpan(characterOffset, animations.Current.Base.Vertices.Length), characterModel);
}
if (simulation != null && characterDraw != null)
PlayerGadgetMaterial.Apply(characterDraw, simulation.Invisible);
{
PlayerGadgetMaterial.Apply(characterDraw,simulation.Appearance);
var color=simulation.Appearance.Color;
for(var i=0;i<animations!.Current.Base.Vertices.Length;i++)
mesh.Vertices[characterOffset+i].Color *= new Vector3(color.X,color.Y,color.Z);
}
renderer.UpdateVertices(mesh.Vertices);
renderer.Render(view * projection);
if (bubbleFixture!=null)
{
bubbleFixture.AfterFrame(count);
if(BubbleSmoke.StageName(count) is{} stage && Option(args,"--screenshot") is{} capture)
renderer.SavePpm(Path.ChangeExtension(capture,$".{stage}.ppm"));
}
if (invisibleFixture != null)
{
invisibleFixture.AfterFrame(count,characterDraw!);
@@ -1485,6 +1529,12 @@ internal static class Program
if (!headless) Console.WriteLine($"Invisible SDL primary received: {sawShrinkKey}.");
if (!invisibleFixture.Passed || !headless && !sawShrinkKey) return 2;
}
if (bubbleFixture!=null)
{
Console.WriteLine(bubbleFixture.Report);
if(!headless)Console.WriteLine($"Bubble SDL input received: {sawBubbleKeys==15}.");
if(!bubbleFixture.Passed || !headless && sawBubbleKeys!=15)return 2;
}
if (shrinkSmoke)
{
var renderedHeight = soldierVisuals!.RenderedHeight(shrinkVictim!.Actor.Tag,mesh);