diff --git a/Obj2Gltf/Ktx2/Ktx2Encoder.cs b/Obj2Gltf/Ktx2/Ktx2Encoder.cs index 621c82d..97ab710 100644 --- a/Obj2Gltf/Ktx2/Ktx2Encoder.cs +++ b/Obj2Gltf/Ktx2/Ktx2Encoder.cs @@ -228,6 +228,7 @@ public static void Encode(string inputImagePath, string outputKtx2Path, bool srg try { using var image = Image.Load(inputImagePath); + AlignToBlocks(image); var width = image.Width; var height = image.Height; var hasAlpha = HasAlpha(image); @@ -350,6 +351,34 @@ public static void Encode(string inputImagePath, string outputKtx2Path, bool srg } } + /// + /// The size nearest to that is a whole number of 4x4 blocks (at least one). + /// + private static int BlockAlignedSize(int size) => Math.Max(BlockSize, (size + BlockSize / 2) / BlockSize * BlockSize); + + private const int BlockSize = 4; + + // KHR_texture_basisu requires the width and height of a KTX2 image to be multiples of 4: the GPU formats + // Basis Universal transcodes to (BC1-7, ETC, ASTC) are made of 4x4 blocks, and WebGL refuses a BC (S3TC) + // texture whose size is not a multiple of 4 (INVALID_OPERATION), so viewers show it black. An image of + // another size is stretched to the nearest aligned size: the texture coordinates are fractions of the + // image, so they still address the same texels (padding would move them). Every mip level of an aligned + // image is then valid too, as WebGL checks the level's size shifted back to level 0. + private static void AlignToBlocks(Image image) + { + var width = BlockAlignedSize(image.Width); + var height = BlockAlignedSize(image.Height); + if (width == image.Width && height == image.Height) + return; + + image.Mutate(ctx => ctx.Resize(new ResizeOptions + { + Size = new Size(width, height), + Sampler = KnownResamplers.Lanczos3, + Mode = ResizeMode.Stretch + })); + } + // Encode one tiny texture to force libktx's lazy, non-thread-safe Basis encoder init to run // once on this (serialized) code path before any concurrent encoding begins. private static void WarmUp(GltfConverterOptions options) diff --git a/Obj2Tiles.Library.Test/ModelPartsLoadingTests.cs b/Obj2Tiles.Library.Test/ModelPartsLoadingTests.cs new file mode 100644 index 0000000..dd7a902 --- /dev/null +++ b/Obj2Tiles.Library.Test/ModelPartsLoadingTests.cs @@ -0,0 +1,178 @@ +using System; +using System.IO; +using System.Linq; +using NUnit.Framework; +using Obj2Tiles.Library.Geometry; +using Obj2Tiles.Library.Materials; +using Shouldly; +using SixLabors.ImageSharp; +using SixLabors.ImageSharp.PixelFormats; +using Path = System.IO.Path; + +namespace Obj2Tiles.Library.Test; + +/// +/// MeshUtils.LoadMesh (the reader of the split stage, so of the finest level) on models whose parts differ: +/// parts with and without texture coordinates, material names with spaces, faces before the first usemtl, +/// vertex colours on some objects only. Every face must reach the mesh with the material it was written with. +/// +public class ModelPartsLoadingTests +{ + private const string TestOutputPath = "TestOutput"; + + private static string Folder(string testName) + { + var folder = Path.Combine(TestOutputPath, nameof(ModelPartsLoadingTests), testName); + if (Directory.Exists(folder)) + Directory.Delete(folder, true); + Directory.CreateDirectory(folder); + return folder; + } + + // Writes model.obj (and model.mtl and a 16x16 tex.png when mtl is given) and returns the OBJ path. + private static string Write(string testName, string obj, string? mtl = null) + { + var folder = Folder(testName); + File.WriteAllText(Path.Combine(folder, "model.obj"), obj); + + if (mtl != null) + { + File.WriteAllText(Path.Combine(folder, "model.mtl"), mtl); + using var texture = new Image(16, 16, new Rgba32(200, 30, 30, 255)); + texture.SaveAsPng(Path.Combine(folder, "tex.png")); + } + + return Path.Combine(folder, "model.obj"); + } + + // Two unit squares (two triangles each): the first textured with "textured", the second without + // texture coordinates, with the material given. No texture coordinate of the textured square is (0, 0), + // the one given to the faces without, so that theirs cannot be mistaken for one of the textured square. + private static string TexturedAndPlain(string plainMaterialStatement) => + "mtllib model.mtl\n" + + "v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\n" + + "vt 0.1 0.1\nvt 0.9 0.1\nvt 0.9 0.9\nvt 0.1 0.9\n" + + "v 5 0 0\nv 6 0 0\nv 6 1 0\nv 5 1 0\n" + + "usemtl textured\nf 1/1 2/2 3/3\nf 1/1 3/3 4/4\n" + + plainMaterialStatement + + "f 5 6 7\nf 5 7 8\n"; + + private const string TexturedAndPlainMtl = + "newmtl textured\nKd 1 1 1\nmap_Kd tex.png\n\nnewmtl Paint 1 Carmine\nKd 0.6 0.05 0.1\n"; + + private static string[] MaterialOfEachFace(MeshT mesh) => + mesh.Faces.Select(f => mesh.Materials[f.MaterialIndex].Name).ToArray(); + + [Test] + public void LoadMesh_FacesWithoutTextureCoordinates_InATexturedModel_AreKeptWithTheirMaterial() + { + var path = Write(nameof(LoadMesh_FacesWithoutTextureCoordinates_InATexturedModel_AreKeptWithTheirMaterial), + TexturedAndPlain("usemtl Paint 1 Carmine\n"), TexturedAndPlainMtl); + + var mesh = MeshUtils.LoadMesh(path).ShouldBeOfType(); + + mesh.FacesCount.ShouldBe(4); + MaterialOfEachFace(mesh).ShouldBe(new[] { "textured", "textured", "Paint 1 Carmine", "Paint 1 Carmine" }, + ignoreOrder: true); + mesh.Faces.ShouldAllBe(f => f.TextureIndexA < mesh.TextureVertices.Count && + f.TextureIndexB < mesh.TextureVertices.Count && + f.TextureIndexC < mesh.TextureVertices.Count); + } + + [Test] + public void LoadMesh_MaterialNameWithSpaces_IsOneName() + { + var path = Write(nameof(LoadMesh_MaterialNameWithSpaces_IsOneName), + "mtllib model.mtl\n" + + "v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 1 1\nvt 0 1\n" + + "usemtl textured\nf 1/1 2/2 3/3\nusemtl Paint 1 Carmine \nf 1/1 3/3 4/4\n", + TexturedAndPlainMtl); + + var mesh = MeshUtils.LoadMesh(path).ShouldBeOfType(); + + MaterialOfEachFace(mesh).ShouldBe(new[] { "textured", "Paint 1 Carmine" }); + } + + private const string TwoSquares = + "mtllib model.mtl\n" + + "v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\n" + + "vt 0 0\nvt 1 0\nvt 1 1\nvt 0 1\n" + + "v 5 0 0\nv 6 0 0\nv 6 1 0\nv 5 1 0\n"; + + [TestCase("f 1/1 2/2 3/3\nf 1/1 3/3 4/4\n", TestName = "LoadMesh_TexturedFacesBeforeTheFirstUsemtl_GetTheDefaultMaterial")] + [TestCase("f 1 2 3\nf 1 3 4\n", TestName = "LoadMesh_UntexturedFacesBeforeTheFirstUsemtl_GetTheDefaultMaterial")] + public void LoadMesh_FacesBeforeTheFirstUsemtl_GetTheDefaultMaterial(string facesWithoutMaterial) + { + var path = Write(TestContext.CurrentContext.Test.Name, + TwoSquares + facesWithoutMaterial + "usemtl textured\nf 5/1 6/2 7/3\nf 5/1 7/3 8/4\n", + TexturedAndPlainMtl); + + var mesh = MeshUtils.LoadMesh(path).ShouldBeOfType(); + + MaterialOfEachFace(mesh).ShouldBe(new[] + { MeshUtils.DefaultMaterialName, MeshUtils.DefaultMaterialName, "textured", "textured" }, + ignoreOrder: true); + mesh.Materials.Single(m => m.Name == MeshUtils.DefaultMaterialName).Texture.ShouldBeNull(); + } + + [Test] + public void LoadMesh_TextureCoordinatesWithoutMaterials_IsAnUntexturedMeshWithEveryFace() + { + // As Blender writes objects without material when only the last one has UVs. + var path = Write(nameof(LoadMesh_TextureCoordinatesWithoutMaterials_IsAnUntexturedMeshWithEveryFace), + "v 0 0 0\nv 1 0 0\nv 1 1 0\nf 1 2 3\n" + + "v 5 0 0\nv 6 0 0\nv 6 1 0\nvt 0 0\nvt 1 0\nvt 1 1\nf 4/1 5/2 6/3\n"); + + var mesh = MeshUtils.LoadMesh(path).ShouldBeOfType(); + + mesh.FacesCount.ShouldBe(2); + mesh.Faces.ShouldAllBe(f => f.GetType() == typeof(Face)); + } + + [Test] + public void LoadMesh_SomeVerticesWithoutColours_AreWhite() + { + var path = Write(nameof(LoadMesh_SomeVerticesWithoutColours_AreWhite), + "v 0 0 0\nv 1 0 0\nv 1 1 0\n" + + "v 5 0 0 1 0 0\nv 6 0 0 0 1 0\nv 6 1 0 0 0 1\n" + + "v 9 0 0\n" + + "f 1 2 3\nf 4 5 6\nf 4 6 7\n"); + + var mesh = MeshUtils.LoadMesh(path).ShouldBeOfType(); + + mesh.VertexColors.ShouldNotBeNull(); + mesh.VertexColors!.Select(c => (c.R, c.G, c.B)).ShouldBe(new[] + { + (1d, 1d, 1d), (1d, 1d, 1d), (1d, 1d, 1d), + (1d, 0d, 0d), (0d, 1d, 0d), (0d, 0d, 1d), + (1d, 1d, 1d) + }); + } + + [TestCase(TexturesStrategy.Repack)] + [TestCase(TexturesStrategy.RepackCompressed)] + [TestCase(TexturesStrategy.KeepOriginal)] + public void WriteObj_TexturedModelWithAnUntexturedPart_KeepsEveryFaceAndValidTextureCoordinates( + TexturesStrategy strategy) + { + var testName = nameof(WriteObj_TexturedModelWithAnUntexturedPart_KeepsEveryFaceAndValidTextureCoordinates) + + strategy; + var path = Write(testName, TexturedAndPlain("usemtl Paint 1 Carmine\n"), TexturedAndPlainMtl); + var mesh = MeshUtils.LoadMesh(path).ShouldBeOfType(); + mesh.TexturesStrategy = strategy; + + var output = Path.Combine(Path.GetDirectoryName(path)!, "out", "Mesh.obj"); + Directory.CreateDirectory(Path.GetDirectoryName(output)!); + mesh.WriteObj(output); + + var written = File.ReadAllLines(output); + var textureVertices = written.Count(l => l.StartsWith("vt ")); + foreach (var face in written.Where(l => l.StartsWith("f "))) + foreach (var corner in face.Split(' ').Skip(1)) + int.Parse(corner.Split('/')[1]).ShouldBeInRange(1, textureVertices, face); + + var reloaded = MeshUtils.LoadMesh(output).ShouldBeOfType(); + MaterialOfEachFace(reloaded).ShouldBe(new[] { "textured", "textured", "Paint 1 Carmine", "Paint 1 Carmine" }, + ignoreOrder: true); + } +} diff --git a/Obj2Tiles.Library.Test/ObjParsingTests.cs b/Obj2Tiles.Library.Test/ObjParsingTests.cs index c354cb7..44dcf8c 100644 --- a/Obj2Tiles.Library.Test/ObjParsingTests.cs +++ b/Obj2Tiles.Library.Test/ObjParsingTests.cs @@ -258,7 +258,8 @@ public void LoadMesh_LeadingWhitespaceOnAllKeywords_ParsesCorrectly() var mesh = MeshUtils.LoadMesh(obj); - mesh.ShouldBeOfType(); + // No material, so no texture: the texture coordinates are not kept. + mesh.ShouldBeOfType(); // Without TrimStart, the second face (leading tabs) would be silently skipped. // With the fix, both faces are parsed. mesh.FacesCount.ShouldBe(2); diff --git a/Obj2Tiles.Library.Test/ObjStatementTests.cs b/Obj2Tiles.Library.Test/ObjStatementTests.cs new file mode 100644 index 0000000..84e6f40 --- /dev/null +++ b/Obj2Tiles.Library.Test/ObjStatementTests.cs @@ -0,0 +1,44 @@ +using System.IO; +using NUnit.Framework; +using Obj2Tiles.Library.Materials; +using Shouldly; + +namespace Obj2Tiles.Library.Test; + +/// +/// The keyword and argument of OBJ and MTL statements: names (usemtl, newmtl, mtllib) run to the end of the line. +/// +public class ObjStatementTests +{ + [TestCase("usemtl Paint 1 Carmine", "usemtl", "Paint 1 Carmine")] + [TestCase(" usemtl Paint 1 Carmine ", "usemtl", "Paint 1 Carmine")] + [TestCase("newmtl\tBand Carbon Fiber\r", "newmtl", "Band Carbon Fiber")] + [TestCase("usemtl", "usemtl", "")] + [TestCase("mtllib my model.mtl", "mtllib", "my model.mtl")] + public void Split_TheArgumentIsTheRestOfTheLine(string line, string keyword, string argument) + { + ObjStatement.Split(line).ShouldBe((keyword, argument)); + ObjStatement.Argument(line).ShouldBe(argument); + } + + [Test] + public void ReadMtl_MaterialNamesWithSpacesOrAfterATab_AreWholeNames() + { + var path = Path.Combine(Path.GetTempPath(), "obj2tiles-names-" + Path.GetRandomFileName() + ".mtl"); + try + { + File.WriteAllText(path, "newmtl Paint 1 Carmine\nKd 1 0 0\n\nnewmtl\tBezel Frame\nKd 0 1 0\n"); + + var materials = Material.ReadMtl(path, out _); + + materials.Length.ShouldBe(2); + materials[0].Name.ShouldBe("Paint 1 Carmine"); + materials[1].Name.ShouldBe("Bezel Frame"); + materials[1].DiffuseColor!.G.ShouldBe(1); + } + finally + { + File.Delete(path); + } + } +} diff --git a/Obj2Tiles.Library/Extenders.cs b/Obj2Tiles.Library/Extenders.cs index 7d2861b..5ef4424 100644 --- a/Obj2Tiles.Library/Extenders.cs +++ b/Obj2Tiles.Library/Extenders.cs @@ -20,4 +20,15 @@ public static int AddIndex(this IDictionary dictionary, T item) return dictionary.Count - 1; } -} \ No newline at end of file + + /// + /// Appends to until it has items: + /// a per-vertex attribute that only some vertices of a model give (a colour, a normal, a texture coordinate) + /// is given this default for the others, so the attribute of a vertex stays at the index of the vertex. + /// + public static void PadTo(this List list, int count, T value) + { + while (list.Count < count) + list.Add(value); + } +} diff --git a/Obj2Tiles.Library/Geometry/MeshT.cs b/Obj2Tiles.Library/Geometry/MeshT.cs index c563c15..0420343 100644 --- a/Obj2Tiles.Library/Geometry/MeshT.cs +++ b/Obj2Tiles.Library/Geometry/MeshT.cs @@ -522,6 +522,14 @@ private void TrimTextures(string targetFolder) if (facesIndexes.Count == 0) continue; + // A material without texture has no atlas: its faces keep their texture coordinates, which must + // move to the new list as the coordinates of the packed faces do. + if (material.Texture == null && material.NormalMap == null) + { + KeepTextureVertices(facesIndexes, newTextureVertices); + continue; + } + var edgesMapper = GetEdgesMapper(facesIndexes, canonicalIndex); var facesMapper = GetFacesMapper(edgesMapper); var clusters = GetFacesClusters(facesIndexes, facesMapper); @@ -547,6 +555,17 @@ private void TrimTextures(string targetFolder) } } + private void KeepTextureVertices(IEnumerable facesIndexes, IDictionary newTextureVertices) + { + foreach (var faceIndex in facesIndexes) + { + var face = _faces[faceIndex]; + face.TextureIndexA = newTextureVertices.AddIndex(_textureVertices[face.TextureIndexA]); + face.TextureIndexB = newTextureVertices.AddIndex(_textureVertices[face.TextureIndexB]); + face.TextureIndexC = newTextureVertices.AddIndex(_textureVertices[face.TextureIndexC]); + } + } + // Exporters (Blender in particular) commonly emit a separate position vertex per // unique (position, normal, uv) corner, so the SAME 3D point can appear under many // different vertex indices. Canonicalizing by value once - now that Vertex3.Equals diff --git a/Obj2Tiles.Library/Geometry/MeshUtils.cs b/Obj2Tiles.Library/Geometry/MeshUtils.cs index 6281052..60777a0 100644 --- a/Obj2Tiles.Library/Geometry/MeshUtils.cs +++ b/Obj2Tiles.Library/Geometry/MeshUtils.cs @@ -21,9 +21,11 @@ public static IMesh LoadMesh(string fileName, out string[] dependencies, bool ig var textureVertices = new List(); var facesT = new List(); var faces = new List(); + // The material of each face of faces (a face without texture coordinates keeps it in a textured model). + var faceMaterials = new List(); var materials = new List(); var materialsDict = new Dictionary(); - var currentMaterial = string.Empty; + var currentMaterial = NoMaterial; var deps = new List(); while (true) @@ -47,6 +49,8 @@ public static IMesh LoadMesh(string fileName, out string[] dependencies, bool ig if (segs.Length >= 7) { + // A vertex without a colour in a model with vertex colours is white, as in the decimation. + vertexColors.PadTo(vertices.Count - 1, White); vertexColors.Add(new RGB( double.Parse(segs[4], CultureInfo.InvariantCulture), double.Parse(segs[5], CultureInfo.InvariantCulture), @@ -78,12 +82,12 @@ public static IMesh LoadMesh(string fileName, out string[] dependencies, bool ig case "vn" when segs.Length >= 4: // Skipping normals (recognized but not used) break; - case "usemtl" when segs.Length == 2: + case "usemtl" when segs.Length >= 2: { - if (!materialsDict.ContainsKey(segs[1])) - throw new Exception($"Material {segs[1]} not found"); + var materialName = ObjStatement.Argument(line); + if (!materialsDict.TryGetValue(materialName, out currentMaterial)) + throw new Exception($"Material {materialName} not found"); - currentMaterial = segs[1]; break; } case "f" when segs.Length == 4: @@ -108,12 +112,6 @@ public static IMesh LoadMesh(string fileName, out string[] dependencies, bool ig var vt2 = int.Parse(second[1]); var vt3 = int.Parse(third[1]); - var materialIndex = 0; - if (currentMaterial != string.Empty) - { - materialIndex = materialsDict[currentMaterial]; - } - var faceT = new FaceT( v1 - 1, v2 - 1, @@ -121,7 +119,7 @@ public static IMesh LoadMesh(string fileName, out string[] dependencies, bool ig vt1 - 1, vt2 - 1, vt3 - 1, - materialIndex); + currentMaterial); facesT.Add(faceT); } @@ -133,6 +131,7 @@ public static IMesh LoadMesh(string fileName, out string[] dependencies, bool ig v3 - 1); faces.Add(face); + faceMaterials.Add(currentMaterial); } break; @@ -174,15 +173,12 @@ public static IMesh LoadMesh(string fileName, out string[] dependencies, bool ig var ft1 = int.Parse(faceVerts[fi][1]) - 1; var ft2 = int.Parse(faceVerts[fi + 1][1]) - 1; - var materialIndex = 0; - if (currentMaterial != string.Empty) - materialIndex = materialsDict[currentMaterial]; - - facesT.Add(new FaceT(fv0, fv1, fv2, ft0, ft1, ft2, materialIndex)); + facesT.Add(new FaceT(fv0, fv1, fv2, ft0, ft1, ft2, currentMaterial)); } else { faces.Add(new Face(fv0, fv1, fv2)); + faceMaterials.Add(currentMaterial); } } @@ -190,7 +186,7 @@ public static IMesh LoadMesh(string fileName, out string[] dependencies, bool ig } case "mtllib" when segs.Length >= 2: { - var mtlFileName = string.Join(" ", segs, 1, segs.Length - 1); + var mtlFileName = ObjStatement.Argument(line); var mtlFilePath = Path.Combine(Path.GetDirectoryName(fileName) ?? string.Empty, mtlFileName); var mats = Material.ReadMtl(mtlFilePath, out var mtlDeps, fileName, ignoreNormalMaps); @@ -218,19 +214,61 @@ public static IMesh LoadMesh(string fileName, out string[] dependencies, bool ig dependencies = deps.ToArray(); - if (vertexColors.Count > 0 && vertexColors.Count != vertices.Count) - throw new InvalidDataException( - $"Vertex color count ({vertexColors.Count}) does not match vertex count ({vertices.Count}). " + - "All vertices must have colors or none."); + if (vertexColors.Count > 0) + vertexColors.PadTo(vertices.Count, White); var colors = vertexColors.Count > 0 ? vertexColors : null; // The colour textures of a model are brought to 8 bits together (see TexturesCache.AddModel). TexturesCache.AddModel(materials.Select(m => m.Texture).OfType()); - return textureVertices.Count != 0 - ? new MeshT(vertices, textureVertices, facesT, materials, colors) - : new Mesh(vertices, faces, colors); + // Texture coordinates without a material have no texture to map: the model is untextured. + if (textureVertices.Count == 0 || materials.Count == 0) + return new Mesh(vertices, faces.Concat(facesT.Select(f => new Face(f.IndexA, f.IndexB, f.IndexC))), + colors); + + // A textured model can also have faces without texture coordinates (an untextured part with its own + // material). They keep their material and map to one shared texture coordinate, as the decimated levels + // give them, so that the finest level keeps them too. + if (faces.Count > 0) + { + var noTexture = textureVertices.AddIndex(new Vertex2(0, 0)); + for (var i = 0; i < faces.Count; i++) + facesT.Add(new FaceT(faces[i].IndexA, faces[i].IndexB, faces[i].IndexC, + noTexture, noTexture, noTexture, faceMaterials[i])); + } + + // Faces before the first usemtl have no material: they get the default one, as the glTF conversion gives + // them, not the first material of the MTL (the texture of another part). + int? defaultMaterial = null; + foreach (var face in facesT) + { + if (face.MaterialIndex == NoMaterial) + face.MaterialIndex = defaultMaterial ??= DefaultMaterialIndex(materials, materialsDict); + } + + return new MeshT(vertices, textureVertices, facesT, materials, colors); + } + + private static readonly RGB White = new(1, 1, 1); + + private const int NoMaterial = -1; + + /// + /// The name of the material of faces without usemtl: the name the glTF conversion gives them too. + /// + public const string DefaultMaterialName = "default"; + + // The index of the material named DefaultMaterialName, added (without colours or texture) if the MTL has none. + private static int DefaultMaterialIndex(List materials, Dictionary materialsDict) + { + if (!materialsDict.TryGetValue(DefaultMaterialName, out var index)) + { + index = materials.AddIndex(new Material(DefaultMaterialName)); + materialsDict.Add(DefaultMaterialName, index); + } + + return index; } #region Splitters diff --git a/Obj2Tiles.Library/Materials/Material.cs b/Obj2Tiles.Library/Materials/Material.cs index 67dcb41..0b3a0f4 100644 --- a/Obj2Tiles.Library/Materials/Material.cs +++ b/Obj2Tiles.Library/Materials/Material.cs @@ -171,10 +171,7 @@ public static Material[] ReadMtl(string path, out string[] dependencies, string? if (line.StartsWith("#") || string.IsNullOrWhiteSpace(line)) continue; - var lineTrimmed = line.Trim(); - var spaceIdx = lineTrimmed.IndexOf(' '); - var keyword = spaceIdx >= 0 ? lineTrimmed[..spaceIdx] : lineTrimmed; - var remainder = spaceIdx >= 0 ? lineTrimmed[(spaceIdx + 1)..] : string.Empty; + var (keyword, remainder) = ObjStatement.Split(line); var parts = remainder.Split(' ', StringSplitOptions.RemoveEmptyEntries); switch (keyword) @@ -184,7 +181,7 @@ public static Material[] ReadMtl(string path, out string[] dependencies, string? materials.Add(new Material(name, texture, normalMap, ambientColor, diffuseColor, specularColor, specularExponent, dissolve, illuminationModel)); - name = remainder.Trim(); + name = remainder; texture = null; normalMap = null; ambientColor = null; diff --git a/Obj2Tiles.Library/ObjStatement.cs b/Obj2Tiles.Library/ObjStatement.cs new file mode 100644 index 0000000..53884b6 --- /dev/null +++ b/Obj2Tiles.Library/ObjStatement.cs @@ -0,0 +1,30 @@ +namespace Obj2Tiles.Library; + +/// +/// Reads the statements of OBJ and MTL files: a keyword, then its argument. +/// +public static class ObjStatement +{ + private static readonly char[] Separators = [' ', '\t']; + + /// + /// Splits into its keyword and its argument, which is the rest of the line without the + /// whitespace around it. The names given to usemtl, newmtl, mtllib, g and + /// o run to the end of the line, so a name with spaces ("Paint 1 Carmine", as Blender and Assimp write + /// them) is one name, and every reader of a name must take it from here to find the same one. + /// + public static (string Keyword, string Argument) Split(string line) + { + var statement = line.AsSpan().Trim(); + var end = statement.IndexOfAny(Separators); + + return end < 0 + ? (statement.ToString(), string.Empty) + : (statement[..end].ToString(), statement[(end + 1)..].Trim().ToString()); + } + + /// + /// The argument of the statement : see . + /// + public static string Argument(string line) => Split(line).Argument; +} diff --git a/Obj2Tiles.Test/ObjMeshParsingTests.cs b/Obj2Tiles.Test/ObjMeshParsingTests.cs index 1162d20..c56d426 100644 --- a/Obj2Tiles.Test/ObjMeshParsingTests.cs +++ b/Obj2Tiles.Test/ObjMeshParsingTests.cs @@ -1,3 +1,4 @@ +using System.Collections.Generic; using System.IO; using System.Linq; using NUnit.Framework; @@ -215,4 +216,109 @@ public void ReadFile_MultiMaterial_TrailingUsemtl_MaterialsMatchIndices() File.Delete(roundTripFile); } } + + // --- Statements of exporters that write several objects --- + + private static ObjMesh ReadText(string obj) + { + var file = Path.GetTempFileName(); + try + { + File.WriteAllText(file, obj); + var mesh = new ObjMesh(); + mesh.ReadFile(file); + return mesh; + } + finally + { + File.Delete(file); + } + } + + private static ObjMesh RoundTrip(ObjMesh mesh) + { + var file = Path.GetTempFileName(); + try + { + mesh.WriteFile(file); + var read = new ObjMesh(); + read.ReadFile(file); + return read; + } + finally + { + File.Delete(file); + } + } + + [Test] + public void ReadFile_TextureCoordinatesOnlyAfterSomeFaces_StayAtTheirVertices() + { + // As Blender writes an untextured object, then a textured one: the vt lines come after faces. + var mesh = ReadText( + "v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n" + + "v 5 0 0\nv 6 0 0\nv 5 1 0\nvt 0.25 0.5\nvt 0.75 0.5\nvt 0.25 1\nf 4/1 5/2 6/3\n"); + + mesh.Vertices!.Length.ShouldBe(6); + mesh.TexCoords2D.ShouldNotBeNull(); + mesh.TexCoords2D!.Length.ShouldBe(6); + + // The untextured object's vertices get the default coordinate (0, 0). + var expected = new Dictionary<(double X, double Y), (float U, float V)> + { + [(0, 0)] = (0, 0), [(1, 0)] = (0, 0), [(0, 1)] = (0, 0), + [(5, 0)] = (0.25f, 0.5f), [(6, 0)] = (0.75f, 0.5f), [(5, 1)] = (0.25f, 1) + }; + for (var i = 0; i < 6; i++) + (mesh.TexCoords2D[i].x, mesh.TexCoords2D[i].y) + .ShouldBe(expected[(mesh.Vertices[i].x, mesh.Vertices[i].y)], $"vertex {i}"); + } + + [Test] + public void ReadFile_NormalsOnlyAfterSomeFaces_StayAtTheirVertices() + { + var mesh = ReadText( + "v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n" + + "v 5 0 0\nv 6 0 0\nv 5 1 0\nvn 0 0 1\nf 4//1 5//1 6//1\n"); + + mesh.Normals.ShouldNotBeNull(); + mesh.Normals!.Length.ShouldBe(mesh.Vertices!.Length); + mesh.Normals.Count(n => n.z == 1).ShouldBe(3); + } + + [Test] + public void ReadFile_FacesBeforeTheFirstUsemtl_HaveNoMaterial() + { + var mesh = ReadText( + "v 0 0 0\nv 1 0 0\nv 0 1 0\nv 1 1 0\n" + + "f 1 2 3\nusemtl A\nf 2 4 3\n"); + + mesh.SubMeshMaterials.ShouldBe(new[] { null, "A" }); + mesh.SubMeshIndices!.Length.ShouldBe(2); + + var read = RoundTrip(mesh); + read.SubMeshMaterials.ShouldBe(new[] { null, "A" }); + read.SubMeshIndices!.Select(s => s.Length).ShouldBe(new[] { 3, 3 }); + } + + [Test] + public void ReadFile_UsemtlWithoutFaces_DoesNotShiftTheNamesOfTheNextSubMeshes() + { + var mesh = ReadText( + "v 0 0 0\nv 1 0 0\nv 0 1 0\nv 1 1 0\n" + + "usemtl Unused\nusemtl A\nf 1 2 3\nusemtl B\nf 2 4 3\n"); + + mesh.SubMeshMaterials.ShouldBe(new[] { "A", "B" }); + } + + [Test] + public void ReadFile_MaterialNameWithSpaces_IsTheRestOfTheLine() + { + var mesh = ReadText( + "v 0 0 0\nv 1 0 0\nv 0 1 0\nv 1 1 0\n" + + "usemtl Paint 1 Carmine \nf 1 2 3\nusemtl Body\nf 2 4 3\n"); + + mesh.SubMeshMaterials.ShouldBe(new[] { "Paint 1 Carmine", "Body" }); + RoundTrip(mesh).SubMeshMaterials.ShouldBe(new[] { "Paint 1 Carmine", "Body" }); + } } diff --git a/Obj2Tiles.Test/Quality/CliHarness.cs b/Obj2Tiles.Test/Quality/CliHarness.cs index fb11c53..f0895f7 100644 --- a/Obj2Tiles.Test/Quality/CliHarness.cs +++ b/Obj2Tiles.Test/Quality/CliHarness.cs @@ -336,6 +336,34 @@ public static QualityDataset MultispectralTextured(bool floatingPoint) folder); } + /// + /// A model written by the test in a folder of its own: model.obj, model.mtl when given, and a PNG + /// texture (a colour gradient) of the given size for each texture name. Generated, not stored. + /// + public static QualityDataset Generated(string displayName, string obj, string? mtl = null, + params (string Name, int Width, int Height)[] textures) + { + var folder = Path.Combine(Path.GetTempPath(), "obj2tiles_quality_gate", + displayName + "_" + CommonUtils.RandomString(8)); + Directory.CreateDirectory(folder); + + File.WriteAllText(Path.Combine(folder, "model.obj"), obj); + if (mtl != null) + File.WriteAllText(Path.Combine(folder, "model.mtl"), mtl); + + foreach (var (name, width, height) in textures) + { + using var image = new SixLabors.ImageSharp.Image(width, height); + for (var y = 0; y < height; y++) + for (var x = 0; x < width; x++) + image[x, y] = new SixLabors.ImageSharp.PixelFormats.Rgba32( + (byte)(255 * x / width), (byte)(255 * y / height), 128, 255); + SixLabors.ImageSharp.ImageExtensions.SaveAsPng(image, Path.Combine(folder, name)); + } + + return Open(Path.Combine(folder, "model.obj"), displayName, folder); + } + private static IEnumerable localCandidates(string relative) { var root = Environment.GetEnvironmentVariable(CliHarness.TestDataSetEnv); diff --git a/Obj2Tiles.Test/Quality/CliQualityGateTests.cs b/Obj2Tiles.Test/Quality/CliQualityGateTests.cs index 11903cf..a16f960 100644 --- a/Obj2Tiles.Test/Quality/CliQualityGateTests.cs +++ b/Obj2Tiles.Test/Quality/CliQualityGateTests.cs @@ -35,9 +35,9 @@ public void CliCombination_producesValidQualityTileset(MatrixCase matrixCase) /// /// Executes the CLI exactly like a user would, then runs the full gate on the output. - /// Shared between the PICT matrix and the curated real-world cases. + /// Shared between the PICT matrix and the curated real-world cases. Returns the output path. /// - public static void RunValidateAndAssert( + public static string RunValidateAndAssert( string caseId, QualityDataset dataset, IEnumerable cliArgs, QualityExpectations expected) { var outBase = CliHarness.FreshOutputFolder(caseId); @@ -55,11 +55,13 @@ public static void RunValidateAndAssert( case Stage.Decimation: case Stage.Splitting: ExpectIntermediateObjOutput(caseId, outPath); - return; + break; default: ExpectTilingOutput(caseId, outBase, outPath, expected, run); break; } + + return outPath; } private static void ExpectIntermediateObjOutput(string caseId, string outPath) diff --git a/Obj2Tiles.Test/Quality/ModelEdgeCaseQualityTests.cs b/Obj2Tiles.Test/Quality/ModelEdgeCaseQualityTests.cs new file mode 100644 index 0000000..0bd4e0f --- /dev/null +++ b/Obj2Tiles.Test/Quality/ModelEdgeCaseQualityTests.cs @@ -0,0 +1,188 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; +using NUnit.Framework; +using Shouldly; + +namespace Obj2Tiles.Test.Quality; + +/// +/// Valid OBJ models that exporters (Blender, Assimp) write and that Obj2Tiles must tile whole: parts without +/// texture coordinates next to textured ones, material names with spaces, textures of any size, vertex colours on +/// some objects only, texture coordinates on the last object only, faces before the first usemtl. Each runs +/// with the options of a KTX2 tiling (the --texture-format Ktx2 --ktx2-quality 192 --split-strategy VertexMedian +/// options of DroneDB), through the whole gate (inspector and official validator). +/// +[TestFixture] +[Category("QualityGate")] +public class ModelEdgeCaseQualityTests +{ + private const int Cells = 20; + private const int GridTriangles = 2 * Cells * Cells; + + private static string Run(string caseId, QualityDataset dataset, int lods, int divisions) + { + var args = new List { "--lods", lods.ToString(CultureInfo.InvariantCulture), + "--divisions", divisions.ToString(CultureInfo.InvariantCulture), "--local", + "--texture-format", "Ktx2", "--ktx2-quality", "192", "--split-strategy", "VertexMedian" }; + if (divisions > 0) + args.Add("--octree"); + + var expected = new QualityExpectations + { + Lods = lods, Divisions = divisions, Octree = divisions > 0, Local = true, + TextureFormat = QualityTextureFormat.Ktx2 + }; + + return CliQualityGateTests.RunValidateAndAssert(caseId, dataset, args, expected); + } + + // The materials of the tiles of a level, without the "-" suffix of the atlases a material is split into. + private static string[] MaterialsOf(string output, string level) => + TilesetInspector.TrianglesByMaterial(output, level).Keys + .Select(name => Regex.Replace(name, "-[0-9]+$", "")).Distinct().ToArray(); + + private static void EveryLevelHasMaterials(string output, int lods, params string[] materials) + { + for (var lod = 0; lod < lods; lod++) + MaterialsOf(output, $"LOD-{lod}").ShouldBe(materials, ignoreOrder: true, $"LOD-{lod}"); + } + + // A textured grid and, beside it, a grid of faces without texture coordinates; both materials have + // spaces in their names (the second one two in a row). + private static QualityDataset TexturedAndPlainParts() => QualityDataset.Generated("textured-and-plain", + new ObjBuilder().Line("mtllib model.mtl") + .Line("usemtl Body Paint").Grid(0, textured: true) + .Line("usemtl Paint 1 Carmine").Grid(Cells + 1, textured: false) + .ToString(), + "newmtl Body Paint\nKd 1 1 1\nmap_Kd body.png\n\nnewmtl Paint 1 Carmine\nKd 0.6 0.05 0.1\n", + ("body.png", 64, 64)); + + [Test] + public void FacesWithoutTextureCoordinates_andMaterialNamesWithSpaces_areInTheFinestLevel() + { + using var dataset = TexturedAndPlainParts(); + + var output = Run("textured-and-plain", dataset, lods: 2, divisions: 0); + + var finest = TilesetInspector.TrianglesByMaterial(output, "LOD-0"); + finest.ShouldBe(new Dictionary { ["Body Paint"] = GridTriangles, ["Paint 1 Carmine"] = GridTriangles }, + ignoreOrder: true); + } + + [Test] + public void FacesWithoutTextureCoordinates_andMaterialNamesWithSpaces_areInEverySplitTileLevel() + { + using var dataset = TexturedAndPlainParts(); + + var output = Run("textured-and-plain-octree", dataset, lods: 3, divisions: 1); + + EveryLevelHasMaterials(output, 3, "Body Paint", "Paint 1 Carmine"); + } + + // The inspector checks that every KTX2 image is a whole number of 4x4 blocks. + [TestCase(250, 250)] + [TestCase(249, 250)] + [TestCase(30, 2)] + public void TextureOfAnySize_isAWholeNumberOfKtx2Blocks(int width, int height) + { + using var dataset = QualityDataset.Generated($"texture-{width}x{height}", + new ObjBuilder().Line("mtllib model.mtl").Line("usemtl t").Grid(0, textured: true).ToString(), + "newmtl t\nKd 1 1 1\nmap_Kd t.png\n", ("t.png", width, height)); + + Run($"texture-{width}x{height}", dataset, lods: 1, divisions: 0); + } + + // As Blender writes several objects: the first without material, texture coordinates or vertex colours, + // the second with vertex colours, the third with a material and texture coordinates. The faces before the + // first usemtl have the default material at every level, not the texture of the last object. + [TestCase(1, 0)] + [TestCase(3, 1)] + public void ObjectsWithDifferentAttributes_areTiled(int lods, int divisions) + { + using var dataset = QualityDataset.Generated("mixed-objects", + new ObjBuilder().Line("mtllib model.mtl") + .Line("o Plain").Grid(0, textured: false) + .Line("o Coloured").Grid(Cells + 1, textured: false, coloured: true) + .Line("o Textured").Line("usemtl t").Grid(2 * (Cells + 1), textured: true) + .ToString(), + "newmtl t\nKd 1 1 1\nmap_Kd t.png\n", ("t.png", 64, 64)); + + var output = Run($"mixed-objects-{lods}-{divisions}", dataset, lods, divisions); + + EveryLevelHasMaterials(output, lods, "default", "t"); + TilesetInspector.TrianglesByMaterial(output, "LOD-0").Values.Sum().ShouldBeGreaterThanOrEqualTo(3 * GridTriangles); + } + + // As Blender writes objects without material when only the last one has texture coordinates: there is no + // texture, so the model is tiled untextured, with every face. + [Test] + public void TextureCoordinatesWithoutMaterials_areTiledUntextured() + { + using var dataset = QualityDataset.Generated("uvs-without-materials", + new ObjBuilder().Line("o Plain").Grid(0, textured: false) + .Line("o Unwrapped").Grid(Cells + 1, textured: true) + .ToString()); + + var output = Run("uvs-without-materials", dataset, lods: 1, divisions: 0); + + TilesetInspector.TrianglesByMaterial(output, "LOD-0").Values.Sum().ShouldBe(2 * GridTriangles); + } + + private sealed class ObjBuilder + { + private readonly StringBuilder _obj = new(); + private int _vertices; + private int _textureVertices; + + public ObjBuilder Line(string line) + { + _obj.Append(line).Append('\n'); + return this; + } + + // A flat grid of Cells x Cells quads (two triangles each) starting at x = x0. + public ObjBuilder Grid(double x0, bool textured, bool coloured = false) + { + var first = _vertices + 1; + var firstUv = _textureVertices + 1; + + for (var j = 0; j <= Cells; j++) + for (var i = 0; i <= Cells; i++) + { + _obj.Append(FormattableString.Invariant($"v {x0 + i} {j} {0.1 * ((i + j) % 2)}")); + if (coloured) + _obj.Append(FormattableString.Invariant($" {(double)i / Cells} {(double)j / Cells} 0.5")); + _obj.Append('\n'); + + if (textured) + _obj.Append(FormattableString.Invariant($"vt {(double)i / Cells} {(double)j / Cells}\n")); + } + + _vertices += (Cells + 1) * (Cells + 1); + if (textured) + _textureVertices += (Cells + 1) * (Cells + 1); + + string Corner(int i, int j) + { + var offset = j * (Cells + 1) + i; + return textured ? $"{first + offset}/{firstUv + offset}" : $"{first + offset}"; + } + + for (var j = 0; j < Cells; j++) + for (var i = 0; i < Cells; i++) + { + _obj.Append($"f {Corner(i, j)} {Corner(i + 1, j)} {Corner(i + 1, j + 1)}\n"); + _obj.Append($"f {Corner(i, j)} {Corner(i + 1, j + 1)} {Corner(i, j + 1)}\n"); + } + + return this; + } + + public override string ToString() => _obj.ToString(); + } +} diff --git a/Obj2Tiles.Test/Quality/TilesetInspector.cs b/Obj2Tiles.Test/Quality/TilesetInspector.cs index 1d6abb3..9a7a086 100644 --- a/Obj2Tiles.Test/Quality/TilesetInspector.cs +++ b/Obj2Tiles.Test/Quality/TilesetInspector.cs @@ -408,6 +408,11 @@ private static void CheckImages(string uri, JToken glbJson, byte[] glbBin, Quali !(e.TextureFormat == QualityTextureFormat.Jpeg && IsLod0RepackTile(uri))) problems.Add($"{uri}: image mimeType '{mime}' mismatches --texture-format {e.TextureFormat}"); + // KHR_texture_basisu: the GPU formats a KTX2 image is transcoded to are made of 4x4 blocks, and + // WebGL rejects a BC (S3TC) texture of another size, which viewers then show black. + if (format == ImageFormat.Ktx2 && (w % 4 != 0 || h % 4 != 0)) + problems.Add($"{uri}: KTX2 image {w}x{h} is not a multiple of 4 in width and height (KHR_texture_basisu)"); + if (w > 0 && e.MaxTextureSize > 0 && Math.Max(w, h) > e.MaxTextureSize + 4) problems.Add($"{uri}: image {w}x{h} exceeds --max-texture-size {e.MaxTextureSize}"); } @@ -452,6 +457,35 @@ private static void CheckImages(string uri, JToken glbJson, byte[] glbBin, Quali return result; } + /// + /// The triangles of each material (by name) in the b3dm tiles of one folder of a tileset directory, such as + /// "LOD-0" for the finest level: what a level shows of each part of the model. + /// + public static Dictionary TrianglesByMaterial(string output, string levelFolder) + { + var triangles = new Dictionary(StringComparer.Ordinal); + var problems = new List(); + + foreach (var file in Directory.GetFiles(Path.Combine(output, levelFolder), "*.b3dm")) + { + var glb = TryParseB3dm(File.ReadAllBytes(file), file, problems) + ?? throw new InvalidDataException(string.Join("; ", problems)); + var materials = glb.Json["materials"] as JArray; + + foreach (var primitive in glb.Json["meshes"]?.SelectMany(m => m["primitives"] ?? new JArray()) ?? []) + { + var material = primitive["material"]?.Value() is { } index + ? materials?[index]?["name"]?.Value() ?? $"#{index}" + : ""; + var counted = primitive["indices"] ?? primitive["attributes"]?["POSITION"]; + var count = glb.Json["accessors"]?[counted!.Value()]?["count"]?.Value() ?? 0; + triangles[material] = triangles.GetValueOrDefault(material) + count / 3; + } + } + + return triangles; + } + // ---- b3dm / GLB framing ---------------------------------------------------------- private static (JToken Json, byte[] Bin)? TryParseB3dm(byte[] data, string name, List problems) diff --git a/Obj2Tiles.Test/Quality/TilesetInspectorTests.cs b/Obj2Tiles.Test/Quality/TilesetInspectorTests.cs index bfe8402..867cb2f 100644 --- a/Obj2Tiles.Test/Quality/TilesetInspectorTests.cs +++ b/Obj2Tiles.Test/Quality/TilesetInspectorTests.cs @@ -55,14 +55,17 @@ private static byte[] B3dmWithGlb(JObject gltf, byte[] bin) } // One JPEG image and the given primitive material indices; materials[0] is the unreferenced "default". - private static string WriteTileset(string name, params int[] primitiveMaterials) + private static string WriteTileset(string name, params int[] primitiveMaterials) => + WriteTileset(name, JpegStub, primitiveMaterials); + + private static string WriteTileset(string name, byte[] image, params int[] primitiveMaterials) { var gltf = new JObject { ["asset"] = new JObject { ["version"] = "2.0" }, ["images"] = new JArray(new JObject { ["bufferView"] = 0 }), - ["bufferViews"] = new JArray(new JObject { ["buffer"] = 0, ["byteOffset"] = 0, ["byteLength"] = JpegStub.Length }), - ["buffers"] = new JArray(new JObject { ["byteLength"] = JpegStub.Length }), + ["bufferViews"] = new JArray(new JObject { ["buffer"] = 0, ["byteOffset"] = 0, ["byteLength"] = image.Length }), + ["buffers"] = new JArray(new JObject { ["byteLength"] = image.Length }), ["materials"] = new JArray(new JObject { ["name"] = "default" }, new JObject { ["name"] = "a" }, new JObject { ["name"] = "b" }), ["meshes"] = new JArray(new JObject { @@ -74,7 +77,7 @@ private static string WriteTileset(string name, params int[] primitiveMaterials) if (Directory.Exists(dir)) Directory.Delete(dir, true); Directory.CreateDirectory(Path.Combine(dir, "LOD-0")); - File.WriteAllBytes(Path.Combine(dir, "LOD-0", "Mesh.b3dm"), B3dmWithGlb(gltf, JpegStub)); + File.WriteAllBytes(Path.Combine(dir, "LOD-0", "Mesh.b3dm"), B3dmWithGlb(gltf, image)); File.WriteAllText(Path.Combine(dir, "tileset.json"), """ { "asset": { "version": "1.0" }, "geometricError": 100, @@ -126,6 +129,39 @@ public void SingleMaterialPerPart_flagsTwoReferencedMaterials() problems.ShouldContain(p => p.Contains("2 materials although --single-material-per-part was set")); } + // KTX 2.0 header with the given size: identifier, vkFormat, typeSize, pixelWidth, pixelHeight, then zeros. + private static byte[] Ktx2Header(int width, int height) + { + var header = new byte[48]; + new byte[] { 0xab, 0x4b, 0x54, 0x58, 0x20, 0x32, 0x30, 0xbb, 0x0d, 0x0a, 0x1a, 0x0a }.CopyTo(header, 0); + BitConverter.GetBytes((uint)width).CopyTo(header, 20); + BitConverter.GetBytes((uint)height).CopyTo(header, 24); + return header; + } + + [TestCase(250, 250)] + [TestCase(256, 250)] + [TestCase(1, 1)] + public void Ktx2ImageNotMultipleOf4_isReported(int width, int height) + { + var dir = WriteTileset($"ktx2-{width}x{height}", Ktx2Header(width, height), 1); + + var problems = TilesetInspector.Inspect(dir, Expect(e => e.TextureFormat = QualityTextureFormat.Ktx2)); + + problems.ShouldContain(p => p.Contains($"KTX2 image {width}x{height} is not a multiple of 4")); + } + + [TestCase(252, 248)] + [TestCase(4, 4)] + public void Ktx2ImageMultipleOf4_isNotReported(int width, int height) + { + var dir = WriteTileset($"ktx2-{width}x{height}", Ktx2Header(width, height), 1); + + var problems = TilesetInspector.Inspect(dir, Expect(e => e.TextureFormat = QualityTextureFormat.Ktx2)); + + problems.ShouldNotContain(p => p.Contains("is not a multiple of 4")); + } + // Minimal JPEG header (SOI + SOF0) the sniffer reads dimensions from. private static byte[] JpegWithEdge(int edge) => new byte[] { 0xff, 0xd8, 0xff, 0xc0, 0x00, 0x11, 0x08, (byte)(edge >> 8), (byte)edge, (byte)(edge >> 8), (byte)edge, 0, 0, 0, 0, 0 }; diff --git a/Obj2Tiles/Stages/Model/ObjMesh.cs b/Obj2Tiles/Stages/Model/ObjMesh.cs index e011b77..53a97b0 100644 --- a/Obj2Tiles/Stages/Model/ObjMesh.cs +++ b/Obj2Tiles/Stages/Model/ObjMesh.cs @@ -28,6 +28,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using System.Globalization; using MeshDecimatorCore.Math; +using Obj2Tiles.Library; using Obj2Tiles.Library.Geometry; namespace Obj2Tiles.Stages.Model @@ -99,7 +100,7 @@ public override string ToString() private Vector2[]? texCoords2D = null; private Vector3[]? texCoords3D = null; private int[][]? subMeshIndices = null; - private string[]? subMeshMaterials = null; + private string?[]? subMeshMaterials = null; private string[]? materialLibraries = null; @@ -229,24 +230,13 @@ public int[][]? SubMeshIndices } /// - /// Gets or sets the names of each sub-mesh material. + /// Gets or sets the names of each sub-mesh material. A name is null for the faces before the first usemtl + /// of a file, which have no material. /// - public string[]? SubMeshMaterials + public string?[]? SubMeshMaterials { get => subMeshMaterials; - set - { - if (value != null) - { - for (int i = 0; i < value.Length; i++) - { - if (value[i] == null) - throw new ArgumentException($"The sub-mesh material name at index {i} is null.", "value"); - } - } - - subMeshMaterials = value; - } + set => subMeshMaterials = value; } /// @@ -317,7 +307,7 @@ public void ReadFile(string path) List? texCoordList = null; var triangleIndexList = new List(IndexInitialCapacity); var subMeshIndicesList = new List(); - var subMeshMaterialList = new List(); + var subMeshMaterialList = new List(); var faceTable = new Dictionary(IndexInitialCapacity); var tempFaceList = new List(6); bool texCoordsAre3D = false; @@ -355,8 +345,7 @@ public void ReadFile(string path) { readColorList ??= new List(VertexInitialCapacity); // Back-fill default white for any previous vertices that had no color - while (readColorList.Count < readVertexList.Count - 1) - readColorList.Add(new Vector4(1f, 1f, 1f, 1f)); + readColorList.PadTo(readVertexList.Count - 1, White); float.TryParse(lineSplit[4], NumberStyles.Float, CultureInfo.InvariantCulture, out var cr); float.TryParse(lineSplit[5], NumberStyles.Float, CultureInfo.InvariantCulture, out var cg); float.TryParse(lineSplit[6], NumberStyles.Float, CultureInfo.InvariantCulture, out var cb); @@ -368,7 +357,7 @@ public void ReadFile(string path) else if (readColorList != null) { // Vertex without color after colors were already detected: pad with default white - readColorList.Add(new Vector4(1f, 1f, 1f, 1f)); + readColorList.Add(White); } if (x < minX) minX = x; else if (x > maxX) maxX = x; @@ -486,47 +475,20 @@ public void ReadFile(string path) vertexList.Add(readVertexList[vertexIndex]); + // An attribute (colour, normal, texture coordinate) can first appear after some + // faces, as in a file of several objects of which only the last has texture + // coordinates: the vertices made before it get its default, so the attribute of + // each vertex stays at the vertex's index. if (readColorList != null) - { - colorList ??= new List(VertexInitialCapacity); - - if (vertexIndex >= 0 && vertexIndex < readColorList.Count) - { - colorList.Add(readColorList[vertexIndex]); - } - else - { - colorList.Add(new Vector4(1f, 1f, 1f, 1f)); - } - } + AddVertexAttribute(ref colorList, vertexList.Count, readColorList, vertexIndex, White); if (readNormalList != null) - { - normalList ??= new List(VertexInitialCapacity); - - if (normalIndex >= 0 && normalIndex < readNormalList.Count) - { - normalList.Add(readNormalList[normalIndex]); - } - else - { - normalList.Add(Vector3.zero); - } - } + AddVertexAttribute(ref normalList, vertexList.Count, readNormalList, normalIndex, + Vector3.zero); if (readTexCoordList != null) - { - texCoordList ??= new List(VertexInitialCapacity); - - if (texIndex >= 0 && texIndex < readTexCoordList!.Count) - { - texCoordList.Add(readTexCoordList[texIndex]); - } - else - { - texCoordList.Add(Vector3.zero); - } - } + AddVertexAttribute(ref texCoordList, vertexList.Count, readTexCoordList, texIndex, + Vector3.zero); } } @@ -548,56 +510,43 @@ public void ReadFile(string path) } else if (string.Equals(firstPart, "g")) { - string groupName = string.Join(" ", lineSplit, 1, lineSplit.Length - 1); - currentGroup = groupName; + currentGroup = ObjStatement.Argument(line); } else if (string.Equals(firstPart, "o")) { - string objectName = string.Join(" ", lineSplit, 1, lineSplit.Length - 1); - currentObject = objectName; + currentObject = ObjStatement.Argument(line); } else if (string.Equals(firstPart, "mtllib")) { - string materialLibraryPath = string.Join(" ", lineSplit, 1, lineSplit.Length - 1); - materialLibraryList.Add(materialLibraryPath); + materialLibraryList.Add(ObjStatement.Argument(line)); } else if (string.Equals(firstPart, "usemtl")) { - string materialName = string.Join(" ", lineSplit, 1, lineSplit.Length - 1); - currentMaterial = materialName; - - if (triangleIndexList.Count > 0) - { - subMeshIndicesList.Add(triangleIndexList.ToArray()); - triangleIndexList.Clear(); - /* - if (subMeshMaterialList.Count != subMeshIndicesList.Count) - { - subMeshMaterialList.Add("none"); - }*/ - } - - subMeshMaterialList.Add(materialName); + CloseSubMesh(); + currentMaterial = ObjStatement.Argument(line); } } } - if (triangleIndexList.Count > 0) + CloseSubMesh(); + + // The faces read since the last usemtl make a sub-mesh of the material they were read with: a sub-mesh + // and its material are recorded together, so faces before the first usemtl (no material), a usemtl + // without faces (Issue #54) or two usemtl in a row never shift the names onto other sub-meshes. + void CloseSubMesh() { + if (triangleIndexList.Count == 0) + return; + subMeshIndicesList.Add(triangleIndexList.ToArray()); + subMeshMaterialList.Add(currentMaterial); triangleIndexList.Clear(); } - // Fix Issue #54: Remove orphan material entries that have no corresponding - // index arrays. This happens when a trailing 'usemtl' appears without - // subsequent faces, causing a mismatch between SubMeshMaterials and - // SubMeshIndices that crashes WriteFile. - while (subMeshMaterialList.Count > subMeshIndicesList.Count) - subMeshMaterialList.RemoveAt(subMeshMaterialList.Count - 1); - int subMeshCount = subMeshIndicesList.Count; - bool hasNormals = (readNormalList != null); - bool hasTexCoords = (readTexCoordList != null); + // An attribute read after the last face is given to no vertex. + bool hasNormals = (normalList != null); + bool hasTexCoords = (texCoordList != null); bool hasColors = (colorList != null); int vertexCount = vertexList.Count; var processedVertexList = new List(vertexCount); @@ -672,7 +621,7 @@ public void ReadFile(string path) } subMeshIndices = processedIndices.ToArray(); - subMeshMaterials = subMeshMaterialList.Any() ? subMeshMaterialList.ToArray() : null; + subMeshMaterials = subMeshMaterialList.Any(name => name != null) ? subMeshMaterialList.ToArray() : null; materialLibraries = materialLibraryList.Any() ? materialLibraryList.ToArray() : null; Bounds = new Box3(minX, minY, minZ, maxX, maxY, maxZ); } @@ -894,7 +843,7 @@ private static void WriteTextureCoords(TextWriter writer, Vector2[]? texCoords2D } } - private static void WriteSubMeshes(TextWriter writer, int[][] subMeshIndices, string[]? subMeshMaterials, + private static void WriteSubMeshes(TextWriter writer, int[][] subMeshIndices, string?[]? subMeshMaterials, int[] posIndexMap, int[]? texIndexMap, int[]? normalIndexMap, bool hasTexCoords, bool hasNormals) { for (int subMeshIndex = 0; subMeshIndex < subMeshIndices.Length; subMeshIndex++) @@ -904,9 +853,9 @@ private static void WriteSubMeshes(TextWriter writer, int[][] subMeshIndices, st writer.WriteLine(); writer.WriteLine("# Sub-mesh {0}", (subMeshIndex + 1)); - if (subMeshMaterials != null) + // A sub-mesh without material can only be the first: it is written before any usemtl. + if (subMeshMaterials?[subMeshIndex] is { } materialName) { - string materialName = subMeshMaterials[subMeshIndex]; writer.Write("usemtl "); writer.WriteLine(materialName); } @@ -955,6 +904,18 @@ private static void WriteFaceCorner(TextWriter writer, int originalIndex, int[] } } + private static readonly Vector4 White = new Vector4(1f, 1f, 1f, 1f); + + // Adds to attributes (made on first use) the attribute of the vertex number vertexCount: read[index], or + // fallback for a vertex that gives none, after giving fallback to the earlier vertices it lacks. + private static void AddVertexAttribute(ref List? attributes, int vertexCount, List read, int index, + T fallback) + { + attributes ??= new List(VertexInitialCapacity); + attributes.PadTo(vertexCount - 1, fallback); + attributes.Add(index >= 0 && index < read.Count ? read[index] : fallback); + } + private static int ShiftIndex(int value, int count) { return value < 0 ? count + value : value - 1;