Render original lab and Jimmy with native Vulkan and SDL3 on .NET 10
This commit is contained in:
1 parent
3df20ac19a
commit
008c0e16da
41 files changed
+2125
-68
No files matched your search
@@ -0,0 +1,51 @@
|
||||
using System.Globalization;
|
||||
using System.Numerics;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace GamePort.Assets;
|
||||
|
||||
/// <summary>First base MESH only; animation frames remain preserved in original ASE.</summary>
|
||||
public static class AseMesh
|
||||
{
|
||||
private static float F(string value) => float.Parse(value, CultureInfo.InvariantCulture);
|
||||
private static int I(string value) => int.Parse(value, CultureInfo.InvariantCulture);
|
||||
|
||||
public static Mesh Load(string path)
|
||||
{
|
||||
var text = File.ReadAllText(path);
|
||||
var start = text.IndexOf("*MESH {", StringComparison.Ordinal);
|
||||
if (start < 0) throw new InvalidDataException("ASE has no mesh.");
|
||||
var end = start + 7;
|
||||
for (int depth = 1; depth > 0 && end < text.Length; end++)
|
||||
{
|
||||
if (text[end] == '{') depth++;
|
||||
else if (text[end] == '}') depth--;
|
||||
}
|
||||
text = text[start..end];
|
||||
const string number = @"([-+0-9.eE]+)";
|
||||
var positions = Regex.Matches(text, @"\*MESH_VERTEX\s+(\d+)\s+" + number + @"\s+" + number + @"\s+" + number)
|
||||
.ToDictionary(m => I(m.Groups[1].Value), m => new Vector3(F(m.Groups[2].Value), F(m.Groups[3].Value), F(m.Groups[4].Value)));
|
||||
var uvs = Regex.Matches(text, @"\*MESH_TVERT\s+(\d+)\s+" + number + @"\s+" + number)
|
||||
.ToDictionary(m => I(m.Groups[1].Value), m => new Vector2(F(m.Groups[2].Value), -F(m.Groups[3].Value)));
|
||||
var uvFaces = Regex.Matches(text, @"\*MESH_TFACE\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)")
|
||||
.ToDictionary(m => I(m.Groups[1].Value), m => new[] {I(m.Groups[2].Value), I(m.Groups[3].Value), I(m.Groups[4].Value)});
|
||||
var vertices = new List<MeshVertex>();
|
||||
foreach (Match m in Regex.Matches(text, @"\*MESH_FACE\s+(\d+):\s+A:\s+(\d+)\s+B:\s+(\d+)\s+C:\s+(\d+)"))
|
||||
{
|
||||
var face = I(m.Groups[1].Value);
|
||||
var a = positions[I(m.Groups[2].Value)];
|
||||
var b = positions[I(m.Groups[3].Value)];
|
||||
var c = positions[I(m.Groups[4].Value)];
|
||||
// Exact ASE/OMT shared mesh comparison establishes (x,y,z)->(x,z,y).
|
||||
Vector3 Map(Vector3 p) => new(p.X, p.Z, p.Y);
|
||||
for (var corner=0; corner<3; corner++)
|
||||
{
|
||||
var p = positions[I(m.Groups[corner+2].Value)];
|
||||
var uv = uvFaces.TryGetValue(face, out var f) && uvs.TryGetValue(f[corner], out var t) ? t : Vector2.Zero;
|
||||
vertices.Add(new MeshVertex(Map(p), uv, Vector3.One));
|
||||
}
|
||||
}
|
||||
if (vertices.Count == 0) throw new InvalidDataException("ASE has no triangles.");
|
||||
return new Mesh(vertices.ToArray(), Enumerable.Range(0, vertices.Count).Select(i => (uint)i).ToArray());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
namespace GamePort.Assets;
|
||||
|
||||
public static class AssetPath
|
||||
{
|
||||
public static string Resolve(string root, string relative)
|
||||
{
|
||||
var current = Path.GetFullPath(root);
|
||||
foreach (var part in relative.Replace('\\', '/').Split('/', StringSplitOptions.RemoveEmptyEntries))
|
||||
{
|
||||
if (part is "." or "..") throw new InvalidDataException("Asset paths must stay within their root.");
|
||||
var direct = Path.Combine(current, part);
|
||||
if (File.Exists(direct) || Directory.Exists(direct)) { current = direct; continue; }
|
||||
var matches = Directory.EnumerateFileSystemEntries(current)
|
||||
.Where(p => string.Equals(Path.GetFileName(p), part, StringComparison.OrdinalIgnoreCase)).ToArray();
|
||||
if (matches.Length != 1) throw new FileNotFoundException($"Missing or ambiguous asset: {relative}");
|
||||
current = matches[0];
|
||||
}
|
||||
return current;
|
||||
}
|
||||
|
||||
public static string FindOriginal(string? requested)
|
||||
{
|
||||
if (requested != null) return Path.GetFullPath(requested);
|
||||
foreach (var start in new[] { Directory.GetCurrentDirectory(), AppContext.BaseDirectory })
|
||||
for (var dir = new DirectoryInfo(start); dir != null; dir = dir.Parent)
|
||||
foreach (var name in new[] { "Original", "original", "assets" })
|
||||
if (Directory.Exists(Path.Combine(dir.FullName, name, "ASE"))) return Path.Combine(dir.FullName, name);
|
||||
throw new DirectoryNotFoundException("Original assets not found. Use --assets /path/to/Original.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
using System.Numerics;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace GamePort.Assets;
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct MeshVertex(Vector3 position, Vector2 uv, Vector3 color)
|
||||
{
|
||||
public Vector3 Position = position;
|
||||
public Vector2 Uv = uv;
|
||||
public Vector3 Color = color;
|
||||
}
|
||||
|
||||
public sealed record Mesh(MeshVertex[] Vertices, uint[] Indices)
|
||||
{
|
||||
public MeshDraw[] Draws { get; init; } = [];
|
||||
public bool HasExplicitDraws { get; init; }
|
||||
public Dictionary<int,PngImage> Textures { get; init; } = [];
|
||||
public (Vector3 Min, Vector3 Max) Bounds()
|
||||
{
|
||||
var min = new Vector3(float.PositiveInfinity);
|
||||
var max = new Vector3(float.NegativeInfinity);
|
||||
foreach (var vertex in Vertices) { min = Vector3.Min(min, vertex.Position); max = Vector3.Max(max, vertex.Position); }
|
||||
return (min, max);
|
||||
}
|
||||
|
||||
public static Mesh LoadSceneJson(string path)
|
||||
{
|
||||
using var doc = JsonDocument.Parse(File.ReadAllText(path));
|
||||
var root = doc.RootElement;
|
||||
var positions = root.GetProperty("vertices").EnumerateArray().ToArray();
|
||||
var uvs = root.TryGetProperty("uvs", out var uvElement) ? uvElement.EnumerateArray().ToArray() : [];
|
||||
var vertices = positions.Select((p, i) => new MeshVertex(
|
||||
new Vector3(p[0].GetSingle(), p[1].GetSingle(), p[2].GetSingle()),
|
||||
i < uvs.Length ? new Vector2(uvs[i][0].GetSingle(), uvs[i][1].GetSingle()) : Vector2.Zero,
|
||||
Vector3.One)).ToArray();
|
||||
var indices = root.GetProperty("indices").EnumerateArray().Select(p => p.GetUInt32()).ToArray();
|
||||
if (indices.Length % 3 != 0 || indices.Any(i => i >= vertices.Length)) throw new InvalidDataException("Invalid scene triangle indices.");
|
||||
if (vertices.Length == 0 || indices.Length == 0) throw new InvalidDataException("Empty scene mesh.");
|
||||
var textures = new Dictionary<int,PngImage>();
|
||||
if(root.TryGetProperty("textures",out var textureList)) foreach(var t in textureList.EnumerateArray())
|
||||
{
|
||||
var id=t.GetProperty("id").GetInt32();
|
||||
var w=t.GetProperty("width").GetUInt32(); var h=t.GetProperty("height").GetUInt32();
|
||||
var bytes=File.ReadAllBytes(Path.Combine(Path.GetDirectoryName(path)!,t.GetProperty("path").GetString()!));
|
||||
if(w>8192 || h>8192 || bytes.Length!=checked((int)(w*h*4)))throw new InvalidDataException("Invalid decoded texture size.");
|
||||
textures[id]=new PngImage(w,h,bytes);
|
||||
}
|
||||
var materials=new Dictionary<int,(int Texture,Vector3 Color)>();
|
||||
var hasMaterials = root.TryGetProperty("materials",out var materialList);
|
||||
if(hasMaterials) foreach(var m in materialList.EnumerateArray())
|
||||
{
|
||||
var texture=-1;
|
||||
if(m.TryGetProperty("texture",out var t) && t.ValueKind==JsonValueKind.Object && t.TryGetProperty("id",out var ti))texture=ti.GetInt32();
|
||||
var diffuse=Vector3.One;
|
||||
if(m.TryGetProperty("colours",out var colors) && colors.TryGetProperty("diffuse",out var d))diffuse=new(d[0].GetSingle(),d[1].GetSingle(),d[2].GetSingle());
|
||||
materials[m.GetProperty("id").GetInt32()]=(texture,diffuse);
|
||||
}
|
||||
var draws=new List<MeshDraw>();
|
||||
if(root.TryGetProperty("meshes",out var meshList))foreach(var m in meshList.EnumerateArray())
|
||||
{
|
||||
var first=m.GetProperty("firstIndex").GetUInt32();var count=m.GetProperty("indexCount").GetUInt32();
|
||||
if((ulong)first+count>(ulong)indices.Length)throw new InvalidDataException("Scene draw exceeds indices.");
|
||||
// Original DX draw_shape at DLL 0x1003756C skips null material
|
||||
// pointers. Retain their geometry, but never invent white surfaces.
|
||||
if (hasMaterials && (!m.TryGetProperty("material", out var materialId)
|
||||
|| materialId.ValueKind != JsonValueKind.Number
|
||||
|| !materials.ContainsKey(materialId.GetInt32()))) continue;
|
||||
var material=m.TryGetProperty("material",out var mid) && mid.ValueKind==JsonValueKind.Number && materials.TryGetValue(mid.GetInt32(),out var mat)?mat:(-1,Vector3.One);
|
||||
for(var i=first;i<first+count;i++)vertices[indices[i]].Color=material.Item2;
|
||||
draws.Add(new MeshDraw(first,count,material.Item1));
|
||||
}
|
||||
return new Mesh(vertices, indices){Draws=draws.ToArray(),HasExplicitDraws=true,Textures=textures};
|
||||
}
|
||||
}
|
||||
|
||||
public sealed record MeshDraw(uint FirstIndex,uint IndexCount,int TextureId);
|
||||
@@ -0,0 +1,88 @@
|
||||
using System.Numerics;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace GamePort.Assets;
|
||||
|
||||
/// <summary>Original vertex samples and base topology, prepared by ase.py.</summary>
|
||||
public sealed class MorphAnimation
|
||||
{
|
||||
public Mesh Base { get; }
|
||||
public PngImage Texture { get; }
|
||||
public double SampleInterval { get; }
|
||||
private readonly Mesh[] frames;
|
||||
|
||||
public MorphAnimation(string manifestPath)
|
||||
{
|
||||
var directory = Path.GetDirectoryName(Path.GetFullPath(manifestPath))!;
|
||||
using var document = JsonDocument.Parse(File.ReadAllText(manifestPath));
|
||||
var root = document.RootElement;
|
||||
var fps = root.GetProperty("framesPerSecond").GetDouble();
|
||||
var ticks = root.GetProperty("ticksPerFrame").GetDouble();
|
||||
if (!double.IsFinite(fps) || !double.IsFinite(ticks) || fps <= 0 || ticks <= 0)
|
||||
throw new InvalidDataException("Invalid morph timing");
|
||||
var samples = root.GetProperty("frames").EnumerateArray().ToArray();
|
||||
if (samples.Length == 0) throw new InvalidDataException("No morph samples");
|
||||
frames = samples.Select(s => Mesh.LoadSceneJson(Path.Combine(directory,
|
||||
s.GetProperty("path").GetString()!))).ToArray();
|
||||
Base = frames[0];
|
||||
if (frames.Any(f => f.Vertices.Length != Base.Vertices.Length
|
||||
|| !f.Indices.SequenceEqual(Base.Indices)))
|
||||
throw new InvalidDataException("Morph sample topology differs from base");
|
||||
for (var i = 0; i < Base.Vertices.Length; i++)
|
||||
if (frames.Any(f => f.Vertices[i].Uv != Base.Vertices[i].Uv))
|
||||
throw new InvalidDataException("Morph sample UV differs from base");
|
||||
SampleInterval = frames.Length > 1
|
||||
? (samples[1].GetProperty("time").GetDouble() - samples[0].GetProperty("time").GetDouble()) / ticks / fps
|
||||
: 1 / fps;
|
||||
if (!double.IsFinite(SampleInterval) || SampleInterval <= 0)
|
||||
throw new InvalidDataException("Invalid morph sample interval");
|
||||
for (var i = 1; i < samples.Length; i++)
|
||||
{
|
||||
var actual = (samples[i].GetProperty("time").GetDouble() - samples[0].GetProperty("time").GetDouble()) / ticks / fps;
|
||||
if (Math.Abs(actual - i * SampleInterval) > 0.000001)
|
||||
throw new NotSupportedException("Irregular sample times require original timing recovery");
|
||||
}
|
||||
var texture = root.GetProperty("texture");
|
||||
var width = texture.GetProperty("width").GetUInt32();
|
||||
var height = texture.GetProperty("height").GetUInt32();
|
||||
var rgba = File.ReadAllBytes(Path.Combine(directory, texture.GetProperty("path").GetString()!));
|
||||
if (width == 0 || height == 0 || width > 8192 || height > 8192
|
||||
|| rgba.Length != checked((int)(width * height * 4)))
|
||||
throw new InvalidDataException("Invalid morph texture");
|
||||
Texture = new PngImage(width, height, rgba);
|
||||
}
|
||||
|
||||
public void Sample(double seconds, Span<MeshVertex> destination, Matrix4x4 model)
|
||||
{
|
||||
if (!double.IsFinite(seconds) || seconds < 0) throw new ArgumentOutOfRangeException(nameof(seconds));
|
||||
if (destination.Length != Base.Vertices.Length) throw new ArgumentException("Morph target size differs");
|
||||
// Linear interpolation is recovered from DLL 0x10002F9A. Loop closure
|
||||
// and gameplay-specific speed remain preview policies until recovered.
|
||||
var frame = seconds / SampleInterval;
|
||||
var first = (int)(Math.Floor(frame) % frames.Length);
|
||||
var next = (first + 1) % frames.Length;
|
||||
var t = (float)(frame - Math.Floor(frame));
|
||||
for (var i = 0; i < destination.Length; i++)
|
||||
{
|
||||
destination[i] = Base.Vertices[i];
|
||||
destination[i].Position = Vector3.Transform(Vector3.Lerp(frames[first].Vertices[i].Position,
|
||||
frames[next].Vertices[i].Position, t), model);
|
||||
}
|
||||
}
|
||||
|
||||
public Mesh AppendTo(Mesh scene)
|
||||
{
|
||||
var vertices = new MeshVertex[scene.Vertices.Length + Base.Vertices.Length];
|
||||
scene.Vertices.CopyTo(vertices, 0);
|
||||
Base.Vertices.CopyTo(vertices, scene.Vertices.Length);
|
||||
var indices = scene.Indices.Concat(Base.Indices.Select(i => checked(i + (uint)scene.Vertices.Length))).ToArray();
|
||||
var draws = scene.HasExplicitDraws ? scene.Draws : [new MeshDraw(0, (uint)scene.Indices.Length, -1)];
|
||||
var textures = new Dictionary<int, PngImage>(scene.Textures) { [int.MinValue] = Texture };
|
||||
return new Mesh(vertices, indices)
|
||||
{
|
||||
HasExplicitDraws = true,
|
||||
Draws = [.. draws, new MeshDraw((uint)scene.Indices.Length, (uint)Base.Indices.Length, int.MinValue)],
|
||||
Textures = textures
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
using System.Buffers.Binary;
|
||||
using System.IO.Compression;
|
||||
|
||||
namespace GamePort.Assets;
|
||||
|
||||
public sealed record PngImage(uint Width, uint Height, byte[] Rgba)
|
||||
{
|
||||
public static PngImage White => new(1, 1, [255,255,255,255]);
|
||||
|
||||
public static PngImage Load(string path)
|
||||
{
|
||||
using var file = File.OpenRead(path);
|
||||
Span<byte> signature = stackalloc byte[8];
|
||||
file.ReadExactly(signature);
|
||||
if(signature[0]==(byte)'B' && signature[1]==(byte)'M')return LoadBmp(path);
|
||||
if (!signature.SequenceEqual(new byte[] {137,80,78,71,13,10,26,10})) throw new InvalidDataException("Invalid PNG signature.");
|
||||
uint width=0, height=0; byte color=0; byte[] palette=[], alpha=[];
|
||||
using var compressed = new MemoryStream();
|
||||
Span<byte> header = stackalloc byte[8];
|
||||
Span<byte> crc = stackalloc byte[4];
|
||||
while (true)
|
||||
{
|
||||
file.ReadExactly(header);
|
||||
var size = BinaryPrimitives.ReadUInt32BigEndian(header);
|
||||
if (size > 64*1024*1024) throw new InvalidDataException("PNG chunk exceeds limit.");
|
||||
var data = new byte[(int)size]; file.ReadExactly(data);
|
||||
file.ReadExactly(crc);
|
||||
var kind = System.Text.Encoding.ASCII.GetString(header[4..]);
|
||||
if (kind == "IHDR")
|
||||
{
|
||||
if (data.Length != 13) throw new InvalidDataException("Invalid PNG IHDR.");
|
||||
width=BinaryPrimitives.ReadUInt32BigEndian(data); height=BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(4));
|
||||
if (width==0 || height==0 || width>8192 || height>8192 || data[8]!=8 || data[10]!=0 || data[11]!=0 || data[12]!=0)
|
||||
throw new NotSupportedException("Only non-interlaced 8-bit PNGs up to 8192 pixels are supported.");
|
||||
color=data[9];
|
||||
}
|
||||
else if (kind == "PLTE") palette=data;
|
||||
else if (kind == "tRNS") alpha=data;
|
||||
else if (kind == "IDAT") compressed.Write(data);
|
||||
else if (kind == "IEND") break;
|
||||
}
|
||||
var channels = color switch {0=>1,2=>3,3=>1,4=>2,6=>4,_=>throw new NotSupportedException($"PNG color type {color} unsupported.")};
|
||||
var stride = checked((int)width*channels);
|
||||
var scan = new byte[checked((stride+1)*(int)height)];
|
||||
compressed.Position=0;
|
||||
using (var z = new ZLibStream(compressed, CompressionMode.Decompress, true)) {z.ReadExactly(scan); if(z.ReadByte()!=-1)throw new InvalidDataException("Excess PNG data.");}
|
||||
var pixels=new byte[checked(stride*(int)height)];
|
||||
for(int y=0;y<height;y++) for(int x=0;x<stride;x++)
|
||||
{
|
||||
var i=y*stride+x; var a=x>=channels?pixels[i-channels]:0; var b=y>0?pixels[i-stride]:0; var c=y>0&&x>=channels?pixels[i-stride-channels]:0;
|
||||
var predictor=scan[y*(stride+1)] switch {0=>0,1=>a,2=>b,3=>(a+b)/2,4=>Paeth(a,b,c),_=>throw new InvalidDataException("Invalid PNG filter.")};
|
||||
pixels[i]=unchecked((byte)(scan[y*(stride+1)+x+1]+predictor));
|
||||
}
|
||||
var rgba=new byte[checked((int)(width*height*4))];
|
||||
for(int i=0;i<width*height;i++)
|
||||
{
|
||||
var s=i*channels; var d=i*4;
|
||||
if(color==3)
|
||||
{
|
||||
var p=pixels[s]; if(p*3+2>=palette.Length)throw new InvalidDataException("PNG palette index out of bounds.");
|
||||
rgba[d]=palette[p*3];rgba[d+1]=palette[p*3+1];rgba[d+2]=palette[p*3+2];rgba[d+3]=p<alpha.Length?alpha[p]:(byte)255;
|
||||
}
|
||||
else if(color is 0 or 4){rgba[d]=rgba[d+1]=rgba[d+2]=pixels[s];rgba[d+3]=color==4?pixels[s+1]:(byte)255;}
|
||||
else {rgba[d]=pixels[s];rgba[d+1]=pixels[s+1];rgba[d+2]=pixels[s+2];rgba[d+3]=color==6?pixels[s+3]:(byte)255;}
|
||||
}
|
||||
return new PngImage(width,height,rgba);
|
||||
}
|
||||
private static PngImage LoadBmp(string path)
|
||||
{
|
||||
var bytes=File.ReadAllBytes(path);
|
||||
if(bytes.Length<54 || BinaryPrimitives.ReadUInt32LittleEndian(bytes.AsSpan(14))<40)throw new InvalidDataException("Unsupported BMP header.");
|
||||
var offset=BinaryPrimitives.ReadUInt32LittleEndian(bytes.AsSpan(10));
|
||||
var w=BinaryPrimitives.ReadInt32LittleEndian(bytes.AsSpan(18));var h=BinaryPrimitives.ReadInt32LittleEndian(bytes.AsSpan(22));
|
||||
var depth=BinaryPrimitives.ReadUInt16LittleEndian(bytes.AsSpan(28));var compression=BinaryPrimitives.ReadUInt32LittleEndian(bytes.AsSpan(30));
|
||||
if(w<1 || w>8192 || h==0 || h< -8192 || h>8192 || compression!=0 || depth is not (8 or 24 or 32))throw new NotSupportedException("Only uncompressed 8/24/32-bit BMP is supported.");
|
||||
var height=Math.Abs(h);var stride=checked((w*depth+31)/32*4);
|
||||
if((ulong)offset+(ulong)stride*(uint)height>(ulong)bytes.Length)throw new InvalidDataException("Truncated BMP pixels.");
|
||||
var palette=14+checked((int)BinaryPrimitives.ReadUInt32LittleEndian(bytes.AsSpan(14)));
|
||||
var rgba=new byte[checked(w*height*4)];
|
||||
for(var y=0;y<height;y++)for(var x=0;x<w;x++)
|
||||
{
|
||||
var src=checked((int)offset)+(h>0?height-1-y:y)*stride+x*(depth/8);
|
||||
if(depth==8){src=palette+bytes[src]*4;if(src+4>offset)throw new InvalidDataException("BMP palette index out of range.");}
|
||||
var dst=(y*w+x)*4;rgba[dst]=bytes[src+2];rgba[dst+1]=bytes[src+1];rgba[dst+2]=bytes[src];rgba[dst+3]=255;
|
||||
}
|
||||
return new PngImage((uint)w,(uint)height,rgba);
|
||||
}
|
||||
private static int Paeth(int a,int b,int c){var p=a+b-c;var pa=Math.Abs(p-a);var pb=Math.Abs(p-b);var pc=Math.Abs(p-c);return pa<=pb&&pa<=pc?a:pb<=pc?b:c;}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
using GamePort.Platform;
|
||||
|
||||
namespace GamePort.Audio;
|
||||
|
||||
/// <summary>Plays recovered WAV unchanged through an SDL3 conversion/mixing stream.</summary>
|
||||
public sealed class SdlAudio : IDisposable
|
||||
{
|
||||
private nint stream;
|
||||
private nint data;
|
||||
private int length;
|
||||
private readonly bool loop;
|
||||
public int QueuedBytes
|
||||
{
|
||||
get
|
||||
{
|
||||
var bytes = Sdl.SDL_GetAudioStreamQueued(stream);
|
||||
return bytes >= 0 ? bytes : throw new InvalidOperationException(Sdl.Error);
|
||||
}
|
||||
}
|
||||
public SdlAudio(string path,bool loop=false)
|
||||
{
|
||||
this.loop=loop;
|
||||
if(!Sdl.SDL_InitSubSystem(Sdl.InitAudio))throw new InvalidOperationException(Sdl.Error);
|
||||
try
|
||||
{
|
||||
if(!Sdl.SDL_LoadWAV(Path.GetFullPath(path),out var spec,out data,out var size))throw new InvalidOperationException(Sdl.Error);
|
||||
length=checked((int)size);
|
||||
stream=Sdl.SDL_OpenAudioDeviceStream(uint.MaxValue,ref spec,0,0);
|
||||
if(stream==0)throw new InvalidOperationException(Sdl.Error);
|
||||
Queue();
|
||||
if(!Sdl.SDL_ResumeAudioStreamDevice(stream))throw new InvalidOperationException(Sdl.Error);
|
||||
Console.WriteLine($"SDL3 WAV stream: {spec.Frequency} Hz, {spec.Channels} channel(s), {length} source bytes.");
|
||||
}
|
||||
catch{Dispose();throw;}
|
||||
}
|
||||
private void Queue(){if(!Sdl.SDL_PutAudioStreamData(stream,data,length))throw new InvalidOperationException(Sdl.Error);}
|
||||
public void Pump(){if(loop && QueuedBytes<length)Queue();}
|
||||
public void Dispose()
|
||||
{
|
||||
if(stream!=0){Sdl.SDL_DestroyAudioStream(stream);stream=0;}
|
||||
if(data!=0){Sdl.SDL_free(data);data=0;}
|
||||
Sdl.SDL_QuitSubSystem(Sdl.InitAudio);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
using System.Numerics;
|
||||
|
||||
namespace GamePort.Game;
|
||||
|
||||
/// <summary>
|
||||
/// Recovered arithmetic fragments, not a complete controller or collision system.
|
||||
/// Addresses and remaining call/gating questions are in docs/analysis/binary.md.
|
||||
/// </summary>
|
||||
public static class RecoveredMotion
|
||||
{
|
||||
public const float SpeedIncrement = 30f; // ctor +0x6BC; EXE 0x4392ED
|
||||
public const float SpeedDecay = 35f; // ctor +0x6C0; EXE 0x439433
|
||||
public const float MaximumSpeed = 600f; // ctor +0x6C4
|
||||
public const float JumpImpulse = 550f; // EXE 0x4383B3, subject to original jump state gating
|
||||
public static readonly Vector3 Gravity = new(0f, -800f, 0f); // EXE 0x44D414
|
||||
public static readonly Vector3 CameraFollowOffset = new(0f, 200f, -350f);
|
||||
public static readonly Vector3 CameraTargetOffset = new(0f, 80f, 0f);
|
||||
|
||||
// Deliberately per invocation: original increments omit dt. Call cadence is
|
||||
// not yet verified. Rendering must not directly choose simulation cadence.
|
||||
public static float AddSpeed(float speed) => MathF.Min(speed + SpeedIncrement, MaximumSpeed);
|
||||
public static float ReleaseSpeed(float speed) => speed > 0
|
||||
? MathF.Max(0, speed - SpeedDecay) : MathF.Min(0, speed + SpeedDecay);
|
||||
|
||||
/// <summary>
|
||||
/// EXE 0x479EBB..0x479FC0: consume impulse, acceleration, gravity, then
|
||||
/// integrate displacement using updated velocity. Collision is applied later
|
||||
/// by original code and must be supplied by the caller after recovery. Player
|
||||
/// airborne states add their own acceleration, e.g. gravity*1.33-gravity in
|
||||
/// states below 3 at EXE 0x438148; gravity alone is not the full jump model.
|
||||
/// </summary>
|
||||
public static Vector3 Integrate(ref Vector3 velocity, ref Vector3 impulse,
|
||||
Vector3 acceleration, Vector3 gravity, float seconds)
|
||||
{
|
||||
if (!float.IsFinite(seconds) || seconds <= 0 || seconds >= 1)
|
||||
throw new ArgumentOutOfRangeException(nameof(seconds), "Original frame accepts 0 < dt < 1");
|
||||
velocity += impulse;
|
||||
impulse = Vector3.Zero;
|
||||
velocity += acceleration * seconds;
|
||||
velocity += gravity * seconds;
|
||||
return velocity * seconds;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Wrapping original LCG at EXE 0x438D52; unrelated to System.Random.</summary>
|
||||
public struct OriginalRandom(uint seed)
|
||||
{
|
||||
public uint State { get; private set; } = seed;
|
||||
public uint Next()
|
||||
{
|
||||
State = unchecked(State * 1664525u + 32767u);
|
||||
return State >> 16;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace GamePort.Platform;
|
||||
|
||||
internal static unsafe class Sdl
|
||||
{
|
||||
private const string Library="SDL3";
|
||||
static Sdl()
|
||||
{
|
||||
NativeLibrary.SetDllImportResolver(typeof(Sdl).Assembly, (name, assembly, path) =>
|
||||
{
|
||||
if(name!=Library)return 0;
|
||||
var filename=OperatingSystem.IsWindows()?"SDL3.dll":"libSDL3.so.0";
|
||||
foreach(var candidate in new[]{Path.Combine(AppContext.BaseDirectory,filename),Path.Combine(Directory.GetCurrentDirectory(),".tools/sdl/lib",filename),filename})
|
||||
if(NativeLibrary.TryLoad(candidate,out var handle))return handle;
|
||||
return 0;
|
||||
});
|
||||
}
|
||||
public const uint InitVideo=0x20, InitAudio=0x10;
|
||||
public const ulong WindowVulkan=0x10000000, WindowResizable=0x20, WindowHighPixelDensity=0x2000;
|
||||
public const uint Quit=0x100, KeyDown=0x300, KeyUp=0x301, WindowResized=0x206, WindowPixelSizeChanged=0x207, WindowFocusLost=0x20F;
|
||||
[StructLayout(LayoutKind.Explicit,Size=128)] public struct Event
|
||||
{
|
||||
[FieldOffset(0)]public uint Type;
|
||||
[FieldOffset(16)]public uint WindowId;
|
||||
[FieldOffset(24)]public uint Scancode;
|
||||
[FieldOffset(28)]public uint Key;
|
||||
[FieldOffset(36)]public byte Down;
|
||||
[FieldOffset(37)]public byte Repeat;
|
||||
}
|
||||
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)] [return:MarshalAs(UnmanagedType.I1)] public static extern bool SDL_Init(uint flags);
|
||||
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)] public static extern void SDL_Quit();
|
||||
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)] private static extern nint SDL_GetError();
|
||||
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)] [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);
|
||||
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)] [return:MarshalAs(UnmanagedType.I1)]public static extern bool SDL_Vulkan_CreateSurface(nint window,nint instance,void* allocator,out ulong surface);
|
||||
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)] [return:MarshalAs(UnmanagedType.I1)]public static extern bool SDL_GetWindowSizeInPixels(nint window,out int w,out int h);
|
||||
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)] [return:MarshalAs(UnmanagedType.I1)]public static extern bool SDL_SetWindowFullscreen(nint window,[MarshalAs(UnmanagedType.I1)]bool fullscreen);
|
||||
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)] [return:MarshalAs(UnmanagedType.I1)]public static extern bool SDL_SetWindowRelativeMouseMode(nint window,[MarshalAs(UnmanagedType.I1)]bool enabled);
|
||||
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)] [return:MarshalAs(UnmanagedType.I1)]public static extern bool SDL_SetWindowSize(nint window,int width,int height);
|
||||
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)] [return:MarshalAs(UnmanagedType.I1)]public static extern bool SDL_PushEvent(ref Event e);
|
||||
[StructLayout(LayoutKind.Sequential)]public struct AudioSpec {public uint Format;public int Channels;public int Frequency;}
|
||||
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)] [return:MarshalAs(UnmanagedType.I1)]public static extern bool SDL_InitSubSystem(uint flags);
|
||||
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)]public static extern void SDL_QuitSubSystem(uint flags);
|
||||
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)] [return:MarshalAs(UnmanagedType.I1)]public static extern bool SDL_LoadWAV([MarshalAs(UnmanagedType.LPUTF8Str)]string path,out AudioSpec spec,out nint buffer,out uint length);
|
||||
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)]public static extern void SDL_free(nint buffer);
|
||||
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)]public static extern nint SDL_OpenAudioDeviceStream(uint device,ref AudioSpec spec,nint callback,nint user);
|
||||
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)] [return:MarshalAs(UnmanagedType.I1)]public static extern bool SDL_ResumeAudioStreamDevice(nint stream);
|
||||
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)] [return:MarshalAs(UnmanagedType.I1)]public static extern bool SDL_PutAudioStreamData(nint stream,nint buffer,int length);
|
||||
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)]public static extern int SDL_GetAudioStreamQueued(nint stream);
|
||||
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)]public static extern void SDL_DestroyAudioStream(nint stream);
|
||||
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)]public static extern void SDL_Delay(uint ms);
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
using System.Diagnostics;
|
||||
using System.Numerics;
|
||||
using GamePort.Assets;
|
||||
using GamePort.Audio;
|
||||
using GamePort.Platform;
|
||||
using GamePort.Rendering.Vulkan;
|
||||
|
||||
namespace GamePort;
|
||||
|
||||
internal static class Program
|
||||
{
|
||||
public static int Main(string[] args)
|
||||
{
|
||||
try { return Run(args); }
|
||||
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 static int Run(string[] args)
|
||||
{
|
||||
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
|
||||
--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)
|
||||
--audio PATH Play recovered WAV; --loop-audio repeats it
|
||||
--audio-smoke PATH Verify audio-stream consumption
|
||||
--verify-assets Decode all original PNG/ASE files
|
||||
--smoke-window Test keyboard event/resize (requires --frames 6 or more)
|
||||
--no-validation Disable development validation
|
||||
Viewer: C toggles stored/orbit camera, arrows/WASD orbit, +/- zoom,
|
||||
F11 fullscreen, Escape quit.
|
||||
Gameplay, original animation speed/state and cutscenes remain under reconstruction.
|
||||
""");
|
||||
return 0;
|
||||
}
|
||||
var root = AssetPath.FindOriginal(Option(args, "--assets"));
|
||||
if (args.Contains("--verify-assets")) return VerifyAssets(root);
|
||||
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 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 = Option(args, "--level") ?? (defaultScene ? "gam/level1b.gam" : null);
|
||||
GamLevel? level = levelPath == null ? null : GamLevel.Load(AssetPath.Resolve(root, levelPath));
|
||||
var originalStart = level?.FindStart();
|
||||
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 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");
|
||||
if (args.Contains("--with-player") && scene != null)
|
||||
animationPath ??= Path.Combine(Path.GetDirectoryName(scene)!, "../animations/jimstop/animation.json");
|
||||
MorphAnimation? animation = null;
|
||||
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.");
|
||||
animation = new MorphAnimation(animationPath);
|
||||
mesh = animation.AppendTo(mesh);
|
||||
characterModel = Matrix4x4.CreateRotationY(-originalStart.Rotation.Y * MathF.PI / 180)
|
||||
* Matrix4x4.CreateTranslation(originalStart.Position);
|
||||
Console.WriteLine("Original morph data loaded; playback looping/speed are preview policies.");
|
||||
}
|
||||
Console.WriteLine($"Loaded original geometry: {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");
|
||||
var frames = int.Parse(Option(args, "--frames") ?? (headless ? "1" : "0"));
|
||||
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.");
|
||||
nint window = 0;
|
||||
if (!headless)
|
||||
{
|
||||
if (!Sdl.SDL_Init(Sdl.InitVideo)) throw new InvalidOperationException(Sdl.Error);
|
||||
window = Sdl.SDL_CreateWindow("Jimmy Neutron reconstruction — scene investigation", 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")) : null;
|
||||
var keys = new HashSet<uint>();
|
||||
var running = true;
|
||||
var fullscreen = false;
|
||||
var sawKey = false;
|
||||
var didResize = false;
|
||||
var clock = Stopwatch.StartNew();
|
||||
double last = clock.Elapsed.TotalSeconds;
|
||||
float angle = 0.6f, elevation = 0.32f;
|
||||
var count = 0;
|
||||
while (running)
|
||||
{
|
||||
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 == Sdl.WindowFocusLost) keys.Clear();
|
||||
if (e.Type == Sdl.KeyDown)
|
||||
{
|
||||
keys.Add(e.Scancode);
|
||||
if (smoke && e.Scancode == 79) sawKey = true;
|
||||
if (e.Scancode == 41) running = false;
|
||||
if (e.Scancode == 6 && e.Repeat == 0 && originalStart != null)
|
||||
originalCamera = !originalCamera;
|
||||
if (e.Scancode == 68 && e.Repeat == 0)
|
||||
{
|
||||
fullscreen = !fullscreen;
|
||||
if (!Sdl.SDL_SetWindowFullscreen(window, fullscreen)) throw new InvalidOperationException(Sdl.Error);
|
||||
}
|
||||
}
|
||||
if (e.Type == Sdl.KeyUp) keys.Remove(e.Scancode);
|
||||
}
|
||||
var now = clock.Elapsed.TotalSeconds;
|
||||
var dt = (float)Math.Min(now - last, 0.1);
|
||||
last = now;
|
||||
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 far = level?.Code == "LV1B" ? 10000 : 3200;
|
||||
var projection = originalCamera
|
||||
? Matrix4x4.CreatePerspectiveFieldOfViewLeftHanded(0xAAA / 16384f * MathF.Tau, (float)renderer.Width / renderer.Height, 20, far)
|
||||
: Matrix4x4.CreatePerspectiveFieldOfView(MathF.PI / 3, (float)renderer.Width / renderer.Height, Math.Max(radius / 10000, 0.01f), radius * 20);
|
||||
projection.M22 *= -1;
|
||||
if (animation != null)
|
||||
{
|
||||
animation.Sample(fixedTime ?? (headless ? count / 60.0 : now), mesh.Vertices.AsSpan(characterOffset), characterModel);
|
||||
renderer.UpdateVertices(mesh.Vertices);
|
||||
}
|
||||
renderer.Render(view * projection);
|
||||
count++;
|
||||
audio?.Pump();
|
||||
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 (smoke && renderer.Width == 800 && renderer.Height == 600) didResize = true;
|
||||
if (frames > 0 && count >= frames) 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 (smoke)
|
||||
{
|
||||
Console.WriteLine($"SDL3 injected keyboard event received: {sawKey}; swapchain resized to 800x600: {didResize}.");
|
||||
if (!sawKey || !didResize) return 2;
|
||||
}
|
||||
return renderer.ValidationErrors > 0 || changed == 0 ? 2 : 0;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (window != 0) { Sdl.SDL_DestroyWindow(window); Sdl.SDL_Quit(); }
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
#version 450
|
||||
layout(location=0) in vec2 texCoord;
|
||||
layout(location=1) in vec3 vertexColor;
|
||||
layout(binding=0) uniform sampler2D diffuseMap;
|
||||
layout(location=0) out vec4 outColor;
|
||||
void main() {
|
||||
vec4 diffuse = texture(diffuseMap, texCoord);
|
||||
if (diffuse.a < 0.5) discard;
|
||||
outColor = vec4(diffuse.rgb * vertexColor, diffuse.a);
|
||||
}
|
||||
Binary file not shown.
@@ -0,0 +1,12 @@
|
||||
#version 450
|
||||
layout(location=0) in vec3 position;
|
||||
layout(location=1) in vec2 uv;
|
||||
layout(location=2) in vec3 color;
|
||||
layout(location=0) out vec2 texCoord;
|
||||
layout(location=1) out vec3 vertexColor;
|
||||
layout(push_constant) uniform Transform { mat4 mvp; } transform;
|
||||
void main() {
|
||||
gl_Position = transform.mvp * vec4(position, 1.0);
|
||||
texCoord = uv;
|
||||
vertexColor = color;
|
||||
}
|
||||
Binary file not shown.
@@ -0,0 +1,431 @@
|
||||
using System.Numerics;
|
||||
using System.Runtime.InteropServices;
|
||||
using GamePort.Assets;
|
||||
using GamePort.Platform;
|
||||
using Silk.NET.Vulkan;
|
||||
using Silk.NET.Vulkan.Extensions.KHR;
|
||||
using Silk.NET.Vulkan.Extensions.EXT;
|
||||
using Buffer = Silk.NET.Vulkan.Buffer;
|
||||
using Image = Silk.NET.Vulkan.Image;
|
||||
using Semaphore = Silk.NET.Vulkan.Semaphore;
|
||||
|
||||
namespace GamePort.Rendering.Vulkan;
|
||||
|
||||
/// <summary>A deliberately small, synchronous renderer for recovering the original scenes.</summary>
|
||||
public sealed unsafe class VulkanRenderer : IDisposable
|
||||
{
|
||||
private readonly Vk vk=Vk.GetApi();
|
||||
private Instance instance;
|
||||
private PhysicalDevice physical;
|
||||
private Device device;
|
||||
private Queue queue;
|
||||
private uint queueFamily;
|
||||
private CommandPool pool;
|
||||
private CommandBuffer command;
|
||||
private Buffer vertexBuffer,indexBuffer,readback;
|
||||
private DeviceMemory vertexMemory,indexMemory,readbackMemory;
|
||||
private Image color,depth;
|
||||
private DeviceMemory colorMemory,depthMemory;
|
||||
private ImageView colorView,depthView;
|
||||
private RenderPass renderPass;
|
||||
private Framebuffer framebuffer;
|
||||
private Pipeline pipeline;
|
||||
private PipelineLayout pipelineLayout;
|
||||
private DescriptorSetLayout descriptorLayout;
|
||||
private DescriptorPool descriptorPool;
|
||||
private Sampler sampler;
|
||||
private readonly List<Texture> textures=[];
|
||||
private readonly Dictionary<int,DescriptorSet> descriptors=[];
|
||||
private readonly Mesh mesh;
|
||||
private readonly nint window;
|
||||
private SurfaceKHR surface;
|
||||
private KhrSurface? surfaceApi;
|
||||
private KhrSwapchain? swapApi;
|
||||
private SwapchainKHR swapchain;
|
||||
private Image[] swapImages=[];
|
||||
private ExtDebugUtils? debugApi;
|
||||
private DebugUtilsMessengerEXT messenger;
|
||||
private readonly DebugUtilsMessengerCallbackFunctionEXT debugCallback;
|
||||
private Semaphore acquired,finished;
|
||||
private uint width,height;
|
||||
public string DeviceName { get; private set; }="";
|
||||
public int ValidationErrors { get; private set; }
|
||||
public uint Width=>width;
|
||||
public uint Height=>height;
|
||||
|
||||
private sealed record Texture(Image Image,DeviceMemory Memory,ImageView View);
|
||||
private static void Check(Result result,string operation)
|
||||
{if(result!=Result.Success)throw new InvalidOperationException($"{operation}: {result}");}
|
||||
|
||||
public VulkanRenderer(Mesh mesh,PngImage texture,uint width=960,uint height=720,nint window=0,bool validation=true)
|
||||
{
|
||||
this.mesh=mesh;this.width=width;this.height=height;this.window=window;
|
||||
debugCallback=OnValidation;
|
||||
try
|
||||
{
|
||||
CreateInstance(validation);
|
||||
if(window!=0)
|
||||
{
|
||||
if(!Sdl.SDL_Vulkan_CreateSurface(window,instance.Handle,null,out var handle))throw new InvalidOperationException(Sdl.Error);
|
||||
surface=new SurfaceKHR(handle);
|
||||
if(!vk.TryGetInstanceExtension(instance,out surfaceApi))throw new NotSupportedException("VK_KHR_surface unavailable.");
|
||||
}
|
||||
CreateDevice();
|
||||
var poolInfo=new CommandPoolCreateInfo{SType=StructureType.CommandPoolCreateInfo,QueueFamilyIndex=queueFamily,Flags=CommandPoolCreateFlags.ResetCommandBufferBit};
|
||||
Check(vk.CreateCommandPool(device,&poolInfo,null,out pool),"CreateCommandPool");
|
||||
var allocation=new CommandBufferAllocateInfo{SType=StructureType.CommandBufferAllocateInfo,CommandPool=pool,Level=CommandBufferLevel.Primary,CommandBufferCount=1};
|
||||
Check(vk.AllocateCommandBuffers(device,&allocation,out command),"AllocateCommandBuffers");
|
||||
UploadBuffers();
|
||||
CreateDescriptors(texture);
|
||||
CreateRenderPass();
|
||||
CreatePipeline();
|
||||
if(window!=0)CreateSwapchain();
|
||||
CreateTarget();
|
||||
}
|
||||
catch{Dispose();throw;}
|
||||
}
|
||||
|
||||
private uint OnValidation(DebugUtilsMessageSeverityFlagsEXT severity,DebugUtilsMessageTypeFlagsEXT type,DebugUtilsMessengerCallbackDataEXT* data,void* user)
|
||||
{
|
||||
if((severity&DebugUtilsMessageSeverityFlagsEXT.ErrorBitExt)!=0)ValidationErrors++;
|
||||
Console.Error.WriteLine($"Vulkan {severity}: {Marshal.PtrToStringUTF8((nint)data->PMessage)}");
|
||||
return Vk.False;
|
||||
}
|
||||
|
||||
private void CreateInstance(bool validation)
|
||||
{
|
||||
uint n=0;Check(vk.EnumerateInstanceLayerProperties(&n,null),"EnumerateInstanceLayers");
|
||||
var layers=new LayerProperties[n];
|
||||
fixed(LayerProperties* p=layers)Check(vk.EnumerateInstanceLayerProperties(&n,p),"EnumerateInstanceLayers");
|
||||
bool hasLayer=false;
|
||||
foreach(var layer in layers){var l=layer;if(Marshal.PtrToStringUTF8((nint)l.LayerName)=="VK_LAYER_KHRONOS_validation")hasLayer=true;}
|
||||
var names=new List<string>();
|
||||
if(window!=0)
|
||||
{
|
||||
var extensions=Sdl.SDL_Vulkan_GetInstanceExtensions(out var count);
|
||||
if(extensions==null)throw new InvalidOperationException(Sdl.Error);
|
||||
for(var i=0;i<count;i++)names.Add(Marshal.PtrToStringUTF8((nint)extensions[i])!);
|
||||
}
|
||||
validation &= hasLayer;
|
||||
if(validation)names.Add(ExtDebugUtils.ExtensionName);
|
||||
Console.WriteLine($"Vulkan validation: {(validation?"enabled":"unavailable or disabled")}");
|
||||
var native=names.Select(s=>Marshal.StringToCoTaskMemUTF8(s)).ToArray();
|
||||
var layerName=Marshal.StringToCoTaskMemUTF8("VK_LAYER_KHRONOS_validation");
|
||||
try
|
||||
{
|
||||
var app=new ApplicationInfo{SType=StructureType.ApplicationInfo,ApiVersion=Vk.Version13};
|
||||
fixed(nint* p=native)
|
||||
{
|
||||
var info=new InstanceCreateInfo{SType=StructureType.InstanceCreateInfo,PApplicationInfo=&app,EnabledExtensionCount=(uint)native.Length,PpEnabledExtensionNames=(byte**)p,
|
||||
EnabledLayerCount=validation?1u:0u,PpEnabledLayerNames=(byte**)&layerName};
|
||||
Check(vk.CreateInstance(&info,null,out instance),"CreateInstance");
|
||||
}
|
||||
if(validation && vk.TryGetInstanceExtension(instance,out debugApi))
|
||||
{
|
||||
var debugInfo=new DebugUtilsMessengerCreateInfoEXT{SType=StructureType.DebugUtilsMessengerCreateInfoExt,
|
||||
MessageSeverity=DebugUtilsMessageSeverityFlagsEXT.WarningBitExt|DebugUtilsMessageSeverityFlagsEXT.ErrorBitExt,
|
||||
MessageType=DebugUtilsMessageTypeFlagsEXT.GeneralBitExt|DebugUtilsMessageTypeFlagsEXT.ValidationBitExt|DebugUtilsMessageTypeFlagsEXT.PerformanceBitExt,
|
||||
PfnUserCallback=debugCallback};
|
||||
Check(debugApi!.CreateDebugUtilsMessenger(instance,&debugInfo,null,out messenger),"CreateDebugMessenger");
|
||||
}
|
||||
}
|
||||
finally{foreach(var p in native)Marshal.FreeCoTaskMem(p);Marshal.FreeCoTaskMem(layerName);}
|
||||
}
|
||||
|
||||
private void CreateDevice()
|
||||
{
|
||||
foreach(var gpu in vk.GetPhysicalDevices(instance))
|
||||
{
|
||||
vk.GetPhysicalDeviceProperties(gpu,out var properties);
|
||||
if(properties.ApiVersion<Vk.Version13)continue;
|
||||
uint count=0;vk.GetPhysicalDeviceQueueFamilyProperties(gpu,&count,null);
|
||||
var families=new QueueFamilyProperties[count];
|
||||
fixed(QueueFamilyProperties* p=families)vk.GetPhysicalDeviceQueueFamilyProperties(gpu,&count,p);
|
||||
for(uint f=0;f<count;f++)
|
||||
{
|
||||
if((families[f].QueueFlags&QueueFlags.GraphicsBit)==0)continue;
|
||||
if(window!=0){Check(surfaceApi!.GetPhysicalDeviceSurfaceSupport(gpu,f,surface,out var supported),"SurfaceSupport");if(!supported)continue;}
|
||||
physical=gpu;queueFamily=f;DeviceName=Marshal.PtrToStringUTF8((nint)properties.DeviceName)!;break;
|
||||
}
|
||||
if(physical.Handle!=0)break;
|
||||
}
|
||||
if(physical.Handle==0)throw new NotSupportedException("A Vulkan 1.3 graphics/presentation device is required.");
|
||||
float priority=1;
|
||||
var queueInfo=new DeviceQueueCreateInfo{SType=StructureType.DeviceQueueCreateInfo,QueueFamilyIndex=queueFamily,QueueCount=1,PQueuePriorities=&priority};
|
||||
var name=Marshal.StringToCoTaskMemUTF8(KhrSwapchain.ExtensionName);
|
||||
try
|
||||
{
|
||||
var info=new DeviceCreateInfo{SType=StructureType.DeviceCreateInfo,QueueCreateInfoCount=1,PQueueCreateInfos=&queueInfo,EnabledExtensionCount=window!=0?1u:0u,PpEnabledExtensionNames=(byte**)&name};
|
||||
Check(vk.CreateDevice(physical,&info,null,out device),"CreateDevice");
|
||||
}
|
||||
finally{Marshal.FreeCoTaskMem(name);}
|
||||
vk.GetDeviceQueue(device,queueFamily,0,out queue);
|
||||
if(window!=0)
|
||||
{
|
||||
if(!vk.TryGetDeviceExtension(instance,device,out swapApi))throw new NotSupportedException("VK_KHR_swapchain unavailable.");
|
||||
var si=new SemaphoreCreateInfo{SType=StructureType.SemaphoreCreateInfo};
|
||||
Check(vk.CreateSemaphore(device,&si,null,out acquired),"CreateSemaphore");
|
||||
Check(vk.CreateSemaphore(device,&si,null,out finished),"CreateSemaphore");
|
||||
}
|
||||
Console.WriteLine($"Vulkan device: {DeviceName}");
|
||||
}
|
||||
|
||||
private uint MemoryType(uint allowed,MemoryPropertyFlags flags)
|
||||
{
|
||||
vk.GetPhysicalDeviceMemoryProperties(physical,out var memory);
|
||||
for(uint i=0;i<memory.MemoryTypeCount;i++)if((allowed&(1u<<(int)i))!=0 && (memory.MemoryTypes[(int)i].PropertyFlags&flags)==flags)return i;
|
||||
throw new NotSupportedException($"No memory type for {flags}.");
|
||||
}
|
||||
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");
|
||||
}
|
||||
private void UploadBuffers()
|
||||
{
|
||||
var vertexBytes=MemoryMarshal.AsBytes(mesh.Vertices.AsSpan());
|
||||
MakeBuffer((ulong)vertexBytes.Length,BufferUsageFlags.VertexBufferBit,MemoryPropertyFlags.HostVisibleBit|MemoryPropertyFlags.HostCoherentBit,out vertexBuffer,out vertexMemory);
|
||||
CopyToMemory(vertexMemory,vertexBytes);
|
||||
var indexBytes=MemoryMarshal.AsBytes(mesh.Indices.AsSpan());
|
||||
MakeBuffer((ulong)indexBytes.Length,BufferUsageFlags.IndexBufferBit,MemoryPropertyFlags.HostVisibleBit|MemoryPropertyFlags.HostCoherentBit,out indexBuffer,out indexMemory);
|
||||
CopyToMemory(indexMemory,indexBytes);
|
||||
}
|
||||
public void UpdateVertices(ReadOnlySpan<MeshVertex> vertices)
|
||||
{
|
||||
if(vertices.Length!=mesh.Vertices.Length)throw new ArgumentException("Vertex count must match the uploaded mesh.");
|
||||
// Frames are completed synchronously; host coherent memory is safe to update here.
|
||||
CopyToMemory(vertexMemory,MemoryMarshal.AsBytes(vertices));
|
||||
}
|
||||
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);
|
||||
}
|
||||
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");
|
||||
}
|
||||
private void Begin()
|
||||
{
|
||||
Check(vk.ResetCommandBuffer(command,0),"ResetCommandBuffer");
|
||||
var info=new CommandBufferBeginInfo{SType=StructureType.CommandBufferBeginInfo,Flags=CommandBufferUsageFlags.OneTimeSubmitBit};
|
||||
Check(vk.BeginCommandBuffer(command,&info),"BeginCommandBuffer");
|
||||
}
|
||||
private void Submit()
|
||||
{
|
||||
Check(vk.EndCommandBuffer(command),"EndCommandBuffer");var cmd=command;
|
||||
var info=new SubmitInfo{SType=StructureType.SubmitInfo,CommandBufferCount=1,PCommandBuffers=&cmd};
|
||||
Check(vk.QueueSubmit(queue,1,&info,default),"QueueSubmit");Check(vk.QueueWaitIdle(queue),"QueueWaitIdle");
|
||||
}
|
||||
private void Barrier(Image image,ImageLayout oldLayout,ImageLayout newLayout,AccessFlags source,AccessFlags destination,PipelineStageFlags srcStage,PipelineStageFlags dstStage)
|
||||
{
|
||||
var barrier=new ImageMemoryBarrier{SType=StructureType.ImageMemoryBarrier,OldLayout=oldLayout,NewLayout=newLayout,SrcAccessMask=source,DstAccessMask=destination,SrcQueueFamilyIndex=Vk.QueueFamilyIgnored,DstQueueFamilyIndex=Vk.QueueFamilyIgnored,Image=image,SubresourceRange=new ImageSubresourceRange(ImageAspectFlags.ColorBit,0,1,0,1)};
|
||||
vk.CmdPipelineBarrier(command,srcStage,dstStage,0,0,null,0,null,1,&barrier);
|
||||
}
|
||||
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;
|
||||
}
|
||||
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");
|
||||
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};
|
||||
Check(vk.CreateDescriptorPool(device,&poolInfo,null,out descriptorPool),"CreateDescriptorPool");
|
||||
var samplerInfo=new SamplerCreateInfo{SType=StructureType.SamplerCreateInfo,MagFilter=Filter.Linear,MinFilter=Filter.Linear,MipmapMode=SamplerMipmapMode.Nearest,AddressModeU=SamplerAddressMode.Repeat,AddressModeV=SamplerAddressMode.Repeat,AddressModeW=SamplerAddressMode.Repeat,MaxLod=0};
|
||||
Check(vk.CreateSampler(device,&samplerInfo,null,out sampler),"CreateSampler");
|
||||
var images=new Dictionary<int,PngImage>(mesh.Textures){[-1]=fallback};
|
||||
foreach(var (id,image) in images)
|
||||
{
|
||||
var texture=UploadTexture(image);var descriptor=descriptorLayout;
|
||||
var alloc=new DescriptorSetAllocateInfo{SType=StructureType.DescriptorSetAllocateInfo,DescriptorPool=descriptorPool,DescriptorSetCount=1,PSetLayouts=&descriptor};
|
||||
Check(vk.AllocateDescriptorSets(device,&alloc,out var set),"AllocateDescriptorSets");
|
||||
var imageInfo=new DescriptorImageInfo{Sampler=sampler,ImageView=texture.View,ImageLayout=ImageLayout.ShaderReadOnlyOptimal};
|
||||
var write=new WriteDescriptorSet{SType=StructureType.WriteDescriptorSet,DstSet=set,DstBinding=0,DescriptorCount=1,DescriptorType=DescriptorType.CombinedImageSampler,PImageInfo=&imageInfo};
|
||||
vk.UpdateDescriptorSets(device,1,&write,0,null);descriptors[id]=set;
|
||||
}
|
||||
}
|
||||
private void CreateRenderPass()
|
||||
{
|
||||
var attachments=stackalloc AttachmentDescription[2];
|
||||
attachments[0]=new AttachmentDescription{Format=Format.R8G8B8A8Unorm,Samples=SampleCountFlags.Count1Bit,LoadOp=AttachmentLoadOp.Clear,StoreOp=AttachmentStoreOp.Store,StencilLoadOp=AttachmentLoadOp.DontCare,StencilStoreOp=AttachmentStoreOp.DontCare,InitialLayout=ImageLayout.Undefined,FinalLayout=ImageLayout.TransferSrcOptimal};
|
||||
attachments[1]=new AttachmentDescription{Format=Format.D32Sfloat,Samples=SampleCountFlags.Count1Bit,LoadOp=AttachmentLoadOp.Clear,StoreOp=AttachmentStoreOp.DontCare,StencilLoadOp=AttachmentLoadOp.DontCare,StencilStoreOp=AttachmentStoreOp.DontCare,InitialLayout=ImageLayout.Undefined,FinalLayout=ImageLayout.DepthStencilAttachmentOptimal};
|
||||
var cr=new AttachmentReference(0,ImageLayout.ColorAttachmentOptimal);var dr=new AttachmentReference(1,ImageLayout.DepthStencilAttachmentOptimal);
|
||||
var subpass=new SubpassDescription{PipelineBindPoint=PipelineBindPoint.Graphics,ColorAttachmentCount=1,PColorAttachments=&cr,PDepthStencilAttachment=&dr};
|
||||
var dependencies=stackalloc SubpassDependency[2];
|
||||
dependencies[0]=new SubpassDependency{SrcSubpass=Vk.SubpassExternal,DstSubpass=0,SrcStageMask=PipelineStageFlags.TopOfPipeBit,DstStageMask=PipelineStageFlags.ColorAttachmentOutputBit|PipelineStageFlags.EarlyFragmentTestsBit,DstAccessMask=AccessFlags.ColorAttachmentWriteBit|AccessFlags.DepthStencilAttachmentWriteBit};
|
||||
dependencies[1]=new SubpassDependency{SrcSubpass=0,DstSubpass=Vk.SubpassExternal,SrcStageMask=PipelineStageFlags.ColorAttachmentOutputBit,DstStageMask=PipelineStageFlags.TransferBit,SrcAccessMask=AccessFlags.ColorAttachmentWriteBit,DstAccessMask=AccessFlags.TransferReadBit};
|
||||
var info=new RenderPassCreateInfo{SType=StructureType.RenderPassCreateInfo,AttachmentCount=2,PAttachments=attachments,SubpassCount=1,PSubpasses=&subpass,DependencyCount=2,PDependencies=dependencies};
|
||||
Check(vk.CreateRenderPass(device,&info,null,out renderPass),"CreateRenderPass");
|
||||
}
|
||||
private ShaderModule Shader(string name)
|
||||
{
|
||||
var bytes=File.ReadAllBytes(Path.Combine(AppContext.BaseDirectory,"Shaders",name));
|
||||
fixed(byte* p=bytes){var info=new ShaderModuleCreateInfo{SType=StructureType.ShaderModuleCreateInfo,CodeSize=(nuint)bytes.Length,PCode=(uint*)p};Check(vk.CreateShaderModule(device,&info,null,out var shader),"CreateShaderModule");return shader;}
|
||||
}
|
||||
private void CreatePipeline()
|
||||
{
|
||||
var vertex=Shader("mesh.vert.spv");var fragment=Shader("mesh.frag.spv");var main=Marshal.StringToCoTaskMemUTF8("main");
|
||||
try
|
||||
{
|
||||
var push=new PushConstantRange(ShaderStageFlags.VertexBit,0,64);var dl=descriptorLayout;
|
||||
var layout=new PipelineLayoutCreateInfo{SType=StructureType.PipelineLayoutCreateInfo,SetLayoutCount=1,PSetLayouts=&dl,PushConstantRangeCount=1,PPushConstantRanges=&push};
|
||||
Check(vk.CreatePipelineLayout(device,&layout,null,out pipelineLayout),"CreatePipelineLayout");
|
||||
var stages=stackalloc PipelineShaderStageCreateInfo[2];
|
||||
stages[0]=new PipelineShaderStageCreateInfo{SType=StructureType.PipelineShaderStageCreateInfo,Stage=ShaderStageFlags.VertexBit,Module=vertex,PName=(byte*)main};
|
||||
stages[1]=new PipelineShaderStageCreateInfo{SType=StructureType.PipelineShaderStageCreateInfo,Stage=ShaderStageFlags.FragmentBit,Module=fragment,PName=(byte*)main};
|
||||
var binding=new VertexInputBindingDescription(0,(uint)sizeof(MeshVertex),VertexInputRate.Vertex);
|
||||
var attributes=stackalloc VertexInputAttributeDescription[3];
|
||||
attributes[0]=new VertexInputAttributeDescription(0,0,Format.R32G32B32Sfloat,0);
|
||||
attributes[1]=new VertexInputAttributeDescription(1,0,Format.R32G32Sfloat,12);
|
||||
attributes[2]=new VertexInputAttributeDescription(2,0,Format.R32G32B32Sfloat,20);
|
||||
var input=new PipelineVertexInputStateCreateInfo{SType=StructureType.PipelineVertexInputStateCreateInfo,VertexBindingDescriptionCount=1,PVertexBindingDescriptions=&binding,VertexAttributeDescriptionCount=3,PVertexAttributeDescriptions=attributes};
|
||||
var assembly=new PipelineInputAssemblyStateCreateInfo{SType=StructureType.PipelineInputAssemblyStateCreateInfo,Topology=PrimitiveTopology.TriangleList};
|
||||
var viewport=new PipelineViewportStateCreateInfo{SType=StructureType.PipelineViewportStateCreateInfo,ViewportCount=1,ScissorCount=1};
|
||||
var raster=new PipelineRasterizationStateCreateInfo{SType=StructureType.PipelineRasterizationStateCreateInfo,PolygonMode=PolygonMode.Fill,CullMode=CullModeFlags.None,FrontFace=FrontFace.CounterClockwise,LineWidth=1};
|
||||
var ms=new PipelineMultisampleStateCreateInfo{SType=StructureType.PipelineMultisampleStateCreateInfo,RasterizationSamples=SampleCountFlags.Count1Bit};
|
||||
var ds=new PipelineDepthStencilStateCreateInfo{SType=StructureType.PipelineDepthStencilStateCreateInfo,DepthTestEnable=true,DepthWriteEnable=true,DepthCompareOp=CompareOp.LessOrEqual};
|
||||
var blendAttachment=new PipelineColorBlendAttachmentState{ColorWriteMask=ColorComponentFlags.RBit|ColorComponentFlags.GBit|ColorComponentFlags.BBit|ColorComponentFlags.ABit};
|
||||
var blend=new PipelineColorBlendStateCreateInfo{SType=StructureType.PipelineColorBlendStateCreateInfo,AttachmentCount=1,PAttachments=&blendAttachment};
|
||||
var dynamicStates=stackalloc DynamicState[2]{DynamicState.Viewport,DynamicState.Scissor};
|
||||
var dynamic=new PipelineDynamicStateCreateInfo{SType=StructureType.PipelineDynamicStateCreateInfo,DynamicStateCount=2,PDynamicStates=dynamicStates};
|
||||
var info=new GraphicsPipelineCreateInfo{SType=StructureType.GraphicsPipelineCreateInfo,StageCount=2,PStages=stages,PVertexInputState=&input,PInputAssemblyState=&assembly,PViewportState=&viewport,PRasterizationState=&raster,PMultisampleState=&ms,PDepthStencilState=&ds,PColorBlendState=&blend,PDynamicState=&dynamic,Layout=pipelineLayout,RenderPass=renderPass,Subpass=0};
|
||||
Check(vk.CreateGraphicsPipelines(device,default,1,&info,null,out pipeline),"CreateGraphicsPipeline");
|
||||
}
|
||||
finally{Marshal.FreeCoTaskMem(main);vk.DestroyShaderModule(device,vertex,null);vk.DestroyShaderModule(device,fragment,null);}
|
||||
}
|
||||
private void CreateTarget()
|
||||
{
|
||||
MakeImage(width,height,Format.R8G8B8A8Unorm,ImageUsageFlags.ColorAttachmentBit|ImageUsageFlags.TransferSrcBit,ImageAspectFlags.ColorBit,out color,out colorMemory,out colorView);
|
||||
MakeImage(width,height,Format.D32Sfloat,ImageUsageFlags.DepthStencilAttachmentBit,ImageAspectFlags.DepthBit,out depth,out depthMemory,out depthView);
|
||||
var views=stackalloc ImageView[2]{colorView,depthView};
|
||||
var info=new FramebufferCreateInfo{SType=StructureType.FramebufferCreateInfo,RenderPass=renderPass,AttachmentCount=2,PAttachments=views,Width=width,Height=height,Layers=1};
|
||||
Check(vk.CreateFramebuffer(device,&info,null,out framebuffer),"CreateFramebuffer");
|
||||
MakeBuffer((ulong)width*height*4,BufferUsageFlags.TransferDstBit,MemoryPropertyFlags.HostVisibleBit|MemoryPropertyFlags.HostCoherentBit,out readback,out readbackMemory);
|
||||
}
|
||||
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);
|
||||
}
|
||||
private void CreateSwapchain()
|
||||
{
|
||||
Check(surfaceApi!.GetPhysicalDeviceSurfaceCapabilities(physical,surface,out var caps),"SurfaceCapabilities");
|
||||
uint count=0;Check(surfaceApi.GetPhysicalDeviceSurfaceFormats(physical,surface,&count,null),"SurfaceFormats");
|
||||
var formats=new SurfaceFormatKHR[count];fixed(SurfaceFormatKHR* p=formats)Check(surfaceApi.GetPhysicalDeviceSurfaceFormats(physical,surface,&count,p),"SurfaceFormats");
|
||||
var format=formats.FirstOrDefault(f=>f.Format==Format.B8G8R8A8Unorm);if(format.Format==0)format=formats[0];
|
||||
Sdl.SDL_GetWindowSizeInPixels(window,out var w,out var h);
|
||||
width=caps.CurrentExtent.Width==uint.MaxValue?Math.Clamp((uint)Math.Max(1,w),caps.MinImageExtent.Width,caps.MaxImageExtent.Width):caps.CurrentExtent.Width;
|
||||
height=caps.CurrentExtent.Height==uint.MaxValue?Math.Clamp((uint)Math.Max(1,h),caps.MinImageExtent.Height,caps.MaxImageExtent.Height):caps.CurrentExtent.Height;
|
||||
if((caps.SupportedUsageFlags&ImageUsageFlags.TransferDstBit)==0)throw new NotSupportedException("Swapchain does not support transfer destinations.");
|
||||
var imageCount=caps.MinImageCount+1;if(caps.MaxImageCount>0)imageCount=Math.Min(imageCount,caps.MaxImageCount);
|
||||
var info=new SwapchainCreateInfoKHR{SType=StructureType.SwapchainCreateInfoKhr,Surface=surface,MinImageCount=imageCount,ImageFormat=format.Format,ImageColorSpace=format.ColorSpace,ImageExtent=new Extent2D(width,height),ImageArrayLayers=1,ImageUsage=ImageUsageFlags.TransferDstBit,ImageSharingMode=SharingMode.Exclusive,PreTransform=caps.CurrentTransform,CompositeAlpha=CompositeAlphaFlagsKHR.OpaqueBitKhr,PresentMode=PresentModeKHR.FifoKhr,Clipped=true};
|
||||
Check(swapApi!.CreateSwapchain(device,&info,null,out swapchain),"CreateSwapchain");
|
||||
count=0;Check(swapApi.GetSwapchainImages(device,swapchain,&count,null),"GetSwapchainImages");swapImages=new Image[count];
|
||||
fixed(Image* p=swapImages)Check(swapApi.GetSwapchainImages(device,swapchain,&count,p),"GetSwapchainImages");
|
||||
}
|
||||
public void Resize()
|
||||
{
|
||||
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();
|
||||
}
|
||||
public void Render(Matrix4x4 mvp)
|
||||
{
|
||||
uint imageIndex=0;
|
||||
if(window!=0)
|
||||
{
|
||||
var result=swapApi!.AcquireNextImage(device,swapchain,ulong.MaxValue,acquired,default,&imageIndex);
|
||||
if(result==Result.ErrorOutOfDateKhr){Resize();return;}
|
||||
if(result!=Result.SuboptimalKhr)Check(result,"AcquireNextImage");
|
||||
}
|
||||
Begin();
|
||||
var clear=stackalloc ClearValue[2];clear[0].Color=new ClearColorValue(0.12f,0.20f,0.30f,1);clear[1].DepthStencil=new ClearDepthStencilValue(1,0);
|
||||
var begin=new RenderPassBeginInfo{SType=StructureType.RenderPassBeginInfo,RenderPass=renderPass,Framebuffer=framebuffer,RenderArea=new Rect2D(new Offset2D(0,0),new Extent2D(width,height)),ClearValueCount=2,PClearValues=clear};
|
||||
vk.CmdBeginRenderPass(command,&begin,SubpassContents.Inline);vk.CmdBindPipeline(command,PipelineBindPoint.Graphics,pipeline);
|
||||
var viewport=new Viewport(0,0,width,height,0,1);var scissor=new Rect2D(new Offset2D(0,0),new Extent2D(width,height));
|
||||
vk.CmdSetViewport(command,0,1,&viewport);vk.CmdSetScissor(command,0,1,&scissor);
|
||||
var vb=vertexBuffer;ulong offset=0;vk.CmdBindVertexBuffers(command,0,1,&vb,&offset);vk.CmdBindIndexBuffer(command,indexBuffer,0,IndexType.Uint32);
|
||||
vk.CmdPushConstants(command,pipelineLayout,ShaderStageFlags.VertexBit,0,64,&mvp);
|
||||
var draws=mesh.HasExplicitDraws?mesh.Draws:[new MeshDraw(0,(uint)mesh.Indices.Length,-1)];
|
||||
foreach(var draw in draws)
|
||||
{
|
||||
var descriptor=descriptors.GetValueOrDefault(draw.TextureId,descriptors[-1]);
|
||||
vk.CmdBindDescriptorSets(command,PipelineBindPoint.Graphics,pipelineLayout,0,1,&descriptor,0,null);
|
||||
vk.CmdDrawIndexed(command,draw.IndexCount,1,draw.FirstIndex,0,0);
|
||||
}
|
||||
vk.CmdEndRenderPass(command);
|
||||
if(window==0){Submit();return;}
|
||||
var target=swapImages[imageIndex];Barrier(target,ImageLayout.Undefined,ImageLayout.TransferDstOptimal,0,AccessFlags.TransferWriteBit,PipelineStageFlags.TopOfPipeBit,PipelineStageFlags.TransferBit);
|
||||
var blit=new ImageBlit{SrcSubresource=new ImageSubresourceLayers(ImageAspectFlags.ColorBit,0,0,1),DstSubresource=new ImageSubresourceLayers(ImageAspectFlags.ColorBit,0,0,1)};
|
||||
blit.SrcOffsets[0]=new Offset3D(0,0,0);blit.SrcOffsets[1]=new Offset3D((int)width,(int)height,1);blit.DstOffsets[0]=new Offset3D(0,0,0);blit.DstOffsets[1]=new Offset3D((int)width,(int)height,1);
|
||||
vk.CmdBlitImage(command,color,ImageLayout.TransferSrcOptimal,target,ImageLayout.TransferDstOptimal,1,&blit,Filter.Nearest);
|
||||
Barrier(target,ImageLayout.TransferDstOptimal,ImageLayout.PresentSrcKhr,AccessFlags.TransferWriteBit,0,PipelineStageFlags.TransferBit,PipelineStageFlags.BottomOfPipeBit);
|
||||
Check(vk.EndCommandBuffer(command),"EndCommandBuffer");var cmd=command;var wait=acquired;var signal=finished;var stage=PipelineStageFlags.TransferBit;
|
||||
var submit=new SubmitInfo{SType=StructureType.SubmitInfo,WaitSemaphoreCount=1,PWaitSemaphores=&wait,PWaitDstStageMask=&stage,CommandBufferCount=1,PCommandBuffers=&cmd,SignalSemaphoreCount=1,PSignalSemaphores=&signal};
|
||||
Check(vk.QueueSubmit(queue,1,&submit,default),"QueueSubmit");var swap=swapchain;
|
||||
var present=new PresentInfoKHR{SType=StructureType.PresentInfoKhr,WaitSemaphoreCount=1,PWaitSemaphores=&signal,SwapchainCount=1,PSwapchains=&swap,PImageIndices=&imageIndex};
|
||||
var presentation=swapApi!.QueuePresent(queue,&present);Check(vk.QueueWaitIdle(queue),"PresentWaitIdle");
|
||||
if(presentation is Result.ErrorOutOfDateKhr or Result.SuboptimalKhr)Resize();else Check(presentation,"QueuePresent");
|
||||
}
|
||||
public byte[] ReadPixels()
|
||||
{
|
||||
Begin();var copy=new BufferImageCopy{ImageSubresource=new ImageSubresourceLayers(ImageAspectFlags.ColorBit,0,0,1),ImageExtent=new Extent3D(width,height,1)};
|
||||
vk.CmdCopyImageToBuffer(command,color,ImageLayout.TransferSrcOptimal,readback,1,©);Submit();
|
||||
var pixels=new byte[checked((int)(width*height*4))];void* data;
|
||||
Check(vk.MapMemory(device,readbackMemory,0,(ulong)pixels.Length,0,&data),"ReadbackMap");new ReadOnlySpan<byte>(data,pixels.Length).CopyTo(pixels);vk.UnmapMemory(device,readbackMemory);return pixels;
|
||||
}
|
||||
public void SavePpm(string path)
|
||||
{
|
||||
var rgba=ReadPixels();Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(path))!);
|
||||
using var file=File.Create(path);file.Write(System.Text.Encoding.ASCII.GetBytes($"P6\n{width} {height}\n255\n"));
|
||||
for(var i=0;i<rgba.Length;i+=4)file.Write(rgba,i,3);
|
||||
}
|
||||
public void Dispose()
|
||||
{
|
||||
if(device.Handle!=0)
|
||||
{
|
||||
vk.DeviceWaitIdle(device);
|
||||
if(framebuffer.Handle!=0)DestroyTarget();
|
||||
if(pipeline.Handle!=0)vk.DestroyPipeline(device,pipeline,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);
|
||||
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);
|
||||
vk.DestroyDevice(device,null);device=default;
|
||||
}
|
||||
if(surface.Handle!=0){surfaceApi!.DestroySurface(instance,surface,null);surface=default;}
|
||||
if(messenger.Handle!=0){debugApi!.DestroyDebugUtilsMessenger(instance,messenger,null);messenger=default;}
|
||||
if(instance.Handle!=0){vk.DestroyInstance(instance,null);instance=default;}
|
||||
vk.Dispose();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user