diff --git a/Gltf/GltfImporter.cs b/Gltf/GltfImporter.cs index f58a8bd..59a66b2 100644 --- a/Gltf/GltfImporter.cs +++ b/Gltf/GltfImporter.cs @@ -593,7 +593,7 @@ private List ProcessMeshes(GltfLoadContext context) GltfRoot gltf = context.Root; byte[]? binaryBuffer = gltf.buffers?[0]?.Data; - List results = GltfMeshProcessor.ProcessMeshes(gltf, binaryBuffer); + List results = GltfMeshProcessor.ProcessMeshes(gltf, binaryBuffer, context.Options); // Register meshes foreach (GltfMeshResult result in results) @@ -742,10 +742,7 @@ private void AttachMesh(GameObject go, GltfMeshResult meshResult, List { defaultMat = GltfMaterialProcessor.CreateDefaultMaterial(context); } - else - { - meshMaterials[i] = defaultMat; - } + meshMaterials[i] = defaultMat!; } } diff --git a/Gltf/Processing/GltfMeshProcessor.cs b/Gltf/Processing/GltfMeshProcessor.cs index f681e5c..7e1f223 100644 --- a/Gltf/Processing/GltfMeshProcessor.cs +++ b/Gltf/Processing/GltfMeshProcessor.cs @@ -26,9 +26,11 @@ internal static class GltfMeshProcessor /// /// The parsed GLTF root object /// The binary buffer containing mesh data + /// Controls generation of missing normals and tangents /// List of processed meshes with material indices - public static List ProcessMeshes(GltfRoot gltf, byte[]? binaryBuffer) + public static List ProcessMeshes(GltfRoot gltf, byte[]? binaryBuffer, GltfImportOptions? options = null) { + options ??= new GltfImportOptions(); List results = new List(); if (gltf.meshes == null) return results; @@ -49,76 +51,78 @@ public static List ProcessMeshes(GltfRoot gltf, byte[]? binaryBu List allSubmeshIndices = new List(); List materialIndices = new List(); + List missingNormals = new List(); + List missingTangents = new List(); + bool hasNormals = false; + bool hasUvs = false; + bool hasTangents = false; + bool hasBoneWeights = false; int vertexOffset = 0; if (gltfMesh.primitives != null) { foreach (GltfPrimitive primitive in gltfMesh.primitives) { - if (primitive.attributes == null) + // Validate topology before appending anything so skipped primitives cannot + // shift later vertex attributes or material slots. + if (primitive.mode != GltfPrimitiveMode.Triangles) { + DebugLog.Warning($"Unsupported primitive mode {primitive.mode} in mesh '{unityMesh.name}'. Only TRIANGLES is supported. Skipping."); continue; } - // Positions - int vertexCount = 0; - if (primitive.attributes.TryGetValue("POSITION", out int posIndex)) + if (primitive.attributes == null || !primitive.attributes.TryGetValue("POSITION", out int posIndex)) { - Vector3[] verts = ReadVector3Array(gltf, binaryBuffer, posIndex, true); - vertexCount = verts.Length; - allVertices.AddRange(verts); - } - - // Normals - if (primitive.attributes.TryGetValue("NORMAL", out int normIndex)) - { - allNormals.AddRange(ReadVector3Array(gltf, binaryBuffer, normIndex, true)); + DebugLog.Warning($"Primitive without POSITION in mesh '{unityMesh.name}'. Skipping."); + continue; } - // UVs - if (primitive.attributes.TryGetValue("TEXCOORD_0", out int uvIndex)) + Vector3[] verts = ReadVector3Array(gltf, binaryBuffer, posIndex, true); + int vertexCount = verts.Length; + int[] indices = primitive.indices.HasValue + ? ReadIntArray(gltf, binaryBuffer, primitive.indices.Value) + : Enumerable.Range(0, vertexCount).ToArray(); + if (vertexCount == 0 || indices.Length == 0 || indices.Length % 3 != 0 || + indices.Any(index => index < 0 || index >= vertexCount)) { - Vector2[] uvs = ReadVector2Array(gltf, binaryBuffer, uvIndex, false); - FlipUVs(uvs); - allUvs.AddRange(uvs); + DebugLog.Warning($"Invalid triangle indices in mesh '{unityMesh.name}'. Skipping primitive."); + continue; } - // Tangents - if (primitive.attributes.TryGetValue("TANGENT", out int tanIndex)) + Vector3[]? normals = primitive.attributes.TryGetValue("NORMAL", out int normIndex) + ? ReadVector3Array(gltf, binaryBuffer, normIndex, true) : null; + Vector2[]? uvs = primitive.attributes.TryGetValue("TEXCOORD_0", out int uvIndex) + ? ReadVector2Array(gltf, binaryBuffer, uvIndex, false) : null; + Vector4[]? tangents = primitive.attributes.TryGetValue("TANGENT", out int tanIndex) + ? ReadVector4Array(gltf, binaryBuffer, tanIndex, true) : null; + BoneWeight[]? boneWeights = primitive.attributes.TryGetValue("JOINTS_0", out int jointsIndex) && + primitive.attributes.TryGetValue("WEIGHTS_0", out int weightsIndex) + ? ReadBoneWeights(gltf, binaryBuffer, jointsIndex, weightsIndex) : null; + if ((normals != null && normals.Length != vertexCount) || + (uvs != null && uvs.Length != vertexCount) || + (tangents != null && tangents.Length != vertexCount) || + (boneWeights != null && boneWeights.Length != vertexCount)) { - allTangents.AddRange(ReadVector4Array(gltf, binaryBuffer, tanIndex, true)); + DebugLog.Warning($"Mismatched vertex attribute counts in mesh '{unityMesh.name}'. Skipping primitive."); + continue; } - // Bone Weights - if (primitive.attributes.TryGetValue("JOINTS_0", out int jointsIndex) && - primitive.attributes.TryGetValue("WEIGHTS_0", out int weightsIndex)) - { - allBoneWeights.AddRange(ReadBoneWeights(gltf, binaryBuffer, jointsIndex, weightsIndex)); - } - - // Indices - if (primitive.indices.HasValue) - { - int[] indices = ReadIntArray(gltf, binaryBuffer, primitive.indices.Value); - FlipTriangles(indices); - - // Apply offset for combined mesh - if (vertexOffset > 0) - { - for (int k = 0; k < indices.Length; k++) - { - indices[k] += vertexOffset; - } - } - - allSubmeshIndices.Add(indices); - } - else - { - // Non-indexed geometry not supported in this simplified version - DebugLog.Warning($"Non-indexed primitive in mesh '{unityMesh.name}'. Skipping."); - allSubmeshIndices.Add(new int[0]); - } + if (uvs != null) FlipUVs(uvs); + allVertices.AddRange(verts); + allNormals.AddRange(normals ?? new Vector3[vertexCount]); + allUvs.AddRange(uvs ?? new Vector2[vertexCount]); + allTangents.AddRange(tangents ?? new Vector4[vertexCount]); + allBoneWeights.AddRange(boneWeights ?? new BoneWeight[vertexCount]); + hasNormals |= normals != null; + hasUvs |= uvs != null; + hasTangents |= tangents != null; + hasBoneWeights |= boneWeights != null; + if (normals == null) missingNormals.AddRange(Enumerable.Range(vertexOffset, vertexCount)); + if (tangents == null) missingTangents.AddRange(Enumerable.Range(vertexOffset, vertexCount)); + + FlipTriangles(indices); + for (int i = 0; i < indices.Length; i++) indices[i] += vertexOffset; + allSubmeshIndices.Add(indices); materialIndices.Add(primitive.material ?? -1); // -1 means default material vertexOffset += vertexCount; @@ -128,16 +132,16 @@ public static List ProcessMeshes(GltfRoot gltf, byte[]? binaryBu // Assign to Unity Mesh #if IL2CPP unityMesh.SetVertices(allVertices.ToIl2CppList()); - if (allNormals.Count > 0) unityMesh.SetNormals(allNormals.ToIl2CppList()); - if (allUvs.Count > 0) unityMesh.SetUVs(0, allUvs.ToIl2CppList()); - if (allTangents.Count > 0) unityMesh.SetTangents(allTangents.ToIl2CppList()); + if (hasNormals) unityMesh.SetNormals(allNormals.ToIl2CppList()); + if (hasUvs) unityMesh.SetUVs(0, allUvs.ToIl2CppList()); + if (hasTangents) unityMesh.SetTangents(allTangents.ToIl2CppList()); #else unityMesh.SetVertices(allVertices); - if (allNormals.Count > 0) unityMesh.SetNormals(allNormals); - if (allUvs.Count > 0) unityMesh.SetUVs(0, allUvs); - if (allTangents.Count > 0) unityMesh.SetTangents(allTangents); + if (hasNormals) unityMesh.SetNormals(allNormals); + if (hasUvs) unityMesh.SetUVs(0, allUvs); + if (hasTangents) unityMesh.SetTangents(allTangents); #endif - if (allBoneWeights.Count > 0) unityMesh.boneWeights = allBoneWeights.ToArray(); + if (hasBoneWeights) unityMesh.boneWeights = allBoneWeights.ToArray(); unityMesh.subMeshCount = allSubmeshIndices.Count; for (int i = 0; i < allSubmeshIndices.Count; i++) @@ -145,6 +149,22 @@ public static List ProcessMeshes(GltfRoot gltf, byte[]? binaryBu unityMesh.SetTriangles(allSubmeshIndices[i], i); } + // Generate only absent attributes; preserve authored data on other primitives. + if (options.GenerateMissingNormals && missingNormals.Count > 0) + { + unityMesh.RecalculateNormals(); + var generatedNormals = unityMesh.normals; + foreach (int index in missingNormals) allNormals[index] = generatedNormals[index]; + unityMesh.normals = allNormals.ToArray(); + } + if (options.GenerateMissingTangents && missingTangents.Count > 0 && hasUvs && + (missingNormals.Count == 0 || options.GenerateMissingNormals)) + { + unityMesh.RecalculateTangents(); + var generatedTangents = unityMesh.tangents; + foreach (int index in missingTangents) allTangents[index] = generatedTangents[index]; + unityMesh.tangents = allTangents.ToArray(); + } unityMesh.RecalculateBounds(); results.Add(new GltfMeshResult diff --git a/S1MAPI.csproj b/S1MAPI.csproj index b2b9136..b4df84d 100644 --- a/S1MAPI.csproj +++ b/S1MAPI.csproj @@ -10,6 +10,7 @@ en-US True false + $(DefaultItemExcludes);Tests/** Mono;Il2cpp enable Library diff --git a/Tests/Gltf/GltfRuntimeTests.cs b/Tests/Gltf/GltfRuntimeTests.cs new file mode 100644 index 0000000..ee8a569 --- /dev/null +++ b/Tests/Gltf/GltfRuntimeTests.cs @@ -0,0 +1,192 @@ +using System.Text; +using MelonLoader; +using S1MAPI.Gltf; +using UnityEngine; + +[assembly: MelonInfo(typeof(S1MAPI.Tests.Gltf.GltfRuntimeTests), "MAPI GLB regression tests", "1.0.0", "S1MAPI")] +[assembly: MelonGame(null, null)] + +namespace S1MAPI.Tests.Gltf; + +/// Opt-in Unity runtime tests exercising the public GLB byte-array entry point. +public sealed class GltfRuntimeTests : MelonMod +{ + private bool _ran; + private readonly List _results = new(); + + /// Runs once in Menu when MAPI_GLB_TEST_RESULT names an output file. + public override void OnSceneWasInitialized(int buildIndex, string sceneName) + { + string? resultPath = Environment.GetEnvironmentVariable("MAPI_GLB_TEST_RESULT"); + if (_ran || sceneName != "Menu" || string.IsNullOrEmpty(resultPath)) return; + _ran = true; + Run("non-indexed", () => CheckMesh("{\"attributes\":{\"POSITION\":0}}", mesh => + { + Equal(mesh.GetTriangles(0).ToArray(), new[] { 2, 1, 0 }); + Require(mesh.vertices[1].x == -1, "X coordinate conversion"); + })); + foreach (int component in new[] { 5121, 5123, 5125 }) + Run($"indexed-{component}", () => CheckMesh("{\"attributes\":{\"POSITION\":0},\"indices\":1}", + mesh => Equal(mesh.GetTriangles(0).ToArray(), new[] { 2, 1, 0 }), component)); + Run("mixed-offsets", () => CheckMesh("{\"attributes\":{\"POSITION\":0},\"indices\":1},{\"attributes\":{\"POSITION\":0}}", + mesh => { Require(mesh.vertexCount == 6, "vertex count"); Equal(mesh.GetTriangles(1).ToArray(), new[] { 5, 4, 3 }); })); + Run("default-material", () => WithModel("{\"attributes\":{\"POSITION\":0}},{\"attributes\":{\"POSITION\":0}}", model => + { + var materials = model.GetComponentInChildren().sharedMaterials; + Require(materials.Length == 2 && materials[0] != null && materials[1] != null, "every default material slot assigned"); + })); + foreach (int mode in new[] { 0, 1, 2, 3, 5, 6 }) + Run($"unsupported-mode-{mode}", () => CheckMesh($"{{\"attributes\":{{\"POSITION\":0}},\"mode\":{mode}}},{{\"attributes\":{{\"POSITION\":0}}}}", + mesh => { Require(mesh.vertexCount == 3 && mesh.subMeshCount == 1, "unsupported primitive skipped before append"); Equal(mesh.GetTriangles(0).ToArray(), new[] { 2, 1, 0 }); })); + Run("mixed-attributes", () => CheckMesh("{\"attributes\":{\"POSITION\":0}},{\"attributes\":{\"POSITION\":0,\"NORMAL\":2,\"TEXCOORD_0\":3,\"TANGENT\":4}}", mesh => + { + Require(mesh.normals.Length == 6, "full normals"); + Require(mesh.uv.Length == 6 && mesh.uv[3].y == 1 && mesh.uv[4].x == 1, "UV offset and flip"); + Require(mesh.tangents.Length == 6, "full tangents"); + Require(mesh.tangents[3].z == 1 && mesh.tangents[3].w == -1, "authored tangent preserved"); + })); + Run("attributes-before-missing", () => CheckMesh("{\"attributes\":{\"POSITION\":0,\"NORMAL\":2,\"TEXCOORD_0\":3,\"TANGENT\":4}},{\"attributes\":{\"POSITION\":0}}", mesh => + { + Require(mesh.uv.Length == 6 && mesh.uv[0].y == 1 && mesh.uv[3].y == 0, "trailing UV defaults"); + Require(mesh.normals.Length == 6 && mesh.normals[0].y == 1, "authored normal preserved"); + Require(mesh.tangents.Length == 6 && mesh.tangents[0].z == 1 && mesh.tangents[0].w == -1, "authored tangent preserved"); + })); + Run("mismatched-attribute-count", () => CheckMesh("{\"attributes\":{\"POSITION\":0,\"NORMAL\":5}},{\"attributes\":{\"POSITION\":0}}", + mesh => Require(mesh.vertexCount == 3 && mesh.subMeshCount == 1, "mismatched primitive skipped atomically"))); + Run("missing-position", () => CheckMesh("{\"attributes\":{\"NORMAL\":2}},{\"attributes\":{\"POSITION\":0}}", + mesh => Require(mesh.vertexCount == 3 && mesh.subMeshCount == 1, "missing POSITION skipped atomically"))); + Run("material-order-after-skip", () => WithModel("{\"attributes\":{\"POSITION\":0},\"mode\":1,\"material\":0},{\"attributes\":{\"POSITION\":0},\"material\":1},{\"attributes\":{\"POSITION\":0}}", model => + { + var materials = model.GetComponentInChildren().sharedMaterials; + Require(materials.Length == 2 && materials[0].name == "Blue" && materials[1].name == "DefaultGltfMaterial", "material slots follow accepted primitives"); + })); + Run("missing-normals", () => CheckMesh("{\"attributes\":{\"POSITION\":0}}", mesh => + Require(mesh.normals.Length == 3 && mesh.normals[0].z > 0.99f, "generated normals and winding"))); + Run("generation-disabled", () => WithModel("{\"attributes\":{\"POSITION\":0}}", model => + Require(model.GetComponentInChildren().sharedMesh.normals.Length == 0, "normals remain absent"), generate: false)); + Run("invalid-index", () => CheckMesh("{\"attributes\":{\"POSITION\":0},\"indices\":1},{\"attributes\":{\"POSITION\":0}}", + mesh => Require(mesh.vertexCount == 3 && mesh.subMeshCount == 1, "bad primitive skipped atomically"), badIndex: true)); + Run("partial-triangle", () => CheckMesh("{\"attributes\":{\"POSITION\":0},\"indices\":1},{\"attributes\":{\"POSITION\":0}}", + mesh => Require(mesh.vertexCount == 3 && mesh.subMeshCount == 1, "partial triangle skipped"), indexCount: 2)); + Run("render-non-indexed", () => RenderTriangle(resultPath + ".png")); + File.WriteAllLines(resultPath, _results); + MelonLogger.Msg($"[MAPI.GlbTests] COMPLETE {_results.Count} cases; failures={_results.Count(x => x.StartsWith("FAIL"))}"); + } + + private void Run(string name, Action test) + { + try { test(); _results.Add($"PASS|{name}"); } + catch (Exception ex) { _results.Add($"FAIL|{name}|{ex}"); } + MelonLogger.Msg($"[MAPI.GlbTests] {_results[^1]}"); + } + + private static void Require(bool condition, string message) + { + if (!condition) throw new InvalidOperationException(message); + } + + private static void Equal(int[] actual, int[] expected) => + Require(actual.SequenceEqual(expected), $"indices: [{string.Join(",", actual)}] expected [{string.Join(",", expected)}]"); + + private static void RenderTriangle(string path) + { + WithModel("{\"attributes\":{\"POSITION\":0}}", model => + { + foreach (Transform child in model.GetComponentsInChildren()) child.gameObject.layer = 31; + var cameraObject = new GameObject("MAPI GLB test camera"); + var texture = new RenderTexture(256, 256, 24); + var pixels = new Texture2D(256, 256, TextureFormat.RGB24, false); + RenderTexture previous = RenderTexture.active; + var material = model.GetComponentInChildren().sharedMaterial; + Shader shader = Shader.Find("Universal Render Pipeline/Unlit"); + Require(shader != null, "URP Unlit shader available for render probe"); + material.shader = shader; + material.SetColor("_BaseColor", Color.red); + try + { + Camera camera = cameraObject.AddComponent(); + camera.cullingMask = 1 << 31; + camera.clearFlags = CameraClearFlags.SolidColor; + camera.backgroundColor = Color.black; + camera.orthographic = true; + camera.orthographicSize = 0.7f; + camera.transform.position = new Vector3(-0.5f, 0.5f, 3); + camera.transform.rotation = Quaternion.Euler(0, 180, 0); + camera.targetTexture = texture; + camera.Render(); + RenderTexture.active = texture; + pixels.ReadPixels(new Rect(0, 0, 256, 256), 0, 0); + pixels.Apply(); + File.WriteAllBytes(path, ImageConversion.EncodeToPNG(pixels)); + Require(pixels.GetPixels().Count(color => color.r > 0.5f && color.g < 0.1f) > 5000, "visible front-facing red triangle"); + } + finally + { + RenderTexture.active = previous; + UnityEngine.Object.Destroy(cameraObject); + UnityEngine.Object.Destroy(texture); + UnityEngine.Object.Destroy(pixels); + } + }); + } + + private static void CheckMesh(string primitives, Action assertion, int component = 5123, bool badIndex = false, int indexCount = 3) => + WithModel(primitives, model => assertion(model.GetComponentInChildren().sharedMesh), component, badIndex, indexCount); + + private static void WithModel(string primitives, Action assertion, int component = 5123, bool badIndex = false, int indexCount = 3, bool generate = true) + { + byte[] bytes = CreateGlb(primitives, component, badIndex, indexCount); + GameObject? model = generate ? GltfLoader.LoadGlb(bytes) : new GltfImporter().GenerateNormals(false).GenerateTangents(false).LoadGlb(bytes); + Require(model != null, "loader returned null"); + try { assertion(model!); } + finally + { + if (model != null) + { + foreach (MeshFilter filter in model.GetComponentsInChildren()) UnityEngine.Object.Destroy(filter.sharedMesh); + foreach (MeshRenderer renderer in model.GetComponentsInChildren()) + foreach (Material material in renderer.sharedMaterials) if (material != null) UnityEngine.Object.Destroy(material); + UnityEngine.Object.Destroy(model); + } + } + } + + // Synthetic, self-contained data. No game or third-party model assets are needed. + private static byte[] CreateGlb(string primitives, int component, bool badIndex, int indexCount) + { + using var bin = new MemoryStream(); + using var writer = new BinaryWriter(bin); + foreach (float f in new float[] { 0, 0, 0, 1, 0, 0, 0, 1, 0 }) writer.Write(f); + foreach (uint i in new uint[] { 0, 1, badIndex ? 3u : 2u }) + { + if (component == 5121) writer.Write((byte)i); + else if (component == 5123) writer.Write((ushort)i); + else writer.Write(i); + } + int indexBytes = (int)bin.Length - 36; + while (bin.Length % 4 != 0) writer.Write((byte)0); + int normalOffset = (int)bin.Length; + for (int i = 0; i < 3; i++) { writer.Write(0f); writer.Write(1f); writer.Write(0f); } + int uvOffset = (int)bin.Length; + foreach (float f in new float[] { 0, 0, 1, 0, 0, 1 }) writer.Write(f); + int tangentOffset = (int)bin.Length; + for (int i = 0; i < 3; i++) { writer.Write(0f); writer.Write(0f); writer.Write(1f); writer.Write(-1f); } + string json = "{\"asset\":{\"version\":\"2.0\"},\"scene\":0,\"scenes\":[{\"nodes\":[0]}],\"nodes\":[{\"mesh\":0}]," + + $"\"buffers\":[{{\"byteLength\":{bin.Length}}}],\"bufferViews\":[" + + $"{{\"buffer\":0,\"byteOffset\":0,\"byteLength\":36}},{{\"buffer\":0,\"byteOffset\":36,\"byteLength\":{indexBytes}}}," + + $"{{\"buffer\":0,\"byteOffset\":{normalOffset},\"byteLength\":36}},{{\"buffer\":0,\"byteOffset\":{uvOffset},\"byteLength\":24}},{{\"buffer\":0,\"byteOffset\":{tangentOffset},\"byteLength\":48}}]," + + "\"accessors\":[{\"bufferView\":0,\"componentType\":5126,\"count\":3,\"type\":\"VEC3\",\"min\":[0,0,0],\"max\":[1,1,0]}," + + $"{{\"bufferView\":1,\"componentType\":{component},\"count\":{indexCount},\"type\":\"SCALAR\"}}," + + "{\"bufferView\":2,\"componentType\":5126,\"count\":3,\"type\":\"VEC3\"},{\"bufferView\":3,\"componentType\":5126,\"count\":3,\"type\":\"VEC2\"},{\"bufferView\":4,\"componentType\":5126,\"count\":3,\"type\":\"VEC4\"},{\"bufferView\":2,\"componentType\":5126,\"count\":2,\"type\":\"VEC3\"}]," + + "\"materials\":[{\"name\":\"Red\",\"pbrMetallicRoughness\":{\"baseColorFactor\":[1,0,0,1]}},{\"name\":\"Blue\",\"pbrMetallicRoughness\":{\"baseColorFactor\":[0,0,1,1]}}]," + + $"\"meshes\":[{{\"primitives\":[{primitives}]}}]}}"; + while (Encoding.UTF8.GetByteCount(json) % 4 != 0) json += " "; + byte[] jsonBytes = Encoding.UTF8.GetBytes(json); + using var glb = new MemoryStream(); + using var output = new BinaryWriter(glb); + output.Write(0x46546C67u); output.Write(2u); output.Write((uint)(28 + jsonBytes.Length + bin.Length)); + output.Write(jsonBytes.Length); output.Write(0x4E4F534Au); output.Write(jsonBytes); + output.Write((int)bin.Length); output.Write(0x004E4942u); output.Write(bin.ToArray()); + return glb.ToArray(); + } +} diff --git a/Tests/Gltf/README.md b/Tests/Gltf/README.md new file mode 100644 index 0000000..549bbc8 --- /dev/null +++ b/Tests/Gltf/README.md @@ -0,0 +1,72 @@ +# GLB runtime regression tests + +These are opt-in MelonLoader tests, not a `dotnet test` suite. They exercise +`GltfLoader.LoadGlb(byte[], Shader?)` inside real Unity, including native Mesh +assignment and material creation. All GLBs are generated from synthetic data in +`GltfRuntimeTests.cs`; no game assets or sample models are distributed. + +## Build + +Configure the repository's ignored `local.build.props` with your Mono and IL2CPP +assembly paths. Build serially because the parent project changes target framework +by configuration. Clear `UserLibsPath` on the command line to prevent automatic +deployment into your normal game install: + +```powershell +dotnet build Tests/Gltf/S1MAPI.Gltf.RuntimeTests.csproj -c Mono -p:UserLibsPath= -p:GeneratePackageOnBuild=false +dotnet build Tests/Gltf/S1MAPI.Gltf.RuntimeTests.csproj -c Il2cpp -p:UserLibsPath= -p:GeneratePackageOnBuild=false +``` + +The Mono test targets netstandard2.1 and references MelonLoader's `net35` assembly +beside the configured `net6` directory. Override `LoaderAssemblies` if your +installation uses another compatible loader layout. IL2CPP tests target net6.0. +The test project does not package or deploy its output. + +## Run each backend separately + +Use a disposable, isolated game install with MelonLoader already set up for the +matching backend. Leave your usual Mods, UserLibs, game configuration, and saves +untouched. The test only needs the Menu scene; do not load a save. + +1. Copy `Tests/Gltf/bin///S1MAPI.Gltf.RuntimeTests.dll` + into the isolated install's `Mods` directory. +2. Copy the matching `S1MAPI_Mono.dll` or `S1MAPI_Il2cpp.dll` from that same build + directory into its `UserLibs`. Do not copy Unity reference DLLs from build + output into either directory. Keep unrelated mods out of the test install. +3. Set `MAPI_GLB_TEST_RESULT` to a new absolute output filename whose parent exists + and launch that install from the same shell. For example: + + ```powershell + $env:MAPI_GLB_TEST_RESULT = 'D:\MAPI-test-results\mono-run-001.txt' + $game = Start-Process 'D:\Isolated-MAPI-Mono\Schedule I.exe' -WorkingDirectory 'D:\Isolated-MAPI-Mono' -WindowStyle Hidden -PassThru + ``` + +4. Require `COMPLETE 22 cases; failures=0` in `MelonLoader/Latest.log` and 22 + `PASS|...` lines in the result file. A loaded mod or a running game alone is not + a pass. Stop on `FAIL|...`, loader failure, process exit, or a bounded startup + timeout (100 seconds is enough on the development machine). Record the last + scene/log marker when startup fails. +5. Open `.png`. The render probe must show a red triangle on black + and also checks a minimum red-pixel count. This validates visibility and + front-face winding with a URP Unlit shader, not lit/PBR/texture fidelity. +6. Stop only the process you launched. Copy any evidence needed for review, then + remove the test DLL, test library, isolated install and disposable outputs. + Clear the shell variable with `Remove-Item Env:\MAPI_GLB_TEST_RESULT`. + +Repeat with IL2CPP and a different result filename. Report each runtime separately. +The result does not validate loaded-save gameplay, game-specific integration, +networking, texture import, animation, skinning, or arbitrary GLBs. + +## Covered behavior + +- Non-indexed triangles, X reflection, reversed winding, and offsets after an indexed primitive. +- Indexed triangles with unsigned byte, unsigned short, and unsigned int indices. +- Default materials and material order after a skipped primitive. +- Rejection of all six non-triangle primitive modes before appending geometry. +- Missing normals, disabled generation, mixed optional attributes in both orders, + authored attribute preservation, UV flipping and zero-filled missing UVs. +- Missing POSITION, mismatched attribute counts, out-of-range indices, and incomplete triangle lists. +- Rendering a synthetic non-indexed triangle through Unity. + +Unsupported features and broader validation limits are listed in the +[GLTF loading guide](../../docs/gltf-loading.md#static-glb-compatibility-profile). diff --git a/Tests/Gltf/S1MAPI.Gltf.RuntimeTests.csproj b/Tests/Gltf/S1MAPI.Gltf.RuntimeTests.csproj new file mode 100644 index 0000000..c02c922 --- /dev/null +++ b/Tests/Gltf/S1MAPI.Gltf.RuntimeTests.csproj @@ -0,0 +1,26 @@ + + + + netstandard2.1 + net6.0 + latest + enable + enable + Mono;Il2cpp + IL2CPP + $(MonoAssembliesPath) + $(Il2CppAssembliesPath) + $(MelonLoaderAssembliesPath)/../net35 + $(Il2CppMLAssembliesPath) + + + + + + + + + + + + diff --git a/docs/gltf-loading.md b/docs/gltf-loading.md index 476cf60..19880fc 100644 --- a/docs/gltf-loading.md +++ b/docs/gltf-loading.md @@ -4,12 +4,14 @@ Learn how to import external 3D models at runtime using S1MAPI's GLTF loader. ## Overview -S1MAPI includes a native GLTF/GLB loader with no external dependencies. It handles: -- GLB (binary GLTF) files -- JSON-based GLTF files -- External resources ( textures, buffers) -- Coordinate system conversion (GLTF right-handed → Unity left-handed) -- Material creation and texture mapping +S1MAPI includes a runtime GLTF/GLB importer using Newtonsoft.Json and Unity. +For static 3D models, use self-contained GLB 2.0 bytes +with uncompressed triangle geometry. `GltfLoader.LoadGlb(byte[], Shader?)` remains +the public entry point; call it on Unity's main thread after shaders are available. + +This is a limited importer, not a full glTF implementation. Use the compatibility +profile below when an editor validates exports for MAPI. A successful preview in +another glTF viewer does not prove that every feature will import here. ## Loading GLB Files @@ -54,7 +56,9 @@ GameObject? model = GltfLoader.LoadFromFile("path/to/model.glb", myShader); ## Loading GLTF JSON -GLTF JSON files can reference external binary buffers and textures: +GLTF JSON can resolve external binary buffers relative to `basePath`. External +image files are not loaded by the active importer; embed images in buffer views +or base64 data URIs: ```csharp string gltfJson = File.ReadAllText("path/to/model.gltf"); @@ -136,11 +140,11 @@ GameObject? model = new GltfImporter() GLTF uses a right-handed coordinate system, while Unity uses left-handed. S1MAPI automatically handles the conversion by: -1. Inverting the Z axis -2. Converting the rotation matrix -3. Properly orienting the mesh data +1. Reflecting X in positions, normals, tangents, and node translations +2. Converting node rotation to `(x, -y, -z, w)` +3. Reversing triangle winding and flipping texture V -This means models appear correctly oriented without manual transformation. +Check the intended orientation and texture mapping in the target game shader. ## Example: Neon Sign @@ -192,7 +196,8 @@ public static class SignLoader 3. **Emission intensity**: Higher values create brighter glow effects but check visual quality. -4. **Resource cleanup**: GLTF imports create meshes, materials, and textures. Unity handles cleanup automatically when GameObjects are destroyed. +4. **Resource cleanup**: GLTF imports create meshes, materials, and textures. Destroy runtime meshes, materials, and textures when no longer shared or needed; + destroying the root GameObject alone does not release those assets. 5. **Packed material maps**: Metallic-roughness conversion creates a Unity-compatible runtime texture per material. Cache imported models instead of repeatedly loading the same asset. @@ -204,23 +209,62 @@ public static class SignLoader ### Model Orientation is Wrong - S1MAPI should handle conversion automatically -- If still wrong, try flipping the Z scale: `model.transform.localScale = new Vector3(1, 1, -1)` +- Check the exporter's transforms and apply/bake mirrored transforms before export ### Model is Too Large/Small - Adjust `localScale` to match your scene - Common GLTF scale factors: 0.01, 0.1, 1.0, 100 (depends on source) ### Missing Textures (GLTF JSON) -- Ensure `basePath` points to the correct directory -- Check that texture files exist and are readable - -## Supported GLTF Features - -- **Meshes**: Positions, normals, UVs, tangents, colors -- **Materials**: PBR metallic-roughness, unlit, emission -- **Textures**: PNG, JPEG formats -- **Nodes**: Hierarchy and transforms -- **Animations**: Not currently supported (contact if needed) +- External image files are not loaded by the active path +- Embed PNG/JPEG images in buffer views or base64 data URIs + +## Static GLB Compatibility Profile + +| Feature | Current behavior / editor rule | +|---|---| +| Geometry | `TRIANGLES` (`mode: 4`, including omitted mode), indexed or non-indexed. Non-indexed triangles use consecutive vertex triples. Each accepted primitive becomes one submesh with its material slot preserved. | +| Other modes | Points, lines, line loops/strips, triangle strips/fans are skipped with a warning. Triangulate before export. | +| Indices | Unsigned byte, unsigned short, unsigned int. Empty/incomplete triangle lists and indices outside the primitive's vertex range are skipped before appending vertices. | +| Vertex accessors | Export dense float32 `POSITION`/`NORMAL` (`VEC3`), `TEXCOORD_0` (`VEC2`), and `TANGENT` (`VEC4`). Existing readers honor byte offsets and byte stride for these attributes. Attribute counts must match positions. Missing POSITION or mismatched decoded attribute counts skip that primitive. | +| Optional attributes | Missing UVs use `(0,0)` when another primitive has UVs. Missing normals/tangents are generated by default through Unity, preserving authored values on other primitives. Tangent generation requires UVs somewhere in the mesh and complete/generated normals. Export authored normals/UVs/tangents for controlled shading; generated normals follow shared vertices, and absent UVs cannot yield meaningful normal mapping. | +| Generation switches | `new GltfImporter().GenerateNormals(false).GenerateTangents(false)` disables generation. Entirely absent attributes stay absent; holes in a mixed attribute stream are zero-filled. | +| Materials | Material slots, fallback materials, base color, metallic/roughness conversion, normal/occlusion maps, alpha settings and emission have implementation paths. Shader-specific rendering is not glTF material fidelity. `KHR_materials_emissive_strength` is handled; unlit/material extensions in general are not. | +| Images | Embedded PNG/JPEG in buffer views or base64 data URIs. External image paths and KTX2/Basis textures are unsupported. Texture-coordinate set selection and `KHR_texture_transform` are not applied; use `TEXCOORD_0` with baked transforms. | +| Hierarchy | Nodes and their TRS are imported, including shared meshes. The active path imports all nodes, not only the selected scene. Export one intended scene with no unused nodes. Bake mirrored matrix transforms; negative-scale matrix decomposition is not verified. | + +### Reject or warn before importing + +An editor targeting this importer should reject sparse accessors, normalized integer +vertex attributes, Draco/meshopt compression, quantization, and geometry referencing +buffers other than buffer 0. The mesh reader still consumes the first resolved +buffer and does not decode these features. They are not reliably rejected at +runtime and can silently produce incorrect geometry. A self-contained GLB can +still contain unsupported features; the file extension alone is insufficient. + +Warn for `COLOR_0`, additional UV sets, skins, morph targets, animations, and +unrecognized required extensions. Vertex colors/additional UVs are ignored. +The active node path creates `MeshRenderer` components, not skinned renderers or +blend shapes. Animation parsing exists but is outside this static compatibility +profile and has not been validated by these tests. `ImportSkins`, +`ImportBlendShapes`, and `ReadableMeshes` options are not wired into this loading +path; imported meshes currently remain CPU-readable. + +Validate GLB structure and accessor bounds before loading. Some malformed inputs +return null or skip a primitive, but other malformed accessor/buffer references +can still throw. A non-null root can contain partial or empty geometry. Inspect +warnings and renderer/mesh counts; this API does not return a structured validation +report. Keep the [Khronos glTF 2.0 specification](https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html) +and MAPI's narrower profile as separate validation checks. + +### Regression coverage + +[Runtime regression instructions](../Tests/Gltf/README.md) cover synthetic GLBs +through the public loader in real Unity Mono and IL2CPP processes. They check +index widths, non-indexed winding/offsets, missing and mixed attributes, material +slots, mode rejection, malformed index lists, and an unlit triangle render. +They do not certify arbitrary exporter output, texture/PBR fidelity, gameplay +placement, networking, animations, or full glTF compliance. ## Next Steps