Implement Baseball aiming, pooled projectiles and VR07 targets

This commit is contained in:
UnixNight committed 2026-11-02 22:54:19 -05:00
1 parent 50fcb87d90
commit d6ca417e9e
50 files changed
+3149 -32

No files matched your search

@@ -0,0 +1,76 @@
using System.Numerics;
using GamePort.Assets;
using GamePort.Game;
namespace GamePort.Application;
/// <summary>Source stationary crosshair strip and prior-capture pitch label.
/// Original TIME set5 glyphs preserve their green pixels and null-space advance. UiViewport supplies the port's uniform centered widescreen policy.</summary>
public sealed class BaseballAimOverlay
{
private static readonly Dictionary<int,(int Width,int Height,string Hash)> Expected = new()
{
[253]=(15,210,"2e16e11b151c8474ba68fd5017d1a3a6304a594a7f34c3b423f3417c7edfb453"),
[118]=(16,16,"edc60e65dcf7320813a80d4312e3c45951ccfc566ea79dfabf7a22ebc4b96049"),
[127]=(16,16,"1fd058ad5bdc0f8a064ef7d2d52b2b036df3f35515691a366799d7e8aab5297f"),
[120]=(16,16,"62aaeaaf107300a6f4f7ff52e98106c1520a9edbe2137626ee41091cf243e5c5"),
[121]=(16,16,"d78bf1895f5838b9eb8c6a22565a9588dae4fc8f7106697df373f4408aae634c"),
[122]=(16,16,"f6d628639de4e40005f62f63a49308ff9ee0656a36bb6eb7787230b4830a5ed9"),
[123]=(16,16,"9f58cad5621d89b7a7012036daa8532b2397b0d9d267ab7d1aa5a7cd10d7ae87"),
[124]=(16,16,"49cdc9ec812f4ef3826011d542c30afbb10229c4b4ce549e7820233bbaa53dd9"),
[125]=(16,16,"aaef2d59c2636c059b446bed643985ca55d15b2d070b0582b2d8994b3bf74f1e"),
[126]=(16,16,"bade574a4624a3f763ddd9c87fa2f102562b00d8d604e9faf32a43b372de64e0"),
[119]=(16,16,"0a663ddf2df9f1065f5e4ffe27b4d1fa96edd5f19b6323217bad4148f8d2f3d7")
};
private static readonly int[] DigitIds = [118,127,120,121,122,123,124,125,126,119];
private readonly int[] offsets = new int[21];
private readonly uint[] firstIndices = new uint[21];
public Mesh Mesh { get; }
public BaseballAimOverlay(Mesh combined, string preparedRoot)
{
var images = BaseballResourcePixels.Load(preparedRoot,"aimTextures",Expected);
var builder = new BaseballQuadBuilder(combined);
(offsets[0],firstIndices[0]) = builder.AddQuad(builder.AddTexture(images[253]),true);
//TextureId is immutable. Two banks of ten digit quads select exact glyphs
//without modifying shared draws or allocating per-frame geometry.
for(var digit=0;digit<10;digit++)
{
var texture=builder.AddTexture(images[DigitIds[digit]]);
for(var place=0;place<2;place++)
{
var index=1+place*10+digit;
(offsets[index],firstIndices[index])=builder.AddQuad(texture,true);
}
}
Mesh=builder.Build();
}
public void Update(Mesh destination, BaseballGadget device, uint width, uint height)
{
if(destination.Vertices.Length<offsets.Max()+4)throw new ArgumentException("Destination omits Baseball aim vertices",nameof(destination));
var viewport=new UiViewport(width,height);
var pitch=device.DisplayPitch;
if(!float.IsFinite(pitch)||pitch<0||pitch>45)throw new ArgumentOutOfRangeException(nameof(device),"Source pitch label must remain0..45");
var number=(int)pitch;
var y=(int)((45-(double)pitch)*4.3+100);
Quad(0,new(315,100),new(15,210),device.AimVisible);
for(var digit=0;digit<10;digit++)
{
//TIME set5 has a null space pointer; source468939 skips both
//drawing and advance for the positive sign blank.
Quad(1+digit,new(286,y),new(16,16),device.AimVisible&&digit==number/10);
Quad(11+digit,new(302,y),new(16,16),device.AimVisible&&digit==number%10);
}
void Quad(int index,Vector2 position,Vector2 size,bool visible)
{
var draw=destination.Draws.First(d=>d.ScreenSpace&&d.FirstIndex==firstIndices[index]&&d.IndexCount==6);
draw.Visible=visible;
if(!visible)return;
var p=position+viewport.CenterOffset;
var corners=new[]{p,p+new Vector2(size.X,0),p+size,p+new Vector2(0,size.Y)};
for(var corner=0;corner<4;corner++)
destination.Vertices[offsets[index]+corner].Position=viewport.ToNdc(corners[corner]);
}
}
}
+72
View File
@@ -0,0 +1,72 @@
using GamePort.Game;
namespace GamePort.Application;
/// <summary>Actual VR07 input fixture. Extra ticks run ordinary body, input,
/// target-frame and director paths; no actor relocation or timer mutation.</summary>
public sealed class BaseballSmoke
{
private readonly LabSimulation player;
private readonly PlayerSceneBinding binding;
private readonly SceneInventory inventory;
private readonly SceneBaseballs scene;
private readonly SceneDirector director;
private readonly bool[] checks=new bool[8];
private readonly float initialEnergy;
private int extraTicks;
private bool hitObserved;
public BaseballSmoke(LabSimulation player,PlayerSceneBinding binding,SceneInventory inventory,
SceneBaseballs scene,SceneDirector director)
{
this.player=player;this.binding=binding;this.inventory=inventory;this.scene=scene;this.director=director;
initialEnergy=player.Energy;
inventory.SetState(0,6,1);inventory.SelectGadget(6);
}
public void BeforeFrame(int count,Action<uint,bool> key,bool headless)
{
if(count==1&&!headless){key(224,true);key(80,true);}
if(count==2&&!headless){key(80,false);key(82,true);}
if(count==3&&!headless){key(224,false);key(82,false);}
if(count is 4 or 5)Advance(40);
if(count==6){if(headless)inventory.SelectGadget(-1);else key(43,true);}
if(count==7)
{
if(!headless)key(43,false);
Advance(930);
}
}
private void Advance(int ticks)
{
for(var i=0;i<ticks;i++)
{
scene.StepBodies(FixedStepClock.Step);
binding.Step(default);
scene.StepTargets(FixedStepClock.Step);
director.Step(FixedStepClock.Step);
hitObserved|=scene.Hits>0;
extraTicks++;
}
}
public void AfterFrame(int count)
{
var gadget=player.Baseball;
if(count==0)checks[0]=gadget.Equipped&&player.GadgetMode==6&&!gadget.PendingThrow;
if(count==1)checks[1]=gadget.PendingThrow&&gadget.AimVisible&&gadget.SavedPitch==0;
if(count==2)checks[2]=gadget.PendingThrow&&gadget.AimVisible&&gadget.SavedPitch>10&&gadget.DisplayPitch==0;
if(count==3)checks[3]=gadget.Throws==1&&!gadget.PendingThrow&&!gadget.AimVisible&&gadget.Projectiles[0].Visible;
if(count==4)checks[4]=gadget.Projectiles[0].Visible&&gadget.Projectiles[0].Position!=gadget.Projectiles[0].PreviousPosition;
if(count==5)checks[5]=scene.Hits>0&&scene.Targets.Any(t=>t.Remaining>0&&!t.Actor.Visible);
if(count==6)checks[6]=player.GadgetMode==-1&&!gadget.Equipped&&gadget.Projectiles.Any(b=>b.Visible);
if(count==7)checks[7]=hitObserved&&scene.Targets.All(t=>t.Remaining==0&&t.Actor.Visible);
}
public bool Passed=>checks.All(v=>v)&&player.Energy==initialEnergy;
public string Report=>$"Baseball fixture: equipped={checks[0]}, arm={checks[1]}, prior-label/capture={checks[2]}, release={checks[3]}, flight={checks[4]}, actual target hit={checks[5]}, unequip retains ball={checks[6]}, respawn={checks[7]}, hits={scene.Hits}, recovered={scene.Recovered}, extra full player/target ticks={extraTicks}, energy={player.Energy:F3}/{initialEnergy:F3}.";
public static PlayerInput Input(int count)=>new(count==2,false,count==1,false,false,Fire:count is 1 or 2);
public static string? StageName(int count)=>count switch
{0=>"equipped",1=>"arm",2=>"aim",3=>"throw",4=>"flight",5=>"hit",6=>"unequip",7=>"respawn",_=>null};
}
+125
View File
@@ -0,0 +1,125 @@
using System.Numerics;
using System.Security.Cryptography;
using System.Text.Json;
using GamePort.Assets;
using GamePort.Game;
namespace GamePort.Application;
/// <summary>Source25-unit ball sprites. Camera-facing centered quads are a
/// declared port policy; frame selection belongs to source gameplay state.</summary>
public sealed class BaseballVisuals
{
private readonly int[] offsets = new int[20];
private readonly uint[] firstIndices = new uint[20];
private readonly Dictionary<int, int> textures = [];
public Mesh Mesh { get; }
public BaseballVisuals(Mesh combined, string preparedRoot)
{
var resources = BaseballResourcePixels.Load(preparedRoot, "textures", BaseballResourcePixels.Balls);
var builder = new BaseballQuadBuilder(combined);
foreach (var (id, image) in resources.Where(p => p.Key is >= 2 and <= 5))
textures.Add(id, builder.AddTexture(image));
for (var i = 0; i < 20; i++)
(offsets[i], firstIndices[i]) = builder.AddQuad(textures[2], false);
Mesh = builder.Build();
}
public void Update(Mesh destination, IReadOnlyList<BaseballProjectile> balls, Vector3 eye, Vector3 target)
{
if (balls.Count > 20) throw new ArgumentException("Baseball source pool contains20 slots", nameof(balls));
if (destination.Vertices.Length < offsets[^1] + 4) throw new ArgumentException("Destination omits Baseball vertices", nameof(destination));
if (!Finite(eye) || !Finite(target)) throw new ArgumentException("Baseball camera must be finite");
var direction = target - eye;
direction = direction.LengthSquared() < .000001f ? Vector3.UnitZ : 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 * 12.5f; var y = up * 12.5f;
for (var i = 0; i < 20; i++)
{
var draw = destination.Draws.First(d => !d.ScreenSpace && d.FirstIndex == firstIndices[i] && d.IndexCount == 6);
draw.Visible = i < balls.Count && balls[i].Visible;
if (!draw.Visible) continue;
var ball = balls[i];
if (!Finite(ball.Position)) throw new ArgumentException("Baseball position must be finite", nameof(balls));
if (!textures.TryGetValue(ball.CanvasId, out var texture) || texture != draw.TextureId)
throw new InvalidDataException("Baseball frame differs from its fixed source canvas2");
var p = ball.Position; var offset = offsets[i];
destination.Vertices[offset] = new(p-x-y, new(0,1), Vector3.One);
destination.Vertices[offset+1] = new(p+x-y, new(1,1), Vector3.One);
destination.Vertices[offset+2] = new(p+x+y, new(1,0), Vector3.One);
destination.Vertices[offset+3] = new(p-x+y, new(0,0), Vector3.One);
}
}
private static bool Finite(Vector3 value) => float.IsFinite(value.X) && float.IsFinite(value.Y) && float.IsFinite(value.Z);
}
internal static class BaseballResourcePixels
{
internal static readonly Dictionary<int,(int Width,int Height,string Hash)> Balls = new()
{
[2]=(32,32,"68904b758e69139de0b01329b2a9844ecd2a466f31598c24324affaccfa2cab9"),
[3]=(32,32,"005def070e18111fbdb067e75285dad8ec677c1608020f55c3db7a4b9745205c"),
[4]=(32,32,"c368a59d5d7a57824c1c6b56b617cf058f5d5d53e18e5e48989710413490c536"),
[5]=(32,32,"e5da21c359d3215759e5c3c238107f526f7109203c0ff9fa391a3c8bc40c17ed"),
[8]=(64,64,"8d31014cb9b9661ebed902c864bf740f562460e74da3f6b86ed3d2be4d10f0ec")
};
internal static Dictionary<int,PngImage> Load(string preparedRoot, string array,
IReadOnlyDictionary<int,(int Width,int Height,string Hash)> expected)
{
var manifest = Path.GetFullPath(Path.Combine(preparedRoot,"baseball/baseball.json"));
if (new FileInfo(manifest).Length > 256*1024) throw new InvalidDataException("Baseball manifest exceeds limit");
using var document = JsonDocument.Parse(File.ReadAllBytes(manifest), new JsonDocumentOptions { MaxDepth=12 });
var root = document.RootElement;
if (root.GetProperty("schema").GetInt32()!=1 || root.GetProperty(array).GetArrayLength()!=expected.Count)
throw new InvalidDataException("Unsupported Baseball resources");
var directory = Path.GetDirectoryName(manifest)!;
var result = new Dictionary<int,PngImage>();
foreach (var entry in root.GetProperty(array).EnumerateArray())
{
var id = entry.GetProperty("id").GetInt32();
if (!expected.TryGetValue(id,out var source) || result.ContainsKey(id)
|| entry.GetProperty("width").GetInt32()!=source.Width || entry.GetProperty("height").GetInt32()!=source.Height
|| entry.GetProperty("rgbaSha256").GetString()!=source.Hash)
throw new InvalidDataException("Invalid original Baseball canvas");
var path = Path.GetFullPath(Path.Combine(directory,entry.GetProperty("path").GetString()!));
if (!path.StartsWith(directory+Path.DirectorySeparatorChar,StringComparison.Ordinal)
|| new FileInfo(path).Length != source.Width*source.Height*4)
throw new InvalidDataException("Invalid Baseball pixel path/length");
var pixels = File.ReadAllBytes(path);
if (Convert.ToHexStringLower(SHA256.HashData(pixels))!=source.Hash)
throw new InvalidDataException("Baseball pixels differ from original canvas");
result.Add(id,new((uint)source.Width,(uint)source.Height,pixels));
}
return result;
}
}
internal sealed class BaseballQuadBuilder(Mesh source)
{
private readonly List<MeshVertex> vertices = source.Vertices.ToList();
private readonly List<uint> indices = source.Indices.ToList();
private readonly List<MeshDraw> draws = source.HasExplicitDraws ? source.Draws.ToList()
: source.Indices.Length == 0 ? [] : [new(0,(uint)source.Indices.Length,-1)];
private readonly Dictionary<int,PngImage> textures = new(source.Textures);
internal int AddTexture(PngImage image)
{
var id=int.MinValue+17000; while(textures.ContainsKey(id))id++;
textures.Add(id,image); return id;
}
internal (int Offset,uint FirstIndex) AddQuad(int texture, bool screen)
{
var offset=vertices.Count; var first=(uint)indices.Count; var vertex=(uint)offset;
vertices.AddRange([new(Vector3.Zero,new(0,0),Vector3.One),new(Vector3.Zero,new(1,0),Vector3.One),
new(Vector3.Zero,new(1,1),Vector3.One),new(Vector3.Zero,new(0,1),Vector3.One)]);
indices.AddRange([vertex,vertex+1,vertex+2,vertex,vertex+2,vertex+3]);
draws.Add(new(first,6,texture){Visible=false,ScreenSpace=screen,Blend=MeshBlend.Alpha});
return(offset,first);
}
internal Mesh Build() => new(vertices.ToArray(),indices.ToArray()) { HasExplicitDraws=true, Draws=draws.ToArray(),
Textures=textures, CollisionPolygons=source.CollisionPolygons, HasCollisionMaterialIds=source.HasCollisionMaterialIds };
}
+8 -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, GiveBubble }
GiveInvisible, UnequipGadget, GiveBubble, GiveBaseball }
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,
@@ -30,6 +30,7 @@ public sealed record DebugSystems
public float InvisibleRecharge { get; init; }
public bool Targetable { get; init; } = true;
public string BubblePhase { get; init; } = "OFF";
public string BaseballState { get; init; } = "OFF";
public float BodyRadius { get; init; } = 60;
public float BodyFactor { get; init; } = 1.265f;
public int Objective { get; init; }
@@ -55,7 +56,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 => 13, 2 => 9, _ => ItemCount };
public int PageItems => Page switch { 1 => 14, 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];
@@ -118,7 +119,8 @@ 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, 12 => DebugAction.GiveBubble, _ => DebugAction.None
10 => DebugAction.GiveInvisible, 11 => DebugAction.UnequipGadget, 12 => DebugAction.GiveBubble,
13 => DebugAction.GiveBaseball, _ => DebugAction.None
};
if (Page == 2) return Selected switch
{
@@ -157,14 +159,15 @@ public sealed class DebugMenu
: $"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}",
$"BUBBLE {system.BubblePhase} BODY R {F(system.BodyRadius)} FACTOR {system.BodyFactor.ToString("0.000",c)}", ""];
$"BUBBLE {system.BubblePhase} BODY R {F(system.BodyRadius)} FACTOR {system.BodyFactor.ToString("0.000",c)}",
$"BASEBALL {system.BaseballState}", ""];
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 BUBBLE"] : [
"GIVE / SELECT INVISIBLE", "UNEQUIP CURRENT GADGET", "GIVE / SELECT BUBBLE", "GIVE / SELECT BASEBALL"] : [
$"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"];
@@ -25,7 +25,7 @@ public sealed class SceneSpriteVisuals
var textures = new Dictionary<int, PngImage>(combined.Textures);
foreach (var actor in director.Actors)
{
if (actor.Kind is not ("3PIC" or "3ANI") || actor.SourceGam is not { } source) continue;
if (actor.Kind is not ("3PIC" or "3ANI" or "3TAR") || actor.SourceGam is not { } source) continue;
var database = source.Text("SpriteDatabase") ?? "none";
var identities = actor.Kind == "3ANI" ? Enumerable.Range(1, 9)
.Select(i => source.Integer("Sprite" + i, -1)).TakeWhile(i => i >= 0).ToArray()
+138
View File
@@ -0,0 +1,138 @@
using System.Numerics;
namespace GamePort.Game;
/// <summary>Jimmy's raw6 aim/release state (42659F/426744). The twenty owned
/// projectiles survive unequip; this object is reset only with the modern scene.
/// Source evidence and precision boundaries: gameplay/baseball.md.</summary>
public sealed class BaseballGadget
{
public const int PoolSize = 20;
private readonly BaseballProjectile[] projectiles = Enumerable.Range(0, PoolSize).Select(_ => new BaseballProjectile()).ToArray();
public IReadOnlyList<BaseballProjectile> Projectiles => projectiles;
public bool Equipped { get; private set; }
public bool PendingThrow { get; private set; }
public bool AimVisible { get; private set; }
public float CameraPitch { get; private set; } = 10;
public float CameraHeight { get; private set; } = 200;
public float SavedPitch { get; private set; }
public float DisplayPitch { get; private set; }
public int NextSlot { get; private set; }
public int Throws { get; private set; }
public event Action<bool>? EquippedChanged;
public event Action? Thrown;
public void Equip()
{
Equipped = true;
CameraHeight += 30; //429707..429713 complete7CC; cleanup resets its defaults.
EquippedChanged?.Invoke(true);
}
public void Release()
{
Equipped = AimVisible = false;
CameraPitch = 0;
CameraHeight = 200;
//42871D does not write Jimmy1E26/1E28 or destroy its AB4 pool.
EquippedChanged?.Invoke(false);
}
public void StepInput(PlayerInput input, Vector3 root, Vector3 euler, bool supported,
float energy, bool exempt, Action stop, Action<bool> shooting, Action<float> adjustEnergy)
{
if (!input.Fire)
{
AimVisible = false;
shooting(false);
if (!PendingThrow) return;
Thrown?.Invoke(); //4265A9 requests10 before the launch virtual.
projectiles[NextSlot].Launch(root, euler, SavedPitch);
NextSlot = (NextSlot + 1) % PoolSize;
PendingThrow = false;
Throws++;
adjustEnergy(-1);
return;
}
if (!Equipped) return;
stop();
if (energy <= 0 && !exempt || !supported) return;
shooting(true);
AimVisible = true;
DisplayPitch = SavedPitch;
if (!PendingThrow)
{
PendingThrow = true;
return; //First hold arms without refreshing the saved pitch.
}
CameraPitch = Math.Clamp(CameraPitch, 0, 45);
SavedPitch = CameraPitch;
}
public void StepCameraInput(PlayerInput input)
{
if (!Equipped) { CameraPitch=10; return; }
if (!input.Fire) return;
if (input.Backward) CameraPitch -= 20 * FixedStepClock.Step;
else if (input.Forward) CameraPitch += 20 * FixedStepClock.Step;
}
public void Reset()
{
if (Equipped) Release();
PendingThrow = AimVisible = false;
CameraPitch = 10; SavedPitch = DisplayPitch = 0;
CameraHeight = 200;
NextSlot = Throws = 0;
foreach (var projectile in projectiles) projectile.Reset();
}
}
/// <summary>C3DBaseball owned pool entry. No invented ammo count or lifetime.</summary>
public sealed class BaseballProjectile
{
public Vector3 Position { get; private set; }
public Vector3 PreviousPosition { get; private set; }
public Vector3 Velocity { get; private set; }
public Vector3 PendingImpulse { get; private set; }
public bool Supported { get; private set; }
public bool Visible { get; private set; }
public int CanvasId => 2; //40FB50 initializes2; a sequence caller is not recovered.
public int Landings { get; private set; }
public void Launch(Vector3 root, Vector3 euler, float pitch)
{
if (!float.IsFinite(root.X + root.Y + root.Z + euler.X + euler.Y + euler.Z + pitch)
|| pitch < 0 || pitch > 45) throw new ArgumentOutOfRangeException(nameof(pitch));
//384/38C use the player's full local transform. This bridge matches the
//port's recovered Bubble Euler convention; generic original Euler remains
//a declared precision/ownership boundary. Upright yaw is the tested path.
var rotation = Matrix4x4.CreateRotationZ(-euler.Z * MathF.PI / 180)
* Matrix4x4.CreateRotationX(-euler.X * MathF.PI / 180)
* Matrix4x4.CreateRotationY(-euler.Y * MathF.PI / 180);
Position = root + Vector3.Transform(new Vector3(0, 80, 50), rotation);
var direction = Vector3.Transform(new Vector3(0, pitch * .02222222276031971f, 1), rotation);
Velocity = direction / OriginalBodySupport.QuickMagnitude(direction) * 1800;
//429A30 does not clear a reused entry's impulse/support state.
PreviousPosition = Position;
Visible = true;
}
public void Step(OriginalBodyPhysics physics, float seconds)
{
if (!Visible) return;
PreviousPosition = Position;
var result = physics.Step(new(Position, Velocity, Vector3.Zero, PendingImpulse, Supported), seconds,
radius: 15, factor: 1, friction: .46f, profile: BodyResponseProfile.Baseball);
Position = result.Body.Position; Velocity = result.Body.Velocity;
PendingImpulse = result.Body.Impulse; Supported = result.Body.Supported;
if (result.Landing != null) Landings++;
}
public void Hide() => Visible = false; //Source disables integration/pairs and hides, retaining body state.
public void Reset()
{
Visible=Supported=false; Position=PreviousPosition=Velocity=PendingImpulse=Vector3.Zero;
Landings=0;
}
}
+11 -2
View File
@@ -41,6 +41,7 @@ public sealed class LabSimulation
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; }
@@ -58,6 +59,7 @@ public sealed class LabSimulation
var previousPose=Pose;
if (gadgetMode == 0) ReleaseBubble();
if (gadgetMode == 2) Invisible.Release();
if (gadgetMode == 6) Baseball.Release();
gadgetMode = -1;
if (value == 0)
{
@@ -70,6 +72,7 @@ public sealed class LabSimulation
return;
}
if (value == 2 && !Invisible.Equip(Energy, IgnoresGadgetEnergy)) return;
if (value == 6) Baseball.Equip();
gadgetMode = value;
}
}
@@ -124,7 +127,7 @@ public sealed class LabSimulation
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 => ActorRoot + new Vector3(0, 99, 0);
public Vector3 CameraTarget => ActorRoot + new Vector3(0, 80 + 1.9f * Baseball.CameraPitch, 0);
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));
@@ -141,6 +144,7 @@ public sealed class LabSimulation
this.energy = energy ?? new PlayerEnergy();
Invisible.AlphaRequested += Appearance.SetAlpha;
Invisible.BlendRequested += Appearance.SetBlend;
Baseball.Thrown += () => GadgetSound?.Invoke(10,false);
sourceStart = start;
startYaw = yaw;
var bounds = standingPose.Bounds();
@@ -161,6 +165,8 @@ public sealed class LabSimulation
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=Roll=targetPitch=targetRoll=0; BubbleBounces=0;
TracksBubbleOrientation=false;
@@ -404,6 +410,7 @@ public sealed class LabSimulation
//438011..43802B adds the independent turn rate directly to yaw.
targetYaw = Yaw;
}
Baseball.StepCameraInput(input);
StepCamera(); //438BC0/439900 input path owns follow; still provisional geometry/state.
if (movementMode==2)
{
@@ -415,6 +422,8 @@ public sealed class LabSimulation
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 StepPlayer(PlayerInput input)
@@ -541,7 +550,7 @@ public sealed class LabSimulation
private (Vector3 Eye, float Gain) DesiredEye()
{
var (sin, cos) = Trig(Yaw);
var eye = ActorRoot + new Vector3(sin * 350, 180, -cos * 350);
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
+31 -5
View File
@@ -13,6 +13,8 @@ public readonly record struct OrdinaryBodyStep(OrdinaryBodyState Body, Vector3 P
Vector3 SupportAnchor, SupportHit? SupportHit, BodyLandingObservation? Landing,
CameraRayPolygon? Contact, int CollisionPasses, int TriangleTests);
public enum BodyResponseProfile { Jimmy, Baseball }
/// <summary>
/// Bounded479D20 composition: enabled integration/support/pairs/static flags,
/// prevent-lowering true, ordinary Jimmy370/374/37C and no dynamic body pass.
@@ -26,10 +28,10 @@ public sealed class OriginalBodyPhysics
{
private readonly OriginalStaticCollision collision;
public OriginalBodyPhysics(OriginalStaticCollision collision)
public OriginalBodyPhysics(OriginalStaticCollision collision, bool allowSpecialMaterials = false)
{
ArgumentNullException.ThrowIfNull(collision);
if (collision.HasSpecialPlayerContacts)
if (collision.HasSpecialPlayerContacts && !allowSpecialMaterials)
throw new NotSupportedException("Ordinary body composition requires recovered special-contact policies for this scene");
this.collision = collision;
}
@@ -38,7 +40,8 @@ public sealed class OriginalBodyPhysics
public OrdinaryBodyStep Step(OrdinaryBodyState body, float seconds,
float radius = OriginalBodySupport.JimmyRadius, float factor = OriginalBodySupport.JimmyFactor,
float friction = .8f, float suppressionScale = .5f, bool geometryEnabled = true)
float friction = .8f, float suppressionScale = .5f, bool geometryEnabled = true,
BodyResponseProfile profile = BodyResponseProfile.Jimmy)
{
Finite(body.Position); Finite(body.Velocity); Finite(body.Acceleration); Finite(body.Impulse);
Finite(body.AngularVelocity); Finite(body.Rotation);
@@ -77,6 +80,21 @@ public sealed class OriginalBodyPhysics
if (velocity.Y > 0) velocity.Y = 0;
if (acceleration.Y > 0) acceleration.Y = 0;
}
else if (profile == BodyResponseProfile.Baseball && move.CallbackPolygon is { } wall)
{
//40FEE0 ->458890 ->472750: reflect horizontal direction, keep Y,
//then damp horizontal components by1-.46. Its angular tail does not
//change position/velocity; sprite/Euler side effects remain separate.
var horizontal = velocity with {Y=0};
var magnitude = OriginalBodySupport.QuickMagnitude(horizontal);
if (magnitude > 0)
{
var direction = horizontal / magnitude;
var reflected = direction - 2 * Vector3.Dot(direction, wall.StoredNormal) * wall.StoredNormal;
velocity = new(reflected.X * magnitude * (1-.46f), velocity.Y,
reflected.Z * magnitude * (1-.46f));
}
}
var position = move.Position;
if (horizontalFirst) position.Y += delta.Y;
position.Y = MathF.Max(position.Y, -25000);
@@ -86,13 +104,21 @@ public sealed class OriginalBodyPhysics
BodyLandingObservation? landing = null;
if (geometryEnabled)
{
var support = OriginalBodySupport.Resolve(new(position, previous, velocity, acceleration, radius, factor),
var support = OriginalBodySupport.Resolve(new(position, previous, velocity, acceleration, radius, factor,
PreventLowering: profile == BodyResponseProfile.Jimmy),
wasSupported, (start, end, sides) => collision.TraceSupport(start, end, sides));
if (support.Supported)
{
//37C observes new root/zero acceleration but old velocity/support.
//Jimmy's inherited37C is a no-op; the observation is diagnostic.
if (support.Landed) landing = new(support.Body.Position, velocity, support.Body.Acceleration, false);
if (support.Landed)
{
landing = new(support.Body.Position, velocity, support.Body.Acceleration, false);
//40FF80 receives old live velocity after root/acceleration
//publication and writes impulse288, before support zeros Y.
if (profile == BodyResponseProfile.Baseball)
body = body with {Impulse = new(velocity.X, velocity.Y * -.65f, velocity.Z)};
}
body = body with { Position = support.Body.Position, Velocity = support.Body.Velocity,
Acceleration = support.Body.Acceleration, Supported = true };
anchor = support.SupportAnchor;
+1 -1
View File
@@ -65,7 +65,7 @@ public sealed class OriginalCameraRay
public static OriginalCameraRay FromRouteScene(Mesh mesh, string levelCode)
{
ArgumentNullException.ThrowIfNull(mesh);
if (levelCode is not ("LV1B" or "VR01" or "VR04" or "LEV1"))
if (levelCode is not ("LV1B" or "VR01" or "VR04" or "VR07" 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");
+1 -1
View File
@@ -61,7 +61,7 @@ public sealed class OriginalStaticCollision
public static OriginalStaticCollision FromRouteScene(Mesh mesh, string level)
{
ArgumentNullException.ThrowIfNull(mesh);
if (level is not ("LV1B" or "VR01" or "VR04" or "LEV1"))
if (level is not ("LV1B" or "VR01" or "VR04" or "VR07" 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");
+10 -1
View File
@@ -20,6 +20,7 @@ public sealed class PlayerSceneBinding : IDisposable
director.GadgetReleaseRequested += Release;
inventory.GadgetSelected += Selected;
player.Invisible.EquippedChanged += InvisibleEquipped;
player.Baseball.EquippedChanged += BaseballEquipped;
player.DefaultGadgetRequested += DefaultGadget;
Selected(inventory.SelectedGadget);
}
@@ -49,7 +50,7 @@ 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 is 0 or 2 || inventory.SelectedGadget is -1 or 3)
if (player.GadgetMode is 0 or 2 or 6 || inventory.SelectedGadget is -1 or 3)
{ inventory.SelectGadget(-1); player.GadgetMode = -1; }
else if (player.GadgetMode != -1) UnsupportedGadgetCleanups++;
}
@@ -70,6 +71,13 @@ public sealed class PlayerSceneBinding : IDisposable
companion.Visible = companion.MovementEnabled = companion.BodyEnabled = !equipped;
}
private void BaseballEquipped(bool equipped)
{
//Raw6 cleanup42871D has no Invisible's complete9E8 restoration veto.
if(director.FindActor("C3DGODDARD") is {} companion)
companion.Visible=companion.MovementEnabled=companion.BodyEnabled=!equipped;
}
private void Transform(DirectorActor actor)
{
if (string.Equals(actor.Tag, tag, StringComparison.OrdinalIgnoreCase))
@@ -83,6 +91,7 @@ public sealed class PlayerSceneBinding : IDisposable
director.GadgetReleaseRequested -= Release;
inventory.GadgetSelected -= Selected;
player.Invisible.EquippedChanged -= InvisibleEquipped;
player.Baseball.EquippedChanged -= BaseballEquipped;
player.DefaultGadgetRequested -= DefaultGadget;
}
}
+149
View File
@@ -0,0 +1,149 @@
using System.Numerics;
using GamePort.Assets;
namespace GamePort.Game;
/// <summary>Owned Baseball bodies and source3TAR callbacks. Pair discovery uses
/// a bounded sphere-overlap adapter; original pair scheduling remains unported.</summary>
public sealed class SceneBaseballs
{
private readonly LabSimulation player;
private readonly OriginalBodyPhysics physics;
private readonly SceneDirector director;
private readonly Dictionary<DirectorActor,int> parentHits = [];
public IReadOnlyList<MovingBaseballTarget> Targets { get; }
public int Hits { get; private set; }
public int Recovered { get; private set; }
public event Action<int>? Sound;
public event Action<int>? ScoreAwarded;
public SceneBaseballs(SceneDirector director, LabSimulation player, Mesh world)
{
this.director=director; this.player=player;
physics=new(OriginalStaticCollision.FromRouteScene(world,player.LevelCode),allowSpecialMaterials:true);
Targets=director.Actors.Where(a=>a.Kind=="3TAR").Select(a=>new MovingBaseballTarget(a)).ToArray();
InitializeTrophyContacts();
}
public void StepBodies(float seconds)
{
foreach(var target in Targets) target.StepBody(seconds);
foreach(var ball in player.Baseball.Projectiles)
{
ball.Step(physics,seconds);
if(!ball.Visible) continue;
//This modern discovery adapter supplies real source callback rules.
//It does not claim original47A580 pair ordering or swept contacts.
foreach(var target in Targets)
if(target.Actor.BodyEnabled && Vector3.DistanceSquared(ball.Position,target.Actor.Position)<90*90
&& target.Hit())
{
Hits++; ScoreAwarded?.Invoke(target.Points);
ActivateParent(target);
}
if(Vector3.DistanceSquared(ball.Position,player.ActorRoot)<(15+player.InteractionRadius)*(15+player.InteractionRadius))
{ ball.Hide(); Recovered++; }
}
}
public void StepTargets(float seconds)
{
foreach(var target in Targets) target.StepFrame(seconds);
}
private void ActivateParent(MovingBaseballTarget target)
{
var parent=director.FindActor(target.ActivateObject);
if(parent==null) { Sound?.Invoke(198); return; }
if(parent.Kind is not ("3TRO" or "3PIC")) return;
var count=parentHits.GetValueOrDefault(parent)+1;
if(count>target.HitsRequired)
{
parentHits[parent]=0;
//The source invokes parent428(1), not the trigger interpreter.
parent.Visible=true;
if(parent.SourceGam?.Integer("HasCollision",-1)!=0)parent.BodyEnabled=true;
Sound?.Invoke(199);
}
else parentHits[parent]=count;
}
public void Reset()
{
Hits=Recovered=0; parentHits.Clear();
foreach(var target in Targets) target.Reset();
InitializeTrophyContacts();
}
private void InitializeTrophyContacts()
{
if(player.LevelCode!="VR07")return;
foreach(var trophy in director.Actors.Where(a=>a.Kind=="3TRO"))
trophy.BodyEnabled=trophy.Visible && trophy.SourceGam?.Integer("HasCollision",-1)!=0;
}
}
/// <summary>Factory45CA06's C3DMOVINGTARGET, not Jimmy's C3DTarget helper.</summary>
public sealed class MovingBaseballTarget
{
public DirectorActor Actor { get; }
private readonly Vector3 initial;
private readonly bool initialVisible;
public Vector3 Start { get; }
public Vector3 Destination { get; }
public Vector3 Velocity { get; private set; }
public float Speed { get; }
public float Remaining { get; private set; }
public float RespawnTime { get; }
public int Points { get; }
public int HitsRequired { get; }
public string ActivateObject { get; }
public MovingBaseballTarget(DirectorActor actor)
{
Actor=actor;
if(actor.Kind!="3TAR" || actor.SourceGam is not {} source)
throw new ArgumentException("Moving target needs its actual source entity",nameof(actor));
initial=actor.Position;
initialVisible=actor.Visible;
Start=new(source.Number("StartPosX"),source.Number("StartPosY"),source.Number("StartPosZ"));
Destination=new(source.Number("DestPosX"),source.Number("DestPosY"),source.Number("DestPosZ"));
Speed=source.Number("Speed",100); RespawnTime=source.Number("RespawnTime",15);
Points=source.Integer("NumPoints",10); HitsRequired=source.Integer("HitsRequired",5);
ActivateObject=source.Text("ActivateObject")??"none";
}
public void StepBody(float seconds)
{
if(!Actor.BodyEnabled) return;
//Source target disables world response and support. Preserve the common
//integrate-before-frame partial order. Full registry/global-flag timing
//remains a separate boundary; this is not a new general actor scheduler.
Velocity+=RecoveredMotion.Gravity*seconds;
Actor.Position+=Velocity*seconds;
}
public void StepFrame(float seconds)
{
if(!float.IsFinite(seconds)||seconds<0||seconds>=1)throw new ArgumentOutOfRangeException(nameof(seconds));
if(Remaining>0)
{
Remaining-=seconds;
if(Remaining<=0) { Remaining=0; Actor.Visible=true; }
}
var delta=Destination-Actor.Position;
var distance=delta.Length(); //Source tests ordinary sqrt distance, normalizes with quick magnitude.
var magnitude=OriginalBodySupport.QuickMagnitude(delta);
Velocity=magnitude>0?delta/magnitude*Speed:Vector3.Zero;
if(distance<100) Actor.Position=Start; //430826 teleports to Start, it does not exchange endpoints.
}
public bool Hit()
{
if(Remaining>0) return false;
Actor.Visible=false; Remaining=RespawnTime;
return true;
}
public void Reset() { Actor.Position=initial; Actor.Visible=initialVisible; Velocity=Vector3.Zero; Remaining=0; }
}
+2 -1
View File
@@ -96,7 +96,8 @@ public sealed class SceneInteractions
}
// Carl InitObject413E2F..45 sets radius100 and support factor0.75.
var radius = playerRadius + (source.Kind == "3TRO" ? 20 : source.Kind == "3CAR" ? 100 : source.Number("Radius"));
var overlaps = actor.Active && OriginalBodySupport.QuickMagnitude(activePlayerRoot - actor.Position) < radius;
var overlaps = actor.Active && (source.Kind!="3TRO" || actor.BodyEnabled)
&& OriginalBodySupport.QuickMagnitude(activePlayerRoot - actor.Position) < radius;
if (!overlaps) { contacts.Remove(source.Offset); continue; }
if (!contacts.Add(source.Offset)) continue;
switch (source.Kind)
+58 -8
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-baseball VR07 aim/release/flight/target/respawn fixture
--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)
@@ -260,6 +261,7 @@ internal static class Program
var shrinkSmoke = args.Contains("--smoke-shrink-ray");
var invisibleSmoke = args.Contains("--smoke-invisible");
var bubbleSmoke = args.Contains("--smoke-bubble");
var baseballSmoke = args.Contains("--smoke-baseball");
var carlSmoke = args.Contains("--smoke-carl-cutscene");
var controlPhaseSmoke = args.Contains("--smoke-control-phases");
var objectiveWindowSmoke = args.Contains("--smoke-objective-window");
@@ -280,7 +282,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 || bubbleSmoke || gadgetWindowSmoke || practiceWindowSmoke || practiceReturnSmoke || carlSmoke || controlPhaseSmoke || objectiveSmoke;
|| args.Contains("--skip-intro") || jetpackSmoke || shrinkSmoke || invisibleSmoke || bubbleSmoke || baseballSmoke || 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.");
@@ -310,6 +312,9 @@ internal static class Program
ShrinkSoldierVisuals? soldierVisuals = null;
JetpackVisuals? jetpackVisuals = null;
BubbleVisuals? bubbleVisuals = null;
SceneBaseballs? baseballs = null;
BaseballVisuals? baseballVisuals = null;
BaseballAimOverlay? baseballAim = null;
var practice = new PracticePrompt();
ObjectivePanel? objectivePanel = null;
var patrols = new Dictionary<string, ActorPatrol>(StringComparer.OrdinalIgnoreCase);
@@ -338,13 +343,13 @@ internal static class Program
var standingPose = AseMesh.Load(AssetPath.Resolve(root, "ASE/jimstop.ase"));
if (walking)
{
var cameraRay = level!.Code is "LV1B" or "VR01" or "VR04" or "LEV1"
var cameraRay = level!.Code is "LV1B" or "VR01" or "VR04" or "VR07" 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 is "VR01" or "VR04" ? OriginalStaticCollision.FromRouteScene(world,level.Code) : null, energy)
level.Code is "VR01" or "VR04" or "VR07" ? OriginalStaticCollision.FromRouteScene(world,level.Code) : null, energy)
{ LevelCode = level.Code, InputAfterPlayerUpdate = carriedSave != null };
if (carriedPlayer != null)
{
@@ -389,6 +394,11 @@ internal static class Program
gadgets = new SceneGadgets(director,interactions.Inventory,simulation,world);
gadgets.ScoreAwarded += interactions.ChangeScore;
}
if(level.Code is "LV1B" or "VR01" or "VR04" or "VR07" or "LEV1")
{
baseballs=new(director,simulation,world);
baseballs.ScoreAwarded+=interactions.ChangeScore;
}
mechanisms = new SceneMechanisms(director);
interactions.Transition += RequestTransition;
interactions.PracticeRequested += practice.Show;
@@ -445,6 +455,8 @@ internal static class Program
mesh = jetpackVisuals.Mesh;
bubbleVisuals = new(mesh,Path.GetFullPath(Path.Combine(Path.GetDirectoryName(scene!)!,"..")));
mesh = bubbleVisuals.Mesh;
baseballVisuals = new(mesh,Path.GetFullPath(Path.Combine(Path.GetDirectoryName(scene!)!,"..")));
mesh = baseballVisuals.Mesh;
if (gadgets != null)
{
rayVisuals = new ShrinkRayVisuals(mesh,Path.GetFullPath(Path.Combine(Path.GetDirectoryName(scene!)!, "..")),root);
@@ -454,6 +466,8 @@ internal static class Program
mesh = hud.Mesh;
invisibleMeter = new InvisibleMeterOverlay(mesh,Path.Combine(Path.GetDirectoryName(scene!)!,"../invisible-meter/meter.json"));
mesh = invisibleMeter.Mesh;
baseballAim = new(mesh,Path.GetFullPath(Path.Combine(Path.GetDirectoryName(scene!)!,"..")));
mesh = baseballAim.Mesh;
gadgetOverlay = new GadgetMenuOverlay(mesh, Path.Combine(Path.GetDirectoryName(scene!)!, "../gadgets/gadgets.json"));
mesh = gadgetOverlay.Mesh;
Console.WriteLine($"Prepared source model actors: {staticVisuals.ActorCount}.");
@@ -486,7 +500,7 @@ 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 || bubbleSmoke ? "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 || baseballSmoke ? "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))
@@ -495,6 +509,8 @@ internal static class Program
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(baseballSmoke && (level?.Code!="VR07" || frames<8 || loadedSave!=null))
throw new ArgumentException("Baseball fixture requires a fresh VR07 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))
@@ -529,6 +545,8 @@ internal static class Program
var sawShrinkKey = false;
InvisibleSmoke? invisibleFixture = null;
BubbleSmoke? bubbleFixture = null;
BaseballSmoke? baseballFixture = null;
var sawBaseballKeys=0;
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}.");
{
@@ -541,6 +559,7 @@ internal static class Program
simulation.GadgetSound += (id,loop) => sceneAudio?.Effect(id,loop?"bubble":null);
simulation.BubbleSoundStopped += () => sceneAudio?.StopLoop("bubble");
}
if(baseballs!=null)baseballs.Sound+=id=>sceneAudio?.Effect(id);
if (gadgets != null)
{
gadgets.Sound += (id,loop) => sceneAudio?.Effect(id,loop ? "shrink-ray" : null);
@@ -568,6 +587,7 @@ internal static class Program
}
director.Begin(originalStart!, activateStartTrigger: !returning);
gadgets?.Reset();
baseballs?.Reset();
interactions!.Reset();
mechanisms!.Reset();
director.SyncActor(level!.Player!.Tag!, simulation!.ActorRoot, new Vector3(0, simulation.Yaw, 0));
@@ -583,7 +603,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 || bubbleSmoke || gadgetWindowSmoke || debugSmoke || diagnosticsSmoke || toolsSmoke || controlPhaseSmoke) { sceneAudio?.StopSpeech(); director.Skip(); }
if (args.Contains("--skip-intro") || jetpackSmoke || shrinkSmoke || invisibleSmoke || bubbleSmoke || baseballSmoke || gadgetWindowSmoke || debugSmoke || diagnosticsSmoke || toolsSmoke || controlPhaseSmoke) { sceneAudio?.StopSpeech(); director.Skip(); }
if (gadgetWindowSmoke) { interactions!.Inventory.SetState(0,3,1); interactions.Inventory.SelectGadget(3); }
if (controlPhaseSmoke)
{
@@ -664,6 +684,7 @@ internal static class Program
gadgetScreen.Point(new(200,380), level!.Code, storyTasks!.Get("SCENE"));
}
if (invisibleSmoke) invisibleFixture = new(simulation!,interactions!.Inventory);
if(baseballSmoke)baseballFixture=new(simulation!,playerBinding!,interactions!.Inventory,baseballs!,director);
if (bubbleSmoke) bubbleFixture = new(simulation!,interactions!.Inventory);
if (shrinkSmoke)
{
@@ -756,7 +777,7 @@ internal static class Program
if (simulation == null) { debugMenu.Message = "RESET REQUIRES PLAY MODE"; return; }
if (practice.Active) practice.Key(17, Vector2.Zero);
simulation.Reset(); poseTime = 0; sceneAudio?.StopSpeech(); director?.Begin(originalStart!);
interactions?.Reset(); mechanisms?.Reset(); gadgets?.Reset(); mouseFire = false;
interactions?.Reset(); mechanisms?.Reset(); gadgets?.Reset(); baseballs?.Reset(); mouseFire = false;
director?.SyncActor(level!.Player!.Tag!, simulation.ActorRoot, new Vector3(0, simulation.Yaw, 0));
}
void ToggleCamera()
@@ -843,6 +864,10 @@ internal static class Program
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.GiveBaseball when interactions != null:
interactions.Inventory.SetState(0,6,1); interactions.Inventory.SelectGadget(6);
debugMenu.Message="BASEBALL EQUIPPED - HOLD FIRE, UP/DOWN AIM, RELEASE TO THROW";
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:
@@ -908,6 +933,11 @@ internal static class Program
}
while (running)
{
baseballFixture?.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);
bubbleFixture?.BeforeFrame(count,(key,down)=>
{
var e=new Sdl.Event{Type=down?Sdl.KeyDown:Sdl.KeyUp,Scancode=key,Down=down?(byte)1:(byte)0};
@@ -964,6 +994,8 @@ internal static class Program
}
while (!headless && Sdl.SDL_PollEvent(out var e))
{
if(baseballSmoke && e.Type==Sdl.KeyDown)
sawBaseballKeys|=e.Scancode switch{224=>1,80=>2,82=>4,43=>8,_=>0};
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;
@@ -1090,12 +1122,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 || bubbleSmoke || gadgetWindowSmoke || objectiveWindowSmoke || debugSmoke || diagnosticsSmoke || toolsSmoke))
if (simulation != null && !debugMenu.Open && !inspecting && !practice.Active && gadgetScreen?.Open != true && (active || headless || walkSmoke || jetpackSmoke || shrinkSmoke || invisibleSmoke || bubbleSmoke || baseballSmoke || gadgetWindowSmoke || objectiveWindowSmoke || debugSmoke || diagnosticsSmoke || toolsSmoke))
{
var steps = headless || walkSmoke || jetpackSmoke || shrinkSmoke || invisibleSmoke || bubbleSmoke || gadgetWindowSmoke || practiceWindowSmoke || carlSmoke || controlPhaseSmoke || objectiveWindowSmoke || debugSmoke || diagnosticsSmoke || toolsSmoke ? 1 : stepClock.Advance(elapsed);
var steps = headless || walkSmoke || jetpackSmoke || shrinkSmoke || invisibleSmoke || bubbleSmoke || baseballSmoke || 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)
: baseballSmoke && headless ? BaseballSmoke.Input(count)
: 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)
@@ -1107,12 +1140,14 @@ internal static class Program
keys.Contains(4), keys.Contains(7), keys.Contains(225) || keys.Contains(229),
mouseFire || keys.Contains(40) || keys.Contains(88) || keys.Contains(224) || keys.Contains(228));
gadgets?.StepBodies(FixedStepClock.Step);
baseballs?.StepBodies(FixedStepClock.Step);
var before = simulation.Position;
var powered = simulation.JetpackEffectVisible && !simulation.Grounded;
bool acceptsInput;
if (playerBinding != null) acceptsInput = playerBinding.Step(input);
else { simulation.Step(input); acceptsInput = true; }
gadgets?.StepTimers(FixedStepClock.Step);
baseballs?.StepTargets(FixedStepClock.Step);
if (jetpackSmoke && powered)
{
poweredAirTravel += Vector2.Distance(new(before.X, before.Z), new(simulation.Position.X, simulation.Position.Z));
@@ -1179,6 +1214,8 @@ internal static class Program
if (shrinkSmoke && gadgets!.Ray.Visible) shrinkPhaseMask |= 1 << gadgets.Ray.TexturePhase;
jetpackVisuals?.Update(mesh, simulation!);
bubbleVisuals?.Update(mesh,simulation!.Bubble,simulation.BubbleRoot,renderEye,renderTarget);
baseballVisuals?.Update(mesh,simulation!.Baseball.Projectiles,renderEye,renderTarget);
baseballAim?.Update(mesh,simulation!.Baseball,renderer.Width,renderer.Height);
spriteVisuals?.FaceCamera(renderEye, renderTarget, mesh);
objectivePanel?.Key(keys.Contains(18) && !debugMenu.Open && !inspecting && !practice.Active && gadgetScreen?.Open != true
&& director is { Controlled: true, InventoryEnabled: true });
@@ -1211,6 +1248,7 @@ internal static class Program
Targetable = simulation?.Invisible.Targetable ?? true,
BubblePhase = simulation?.Bubble.Active==true ? "ACTIVE" : simulation?.Bubble.Expanding==true ? "EXPAND"
: simulation?.Bubble.Collapsing==true ? "FADE" : "OFF",
BaseballState=simulation==null?"OFF":$"{(simulation.Baseball.Equipped?"ON":"OFF")} AIM {simulation.Baseball.SavedPitch:F1} PENDING {simulation.Baseball.PendingThrow} THROWS {simulation.Baseball.Throws}",
BodyRadius = simulation?.InteractionRadius ?? 60, BodyFactor=simulation?.BodyFactor ?? 1.265f,
Objective = interactions?.CurrentObjective ?? 0, ObjectiveTime = objectivePanel?.Elapsed ?? 0,
CameraObstruction = debugCameraRay?.Enabled, CameraPolygons = debugCameraRay?.PolygonCount ?? 0,
@@ -1249,6 +1287,12 @@ internal static class Program
}
renderer.UpdateVertices(mesh.Vertices);
renderer.Render(view * projection);
if(baseballFixture!=null)
{
baseballFixture.AfterFrame(count);
if(BaseballSmoke.StageName(count) is{} stage && Option(args,"--screenshot") is{} capture)
renderer.SavePpm(Path.ChangeExtension(capture,$".{stage}.ppm"));
}
if (bubbleFixture!=null)
{
bubbleFixture.AfterFrame(count);
@@ -1529,6 +1573,12 @@ internal static class Program
if (!headless) Console.WriteLine($"Invisible SDL primary received: {sawShrinkKey}.");
if (!invisibleFixture.Passed || !headless && !sawShrinkKey) return 2;
}
if(baseballFixture!=null)
{
Console.WriteLine(baseballFixture.Report);
if(!headless)Console.WriteLine($"Baseball SDL keys received: {sawBaseballKeys==15}.");
if(!baseballFixture.Passed || !headless && sawBaseballKeys!=15)return 2;
}
if (bubbleFixture!=null)
{
Console.WriteLine(bubbleFixture.Report);