Files
Neutron/src/GamePort/Assets/Mesh.cs
T

120 lines
7.1 KiB
C#

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 MeshPolygonSource[] CollisionPolygons { get; init; } = [];
public bool HasCollisionMaterialIds { get; init; }
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.");
// Level loaders omit NC-prefixed SHAPE names from terrain registration
// (LV1B44DD2F..44DD70). Material names and draw visibility are separate.
var shapeNames = new Dictionary<int, string>();
if (root.TryGetProperty("meshes", out var shapeMeshes))
foreach (var shape in shapeMeshes.EnumerateArray())
{
if (!shape.TryGetProperty("shapeId", out var id) || !shape.TryGetProperty("name", out var name)) continue;
var text = name.GetString() ?? "";
if (shapeNames.TryGetValue(id.GetInt32(), out var existing) && existing != text)
throw new InvalidDataException("Conflicting source shape names");
shapeNames[id.GetInt32()] = text;
}
var collisionPolygons = root.TryGetProperty("collisionPolygons", out var polygonList)
? polygonList.EnumerateArray().Select(p => new MeshPolygonSource(p.GetProperty("shapeId").GetInt32(),
p.GetProperty("polygonIndex").GetInt32(),
new Vector3(p.GetProperty("normal")[0].GetSingle(), p.GetProperty("normal")[1].GetSingle(), p.GetProperty("normal")[2].GetSingle()),
p.GetProperty("materialName").GetString(), shapeNames.GetValueOrDefault(p.GetProperty("shapeId").GetInt32()),
p.TryGetProperty("materialId", out var materialId) && materialId.ValueKind == JsonValueKind.Number
? materialId.GetInt32() : null)).ToArray() : [];
if (collisionPolygons.Length != 0 && (collisionPolygons.Length != indices.Length / 3
|| collisionPolygons.Any(p => !float.IsFinite(p.Normal.X + p.Normal.Y + p.Normal.Z))))
throw new InvalidDataException("Invalid source collision polygon metadata");
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,CollisionPolygons=collisionPolygons,
HasCollisionMaterialIds=root.TryGetProperty("collisionPolygons", out var sourcePolygons)
&& sourcePolygons.EnumerateArray().All(p => p.TryGetProperty("materialId", out var id)
&& id.ValueKind is JsonValueKind.Number or JsonValueKind.Null)};
}
}
public readonly record struct MeshPolygonSource(int ShapeId, int PolygonIndex, Vector3 Normal, string? MaterialName,
string? ShapeName = null, int? MaterialId = null)
{
public bool TerrainCollision => ShapeName?.StartsWith("nc", StringComparison.OrdinalIgnoreCase) != true;
}
public enum MeshBlend { Opaque, Alpha, Additive }
public sealed record MeshDraw(uint FirstIndex,uint IndexCount,int TextureId)
{
public bool Visible { get; set; } = true;
public bool ScreenSpace { get; init; }
public float Opacity { get; set; } = 1;
public MeshBlend Blend { get; set; } = MeshBlend.Opaque;
}