Files
Neutron/src/GamePort/Program.cs
T

1108 lines
75 KiB
C#

using System.Diagnostics;
using System.Numerics;
using GamePort.Assets;
using GamePort.Application;
using GamePort.Audio;
using GamePort.Game;
using GamePort.Platform;
using GamePort.Rendering.Vulkan;
namespace GamePort;
internal static class Program
{
public static int Main(string[] args)
{
try
{
using var presentation = new RenderSession();
OriginalSave? carriedSave = null;
var returning = false;
var diagnostics = new DebugDiagnostics { Enabled = args.Contains("--debug-overlay") };
while (true)
{
var result = Run(args, carriedSave, returning, diagnostics, presentation, out var continuation);
if (result != 0 || continuation == null) return result;
args = continuation.Args; carriedSave = continuation.Save; returning = continuation.Returning;
}
}
catch (Exception error) { Console.Error.WriteLine(error); return 1; }
}
private static string? Option(string[] args, string name)
{
var i = Array.IndexOf(args, name);
if (i < 0) return null;
if (i + 1 >= args.Length || args[i + 1].StartsWith("--", StringComparison.Ordinal))
throw new ArgumentException($"{name} requires a value.");
return args[i + 1];
}
private sealed record SceneContinuation(string[] Args, OriginalSave Save, bool Returning);
private static int Run(string[] args, OriginalSave? carriedSave, bool returning, DebugDiagnostics diagnostics,
RenderSession presentation, out SceneContinuation? continuation)
{
continuation = null;
if (args.Contains("--help"))
{
Console.WriteLine("""
Neutron reconstruction investigation runtime
--assets PATH Original asset directory
--scene PATH Extracted OMT scene JSON (default: prepared LV1B)
--model RELPATH Original ASE model (default without scene: ASE/jimstop.ase)
--texture RELPATH PNG override (default: png/jimycarl.png)
--level RELPATH Original GAM (default with prepared LV1B: gam/level1b.gam)
--original-camera Stored GAM start camera and recovered projection
--animation PATH Prepared Jimmy animation.json; place at GAM startpoint
--with-player Use prepared jimstop animation in scene
--walk Play prepared scene with recovered story/interactions
--inspect Pause simulation and inspect scene/animation
--smoke-walk Deterministic 240-step movement/jump check
--story Execute recovered original CAM/MCA/AI trigger sequence
--story-time N Headless scene-sequence time for GPU comparisons
--skip-intro Fast-forward original intro actions and restore control
--start TAG Use a named original STRT checkpoint
--load-save PATH Resume original TSK task/items/checkpoint state
--write-save PATH Write checkpoint state as TSK outside asset directory
--mute Disable scene audio
--time SECONDS Fixed animation time for comparisons
--headless Render offscreen through Vulkan
--screenshot PATH Save actual GPU readback as PPM
--frames N Exit after N frames (headless default: 1)
--width N --height N Initial window/offscreen size (default960x720)
--audio PATH Play recovered WAV; --loop-audio repeats it
--audio-smoke PATH Verify audio-stream consumption
--scene-audio-smoke PATH Verify music/speech streams from entities.json
--cutscene-audio-smoke PATH Verify original cutscene music stop/restart
--effects-audio-smoke PATH Verify default effect bank and loop lifetime
--smoke-transition Headless VR01 RETURN / renderer-recreation check
--smoke-lab-route Headless source lab contact route / next-scene rebuild
--smoke-practice-prompt Headless original jet pack practice prompt
--smoke-practice-transition Headless lab-to-VR04 practice transition
--smoke-practice-return Headless lab/VR04/RETURN root and intro-suppression check
--smoke-practice-window SDL practice pause/dismiss/resize check (12 frames)
--smoke-jetpack 300-step powered steering/jump check in VR04
--smoke-jump-key NAME Replay using shift/right-shift/insert/keypad0/right-mouse
--smoke-carl-cutscene Verify input stays locked during the lab conversation
--smoke-objective-panel Show original lab objective; --story-time tests timeout
--smoke-objective-window SDL O-key reopen/close/timeout check
--debug-menu Start with the F1 debug menu open
--debug-overlay Start with live F2 diagnostics visible
--smoke-debug-menu SDL debug navigation/pause/actions/resize check
--smoke-debug-overlay SDL live diagnostics/input/menu/resize check
--smoke-window-transitions Persistent window/renderer and widescreen UI check
--verify-assets Decode all original PNG/ASE files
--smoke-window Test keyboard event/resize (requires --frames 6 or more)
--no-validation Disable development validation
Walk: arrows move/turn; Shift, Insert or right mouse jump; R reset.
F1 debug menu. F2 live diagnostics. C inspect / chase camera. F11 fullscreen, Escape quit.
Inspector: arrows/WASD orbit, +/- zoom,
F11 fullscreen, Escape quit. Animation preview: 1 idle, 2 run, 3 jump, 4 scratch.
Collision/pivot/cadence and animation timing are provisional. Full gameplay remains incomplete.
""");
return 0;
}
var root = AssetPath.FindOriginal(Option(args, "--assets"));
if (args.Contains("--smoke-window-transitions"))
{
var preparedCandidates = new List<string>();
if (Option(args, "--scene") is { } explicitScene)
preparedCandidates.Add(Path.GetFullPath(Path.Combine(Path.GetDirectoryName(explicitScene)!, "..")));
preparedCandidates.AddRange([Path.Combine(AppContext.BaseDirectory, "scenes"), "artifacts/extracted"]);
var prepared = preparedCandidates
.FirstOrDefault(p => File.Exists(Path.Combine(p, "ui/ui.json")))
?? throw new DirectoryNotFoundException("Prepare scene/UI assets before window transition check");
var output = Option(args, "--screenshot") is { } capture
? Path.Combine(Path.GetDirectoryName(Path.GetFullPath(capture))!, "window-transitions") : "artifacts/window-transitions";
return WindowTransitionSmoke.Run(presentation, root, Path.GetFullPath(prepared), output, !args.Contains("--no-validation"));
}
var saveOutput = Option(args, "--write-save");
if (saveOutput != null)
{
saveOutput = Path.GetFullPath(saveOutput);
if (saveOutput.StartsWith(Path.GetFullPath(root) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
throw new ArgumentException("Save output must be outside original asset directory");
for (var parent = new DirectoryInfo(Path.GetDirectoryName(saveOutput)!); parent != null; parent = parent.Parent)
if (parent.Exists && parent.LinkTarget != null) throw new ArgumentException("Save output directory must not redirect through a symbolic link");
}
if (args.Contains("--verify-assets")) return VerifyAssets(root);
if (Option(args, "--cutscene-audio-smoke") is { } cutsceneManifest)
{
var bank = new PreparedEntityResources(cutsceneManifest);
var cutsceneLevel = GamLevel.Load(AssetPath.Resolve(root, "gam/level1b.gam"));
var cutsceneSave = OriginalSave.Load(AssetPath.Resolve(root, "NewGame.tsk"));
var cutscene = new SceneDirector(cutsceneLevel, new TaskStates(cutsceneSave.Tasks), bank.Duration);
using var mixer = new SceneAudio(bank);
cutscene.Speech += mixer.Speech;
cutscene.MusicStopped += mixer.StopMusic;
cutscene.MusicRestarted += mixer.RestartMusic;
mixer.Music("musicsecretlab.omt", 0);
if (mixer.QueuedMusicBytes <= 0) throw new InvalidOperationException("No gameplay music before cutscene test");
cutscene.Begin(cutsceneLevel.FindStart()!);
var silentDuring = mixer.QueuedMusicBytes == 0 && mixer.QueuedSpeechBytes > 0;
for (var tick = 0; tick < 18000 && !cutscene.Controlled; tick++)
{
cutscene.Step(FixedStepClock.Step);
if (!cutscene.Controlled && mixer.QueuedMusicBytes != 0) silentDuring = false;
}
var naturalRestart = cutscene.Controlled && mixer.QueuedMusicBytes > 0;
cutscene.Begin(cutsceneLevel.FindStart()!);
var resetSilent = mixer.QueuedMusicBytes == 0;
mixer.StopSpeech(); cutscene.Skip();
var skipRestart = cutscene.Controlled && mixer.QueuedMusicBytes > 0;
Console.WriteLine($"Cutscene audio: music silent through intro={silentDuring}, natural restart={naturalRestart}, reset silent={resetSilent}, skip restart={skipRestart}.");
return silentDuring && naturalRestart && resetSilent && skipRestart ? 0 : 2;
}
if (Option(args, "--effects-audio-smoke") is { } effectsManifest)
{
using var mixer = new SceneAudio(new PreparedEntityResources(effectsManifest));
mixer.Effect(59, "bars"); mixer.Effect(58);
var before = mixer.QueuedEffectBytes;
Thread.Sleep(200);
var consumed = mixer.QueuedEffectBytes < before;
mixer.Pump();
mixer.StopLoop("bars");
var stopped = mixer.LoopCount == 0 && mixer.EffectCount == 1;
mixer.Effect(230);
var mixed = mixer.EffectCount == 2;
mixer.StopEffects();
Console.WriteLine($"Original effects: consumed={consumed}, loop stopped={stopped}, independent one-shots={mixed}, cleared={mixer.QueuedEffectBytes == 0}.");
return consumed && stopped && mixed && mixer.QueuedEffectBytes == 0 ? 0 : 2;
}
if (Option(args, "--scene-audio-smoke") is { } sceneAudioManifest)
{
var bank = new PreparedEntityResources(sceneAudioManifest);
using var mixer = new SceneAudio(bank);
mixer.Music("musicsecretlab.omt", 0);
mixer.Speech("voiceneighborhood.omt", 36);
var beforeMusic = mixer.QueuedMusicBytes;
var beforeSpeech = mixer.QueuedSpeechBytes;
Thread.Sleep(500);
var consumed = mixer.QueuedMusicBytes < beforeMusic && mixer.QueuedSpeechBytes < beforeSpeech;
mixer.StopSpeech();
mixer.Speech("voiceneighborhood.omt", 46);
var restarted = mixer.QueuedMusicBytes > 0 && mixer.QueuedSpeechBytes > 0;
Console.WriteLine($"Scene music and speech consumed independently: {consumed}; speech replacement retained music: {restarted}.");
return consumed && restarted ? 0 : 2;
}
if (Option(args, "--audio-smoke") is { } audioSmoke)
{
using var sound = new SdlAudio(audioSmoke);
var before = sound.QueuedBytes;
Thread.Sleep(500);
var after = sound.QueuedBytes;
Console.WriteLine($"SDL3 audio stream consumed {before - after} source bytes in 500 ms; queued {after}.");
return after < before ? 0 : 2;
}
var scene = Option(args, "--scene");
var loadedSave = carriedSave ?? (Option(args, "--load-save") is { } savePath ? OriginalSave.Load(savePath) : null);
string? savedLevelPath = null;
if (loadedSave != null && carriedSave == null)
{
savedLevelPath = Directory.EnumerateFiles(AssetPath.Resolve(root, "gam"))
.Where(p => p.EndsWith(".gam", StringComparison.OrdinalIgnoreCase))
.FirstOrDefault(p => GamLevel.Load(p).Code == loadedSave.LevelCode)
?? throw new FileNotFoundException($"No GAM matches saved level {loadedSave.LevelCode}");
var prepared = new[] { "artifacts/extracted", Path.Combine(AppContext.BaseDirectory, "scenes") }
.FirstOrDefault(p => Directory.Exists(Path.Combine(p, "animations")))
?? throw new DirectoryNotFoundException("Prepare original scenes before loading saves");
scene = AssetPath.Resolve(prepared, Path.GetFileNameWithoutExtension(savedLevelPath) + "/scene.json");
}
var defaultScene = false;
if (scene == null && Option(args, "--model") == null)
{
scene = new[] { "artifacts/extracted/level1b/scene.json",
Path.Combine(AppContext.BaseDirectory, "scenes/level1b/scene.json") }.FirstOrDefault(File.Exists);
defaultScene = scene != null;
}
var levelPath = savedLevelPath == null ? Option(args, "--level") ?? (defaultScene ? "gam/level1b.gam" : null)
: "gam/" + Path.GetFileName(savedLevelPath);
GamLevel? level = levelPath == null ? null : GamLevel.Load(AssetPath.Resolve(root, levelPath));
var startTag = Option(args, "--start") ?? loadedSave?.StartPoint;
if (string.Equals(startTag, "none", StringComparison.OrdinalIgnoreCase)) startTag = null;
var originalStart = level?.FindStart(startTag);
if (level != null) Console.WriteLine($"Decoded GAM {level.Code}: {level.Entities.Count} entities.");
var originalCamera = args.Contains("--original-camera") || defaultScene;
if (originalCamera && originalStart == null)
throw new ArgumentException("Original camera requires a GAM with a matching startpoint.");
var mesh = scene != null ? Mesh.LoadSceneJson(scene)
: AseMesh.Load(AssetPath.Resolve(root, Option(args, "--model") ?? "ASE/jimstop.ase"));
var world = mesh;
var texture = scene != null ? PngImage.White
: PngImage.Load(AssetPath.Resolve(root, Option(args, "--texture") ?? "png/jimycarl.png"));
var bounds = mesh.Bounds();
var target = (bounds.Min + bounds.Max) / 2;
var radius = Math.Max(Vector3.Distance(bounds.Min, bounds.Max) * 1.15f, 1);
var animationPath = Option(args, "--animation");
var walkSmoke = args.Contains("--smoke-walk");
var jetpackSmoke = args.Contains("--smoke-jetpack");
var carlSmoke = args.Contains("--smoke-carl-cutscene");
var objectiveWindowSmoke = args.Contains("--smoke-objective-window");
var objectiveSmoke = args.Contains("--smoke-objective-panel") || objectiveWindowSmoke;
var jumpBinding = Option(args, "--smoke-jump-key") ?? "shift";
uint jumpScancode = jumpBinding switch { "shift" => 225, "right-shift" => 229,
"insert" => 73, "keypad0" => 98, "right-mouse" => 0,
_ => throw new ArgumentException("Unknown jump smoke binding") };
if (Option(args, "--smoke-jump-key") != null && !(walkSmoke || jetpackSmoke))
throw new ArgumentException("Jump binding smoke option requires a movement smoke mode");
var practiceWindowSmoke = args.Contains("--smoke-practice-window");
var practiceReturnSmoke = args.Contains("--smoke-practice-return");
var debugSmoke = args.Contains("--smoke-debug-menu");
var diagnosticsSmoke = args.Contains("--smoke-debug-overlay");
if (walkSmoke && jetpackSmoke) throw new ArgumentException("Select one movement smoke check");
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 || practiceWindowSmoke || practiceReturnSmoke || carlSmoke || 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.");
if (walkSmoke && args.Contains("--smoke-window")) throw new ArgumentException("Select one window smoke mode.");
var walking = !args.Contains("--inspect") && !args.Contains("--smoke-window") && (story || args.Contains("--walk") || walkSmoke
|| defaultScene && animationPath == null && !args.Contains("--time"));
if ((args.Contains("--with-player") || args.Contains("--walk") || defaultScene || walking) && scene != null)
animationPath ??= Path.Combine(Path.GetDirectoryName(scene)!, "../animations/jimstop/animation.json");
if (walking && (scene == null || originalStart == null))
throw new ArgumentException("Walking requires a scene and matching GAM startpoint.");
PreviewAnimationLibrary? animations = null;
LabSimulation? simulation = null;
SceneDirector? director = null;
TaskStates? storyTasks = null;
SceneActorVisuals? actorVisuals = null;
SceneSpriteVisuals? spriteVisuals = null;
StaticSceneVisuals? staticVisuals = null;
PreparedEntityResources? resources = null;
SceneInteractions? interactions = null;
SceneMechanisms? mechanisms = null;
SceneHud? hud = null;
JetpackVisuals? jetpackVisuals = null;
var practice = new PracticePrompt();
ObjectivePanel? objectivePanel = null;
var patrols = new Dictionary<string, ActorPatrol>(StringComparer.OrdinalIgnoreCase);
LevelTransition? transitionRequest = null;
Vector3 returnRoot = loadedSave?.StoredVector ?? Vector3.Zero;
void RequestTransition(LevelTransition request)
{
if (transitionRequest != null) return;
//43B5A0 captures live root for ordinary outbound transitions;
//RETURN preserves it for the destination PostLoad restore.
returnRoot = RuntimeCheckpoint.Stage(returnRoot, simulation!.ActorRoot, request.Returning).Root;
transitionRequest = request;
}
var characterOffset = mesh.Vertices.Length;
var characterModel = Matrix4x4.Identity;
if (animationPath != null)
{
if (scene == null || originalStart == null)
throw new ArgumentException("A scene and matching GAM are required to place an animated player.");
animations = new PreviewAnimationLibrary(animationPath);
var standingPose = AseMesh.Load(AssetPath.Resolve(root, "ASE/jimstop.ase"));
if (walking)
{
var cameraRay = level!.Code is "LV1B" or "VR04" or "LEV1"
? OriginalCameraRay.FromRouteScene(world, level.Code) : null;
simulation = new LabSimulation(new SceneCollision(world), standingPose, originalStart.Position, originalStart.Rotation.Y,
cameraRay == null ? null : (look, eye) => cameraRay.Trace(look, eye))
{ LevelCode = level.Code, InputAfterPlayerUpdate = carriedSave != null };
}
if (walking && returning) simulation!.RestoreReturnRoot(returnRoot);
var placement = PreviewCharacterPlacement.Create(mesh, standingPose, originalStart.Position, originalStart.Rotation.Y);
characterModel = placement.Model;
mesh = animations.Current.AppendTo(mesh);
if (walking)
Console.WriteLine("Controllable lab: arrows move/turn; Shift/Insert/right mouse jump; R reset; C pause/inspect; F11 fullscreen; Escape quit. Collision, pivot and timing remain provisional.");
else
Console.WriteLine($"Preview floor correction: +{placement.VerticalCorrection:F3} Y. 1 idle, 2 run, 3 jump, 4 scratch.");
}
if (story)
{
resources = new PreparedEntityResources(Path.Combine(Path.GetDirectoryName(scene!)!, "entities/entities.json"),
Path.Combine(Path.GetDirectoryName(scene!)!, "../effects/effects.json"));
var save = loadedSave ?? OriginalSave.Load(AssetPath.Resolve(root, "NewGame.tsk"));
returnRoot = save.StoredVector;
var tasks = new TaskStates(save.Tasks);
storyTasks = tasks;
director = new SceneDirector(level!, tasks, resources.Duration);
interactions = new SceneInteractions(director, tasks, save);
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);
mechanisms = new SceneMechanisms(director);
interactions.Transition += RequestTransition;
interactions.PracticeRequested += practice.Show;
practice.Chosen += (mode, accepted) =>
{
if (!accepted) { objectivePanel.Show(); return; }
// Player43B5A0 captures root separately from42AF00's pickup checkpoint.
interactions.SetReturnContext(Path.GetFileName(levelPath!), originalStart!.Tag!);
RequestTransition(new(PracticePrompt.Destination(mode), "PHONEBOOTH", 0, -1));
};
interactions.Collected += (entity, points) => Console.WriteLine($"Collected {entity.Tag}: +{points}; score={interactions.Score}.");
foreach (var actor in director.Actors.Where(a => a.Kind is "3DOG" or "3CAR"))
{
var physics = new OriginalScenePhysics(world);
var grounded = false;
var patrol = new ActorPatrol(actor, director.FindActor, (body, dt) =>
{
var resolved = physics.Step(body.Position, body.Velocity,
actor.Kind == "3DOG" ? OriginalBodySupport.GoddardRadius : 100,
actor.Kind == "3DOG" ? OriginalBodySupport.GoddardFactor : .75f, grounded, dt);
grounded = resolved.Supported;
return new(resolved.Body.Position, resolved.Body.Velocity);
});
patrols.Add(actor.Tag, patrol);
director.RegisterPatrolConsumer(actor.Tag);
director.ActorChanged += changed => { if (ReferenceEquals(changed, actor)) patrol.SynchronizeAuthoredState(); };
}
actorVisuals = new SceneActorVisuals(mesh, world, director, Path.GetFullPath(Path.Combine(Path.GetDirectoryName(scene!)!, "..")),
actor => patrols.ContainsKey(actor.Tag));
mesh = actorVisuals.Mesh;
spriteVisuals = new SceneSpriteVisuals(mesh, director, resources);
mesh = spriteVisuals.Mesh;
staticVisuals = new StaticSceneVisuals(mesh, director, root, Path.Combine(Path.GetDirectoryName(scene!)!, "models"));
mesh = staticVisuals.Mesh;
simulation!.DynamicRootResolver = (previous, position, radius) =>
DynamicBodyResponse.Resolve(staticVisuals.DoorColliders(), previous, position, radius);
jetpackVisuals = new JetpackVisuals(mesh, Path.GetFullPath(Path.Combine(Path.GetDirectoryName(scene!)!, "..")));
mesh = jetpackVisuals.Mesh;
hud = new SceneHud(mesh, Path.Combine(Path.GetDirectoryName(scene!)!, "../ui/ui.json"));
mesh = hud.Mesh;
Console.WriteLine($"Prepared source model actors: {staticVisuals.ActorCount}.");
}
var debugMenu = new DebugMenu(scene != null && level != null
? DebugMenu.AvailableScenes(root, Path.GetFullPath(Path.Combine(Path.GetDirectoryName(scene)!, ".."))) : [],
Path.GetFileName(levelPath), originalStart?.Tag);
if (args.Contains("--debug-menu")) debugMenu.Toggle(storyTasks?.Get("SCENE") ?? 0);
var debugOverlay = new DebugMenuOverlay(mesh);
mesh = debugOverlay.Mesh;
Console.WriteLine($"Loaded original geometry and overlays: {mesh.Vertices.Length} vertices, {mesh.Indices.Length / 3} triangles, {mesh.Textures.Count + (scene == null ? 1 : 0)} textures.");
var fixedTimeText = Option(args, "--time");
double? fixedTime = fixedTimeText == null ? null : double.Parse(fixedTimeText, System.Globalization.CultureInfo.InvariantCulture);
var headless = args.Contains("--headless");
if (practiceReturnSmoke && (!headless || level?.Code is not ("LV1B" or "VR04") || carriedSave == null && loadedSave != null))
throw new ArgumentException("Practice RETURN check requires a fresh headless lab or its carried tutorial/return");
if (args.Contains("--smoke-transition") && (!headless || level?.Code is not ("VR01" or "VR04") || interactions == null))
throw new ArgumentException("Transition smoke requires headless story playback of VR01 or VR04.");
if (args.Contains("--smoke-lab-route") && (!headless || level?.Code != "LV1B" || interactions == null || loadedSave != null))
throw new ArgumentException("Lab route smoke requires fresh headless story playback of LV1B.");
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" : objectiveWindowSmoke ? "180" : carlSmoke ? "60" : debugSmoke ? "16" : diagnosticsSmoke ? "24" : headless ? "1" : "0"));
if (debugSmoke && (headless || frames < 16 || director == null || level?.Code != "LV1B" || loadedSave != null || debugMenu.Open))
throw new ArgumentException("Debug SDL smoke requires fresh windowed LV1B, closed debug menu and at least16 frames");
if (diagnosticsSmoke && (headless || frames < 24 || director == null || level?.Code != "LV1B" || loadedSave != null
|| debugMenu.Open || diagnostics.Enabled || debugSmoke))
throw new ArgumentException("Live debug SDL smoke requires fresh windowed LV1B, hidden diagnostics and at least24 frames");
if (objectiveWindowSmoke && (headless || frames < 180)) throw new ArgumentException("Objective window smoke needs180 window frames");
if ((carlSmoke || objectiveSmoke) && (level?.Code != "LV1B" || loadedSave != null || objectiveSmoke && !headless && !objectiveWindowSmoke))
throw new ArgumentException("Lab conversation/objective smoke requires fresh LV1B (objective check is headless)");
if (jetpackSmoke && (level?.Code != "VR04" || frames < 300))
throw new ArgumentException("Jetpack smoke requires VR04 and at least300 frames");
if (walkSmoke && frames < 240) throw new ArgumentException("Walk smoke requires at least 240 frames.");
var smoke = args.Contains("--smoke-window");
if (frames < 0 || (smoke && (headless || frames < 6)))
throw new ArgumentException("Invalid frame count; window smoke requires at least six frames.");
if (practiceWindowSmoke && (headless || frames < 12 || level?.Code != "LV1B" || loadedSave != null))
throw new ArgumentException("Practice window smoke requires fresh LV1B and at least12 windowed frames.");
var width = uint.Parse(Option(args, "--width") ?? "960");
var height = uint.Parse(Option(args, "--height") ?? "720");
if (width is < 64 or > 8192 || height is < 64 or > 8192) throw new ArgumentException("Viewport dimensions must be64..8192");
var renderer = presentation.LoadScene(mesh, texture, headless,
walking ? WalkTitle : animations?.WindowTitle ?? "Jimmy Neutron — scene preview | C camera",
width, height, !args.Contains("--no-validation"));
var window = presentation.Window;
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);
double initialPoseTime = 0;
if (director != null)
{
if (sceneAudio != null)
{
director.Speech += sceneAudio.Speech;
director.MusicStopped += sceneAudio.StopMusic;
director.MusicRestarted += sceneAudio.RestartMusic;
objectivePanel!.SoundEffect += id => { if (level!.Code == "LV1B") sceneAudio.Effect(id); };
interactions!.SoundEffect += id => sceneAudio.Effect(id);
mechanisms!.Sound += (actor, id, loop) => sceneAudio.Effect(id, loop ? actor.Tag : null);
mechanisms.StopSound += actor => sceneAudio.StopLoop(actor.Tag);
sceneAudio.Music(originalStart!.Text("MusicDatabase") ?? "none", originalStart.Integer("MusicIndex", -1));
}
director.Begin(originalStart!, activateStartTrigger: !returning);
interactions!.Reset();
mechanisms!.Reset();
director.SyncActor(level!.Player!.Tag!, simulation!.ActorRoot, new Vector3(0, simulation.Yaw, 0));
if (returning && director.FindActor("C3DGODDARD") is { } companion)
director.SyncActor(companion.Tag, returnRoot, companion.Rotation); //423AE3..423B1E, no offset.
if (practiceReturnSmoke && returning)
{
var restored = director.Controlled && !director.Playing && director.CurrentTag == null
&& Vector3.Distance(simulation.ActorRoot, returnRoot) < .001f
&& Vector2.Distance(new(returnRoot.X, returnRoot.Z), new(originalStart!.Position.X, originalStart.Position.Z)) > 100;
var companionRestored = director.FindActor("C3DGODDARD")?.Position == returnRoot;
restored &= companionRestored && simulation.InputAfterPlayerUpdate && interactions.Inventory.State(0, 3) == 1;
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 || debugSmoke || diagnosticsSmoke) { sceneAudio?.StopSpeech(); director.Skip(); }
if (practiceReturnSmoke && level.Code == "VR04")
{
if (interactions!.Inventory.State(0, 3) != 4)
throw new InvalidOperationException("Tutorial PostLoad did not disable the owned gadget before VR04's bypass");
director.Skip();
interactions!.Update(level.Entities.First(e => e.Kind == "LOAD").Position);
if (transitionRequest is not { Returning: true }) throw new InvalidOperationException("VR04 exit did not preserve RETURN identity");
}
if (args.Contains("--smoke-transition"))
{
director.Skip();
interactions!.Update(level!.Entities.First(e => e.Kind == "LOAD").Position);
if (transitionRequest == null) throw new InvalidOperationException("Original VR01 RETURN contact did not request a transition");
}
if (args.Contains("--smoke-lab-route"))
{
LabRouteSmoke.Run(level!, director, interactions!, () => practice.Key(17, Vector2.Zero));
if (transitionRequest?.LevelFile != "level1.gam")
throw new InvalidOperationException("Original lab exit did not request level1.gam");
}
if (carlSmoke) LabRouteSmoke.StartCarl(level!, director, interactions!, () => practice.Key(17, Vector2.Zero));
if (objectiveSmoke)
{
director.Skip();
director.Touch(level!.Player!.Tag!, level.Entities.Single(e => e.Tag == "teleportexplanation").Position);
director.Skip();
if (interactions!.CurrentObjective != 1) throw new InvalidOperationException("Original explanation did not assign objective1");
if (objectiveWindowSmoke) objectivePanel!.Step(9);
}
if (args.Contains("--smoke-practice-prompt") || args.Contains("--smoke-practice-transition") || practiceWindowSmoke
|| practiceReturnSmoke && level.Code == "LV1B" && !returning)
{
if ((!headless && !practiceWindowSmoke) || level?.Code != "LV1B") throw new ArgumentException("Practice smoke requires the original lab");
director.Skip();
if (practiceReturnSmoke)
{
// Move the real player away from STRT so an accidental
// restart at the authored spawn cannot pass this check.
for (var tick = 0; tick < 45; tick++) simulation.Step(new(true, false, false, false, false));
director.SyncActor(level.Player!.Tag!, simulation.ActorRoot, new(0, simulation.Yaw, 0));
}
director.Touch(level!.Player!.Tag!, level.Entities.Single(e => e.Tag == "teleportexplanation").Position);
director.Skip();
interactions!.Update(director.FindActor("shrinkray")!.Position);
if (!practice.Active) throw new InvalidOperationException("Original lab pickup did not open practice modal");
if (args.Contains("--smoke-practice-transition") || practiceReturnSmoke) practice.Key(28, Vector2.Zero);
}
for (var tick = 0; tick < (int)Math.Round(storyTime * 60) && !practice.Active && !debugMenu.Open; tick++)
{
foreach (var patrol in patrols.Values) patrol.Step(FixedStepClock.Step);
mechanisms!.Step(FixedStepClock.Step);
director.Step(FixedStepClock.Step);
objectivePanel!.Step(FixedStepClock.Step, director.ControlledTag != null, practice.Active);
if (animations!.SelectAction(director.FindActor(level!.Player!.Tag!)!.Animation)) initialPoseTime = 0;
initialPoseTime += FixedStepClock.Step;
actorVisuals!.Update(FixedStepClock.Step, mesh);
spriteVisuals!.Step(FixedStepClock.Step);
}
}
var keys = new HashSet<uint>();
var debugCapturedKeys = new HashSet<uint>();
var running = true;
var sawKey = false;
var didResize = false;
var clock = Stopwatch.StartNew();
var animationStarted = 0.0;
var animationSwitched = false;
var inspecting = !walking;
var active = presentation.HasInputFocus;
var mouseJump = false;
var stepClock = new FixedStepClock();
double poseTime = initialPoseTime;
var injectedInput = default(PlayerInput);
var sawWalkKeys = 0;
var sawJetpackKeys = 0;
float poweredAirTravel = 0;
var poweredAirTurn = false;
var objectiveWasHidden = false;
var objectiveReopened = false;
var objectiveClosing = false;
var sawPracticeDismiss = false;
var sawPracticePause = false;
double last = clock.Elapsed.TotalSeconds;
float angle = 0.6f, elevation = 0.32f;
var count = 0;
var lastPresentedAt = clock.Elapsed.TotalSeconds;
var debugPauseObserved = false;
var debugActionsObserved = false;
var debugEscapeObserved = false;
var debugResumeObserved = false;
var debugForceObserved = false;
float debugForceTravel = 0;
var diagnosticsShown = false;
var diagnosticsHidden = false;
var diagnosticsMoves = false;
var diagnosticsMenuPriority = false;
var diagnosticsPreference = false;
var diagnosticsMenuToggle = false;
var diagnosticsPausedSteps = 0;
var diagnosticsInitialTravel = simulation?.Travel ?? 0;
var debugPausedRoot = simulation?.ActorRoot ?? Vector3.Zero;
var debugPausedSteps = simulation?.Steps ?? 0;
void ResetScene()
{
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();
director?.SyncActor(level!.Player!.Tag!, simulation.ActorRoot, new Vector3(0, simulation.Yaw, 0));
}
void ToggleCamera()
{
if (originalStart == null) { debugMenu.Message = "CAMERA REQUIRES A SCENE START"; return; }
if (simulation == null) { originalCamera = !originalCamera; return; }
inspecting = !inspecting;
originalCamera = false; target = simulation.ActorRoot; radius = 600;
if (window != 0 && !Sdl.SDL_SetWindowTitle(window, inspecting ? animations!.WindowTitle : WalkTitle))
throw new InvalidOperationException(Sdl.Error);
}
void DebugInputBoundary()
{
debugCapturedKeys.UnionWith(keys);
keys.Clear(); mouseJump = false; stepClock.Reset(); last = clock.Elapsed.TotalSeconds;
audio?.SetPaused(debugMenu.Open); sceneAudio?.SetPaused(debugMenu.Open);
}
void DebugCommand(DebugAction action)
{
switch (action)
{
case DebugAction.Resume: debugMenu.Close(); break;
case DebugAction.Camera: ToggleCamera(); debugMenu.Close(); break;
case DebugAction.SkipCutscene:
if (director is { Playing: true } or { Blocked: true } or { Controlled: false })
{ sceneAudio?.StopSpeech(); director.Skip(); debugMenu.Message = "CUTSCENE SKIPPED"; }
else debugMenu.Message = "NO ACTIVE CUTSCENE";
break;
case DebugAction.RefillEnergy when simulation != null:
simulation.Energy = 100; interactions?.UpdateEnergy(100); debugMenu.Message = "ENERGY REFILLED"; break;
case DebugAction.GiveJetpack when interactions != null:
interactions.Inventory.SetState(0, 3, 1); interactions.Inventory.SelectGadget(3);
debugMenu.Message = "JET PACK GIVEN AND SELECTED"; break;
case DebugAction.ApplySceneTask when storyTasks != null:
storyTasks.SetExisting("SCENE", debugMenu.SceneTask); debugMenu.Message = $"SCENE TASK SET TO {debugMenu.SceneTask}"; break;
case DebugAction.LoadScene when simulation != null && interactions != null && debugMenu.Scene is { } selected:
var prepared = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(scene!)!, ".."));
var selectedWorld = Mesh.LoadSceneJson(AssetPath.Resolve(prepared,
Path.GetFileNameWithoutExtension(selected.LevelFile) + "/scene.json"));
var selectedStart = GamLevel.Load(AssetPath.Resolve(root, "gam/" + selected.LevelFile)).FindStart(debugMenu.Start)!;
if (new SceneCollision(selectedWorld).GroundHeight(selectedStart.Position, 2500) == null)
{ debugMenu.Message = "SELECTED START HAS NO SUPPORTED FLOOR"; break; }
RequestTransition(new(selected.LevelFile, debugMenu.Start!, 0, -1)); debugMenu.Close(); break;
case DebugAction.Reset: ResetScene(); debugMenu.Close(); break;
case DebugAction.ForceControl when director != null:
director.DebugForceControl = !director.DebugForceControl;
debugMenu.Message = $"FORCE CONTROL {director.DebugForceControl}; CLOSE MENU TO RESUME"; break;
case DebugAction.ToggleOverlay:
diagnostics.Enabled = !diagnostics.Enabled;
debugMenu.Message = $"LIVE OVERLAY {diagnostics.Enabled}; F2 TOGGLE DURING PLAY"; break;
case DebugAction.None: break;
default: debugMenu.Message = "ACTION REQUIRES PLAY MODE"; break;
}
}
Vector2 Pointer()
{
Sdl.SDL_GetMouseState(out var x, out var y);
if (!Sdl.SDL_GetWindowSize(window, out var w, out var h) || w < 1 || h < 1) return Vector2.Zero;
return new UiViewport(renderer.Width, renderer.Height).InverseModal(new(x, y), (uint)w, (uint)h);
}
while (running)
{
if ((walkSmoke || jetpackSmoke) && !headless)
{
var requested = jetpackSmoke ? LabSimulation.JetpackSmokeInput(simulation!.Steps)
: LabSimulation.SmokeInput(simulation!.Steps);
foreach (var (scancode, down, previous) in new[] {
(82u, requested.Forward, injectedInput.Forward),
(81u, requested.Backward, injectedInput.Backward), (80u, requested.Left, injectedInput.Left),
(79u, requested.Right, injectedInput.Right), (jumpScancode, requested.Jump, injectedInput.Jump) })
{
if (down == previous) continue;
var injected = scancode == 0
? new Sdl.Event { Type = down ? Sdl.MouseButtonDown : Sdl.MouseButtonUp, MouseButton = 3 }
: new Sdl.Event { Type = down ? Sdl.KeyDown : Sdl.KeyUp, Scancode = scancode, Down = down ? (byte)1 : (byte)0 };
if (!Sdl.SDL_PushEvent(ref injected)) throw new InvalidOperationException(Sdl.Error);
}
injectedInput = requested;
}
while (!headless && Sdl.SDL_PollEvent(out var e))
{
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)
{ keys.Clear(); debugCapturedKeys.Clear(); mouseJump = false; active = false; stepClock.Reset(); }
if (e.Type is Sdl.WindowFocusGained or Sdl.WindowRestored)
{ active = true; stepClock.Reset(); last = clock.Elapsed.TotalSeconds; }
if (e.Type == Sdl.KeyUp && debugCapturedKeys.Remove(e.Scancode)) continue;
if (e.Type == Sdl.KeyDown && !debugMenu.Open && debugCapturedKeys.Contains(e.Scancode)) continue;
if (e.Type == Sdl.KeyDown && e.Scancode == DebugDiagnostics.ToggleKey)
{
debugCapturedKeys.Add(e.Scancode);
if (e.Repeat == 0) diagnostics.Enabled = !diagnostics.Enabled;
continue;
}
if (e.Type == Sdl.KeyDown && e.Scancode == DebugMenu.ToggleKey)
{
debugCapturedKeys.Add(e.Scancode);
if (e.Repeat == 0) { debugMenu.Toggle(storyTasks?.Get("SCENE") ?? 0); DebugInputBoundary(); }
continue;
}
if (debugMenu.Open)
{
if (e.Type == Sdl.KeyDown)
{
debugCapturedKeys.Add(e.Scancode);
DebugCommand(debugMenu.Key(e.Scancode, e.Repeat != 0));
if (!debugMenu.Open) DebugInputBoundary();
}
continue;
}
if (practice.Active && e.Type == Sdl.MouseButtonDown)
{ if (e.MouseButton == 1) practice.Click(Pointer()); keys.Clear(); mouseJump = false; stepClock.Reset(); continue; }
if (practice.Active && e.Type == Sdl.KeyDown)
{
if (e.Repeat == 0) practice.Key(e.Scancode, Pointer());
if (practiceWindowSmoke && e.Scancode == 17 && !practice.Active) sawPracticeDismiss = true;
keys.Clear(); mouseJump = false; stepClock.Reset(); continue;
}
if (e.Type == Sdl.MouseButtonDown && e.MouseButton == 3)
{
mouseJump = true;
if (jumpScancode == 0) { if (jetpackSmoke) sawJetpackKeys |= 8; if (walkSmoke) sawWalkKeys |= 4; }
}
if (e.Type == Sdl.MouseButtonUp && e.MouseButton == 3) mouseJump = false;
if (e.Type == Sdl.KeyDown)
{
keys.Add(e.Scancode);
if (walkSmoke) sawWalkKeys |= e.Scancode == 82 ? 1 : e.Scancode == 79 ? 2 : e.Scancode == jumpScancode ? 4 : 0;
if (jetpackSmoke) sawJetpackKeys |= e.Scancode == 82 ? 1 : e.Scancode == 81 ? 2 : e.Scancode == 80 ? 4 : e.Scancode == jumpScancode ? 8 : 0;
if (smoke && e.Scancode == 79) sawKey = true;
if (e.Scancode is 41 or 44 && e.Repeat == 0 && director is { Controlled: false })
{ sceneAudio?.StopSpeech(); director.Skip(); keys.Clear(); mouseJump = false; }
else if (e.Scancode == 41) running = false;
if (inspecting && e.Repeat == 0 && animations?.Select(e.Scancode) == true)
{
animationStarted = clock.Elapsed.TotalSeconds;
animationSwitched = true;
if (!Sdl.SDL_SetWindowTitle(window, animations.WindowTitle)) throw new InvalidOperationException(Sdl.Error);
}
if (e.Scancode == 6 && e.Repeat == 0 && originalStart != null)
{
ToggleCamera(); keys.Clear(); mouseJump = false; stepClock.Reset();
}
if (!inspecting && e.Scancode == 21 && e.Repeat == 0)
{
ResetScene();
}
if (e.Scancode == 68 && e.Repeat == 0)
{
presentation.ToggleFullscreen();
}
}
if (e.Type == Sdl.KeyUp) keys.Remove(e.Scancode);
}
var now = clock.Elapsed.TotalSeconds;
var elapsed = now - last;
var dt = (float)Math.Min(elapsed, 0.1);
last = now;
if (debugMenu.Open) animationStarted += elapsed;
if (simulation != null && !debugMenu.Open && !inspecting && !practice.Active && (active || headless || walkSmoke || jetpackSmoke || objectiveWindowSmoke || debugSmoke || diagnosticsSmoke))
{
var steps = headless || walkSmoke || jetpackSmoke || practiceWindowSmoke || carlSmoke || objectiveWindowSmoke || debugSmoke || diagnosticsSmoke ? 1 : stepClock.Advance(elapsed);
for (var step = 0; step < steps; step++)
{
var input = carlSmoke ? new PlayerInput(true, false, true, false, true)
: jetpackSmoke && headless ? LabSimulation.JetpackSmokeInput(simulation.Steps)
: walkSmoke && headless ? LabSimulation.SmokeInput(simulation.Steps) : new PlayerInput(
keys.Contains(82), keys.Contains(81), keys.Contains(80), keys.Contains(79),
mouseJump || keys.Contains(225) || keys.Contains(229) || keys.Contains(73) || keys.Contains(98));
if (director?.Controlled != false)
{
var before = simulation.Position;
var powered = simulation.JetpackEffectVisible && !simulation.Grounded;
simulation.Step(input);
if (jetpackSmoke && powered)
{
poweredAirTravel += Vector2.Distance(new(before.X, before.Z), new(simulation.Position.X, simulation.Position.Z));
poweredAirTurn |= MathF.Abs(simulation.TurnRate) > 1;
}
interactions?.UpdateEnergy(simulation.Energy);
director?.SyncActor(level!.Player!.Tag!, simulation.ActorRoot, new Vector3(0, simulation.Yaw, 0));
director?.Touch(level!.Player!.Tag!, simulation.ActorRoot);
interactions?.Update(simulation.ActorRoot, simulation.InteractionRadius);
if (practice.Active) { keys.Clear(); mouseJump = false; stepClock.Reset(); break; }
mechanisms?.Update(simulation.ActorRoot, simulation.InteractionRadius);
}
mechanisms?.Step(FixedStepClock.Step);
foreach (var patrol in patrols.Values) patrol.Step(FixedStepClock.Step);
director?.Step(FixedStepClock.Step);
objectivePanel?.Key(keys.Contains(18) && director is { Controlled: true, InventoryEnabled: true });
objectivePanel?.Step(FixedStepClock.Step, director?.ControlledTag != null, practice.Active);
var switched = director is { Controlled: false }
? animations!.SelectAction(director.FindActor(level!.Player!.Tag!)!.Animation)
: animations!.SelectPose(simulation.Pose);
if (switched) poseTime = 0;
poseTime += FixedStepClock.Step;
actorVisuals?.Update(FixedStepClock.Step, mesh);
spriteVisuals?.Step(FixedStepClock.Step);
}
characterModel = simulation.Model;
}
if (inspecting && !debugMenu.Open)
{
if (keys.Contains(80) || keys.Contains(4)) angle -= dt;
if (keys.Contains(79) || keys.Contains(7)) angle += dt;
if (keys.Contains(82) || keys.Contains(26)) elevation = Math.Min(elevation + dt, 1.4f);
if (keys.Contains(81) || keys.Contains(22)) elevation = Math.Max(elevation - dt, -1.4f);
if (keys.Contains(46) || keys.Contains(87)) radius *= MathF.Exp(-dt);
if (keys.Contains(45) || keys.Contains(86)) radius *= MathF.Exp(dt);
}
radius = Math.Max(radius, 0.01f);
var eye = target + radius * new Vector3(MathF.Cos(elevation) * MathF.Sin(angle),
MathF.Sin(elevation), MathF.Cos(elevation) * MathF.Cos(angle));
var view = originalCamera
? Matrix4x4.CreateLookAtLeftHanded(originalStart!.CameraPosition, originalStart.Position + new Vector3(0, 80, 0), Vector3.UnitY)
: Matrix4x4.CreateLookAt(eye, target, Vector3.UnitY);
var renderEye = originalCamera ? originalStart!.CameraPosition : eye;
var renderTarget = originalCamera ? originalStart!.Position + new Vector3(0,80,0) : target;
if (simulation != null && !inspecting)
{
view = Matrix4x4.CreateLookAtLeftHanded(simulation.CameraEye, simulation.CameraTarget, Vector3.UnitY);
renderEye = simulation.CameraEye; renderTarget = simulation.CameraTarget;
}
if (!inspecting && director?.CameraEye is { } storyEye && director.CameraTarget is { } storyTarget)
{
view = Matrix4x4.CreateLookAtLeftHanded(storyEye, storyTarget, Vector3.UnitY);
renderEye = storyEye; renderTarget = storyTarget;
}
staticVisuals?.Update(mesh);
jetpackVisuals?.Update(mesh, simulation!);
spriteVisuals?.FaceCamera(renderEye, renderTarget, mesh);
objectivePanel?.Key(keys.Contains(18) && !debugMenu.Open && !inspecting && !practice.Active
&& director is { Controlled: true, InventoryEnabled: true });
objectivePanel?.Step(0, director?.ControlledTag != null, practice.Active);
hud?.Update(mesh, interactions!.CurrentObjective, level!.Code == "LV1B" && objectivePanel!.PadVisible,
practice.Active, objectivePanel!.YOffset, objectivePanel.ContentVisible, renderer.Width, renderer.Height);
var gameplayProjection = originalCamera || simulation != null && !inspecting;
var cameraMode = !inspecting && director?.CameraEye != null ? "CUTSCENE"
: simulation != null && !inspecting ? "GAMEPLAY" : originalCamera ? "STRT" : "ORBIT";
var debugStatus = new DebugStatus(level?.Code ?? "PREVIEW", originalStart?.Tag ?? "NONE",
simulation?.ActorRoot ?? Vector3.Zero, simulation?.Yaw ?? 0, simulation?.Speed ?? 0,
simulation?.Grounded ?? false, simulation?.Energy ?? 0, interactions?.Score ?? 0,
storyTasks?.Get("SCENE") ?? 0, director?.CurrentTag ?? "NONE", director?.Controlled ?? false,
(director?.Issues.Count ?? 0) + (interactions?.Unsupported.Count ?? 0) + (mechanisms?.Unsupported.Count ?? 0),
gameplayProjection ? SceneProjection.FarPlane(level?.Code) : radius * 20,
inspecting, director?.DebugForceControl ?? false, diagnostics.Enabled, cameraMode);
var debugView = debugMenu.View(debugStatus);
var liveDebugLines = diagnostics.Lines(debugStatus, new(simulation?.Velocity ?? Vector3.Zero,
simulation?.TurnRate ?? 0, simulation?.Pose.ToString() ?? "NONE", simulation?.Steps ?? 0,
simulation?.Jumps ?? 0, simulation?.WallHits ?? 0, interactions?.Inventory.State(0, 3) ?? 0,
simulation?.JetpackRemaining ?? 0, director?.CurrentShot ?? -1, director?.Blocked ?? false,
renderer.ValidationErrors, debugMenu.Open || practice.Active || inspecting || !active));
var liveDebugVisible = !debugMenu.Open && liveDebugLines.Length > 0;
debugOverlay.Update(mesh, debugMenu.Open ? debugView.Lines : liveDebugLines,
debugMenu.Open ? debugView.SelectedLine : -1, compact: !debugMenu.Open,
viewportWidth: renderer.Width, viewportHeight: renderer.Height);
var projection = gameplayProjection
? SceneProjection.CreateGameplay(level?.Code, (float)renderer.Width / renderer.Height)
: Matrix4x4.CreatePerspectiveFieldOfView(MathF.PI / 3, (float)renderer.Width / renderer.Height, Math.Max(radius / 10000, 0.01f), radius * 20);
projection.M22 *= -1;
if (animations != null)
{
animations.Current.Sample(simulation != null && !inspecting ? poseTime
: fixedTime ?? (headless ? count / 60.0 : now - animationStarted),
mesh.Vertices.AsSpan(characterOffset, animations.Current.Base.Vertices.Length), characterModel);
}
renderer.UpdateVertices(mesh.Vertices);
renderer.Render(view * projection);
var presentedAt = clock.Elapsed.TotalSeconds;
diagnostics.ObserveFrame(presentedAt - lastPresentedAt);
lastPresentedAt = presentedAt;
count++;
audio?.Pump();
sceneAudio?.Pump();
if (diagnosticsSmoke)
{
void Push(uint key, bool down = true, bool repeat = false)
{
var e = new Sdl.Event { Type = down ? Sdl.KeyDown : Sdl.KeyUp, Scancode = key,
Down = down ? (byte)1 : (byte)0, Repeat = repeat ? (byte)1 : (byte)0 };
if (!Sdl.SDL_PushEvent(ref e)) throw new InvalidOperationException(Sdl.Error);
}
void Tap(uint key) { Push(key); Push(key, false); }
if (count == 1)
{
Push(82); Push(DebugDiagnostics.ToggleKey); Push(DebugDiagnostics.ToggleKey, repeat: true);
Push(DebugDiagnostics.ToggleKey, false);
if (!Sdl.SDL_SetWindowSize(window, 800, 600)) throw new InvalidOperationException(Sdl.Error);
}
if (count == 3)
diagnosticsShown = liveDebugVisible && !debugMenu.Open && sceneAudio?.Paused != true && liveDebugLines.Length == 12;
if (count == 4) Tap(DebugDiagnostics.ToggleKey);
if (count == 5) diagnosticsHidden = !liveDebugVisible && !diagnostics.Enabled && simulation!.Steps >= 5;
if (count == 6) Tap(DebugDiagnostics.ToggleKey);
if (count == 8)
{
diagnosticsMoves = liveDebugVisible && simulation!.Travel > diagnosticsInitialTravel + 5;
diagnosticsPausedSteps = simulation!.Steps;
Tap(DebugMenu.ToggleKey);
}
if (count == 9)
{
diagnosticsMenuPriority = debugMenu.Open && diagnostics.Enabled && !liveDebugVisible
&& simulation!.Steps == diagnosticsPausedSteps && sceneAudio?.Paused != false;
Tap(DebugDiagnostics.ToggleKey);
}
if (count == 10)
{
diagnosticsPreference = !diagnostics.Enabled && debugMenu.Open && sceneAudio?.Paused != false;
Tap(DebugDiagnostics.ToggleKey); Tap(DebugMenu.ToggleKey);
}
if (count == 11)
{
diagnosticsPreference &= diagnostics.Enabled && liveDebugVisible && !debugMenu.Open && sceneAudio?.Paused != true;
Push(82, false); Push(82);
}
if (count == 16) Tap(DebugDiagnostics.ToggleKey);
if (count == 18)
{
Tap(DebugMenu.ToggleKey); Tap(82); Tap(40); Tap(41); // Last menu row toggles the live panel.
}
if (count == 19) diagnosticsMenuToggle = diagnostics.Enabled && liveDebugVisible && !debugMenu.Open;
if (count == 20) Push(82, false);
}
if (debugSmoke)
{
void Push(uint key, bool down = true, bool repeat = false)
{
var e = new Sdl.Event { Type = down ? Sdl.KeyDown : Sdl.KeyUp, Scancode = key,
Down = down ? (byte)1 : (byte)0, Repeat = repeat ? (byte)1 : (byte)0 };
if (!Sdl.SDL_PushEvent(ref e)) throw new InvalidOperationException(Sdl.Error);
}
void Tap(uint key) { Push(key); Push(key, false); }
if (count == 1)
{
debugPausedRoot = simulation!.ActorRoot; debugPausedSteps = simulation.Steps;
director!.Trigger("neutron1a"); // Exercise opening the menu during an actual source MCA.
Push(82); Tap(DebugMenu.ToggleKey);
if (!Sdl.SDL_SetWindowSize(window, 800, 600)) throw new InvalidOperationException(Sdl.Error);
}
if (count == 3)
{
debugPauseObserved = debugMenu.Open && simulation!.ActorRoot == debugPausedRoot
&& simulation.Steps == debugPausedSteps && sceneAudio?.Paused != false && director!.Playing;
Tap(81); Tap(81); Tap(40); // Skip cutscene.
Tap(81); Tap(40); // Refill.
Tap(81); Tap(40); // Jet pack.
Tap(81); Tap(75); Tap(40); // SCENE30 ->40 via staged PageUp then apply.
}
if (count == 5)
{
debugActionsObserved = debugMenu.Open && director!.Controlled && !director.Playing
&& simulation!.Energy == 100 && interactions!.Inventory.State(0, 3) == 1
&& storyTasks!.Get("SCENE") == 40 && simulation.ActorRoot == debugPausedRoot
&& simulation.Steps == debugPausedSteps;
if (Option(args, "--screenshot") is { } debugScreenshot)
renderer.SavePpm(Path.ChangeExtension(debugScreenshot, ".open.ppm"));
}
if (count == 7) { Push(41); Push(41, repeat: true); Push(82, repeat: true); }
if (count == 8)
{
debugEscapeObserved = running && !debugMenu.Open && sceneAudio?.Paused != true
&& MathF.Abs(simulation!.ActorRoot.X - debugPausedRoot.X) < .001f
&& MathF.Abs(simulation.ActorRoot.Z - debugPausedRoot.Z) < .001f;
Push(41, false); Push(82, false); Push(82); // Release captured input, then a fresh movement press.
}
if (count == 12)
{
debugResumeObserved = simulation!.Steps > debugPausedSteps && simulation.Travel > 1;
Push(82, false);
director!.Trigger("neutron1a");
Tap(DebugMenu.ToggleKey);
for (var row = 5; row < 10; row++) Tap(81);
Tap(40); // Enable force control while the new MCA remains active.
}
if (count == 13) { debugForceTravel = simulation!.Travel; Tap(41); Push(82); }
if (count == 16)
debugForceObserved = director is { DebugForceControl: true, Controlled: true, Playing: true }
&& simulation!.Travel > debugForceTravel + .1f;
}
if (objectiveWindowSmoke)
{
if (count == 1) objectiveWasHidden = !objectivePanel!.PadVisible;
if (count == 60) objectiveReopened = objectivePanel!.ContentVisible;
if (count == 61) objectiveClosing = objectivePanel!.PadVisible && !objectivePanel.ContentVisible;
if (count is 1 or 2 or 60 or 61)
{
var down = count is 1 or 60;
var key = new Sdl.Event { Type = down ? Sdl.KeyDown : Sdl.KeyUp, Scancode = 18, Down = down ? (byte)1 : (byte)0 };
if (!Sdl.SDL_PushEvent(ref key)) throw new InvalidOperationException(Sdl.Error);
}
if (count == 1 && !Sdl.SDL_SetWindowSize(window, 800, 600)) throw new InvalidOperationException(Sdl.Error);
}
if (practiceWindowSmoke && count == 1)
{
sawPracticePause = practice.Active && simulation!.Steps == 0;
var key = new Sdl.Event { Type = Sdl.KeyDown, Scancode = 17, Down = 1 };
if (!Sdl.SDL_PushEvent(ref key) || !Sdl.SDL_SetWindowSize(window, 800, 600))
throw new InvalidOperationException(Sdl.Error);
}
if ((walkSmoke || jetpackSmoke) && !headless && count == 1 && !Sdl.SDL_SetWindowSize(window, 800, 600))
throw new InvalidOperationException(Sdl.Error);
if (smoke && count == 1)
{
var key = new Sdl.Event { Type = Sdl.KeyDown, Scancode = 79, Down = 1 };
if (!Sdl.SDL_PushEvent(ref key) || !Sdl.SDL_SetWindowSize(window, 800, 600))
throw new InvalidOperationException(Sdl.Error);
if (animations != null)
{
var cycle = new Sdl.Event { Type = Sdl.KeyDown, Scancode = 31, Down = 1 };
if (!Sdl.SDL_PushEvent(ref cycle)) throw new InvalidOperationException(Sdl.Error);
}
}
if ((smoke || walkSmoke || jetpackSmoke || practiceWindowSmoke || objectiveWindowSmoke || debugSmoke || diagnosticsSmoke) && renderer.Width == 800 && renderer.Height == 600) didResize = true;
if (frames > 0 && count >= frames) break;
if (transitionRequest != null) break;
}
if (Option(args, "--screenshot") is { } screenshot)
{
renderer.SavePpm(screenshot);
Console.WriteLine($"Saved Vulkan GPU readback: {screenshot}");
}
var pixels = renderer.ReadPixels();
var changed = 0;
for (var i = 0; i < pixels.Length; i += 4)
if (Math.Abs(pixels[i] - 31) + Math.Abs(pixels[i + 1] - 51) + Math.Abs(pixels[i + 2] - 76) > 6) changed++;
Console.WriteLine($"Rendered {count} frame(s), {changed} non-background pixels, {renderer.ValidationErrors} Vulkan validation error(s).");
if (simulation != null) Console.WriteLine(simulation.Report);
if (diagnostics.Enabled) Console.WriteLine($"Live debug overlay: enabled=True, frame samples={diagnostics.Frames}.");
if (diagnosticsSmoke)
{
Console.WriteLine($"Live debug SDL check: shown={diagnosticsShown}, hidden={diagnosticsHidden}, movement={diagnosticsMoves}, menu priority={diagnosticsMenuPriority}, preference={diagnosticsPreference}, menu toggle={diagnosticsMenuToggle}, resize800x600={didResize}.");
if (!diagnosticsShown || !diagnosticsHidden || !diagnosticsMoves || !diagnosticsMenuPriority
|| !diagnosticsPreference || !diagnosticsMenuToggle || !didResize) return 2;
}
if (debugSmoke)
{
Console.WriteLine($"Debug SDL check: paused={debugPauseObserved}, actions={debugActionsObserved}, Escape/input capture={debugEscapeObserved}, resumed={debugResumeObserved}, forced movement during MCA={debugForceObserved}, resize800x600={didResize}.");
if (!debugPauseObserved || !debugActionsObserved || !debugEscapeObserved || !debugResumeObserved || !debugForceObserved || !didResize) return 2;
}
if (carlSmoke)
{
var locked = director is { Controlled: false, Playing: true, CurrentTag: "neutron1a" } && simulation!.Steps == 0;
Console.WriteLine($"Carl cutscene input lock with held move/turn/jump: {locked}.");
if (!locked) return 2;
}
if (objectiveSmoke) Console.WriteLine($"Objective panel: time={objectivePanel!.Elapsed:F3}, pad={objectivePanel.PadVisible}, content={objectivePanel.ContentVisible}, offset={objectivePanel.YOffset:F3}.");
if (objectiveWindowSmoke)
{
var timedOut = !objectivePanel!.PadVisible;
Console.WriteLine($"Objective SDL check: hidden={objectiveWasHidden}, O reopened={objectiveReopened}, O closed={objectiveClosing}, timed out={timedOut}, resize800x600={didResize}.");
if (!objectiveWasHidden || !objectiveReopened || !objectiveClosing || !timedOut || !didResize) return 2;
}
if (jetpackSmoke)
{
Console.WriteLine($"Powered jump: bursts={simulation!.Bursts}, remaining={simulation.JetpackRemaining:F3}, energy={simulation.Energy:F3}, grounded={simulation.Grounded}.");
Console.WriteLine($"Powered air steering: travel={poweredAirTravel:F2}, turned={poweredAirTurn}.");
if (!headless) Console.WriteLine($"Jetpack SDL keys received={sawJetpackKeys == 15}, resize800x600={didResize}, jump={jumpBinding}.");
if (simulation.Bursts == 0 || simulation.MaximumRise <= 137.62f || !simulation.Grounded
|| poweredAirTravel <= 20 || !poweredAirTurn || !headless && (sawJetpackKeys != 15 || !didResize)) return 2;
}
if (director != null)
{
Console.WriteLine($"Scene sequence: {director.CurrentTag ?? "none"}, shot={director.CurrentShot}, control={director.Controlled}, blocked={director.Blocked}, issues={director.Issues.Count}.");
foreach (var issue in director.Issues) Console.WriteLine($"Unrecovered scene behavior {issue.Tag}: {issue.Detail}");
foreach (var missing in actorVisuals!.UnsupportedAnimations) Console.WriteLine($"Unrecovered animation alias {missing}");
foreach (var missing in interactions!.Unsupported) Console.WriteLine(missing);
foreach (var missing in mechanisms!.Unsupported) Console.WriteLine(missing);
foreach (var (tag, patrol) in patrols)
Console.WriteLine($"Patrol {tag}: root={director.FindActor(tag)!.Position}, waypoint={patrol.CurrentWaypoint ?? "none"}, velocity={patrol.Velocity}; recovered support, provisional wall response.");
}
if (interactions != null && saveOutput is { } output)
{
Directory.CreateDirectory(Path.GetDirectoryName(output)!);
var snapshot = interactions.Snapshot() with { LevelCode = level!.Code, StartPoint = originalStart!.Tag!, StoredVector = returnRoot };
var temporary = output + "." + Guid.NewGuid().ToString("N") + ".tmp";
try
{
using (var stream = new FileStream(temporary, FileMode.CreateNew, FileAccess.Write, FileShare.None)) stream.Write(snapshot.Encode());
File.Move(temporary, output, true);
}
finally { if (File.Exists(temporary)) File.Delete(temporary); }
Console.WriteLine($"Wrote original-format checkpoint state: {output}");
}
if (transitionRequest != null && renderer.ValidationErrors == 0)
{
var prepared = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(scene!)!, ".."));
var nextScene = AssetPath.Resolve(prepared, Path.GetFileNameWithoutExtension(transitionRequest.LevelFile) + "/scene.json");
var nextArgs = new List<string>();
for (var i = 0; i < args.Length; i++)
{
if (args[i] is "--smoke-transition" or "--smoke-lab-route" or "--smoke-practice-prompt" or "--smoke-practice-transition"
or "--debug-menu" or "--smoke-debug-menu" or "--smoke-debug-overlay") continue;
if (args[i] is "--scene" or "--level" or "--start" or "--load-save" or "--story-time") { i++; continue; }
nextArgs.Add(args[i]);
}
nextArgs.AddRange(["--scene", nextScene, "--level", "gam/" + transitionRequest.LevelFile,
"--start", transitionRequest.StartPoint]);
continuation = new(nextArgs.ToArray(), interactions!.Snapshot() with {
StartPoint = transitionRequest.StartPoint, StoredVector = returnRoot }, transitionRequest.Returning);
Console.WriteLine($"Loading original destination: {transitionRequest.LevelFile}, start={transitionRequest.StartPoint}; fade behavior remains unreconstructed.");
}
if (walkSmoke && !simulation!.SmokePassed) return 2;
if (walkSmoke && !headless)
{
Console.WriteLine($"Walk SDL keyboard events received: {sawWalkKeys == 7}; resize800x600: {didResize}.");
if (sawWalkKeys != 7 || !didResize) return 2;
}
if (smoke)
{
Console.WriteLine($"SDL3 injected keyboard event received: {sawKey}; swapchain resized to 800x600: {didResize}.");
if (!sawKey || !didResize) return 2;
if (animations != null)
{
Console.WriteLine($"Animation preview switched by keyboard to {animations.Name}: {animationSwitched}; moving source samples: {animations.Current.HasVertexMotion}.");
if (!animationSwitched || !animations.Current.HasVertexMotion) return 2;
}
}
if (practiceWindowSmoke)
{
var resumed = !practice.Active && simulation!.Steps > 0;
Console.WriteLine($"Practice SDL check: paused={sawPracticePause}, N dismiss={sawPracticeDismiss}, resumed={resumed}, resize800x600={didResize}.");
if (!sawPracticePause || !sawPracticeDismiss || !resumed || !didResize) return 2;
}
return renderer.ValidationErrors > 0 || changed == 0 ? 2 : 0;
}
}
private const string WalkTitle = "Jimmy Neutron — lab checkpoint | Arrows move | Shift / Insert / right mouse jump | F1 menu | F2 overlay | R reset | C inspect";
private static int VerifyAssets(string root)
{
var pngs = Directory.GetFiles(root, "*", SearchOption.AllDirectories)
.Where(p => p.EndsWith(".png", StringComparison.OrdinalIgnoreCase)).ToArray();
foreach (var path in pngs) PngImage.Load(path);
var models = Directory.GetFiles(AssetPath.Resolve(root, "ASE"), "*", SearchOption.AllDirectories)
.Where(p => p.EndsWith(".ase", StringComparison.OrdinalIgnoreCase)).ToArray();
foreach (var path in models) AseMesh.Load(path);
Console.WriteLine($"Verified runtime decoders: {pngs.Length} PNG textures and {models.Length} ASE base meshes.");
return 0;
}
}