Keep presentation alive across levels and scale UI for widescreen
This commit is contained in:
1 parent
113e9a41cc
commit
69d0187a21
26 files changed
+889
-70
No files matched your search
@@ -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()
|
||||
{
|
||||
|
||||
@@ -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; }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -38,6 +38,12 @@ internal static unsafe class Sdl
|
||||
public static string Error=>Marshal.PtrToStringUTF8(SDL_GetError())??"SDL error";
|
||||
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)] public static extern nint SDL_CreateWindow([MarshalAs(UnmanagedType.LPUTF8Str)]string title,int w,int h,ulong flags);
|
||||
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)]public static extern void SDL_DestroyWindow(nint window);
|
||||
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)]public static extern uint SDL_GetWindowID(nint window);
|
||||
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)]public static extern ulong SDL_GetWindowFlags(nint window);
|
||||
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)] [return:MarshalAs(UnmanagedType.I1)]public static extern bool SDL_GetWindowPosition(nint window,out int x,out int y);
|
||||
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)] [return:MarshalAs(UnmanagedType.I1)]public static extern bool SDL_SetWindowPosition(nint window,int x,int y);
|
||||
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)] [return:MarshalAs(UnmanagedType.I1)]public static extern bool SDL_SyncWindow(nint window);
|
||||
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)]public static extern void SDL_WarpMouseInWindow(nint window,float x,float y);
|
||||
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)] [return:MarshalAs(UnmanagedType.I1)]public static extern bool SDL_SetWindowTitle(nint window,[MarshalAs(UnmanagedType.LPUTF8Str)]string title);
|
||||
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)] [return:MarshalAs(UnmanagedType.I1)]public static extern bool SDL_PollEvent(out Event e);
|
||||
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)]public static extern byte** SDL_Vulkan_GetInstanceExtensions(out uint count);
|
||||
|
||||
+33
-23
@@ -15,12 +15,13 @@ internal static class Program
|
||||
{
|
||||
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, out var continuation);
|
||||
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;
|
||||
}
|
||||
@@ -39,7 +40,8 @@ internal static class Program
|
||||
|
||||
private sealed record SceneContinuation(string[] Args, OriginalSave Save, bool Returning);
|
||||
|
||||
private static int Run(string[] args, OriginalSave? carriedSave, bool returning, DebugDiagnostics diagnostics, out SceneContinuation? continuation)
|
||||
private static int Run(string[] args, OriginalSave? carriedSave, bool returning, DebugDiagnostics diagnostics,
|
||||
RenderSession presentation, out SceneContinuation? continuation)
|
||||
{
|
||||
continuation = null;
|
||||
if (args.Contains("--help"))
|
||||
@@ -68,6 +70,7 @@ internal static class Program
|
||||
--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
|
||||
@@ -88,6 +91,7 @@ internal static class Program
|
||||
--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
|
||||
@@ -100,6 +104,19 @@ internal static class Program
|
||||
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)
|
||||
{
|
||||
@@ -386,17 +403,15 @@ internal static class Program
|
||||
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.");
|
||||
nint window = 0;
|
||||
if (!headless)
|
||||
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}.");
|
||||
{
|
||||
if (!Sdl.SDL_Init(Sdl.InitVideo)) throw new InvalidOperationException(Sdl.Error);
|
||||
window = Sdl.SDL_CreateWindow(walking ? WalkTitle : animations?.WindowTitle ?? "Jimmy Neutron — scene preview | C camera", 960, 720,
|
||||
Sdl.WindowVulkan | Sdl.WindowResizable | Sdl.WindowHighPixelDensity);
|
||||
if (window == 0) { Sdl.SDL_Quit(); throw new InvalidOperationException(Sdl.Error); }
|
||||
}
|
||||
try
|
||||
{
|
||||
using var renderer = new VulkanRenderer(mesh, texture, 960, 720, window, !args.Contains("--no-validation"));
|
||||
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;
|
||||
@@ -492,14 +507,13 @@ internal static class Program
|
||||
var keys = new HashSet<uint>();
|
||||
var debugCapturedKeys = new HashSet<uint>();
|
||||
var running = true;
|
||||
var fullscreen = false;
|
||||
var sawKey = false;
|
||||
var didResize = false;
|
||||
var clock = Stopwatch.StartNew();
|
||||
var animationStarted = 0.0;
|
||||
var animationSwitched = false;
|
||||
var inspecting = !walking;
|
||||
var active = true;
|
||||
var active = presentation.HasInputFocus;
|
||||
var mouseJump = false;
|
||||
var stepClock = new FixedStepClock();
|
||||
double poseTime = initialPoseTime;
|
||||
@@ -597,7 +611,7 @@ internal static class Program
|
||||
{
|
||||
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(x * 640 / w, y * 480 / h);
|
||||
return new UiViewport(renderer.Width, renderer.Height).InverseModal(new(x, y), (uint)w, (uint)h);
|
||||
}
|
||||
while (running)
|
||||
{
|
||||
@@ -689,8 +703,7 @@ internal static class Program
|
||||
}
|
||||
if (e.Scancode == 68 && e.Repeat == 0)
|
||||
{
|
||||
fullscreen = !fullscreen;
|
||||
if (!Sdl.SDL_SetWindowFullscreen(window, fullscreen)) throw new InvalidOperationException(Sdl.Error);
|
||||
presentation.ToggleFullscreen();
|
||||
}
|
||||
}
|
||||
if (e.Type == Sdl.KeyUp) keys.Remove(e.Scancode);
|
||||
@@ -776,7 +789,7 @@ internal static class Program
|
||||
&& 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);
|
||||
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";
|
||||
@@ -795,7 +808,8 @@ internal static class Program
|
||||
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);
|
||||
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);
|
||||
@@ -1066,10 +1080,6 @@ internal static class Program
|
||||
}
|
||||
return renderer.ValidationErrors > 0 || changed == 0 ? 2 : 0;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (window != 0) { Sdl.SDL_DestroyWindow(window); Sdl.SDL_Quit(); }
|
||||
}
|
||||
}
|
||||
|
||||
private const string WalkTitle = "Jimmy Neutron — lab checkpoint | Arrows move | Shift / Insert / right mouse jump | F1 menu | F2 overlay | R reset | C inspect";
|
||||
|
||||
@@ -36,7 +36,7 @@ public sealed unsafe class VulkanRenderer : IDisposable
|
||||
private Sampler sampler;
|
||||
private readonly List<Texture> textures=[];
|
||||
private readonly Dictionary<int,DescriptorSet> descriptors=[];
|
||||
private readonly Mesh mesh;
|
||||
private Mesh mesh;
|
||||
private readonly nint window;
|
||||
private SurfaceKHR surface;
|
||||
private KhrSurface? surfaceApi;
|
||||
@@ -52,8 +52,14 @@ public sealed unsafe class VulkanRenderer : IDisposable
|
||||
public int ValidationErrors { get; private set; }
|
||||
public uint Width=>width;
|
||||
public uint Height=>height;
|
||||
public int SceneRevision { get; private set; }
|
||||
public RendererIdentity Identity => new(unchecked((ulong)instance.Handle), unchecked((ulong)device.Handle),
|
||||
surface.Handle, swapchain.Handle, pipeline.Handle, pipelineLayout.Handle, descriptorLayout.Handle);
|
||||
|
||||
private sealed record Texture(Image Image,DeviceMemory Memory,ImageView View);
|
||||
private sealed record SceneResources(Mesh Mesh, Buffer VertexBuffer, DeviceMemory VertexMemory,
|
||||
Buffer IndexBuffer, DeviceMemory IndexMemory, DescriptorPool DescriptorPool, Sampler Sampler,
|
||||
Texture[] Textures, KeyValuePair<int,DescriptorSet>[] Descriptors);
|
||||
private static void Check(Result result,string operation)
|
||||
{if(result!=Result.Success)throw new InvalidOperationException($"{operation}: {result}");}
|
||||
|
||||
@@ -63,6 +69,7 @@ public sealed unsafe class VulkanRenderer : IDisposable
|
||||
debugCallback=OnValidation;
|
||||
try
|
||||
{
|
||||
ValidateScene(mesh,texture);
|
||||
CreateInstance(validation);
|
||||
if(window!=0)
|
||||
{
|
||||
@@ -81,10 +88,97 @@ public sealed unsafe class VulkanRenderer : IDisposable
|
||||
CreatePipeline();
|
||||
if(window!=0)CreateSwapchain();
|
||||
CreateTarget();
|
||||
SceneRevision=1;
|
||||
}
|
||||
catch{Dispose();throw;}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Replace only scene buffers/textures/descriptors. The renderer, SDL surface,
|
||||
/// pipelines, swapchain and current render target remain alive. Staging keeps
|
||||
/// the previous scene usable if allocation/upload of the replacement fails.
|
||||
/// </summary>
|
||||
public void ReplaceScene(Mesh replacement,PngImage fallback)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(device.Handle==0,this);
|
||||
ValidateScene(replacement,fallback);
|
||||
Check(vk.DeviceWaitIdle(device),"ReplaceSceneWaitIdle");
|
||||
var previous=DetachScene();
|
||||
mesh=replacement;
|
||||
try
|
||||
{
|
||||
UploadBuffers();
|
||||
CreateDescriptors(fallback);
|
||||
}
|
||||
catch
|
||||
{
|
||||
vk.DeviceWaitIdle(device);
|
||||
DestroySceneResources();
|
||||
RestoreScene(previous);
|
||||
throw;
|
||||
}
|
||||
DestroySceneResources(previous);
|
||||
SceneRevision++;
|
||||
}
|
||||
|
||||
private static void ValidateScene(Mesh mesh,PngImage fallback)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(mesh);
|
||||
ArgumentNullException.ThrowIfNull(fallback);
|
||||
if(mesh.Vertices.Length==0 || mesh.Indices.Length==0 || mesh.Indices.Length%3!=0
|
||||
|| mesh.Indices.Any(i=>i>=mesh.Vertices.Length))
|
||||
throw new ArgumentException("Scene requires nonempty, bounded triangle geometry.",nameof(mesh));
|
||||
if(mesh.Draws.Any(d=>(ulong)d.FirstIndex+d.IndexCount>(ulong)mesh.Indices.Length))
|
||||
throw new ArgumentException("Scene draw exceeds index buffer.",nameof(mesh));
|
||||
ValidateTexture(fallback);
|
||||
foreach(var image in mesh.Textures.Values)ValidateTexture(image);
|
||||
|
||||
static void ValidateTexture(PngImage image)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(image);
|
||||
if(image.Width is 0 or >8192 || image.Height is 0 or >8192
|
||||
|| (long)image.Width*image.Height*4!=image.Rgba.LongLength)
|
||||
throw new ArgumentException("Scene texture has invalid dimensions or RGBA length.",nameof(image));
|
||||
}
|
||||
}
|
||||
|
||||
private SceneResources DetachScene()
|
||||
{
|
||||
var scene=new SceneResources(mesh,vertexBuffer,vertexMemory,indexBuffer,indexMemory,
|
||||
descriptorPool,sampler,textures.ToArray(),descriptors.ToArray());
|
||||
vertexBuffer=default;vertexMemory=default;indexBuffer=default;indexMemory=default;
|
||||
descriptorPool=default;sampler=default;textures.Clear();descriptors.Clear();
|
||||
return scene;
|
||||
}
|
||||
|
||||
private void RestoreScene(SceneResources scene)
|
||||
{
|
||||
mesh=scene.Mesh;
|
||||
vertexBuffer=scene.VertexBuffer;vertexMemory=scene.VertexMemory;
|
||||
indexBuffer=scene.IndexBuffer;indexMemory=scene.IndexMemory;
|
||||
descriptorPool=scene.DescriptorPool;sampler=scene.Sampler;
|
||||
textures.AddRange(scene.Textures);
|
||||
foreach(var entry in scene.Descriptors)descriptors.Add(entry.Key,entry.Value);
|
||||
}
|
||||
|
||||
private void DestroySceneResources() => DestroySceneResources(DetachScene());
|
||||
|
||||
private void DestroySceneResources(SceneResources scene)
|
||||
{
|
||||
if(scene.DescriptorPool.Handle!=0)vk.DestroyDescriptorPool(device,scene.DescriptorPool,null);
|
||||
if(scene.Sampler.Handle!=0)vk.DestroySampler(device,scene.Sampler,null);
|
||||
foreach(var texture in scene.Textures)
|
||||
{
|
||||
vk.DestroyImageView(device,texture.View,null);
|
||||
vk.DestroyImage(device,texture.Image,null);
|
||||
vk.FreeMemory(device,texture.Memory,null);
|
||||
}
|
||||
if(scene.VertexBuffer.Handle!=0)vk.DestroyBuffer(device,scene.VertexBuffer,null);
|
||||
if(scene.VertexMemory.Handle!=0)vk.FreeMemory(device,scene.VertexMemory,null);
|
||||
if(scene.IndexBuffer.Handle!=0)vk.DestroyBuffer(device,scene.IndexBuffer,null);
|
||||
if(scene.IndexMemory.Handle!=0)vk.FreeMemory(device,scene.IndexMemory,null);
|
||||
}
|
||||
|
||||
private uint OnValidation(DebugUtilsMessageSeverityFlagsEXT severity,DebugUtilsMessageTypeFlagsEXT type,DebugUtilsMessengerCallbackDataEXT* data,void* user)
|
||||
{
|
||||
if((severity&DebugUtilsMessageSeverityFlagsEXT.ErrorBitExt)!=0)ValidationErrors++;
|
||||
@@ -178,12 +272,23 @@ public sealed unsafe class VulkanRenderer : IDisposable
|
||||
}
|
||||
private void MakeBuffer(ulong size,BufferUsageFlags usage,MemoryPropertyFlags flags,out Buffer buffer,out DeviceMemory memory)
|
||||
{
|
||||
var info=new BufferCreateInfo{SType=StructureType.BufferCreateInfo,Size=size,Usage=usage,SharingMode=SharingMode.Exclusive};
|
||||
Check(vk.CreateBuffer(device,&info,null,out buffer),"CreateBuffer");
|
||||
vk.GetBufferMemoryRequirements(device,buffer,out var requirements);
|
||||
var allocation=new MemoryAllocateInfo{SType=StructureType.MemoryAllocateInfo,AllocationSize=requirements.Size,MemoryTypeIndex=MemoryType(requirements.MemoryTypeBits,flags)};
|
||||
Check(vk.AllocateMemory(device,&allocation,null,out memory),"AllocateBufferMemory");
|
||||
Check(vk.BindBufferMemory(device,buffer,memory,0),"BindBufferMemory");
|
||||
buffer=default;memory=default;
|
||||
try
|
||||
{
|
||||
var info=new BufferCreateInfo{SType=StructureType.BufferCreateInfo,Size=size,Usage=usage,SharingMode=SharingMode.Exclusive};
|
||||
Check(vk.CreateBuffer(device,&info,null,out buffer),"CreateBuffer");
|
||||
vk.GetBufferMemoryRequirements(device,buffer,out var requirements);
|
||||
var allocation=new MemoryAllocateInfo{SType=StructureType.MemoryAllocateInfo,AllocationSize=requirements.Size,MemoryTypeIndex=MemoryType(requirements.MemoryTypeBits,flags)};
|
||||
Check(vk.AllocateMemory(device,&allocation,null,out memory),"AllocateBufferMemory");
|
||||
Check(vk.BindBufferMemory(device,buffer,memory,0),"BindBufferMemory");
|
||||
}
|
||||
catch
|
||||
{
|
||||
if(buffer.Handle!=0)vk.DestroyBuffer(device,buffer,null);
|
||||
if(memory.Handle!=0)vk.FreeMemory(device,memory,null);
|
||||
buffer=default;memory=default;
|
||||
throw;
|
||||
}
|
||||
}
|
||||
private void UploadBuffers()
|
||||
{
|
||||
@@ -203,17 +308,30 @@ public sealed unsafe class VulkanRenderer : IDisposable
|
||||
private void CopyToMemory(DeviceMemory memory,ReadOnlySpan<byte> bytes)
|
||||
{
|
||||
void* data;Check(vk.MapMemory(device,memory,0,(ulong)bytes.Length,0,&data),"MapMemory");
|
||||
bytes.CopyTo(new Span<byte>(data,bytes.Length));vk.UnmapMemory(device,memory);
|
||||
try{bytes.CopyTo(new Span<byte>(data,bytes.Length));}
|
||||
finally{vk.UnmapMemory(device,memory);}
|
||||
}
|
||||
private void MakeImage(uint w,uint h,Format format,ImageUsageFlags usage,ImageAspectFlags aspect,out Image image,out DeviceMemory memory,out ImageView view)
|
||||
{
|
||||
var info=new ImageCreateInfo{SType=StructureType.ImageCreateInfo,ImageType=ImageType.Type2D,Format=format,Extent=new Extent3D(w,h,1),MipLevels=1,ArrayLayers=1,Samples=SampleCountFlags.Count1Bit,Tiling=ImageTiling.Optimal,Usage=usage,SharingMode=SharingMode.Exclusive,InitialLayout=ImageLayout.Undefined};
|
||||
Check(vk.CreateImage(device,&info,null,out image),"CreateImage");
|
||||
vk.GetImageMemoryRequirements(device,image,out var req);
|
||||
var alloc=new MemoryAllocateInfo{SType=StructureType.MemoryAllocateInfo,AllocationSize=req.Size,MemoryTypeIndex=MemoryType(req.MemoryTypeBits,MemoryPropertyFlags.DeviceLocalBit)};
|
||||
Check(vk.AllocateMemory(device,&alloc,null,out memory),"AllocateImageMemory");Check(vk.BindImageMemory(device,image,memory,0),"BindImageMemory");
|
||||
var vi=new ImageViewCreateInfo{SType=StructureType.ImageViewCreateInfo,Image=image,ViewType=ImageViewType.Type2D,Format=format,SubresourceRange=new ImageSubresourceRange(aspect,0,1,0,1)};
|
||||
Check(vk.CreateImageView(device,&vi,null,out view),"CreateImageView");
|
||||
image=default;memory=default;view=default;
|
||||
try
|
||||
{
|
||||
var info=new ImageCreateInfo{SType=StructureType.ImageCreateInfo,ImageType=ImageType.Type2D,Format=format,Extent=new Extent3D(w,h,1),MipLevels=1,ArrayLayers=1,Samples=SampleCountFlags.Count1Bit,Tiling=ImageTiling.Optimal,Usage=usage,SharingMode=SharingMode.Exclusive,InitialLayout=ImageLayout.Undefined};
|
||||
Check(vk.CreateImage(device,&info,null,out image),"CreateImage");
|
||||
vk.GetImageMemoryRequirements(device,image,out var req);
|
||||
var alloc=new MemoryAllocateInfo{SType=StructureType.MemoryAllocateInfo,AllocationSize=req.Size,MemoryTypeIndex=MemoryType(req.MemoryTypeBits,MemoryPropertyFlags.DeviceLocalBit)};
|
||||
Check(vk.AllocateMemory(device,&alloc,null,out memory),"AllocateImageMemory");Check(vk.BindImageMemory(device,image,memory,0),"BindImageMemory");
|
||||
var vi=new ImageViewCreateInfo{SType=StructureType.ImageViewCreateInfo,Image=image,ViewType=ImageViewType.Type2D,Format=format,SubresourceRange=new ImageSubresourceRange(aspect,0,1,0,1)};
|
||||
Check(vk.CreateImageView(device,&vi,null,out view),"CreateImageView");
|
||||
}
|
||||
catch
|
||||
{
|
||||
if(view.Handle!=0)vk.DestroyImageView(device,view,null);
|
||||
if(image.Handle!=0)vk.DestroyImage(device,image,null);
|
||||
if(memory.Handle!=0)vk.FreeMemory(device,memory,null);
|
||||
image=default;memory=default;view=default;
|
||||
throw;
|
||||
}
|
||||
}
|
||||
private void Begin()
|
||||
{
|
||||
@@ -234,21 +352,39 @@ public sealed unsafe class VulkanRenderer : IDisposable
|
||||
}
|
||||
private Texture UploadTexture(PngImage image)
|
||||
{
|
||||
MakeBuffer((ulong)image.Rgba.Length,BufferUsageFlags.TransferSrcBit,MemoryPropertyFlags.HostVisibleBit|MemoryPropertyFlags.HostCoherentBit,out var staging,out var memory);
|
||||
CopyToMemory(memory,image.Rgba);
|
||||
MakeImage(image.Width,image.Height,Format.R8G8B8A8Unorm,ImageUsageFlags.TransferDstBit|ImageUsageFlags.SampledBit,ImageAspectFlags.ColorBit,out var texture,out var textureMemory,out var view);
|
||||
Begin();Barrier(texture,ImageLayout.Undefined,ImageLayout.TransferDstOptimal,0,AccessFlags.TransferWriteBit,PipelineStageFlags.TopOfPipeBit,PipelineStageFlags.TransferBit);
|
||||
var copy=new BufferImageCopy{ImageSubresource=new ImageSubresourceLayers(ImageAspectFlags.ColorBit,0,0,1),ImageExtent=new Extent3D(image.Width,image.Height,1)};
|
||||
vk.CmdCopyBufferToImage(command,staging,texture,ImageLayout.TransferDstOptimal,1,©);
|
||||
Barrier(texture,ImageLayout.TransferDstOptimal,ImageLayout.ShaderReadOnlyOptimal,AccessFlags.TransferWriteBit,AccessFlags.ShaderReadBit,PipelineStageFlags.TransferBit,PipelineStageFlags.FragmentShaderBit);Submit();
|
||||
vk.DestroyBuffer(device,staging,null);vk.FreeMemory(device,memory,null);
|
||||
var result=new Texture(texture,textureMemory,view);textures.Add(result);return result;
|
||||
Buffer staging=default;DeviceMemory memory=default;
|
||||
Image texture=default;DeviceMemory textureMemory=default;ImageView view=default;
|
||||
try
|
||||
{
|
||||
MakeBuffer((ulong)image.Rgba.Length,BufferUsageFlags.TransferSrcBit,MemoryPropertyFlags.HostVisibleBit|MemoryPropertyFlags.HostCoherentBit,out staging,out memory);
|
||||
CopyToMemory(memory,image.Rgba);
|
||||
MakeImage(image.Width,image.Height,Format.R8G8B8A8Unorm,ImageUsageFlags.TransferDstBit|ImageUsageFlags.SampledBit,ImageAspectFlags.ColorBit,out texture,out textureMemory,out view);
|
||||
Begin();Barrier(texture,ImageLayout.Undefined,ImageLayout.TransferDstOptimal,0,AccessFlags.TransferWriteBit,PipelineStageFlags.TopOfPipeBit,PipelineStageFlags.TransferBit);
|
||||
var copy=new BufferImageCopy{ImageSubresource=new ImageSubresourceLayers(ImageAspectFlags.ColorBit,0,0,1),ImageExtent=new Extent3D(image.Width,image.Height,1)};
|
||||
vk.CmdCopyBufferToImage(command,staging,texture,ImageLayout.TransferDstOptimal,1,©);
|
||||
Barrier(texture,ImageLayout.TransferDstOptimal,ImageLayout.ShaderReadOnlyOptimal,AccessFlags.TransferWriteBit,AccessFlags.ShaderReadBit,PipelineStageFlags.TransferBit,PipelineStageFlags.FragmentShaderBit);Submit();
|
||||
var result=new Texture(texture,textureMemory,view);
|
||||
textures.Add(result);
|
||||
texture=default;textureMemory=default;view=default;
|
||||
return result;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if(staging.Handle!=0)vk.DestroyBuffer(device,staging,null);
|
||||
if(memory.Handle!=0)vk.FreeMemory(device,memory,null);
|
||||
if(view.Handle!=0)vk.DestroyImageView(device,view,null);
|
||||
if(texture.Handle!=0)vk.DestroyImage(device,texture,null);
|
||||
if(textureMemory.Handle!=0)vk.FreeMemory(device,textureMemory,null);
|
||||
}
|
||||
}
|
||||
private void CreateDescriptors(PngImage fallback)
|
||||
{
|
||||
var binding=new DescriptorSetLayoutBinding{Binding=0,DescriptorType=DescriptorType.CombinedImageSampler,DescriptorCount=1,StageFlags=ShaderStageFlags.FragmentBit};
|
||||
var layout=new DescriptorSetLayoutCreateInfo{SType=StructureType.DescriptorSetLayoutCreateInfo,BindingCount=1,PBindings=&binding};
|
||||
Check(vk.CreateDescriptorSetLayout(device,&layout,null,out descriptorLayout),"CreateDescriptorSetLayout");
|
||||
if(descriptorLayout.Handle==0)
|
||||
{
|
||||
var binding=new DescriptorSetLayoutBinding{Binding=0,DescriptorType=DescriptorType.CombinedImageSampler,DescriptorCount=1,StageFlags=ShaderStageFlags.FragmentBit};
|
||||
var layout=new DescriptorSetLayoutCreateInfo{SType=StructureType.DescriptorSetLayoutCreateInfo,BindingCount=1,PBindings=&binding};
|
||||
Check(vk.CreateDescriptorSetLayout(device,&layout,null,out descriptorLayout),"CreateDescriptorSetLayout");
|
||||
}
|
||||
var count=(uint)mesh.Textures.Count+1;
|
||||
var size=new DescriptorPoolSize(DescriptorType.CombinedImageSampler,count);
|
||||
var poolInfo=new DescriptorPoolCreateInfo{SType=StructureType.DescriptorPoolCreateInfo,MaxSets=count,PoolSizeCount=1,PPoolSizes=&size};
|
||||
@@ -328,9 +464,17 @@ public sealed unsafe class VulkanRenderer : IDisposable
|
||||
}
|
||||
private void DestroyTarget()
|
||||
{
|
||||
vk.DestroyFramebuffer(device,framebuffer,null);vk.DestroyImageView(device,colorView,null);vk.DestroyImageView(device,depthView,null);
|
||||
vk.DestroyImage(device,color,null);vk.DestroyImage(device,depth,null);vk.FreeMemory(device,colorMemory,null);vk.FreeMemory(device,depthMemory,null);
|
||||
vk.DestroyBuffer(device,readback,null);vk.FreeMemory(device,readbackMemory,null);
|
||||
if(framebuffer.Handle!=0)vk.DestroyFramebuffer(device,framebuffer,null);
|
||||
if(colorView.Handle!=0)vk.DestroyImageView(device,colorView,null);
|
||||
if(depthView.Handle!=0)vk.DestroyImageView(device,depthView,null);
|
||||
if(color.Handle!=0)vk.DestroyImage(device,color,null);
|
||||
if(depth.Handle!=0)vk.DestroyImage(device,depth,null);
|
||||
if(colorMemory.Handle!=0)vk.FreeMemory(device,colorMemory,null);
|
||||
if(depthMemory.Handle!=0)vk.FreeMemory(device,depthMemory,null);
|
||||
if(readback.Handle!=0)vk.DestroyBuffer(device,readback,null);
|
||||
if(readbackMemory.Handle!=0)vk.FreeMemory(device,readbackMemory,null);
|
||||
framebuffer=default;colorView=default;depthView=default;color=default;depth=default;
|
||||
colorMemory=default;depthMemory=default;readback=default;readbackMemory=default;
|
||||
}
|
||||
private void CreateSwapchain()
|
||||
{
|
||||
@@ -352,7 +496,9 @@ public sealed unsafe class VulkanRenderer : IDisposable
|
||||
{
|
||||
if(window==0)return;
|
||||
Sdl.SDL_GetWindowSizeInPixels(window,out var w,out var h);if(w<1||h<1)return;
|
||||
Check(vk.DeviceWaitIdle(device),"ResizeWaitIdle");DestroyTarget();swapApi!.DestroySwapchain(device,swapchain,null);CreateSwapchain();CreateTarget();
|
||||
Check(vk.DeviceWaitIdle(device),"ResizeWaitIdle");DestroyTarget();
|
||||
swapApi!.DestroySwapchain(device,swapchain,null);swapchain=default;swapImages=[];
|
||||
CreateSwapchain();CreateTarget();
|
||||
}
|
||||
public void Render(Matrix4x4 mvp)
|
||||
{
|
||||
@@ -416,17 +562,13 @@ public sealed unsafe class VulkanRenderer : IDisposable
|
||||
if(device.Handle!=0)
|
||||
{
|
||||
vk.DeviceWaitIdle(device);
|
||||
if(framebuffer.Handle!=0)DestroyTarget();
|
||||
DestroyTarget();
|
||||
if(pipeline.Handle!=0)vk.DestroyPipeline(device,pipeline,null);
|
||||
if(overlayPipeline.Handle!=0)vk.DestroyPipeline(device,overlayPipeline,null);
|
||||
if(pipelineLayout.Handle!=0)vk.DestroyPipelineLayout(device,pipelineLayout,null);
|
||||
if(renderPass.Handle!=0)vk.DestroyRenderPass(device,renderPass,null);
|
||||
if(descriptorPool.Handle!=0)vk.DestroyDescriptorPool(device,descriptorPool,null);
|
||||
DestroySceneResources();
|
||||
if(descriptorLayout.Handle!=0)vk.DestroyDescriptorSetLayout(device,descriptorLayout,null);
|
||||
if(sampler.Handle!=0)vk.DestroySampler(device,sampler,null);
|
||||
foreach(var t in textures){vk.DestroyImageView(device,t.View,null);vk.DestroyImage(device,t.Image,null);vk.FreeMemory(device,t.Memory,null);}
|
||||
if(vertexBuffer.Handle!=0)vk.DestroyBuffer(device,vertexBuffer,null);if(vertexMemory.Handle!=0)vk.FreeMemory(device,vertexMemory,null);
|
||||
if(indexBuffer.Handle!=0)vk.DestroyBuffer(device,indexBuffer,null);if(indexMemory.Handle!=0)vk.FreeMemory(device,indexMemory,null);
|
||||
if(acquired.Handle!=0)vk.DestroySemaphore(device,acquired,null);if(finished.Handle!=0)vk.DestroySemaphore(device,finished,null);
|
||||
if(swapchain.Handle!=0)swapApi!.DestroySwapchain(device,swapchain,null);
|
||||
if(pool.Handle!=0)vk.DestroyCommandPool(device,pool,null);
|
||||
@@ -438,3 +580,8 @@ public sealed unsafe class VulkanRenderer : IDisposable
|
||||
vk.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Presentation/device identities for transition verification; swapchain
|
||||
/// identity may legitimately change on resize, unlike device and surface.</summary>
|
||||
public readonly record struct RendererIdentity(ulong Instance,ulong Device,ulong Surface,
|
||||
ulong Swapchain,ulong Pipeline,ulong PipelineLayout,ulong DescriptorLayout);
|
||||
Reference in new issue
Block a user