Keep presentation alive across levels and scale UI for widescreen

This commit is contained in:
UnixNight committed 2026-10-25 03:14:04 -04:00
1 parent 113e9a41cc
commit 69d0187a21
26 files changed
+889 -70

No files matched your search

+6 -3
View File
@@ -65,7 +65,8 @@ public sealed class DebugMenuOverlay
/// Layout uses the same640x480 reference viewport as the original HUD.
/// Compact mode uses a corner panel with58 columns and smaller live text.
/// </summary>
public void Update(Mesh destination, IReadOnlyList<string> lines, int selectedLine = -1, bool compact = false)
public void Update(Mesh destination, IReadOnlyList<string> lines, int selectedLine = -1, bool compact = false,
uint viewportWidth = 640, uint viewportHeight = 480)
{
ArgumentNullException.ThrowIfNull(destination);
ArgumentNullException.ThrowIfNull(lines);
@@ -73,6 +74,8 @@ public sealed class DebugMenuOverlay
if (selectedLine < -1 || selectedLine >= lines.Count) throw new ArgumentOutOfRangeException(nameof(selectedLine));
if (destination.Vertices.Length < Mesh.Vertices.Length || destination.Indices.Length < Mesh.Indices.Length)
throw new ArgumentException("Destination omits debug overlay ranges", nameof(destination));
var viewport = new UiViewport(viewportWidth, viewportHeight);
var anchor = compact ? Vector2.Zero : viewport.CenterOffset;
var background = FindDraw(firstIndex, 6);
var highlight = FindDraw(firstIndex + 6, 6);
background.Visible = lines.Count > 0;
@@ -120,9 +123,9 @@ public sealed class DebugMenuOverlay
destination.Vertices[start + 2] = new(Position(x + width, y + height), maxUv, color);
destination.Vertices[start + 3] = new(Position(x, y + height), new(minUv.X, maxUv.Y), color);
}
}
private static Vector3 Position(float x, float y) => new(2 * x / 640 - 1, 2 * y / 480 - 1, 0);
Vector3 Position(float x, float y) => viewport.ToNdc(new Vector2(x, y) + anchor);
}
private static PngImage CreateFont()
{
+58
View File
@@ -0,0 +1,58 @@
using GamePort.Assets;
using GamePort.Platform;
using GamePort.Rendering.Vulkan;
namespace GamePort.Application;
/// <summary>Application-owned presentation; level loads replace only scene resources.</summary>
public sealed class RenderSession : IDisposable
{
private VulkanRenderer? renderer;
private bool videoInitialized;
public nint Window { get; private set; }
public int WindowCreationCount { get; private set; }
public int RendererCreationCount { get; private set; }
public bool Fullscreen => Window != 0 && (Sdl.SDL_GetWindowFlags(Window) & 1) != 0;
public bool HasInputFocus => Window == 0 || (Sdl.SDL_GetWindowFlags(Window) & 0x200) != 0;
public VulkanRenderer LoadScene(Mesh mesh, PngImage fallback, bool headless, string title,
uint width, uint height, bool validation)
{
if (renderer != null)
{
if (headless != (Window == 0)) throw new InvalidOperationException("Cannot change presentation mode during a session");
if (Window != 0 && !Sdl.SDL_SetWindowTitle(Window, title)) throw new InvalidOperationException(Sdl.Error);
renderer.ReplaceScene(mesh, fallback);
return renderer;
}
if (!headless)
{
if (!Sdl.SDL_Init(Sdl.InitVideo)) throw new InvalidOperationException(Sdl.Error);
videoInitialized = true;
Window = Sdl.SDL_CreateWindow(title, checked((int)width), checked((int)height),
Sdl.WindowVulkan | Sdl.WindowResizable | Sdl.WindowHighPixelDensity);
if (Window == 0) throw new InvalidOperationException(Sdl.Error);
WindowCreationCount++;
}
renderer = new(mesh, fallback, width, height, Window, validation);
RendererCreationCount++;
return renderer;
}
public void ToggleFullscreen()
{
if (Window != 0 && !Sdl.SDL_SetWindowFullscreen(Window, !Fullscreen)) throw new InvalidOperationException(Sdl.Error);
}
public void Dispose()
{
var current = renderer;
renderer = null;
try { current?.Dispose(); }
finally
{
if (Window != 0) { Sdl.SDL_DestroyWindow(Window); Window = 0; }
if (videoInitialized) { Sdl.SDL_Quit(); videoInitialized = false; }
}
}
}
+5 -2
View File
@@ -72,12 +72,14 @@ public sealed class SceneHud
/// <summary>Writes the final merged buffer, including when later visual composers copied these vertices.</summary>
public void Update(Mesh destination, int currentObjective, bool objectivesVisible, bool practiceVisible,
float objectiveYOffset = -69, bool objectiveContentVisible = true)
float objectiveYOffset = -69, bool objectiveContentVisible = true,
uint viewportWidth = 640, uint viewportHeight = 480)
{
if (!float.IsFinite(objectiveYOffset) || objectiveYOffset < -480 || objectiveYOffset > 480)
throw new ArgumentOutOfRangeException(nameof(objectiveYOffset));
if (destination.Vertices.Length < Mesh.Vertices.Length || destination.Indices.Length < Mesh.Indices.Length)
throw new ArgumentException("Destination omits HUD ranges", nameof(destination));
var viewport = new UiViewport(viewportWidth, viewportHeight);
foreach (var quad in quads)
{
var draw = destination.Draws.FirstOrDefault(d => d.FirstIndex == quad.FirstIndex && d.ScreenSpace
@@ -88,7 +90,8 @@ public sealed class SceneHud
var digit = quad.Canvas is >= 83 and <= 85;
var x = quad.Canvas == 169 ? 210f : digit ? 393f : 384f;
var y = quad.Canvas == 169 ? 210f : (quad.Canvas == 156 ? 380f : digit ? 450f : 448f) + objectiveYOffset;
Vector3 Position(float px, float py) => new(2 * px / 640 - 1, 2 * py / 480 - 1, 0);
var anchor = quad.Canvas == 169 ? viewport.CenterOffset : viewport.BottomRightOffset;
Vector3 Position(float px, float py) => viewport.ToNdc(new Vector2(px, py) + anchor);
destination.Vertices[quad.VertexOffset].Position = Position(x, y);
destination.Vertices[quad.VertexOffset + 1].Position = Position(x + quad.Width, y);
destination.Vertices[quad.VertexOffset + 2].Position = Position(x + quad.Width, y + quad.Height);
+67
View File
@@ -0,0 +1,67 @@
using System.Numerics;
namespace GamePort.Application;
/// <summary>
/// Modern viewport policy for original640x480 UI: uniform art/text scale with
/// explicit anchors. The3D scene still occupies the entire physical viewport.
/// </summary>
public readonly struct UiViewport
{
private readonly double pixelScale, modalPixelX, modalPixelY;
private readonly uint pixelWidth, pixelHeight;
public float Scale { get; }
public float LogicalWidth { get; }
public float LogicalHeight { get; }
public Vector2 CenterOffset => new((LogicalWidth - 640) / 2, (LogicalHeight - 480) / 2);
public Vector2 BottomRightOffset => new(LogicalWidth - 640, LogicalHeight - 480);
public UiViewport(uint width, uint height)
{
if (width == 0 || height == 0) throw new ArgumentOutOfRangeException(nameof(width), "UI viewport must be nonzero");
pixelWidth = width; pixelHeight = height;
pixelScale = Math.Min(width / 640d, height / 480d);
Scale = (float)pixelScale;
LogicalWidth = (float)(width / pixelScale);
LogicalHeight = (float)(height / pixelScale);
modalPixelX = (width - 640 * pixelScale) / 2;
modalPixelY = (height - 480 * pixelScale) / 2;
}
/// <summary>Map anchored logical coordinates into Vulkan overlay NDC, Y down.</summary>
public Vector3 ToNdc(Vector2 logicalPoint)
{
Validate(logicalPoint);
return new(2 * logicalPoint.X / LogicalWidth - 1, 2 * logicalPoint.Y / LogicalHeight - 1, 0);
}
/// <summary>
/// Inverse of centered modal placement. Use SDL logical window dimensions
/// with SDL logical pointer pixels; render using drawable pixel dimensions.
/// Coordinates remain unclamped to preserve strict original Yes/No bounds.
/// </summary>
public Vector2 InverseModal(Vector2 windowPixels)
{
Validate(windowPixels);
// Subtract the physical center before dividing, using double precision.
// Float logical-space cancellation can turn an exact source boundary225
// into225.00003 on ultrawide and incorrectly enter a strict hit region.
return new((float)((windowPixels.X - modalPixelX) / pixelScale),
(float)((windowPixels.Y - modalPixelY) / pixelScale));
}
/// <summary>Map SDL logical mouse coordinates to the actual drawable before
/// hit testing; this also handles fractional DPI sizes rounded by the OS.</summary>
public Vector2 InverseModal(Vector2 windowPoint, uint windowWidth, uint windowHeight)
{
Validate(windowPoint);
if (windowWidth == 0 || windowHeight == 0) throw new ArgumentOutOfRangeException(nameof(windowWidth));
return new((float)(((double)windowPoint.X * pixelWidth / windowWidth - modalPixelX) / pixelScale),
(float)(((double)windowPoint.Y * pixelHeight / windowHeight - modalPixelY) / pixelScale));
}
private static void Validate(Vector2 point)
{
if (!float.IsFinite(point.X) || !float.IsFinite(point.Y)) throw new ArgumentOutOfRangeException(nameof(point));
}
}
@@ -0,0 +1,170 @@
using System.Numerics;
using GamePort.Assets;
using GamePort.Game;
using GamePort.Platform;
using GamePort.Rendering.Vulkan;
namespace GamePort.Application;
/// <summary>Local native presentation/scene-resource regression, not a gameplay replay.</summary>
public static class WindowTransitionSmoke
{
private readonly record struct WindowState(uint Id, int X, int Y, int Width, int Height, bool Fullscreen, bool Focused);
public static int Run(RenderSession session, string assets, string prepared, string output, bool validation)
{
Directory.CreateDirectory(output);
VulkanRenderer? renderer = null;
Mesh? mesh = null;
SceneHud? hud = null;
DebugMenuOverlay? overlay = null;
GamLevel? level = null;
var sceneNumber = 0;
var menu = new DebugMenu([], null, null);
menu.Toggle(30);
var diagnostics = new DebugDiagnostics { Enabled = true };
var viewportCases = new (uint Width, uint Height, string Scene, string Ui)[]
{
(960, 720, "level1b", "menu"),
(1280, 720, "VR04", "practice"),
(1680, 720, "level1b", "objectives"),
(2560, 720, "level1", "live")
};
foreach (var test in viewportCases)
{
if (renderer != null) Resize(test.Width, test.Height);
Replace(test.Scene, test.Width, test.Height);
Render(test.Ui, $"{sceneNumber}-{test.Scene}-{test.Width}x{test.Height}");
if (test.Ui == "practice") CheckPracticePointer();
}
var windowed = State();
session.ToggleFullscreen();
Require(Sdl.SDL_SyncWindow(session.Window), Sdl.Error);
DrainAndResize();
Require(session.Fullscreen, "SDL did not enter fullscreen");
Replace("VR04", renderer!.Width, renderer.Height);
Render("practice", "fullscreen-practice");
CheckPracticePointer();
Replace("level1b", renderer.Width, renderer.Height);
Render("menu", "fullscreen-menu");
session.ToggleFullscreen();
Require(Sdl.SDL_SyncWindow(session.Window), Sdl.Error);
DrainAndResize();
var restored = State();
Require(!restored.Fullscreen && restored.Width == windowed.Width && restored.Height == windowed.Height
&& restored.X == windowed.X && restored.Y == windowed.Y, "Windowed bounds did not survive fullscreen and scene replacement");
var revision = renderer.SceneRevision;
var identity = renderer.Identity;
Reject(() => renderer.ReplaceScene(new Mesh([new(Vector3.Zero, Vector2.Zero, Vector3.One)], [0, 1, 2]), PngImage.White));
Reject(() => renderer.ReplaceScene(mesh!, new PngImage(2, 2, [255])));
Require(renderer.SceneRevision == revision && renderer.Identity == identity, "Rejected replacement changed presentation state");
Render("live", "after-rejected-replacement");
Require(session.WindowCreationCount == 1 && session.RendererCreationCount == 1 && renderer.ValidationErrors == 0,
"Window/renderer were recreated or Vulkan validation failed");
Console.WriteLine($"Window transition check: scenes={sceneNumber}, windows={session.WindowCreationCount}, renderers={session.RendererCreationCount}, fullscreen retained=True, bounds retained=True, invalid scene retained=True, Vulkan errors={renderer.ValidationErrors}.");
return 0;
void Replace(string name, uint width, uint height)
{
level = GamLevel.Load(AssetPath.Resolve(assets, "gam/" + name + ".gam"));
var world = Mesh.LoadSceneJson(AssetPath.Resolve(prepared, name + "/scene.json"));
hud = new(world, Path.Combine(prepared, "ui/ui.json"));
overlay = new(hud.Mesh);
mesh = overlay.Mesh;
var before = renderer == null ? (WindowState?)null : State();
var beforeIdentity = renderer?.Identity;
var beforeRenderer = renderer;
renderer = session.LoadScene(mesh, PngImage.White, false, "Neutron — persistent-window check", width, height, validation);
sceneNumber++;
if (before != null)
{
Require(ReferenceEquals(renderer, beforeRenderer) && renderer.Identity == beforeIdentity,
"Scene replacement recreated the device/surface/swapchain/pipelines");
Require(State() == before.Value, "Scene replacement changed native window state");
}
else
{
Require(Sdl.SDL_SetWindowPosition(session.Window, 37, 53) && Sdl.SDL_SyncWindow(session.Window), Sdl.Error);
DrainAndResize();
}
Require(renderer.SceneRevision == sceneNumber, "Wrong scene revision after resource replacement");
Console.WriteLine($"PASS retained presentation for{name}: revision={renderer.SceneRevision}, window={Sdl.SDL_GetWindowID(session.Window)}, size={renderer.Width}x{renderer.Height}, fullscreen={session.Fullscreen}.");
}
void Resize(uint width, uint height)
{
Require(Sdl.SDL_SetWindowSize(session.Window, (int)width, (int)height) && Sdl.SDL_SyncWindow(session.Window), Sdl.Error);
DrainAndResize();
Require(Sdl.SDL_GetWindowSize(session.Window, out var logicalWidth, out var logicalHeight), Sdl.Error);
Require(Sdl.SDL_GetWindowSizeInPixels(session.Window, out var pixelWidth, out var pixelHeight), Sdl.Error);
Require(logicalWidth == width && logicalHeight == height && renderer!.Width == pixelWidth && renderer.Height == pixelHeight,
"Window/drawable dimensions did not match resize");
}
void DrainAndResize()
{
while (Sdl.SDL_PollEvent(out var e))
if (e.Type == Sdl.Quit) throw new InvalidOperationException("Window closed during transition check");
if (!Sdl.SDL_GetWindowSizeInPixels(session.Window, out var width, out var height)) throw new InvalidOperationException(Sdl.Error);
if (renderer != null && (renderer.Width != width || renderer.Height != height)) renderer.Resize();
}
WindowState State()
{
if (!Sdl.SDL_GetWindowPosition(session.Window, out var x, out var y)
|| !Sdl.SDL_GetWindowSize(session.Window, out var width, out var height))
throw new InvalidOperationException(Sdl.Error);
return new(Sdl.SDL_GetWindowID(session.Window), x, y, width, height, session.Fullscreen, session.HasInputFocus);
}
void Render(string mode, string filename)
{
var start = level!.FindStart() ?? level.Entities.First(e => e.Kind == "STRT");
hud!.Update(mesh!, 1, mode == "objectives", mode == "practice", -69, true, renderer!.Width, renderer.Height);
var status = new DebugStatus(level.Code, start.Tag!, start.Position, start.Rotation.Y, 0, true,
20, 0, 30, "NONE", true, 0, SceneProjection.FarPlane(level.Code), false);
var view = mode == "menu" ? menu.View(status) : new DebugMenuView([], -1);
var lines = mode == "live" ? diagnostics.Lines(status,
new(Vector3.Zero, 0, "IDLE", 0, 0, 0, 0, 0, -1, false, renderer.ValidationErrors, false)) : view.Lines;
overlay!.Update(mesh!, lines, view.SelectedLine, mode == "live", renderer.Width, renderer.Height);
var projection = SceneProjection.CreateGameplay(level.Code, (float)renderer.Width / renderer.Height);
projection.M22 *= -1;
var camera = Matrix4x4.CreateLookAtLeftHanded(start.CameraPosition, start.Position + new Vector3(0, 80, 0), Vector3.UnitY);
renderer.UpdateVertices(mesh!.Vertices);
renderer.Render(camera * projection);
renderer.SavePpm(Path.Combine(output, filename + ".ppm"));
Require(renderer.ValidationErrors == 0, "Vulkan error during scene/UI render");
}
void CheckPracticePointer()
{
Require(Sdl.SDL_GetWindowSize(session.Window, out var width, out var height), Sdl.Error);
var layout = new UiViewport(renderer!.Width, renderer.Height);
foreach (var yes in new[] { true, false })
{
var authored = new Vector2(yes ? 265 : 355, 270);
var pixel = (authored + layout.CenterOffset) * layout.Scale;
Sdl.SDL_WarpMouseInWindow(session.Window, pixel.X * width / renderer.Width, pixel.Y * height / renderer.Height);
DrainAndResize(); // SDL mouse state reflects the most recent event pump.
Sdl.SDL_GetMouseState(out var x, out var y);
var prompt = new PracticePrompt();
bool? accepted = null;
prompt.Chosen += (_, value) => accepted = value;
prompt.Show(0); prompt.Click(layout.InverseModal(new(x, y), (uint)width, (uint)height));
Require(accepted == yes && !prompt.Active,
$"Scaled native pointer missed practice bounds: expected={yes}, target={pixel}, mouse=<{x},{y}>, authored={layout.InverseModal(new(x, y), (uint)width, (uint)height)}");
}
Console.WriteLine($"PASS native scaled practice pointer at{width}x{height}.");
}
}
private static void Require(bool condition, string message)
{ if (!condition) throw new InvalidOperationException(message); }
private static void Reject(Action action)
{
try { action(); } catch (ArgumentException) { return; }
throw new InvalidOperationException("Expected bounded scene replacement rejection");
}
}