Render original lab and Jimmy with native Vulkan and SDL3 on .NET 10

This commit is contained in:
UnixNight committed 2026-10-23 17:36:04 -04:00
1 parent 3df20ac19a
commit 008c0e16da
41 files changed
+2125 -68

No files matched your search

+51
View File
@@ -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());
}
}
+30
View File
@@ -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.");
}
}
+78
View File
@@ -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);
+88
View File
@@ -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
};
}
}
+89
View File
@@ -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;}
}