LoadSpecialModelsTest.cs 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Numerics;
  5. using System.Text;
  6. using NUnit.Framework;
  7. namespace SharpGLTF.Schema2.LoadAndSave
  8. {
  9. /// <summary>
  10. /// Test cases for models found in <see href="https://github.com/KhronosGroup/glTF-Blender-Exporter"/>
  11. /// </summary>
  12. [TestFixture]
  13. [AttachmentPathFormat("*/TestResults/LoadAndSave/?", true)]
  14. [Category("Model Load and Save")]
  15. public class LoadSpecialModelsTest
  16. {
  17. #region setup
  18. [OneTimeSetUp]
  19. public void Setup()
  20. {
  21. // TestFiles.DownloadReferenceModels();
  22. }
  23. #endregion
  24. [Test]
  25. public void LoadEscapedUriModel()
  26. {
  27. var model = ModelRoot.Load(ResourceInfo.From("white space.gltf"));
  28. Assert.That(model, Is.Not.Null);
  29. model.AttachToCurrentTest("white space.glb");
  30. }
  31. public void LoadWithCustomImageLoader()
  32. {
  33. // load Polly model
  34. var model = ModelRoot.Load(TestFiles.GetPollyFileModelPath());
  35. }
  36. [Test(Description = "Example of traversing the visual tree all the way to individual vertices and indices")]
  37. public void LoadPollyModel()
  38. {
  39. // load Polly model
  40. var model = ModelRoot.Load(TestFiles.GetPollyFileModelPath(), Validation.ValidationMode.TryFix);
  41. Assert.That(model, Is.Not.Null);
  42. var triangles = model.DefaultScene
  43. .EvaluateTriangles<Geometry.VertexTypes.VertexPosition, Geometry.VertexTypes.VertexTexture1>(null, model.LogicalAnimations[0], 0.5f)
  44. .ToList();
  45. // Save as GLB, and also evaluate all triangles and save as Wavefront OBJ
  46. model.AttachToCurrentTest("polly_out.glb");
  47. model.AttachToCurrentTest("polly_out.obj");
  48. // hierarchically browse some elements of the model:
  49. var scene = model.DefaultScene;
  50. var pollyNode = scene.FindNode(n => n.Name == "Polly_Display");
  51. var pollyPrimitive = pollyNode.Mesh.Primitives[0];
  52. var pollyIndices = pollyPrimitive.GetIndices();
  53. var pollyPositions = pollyPrimitive.GetVertices("POSITION").AsVector3Array();
  54. var pollyNormals = pollyPrimitive.GetVertices("NORMAL").AsVector3Array();
  55. for (int i = 0; i < pollyIndices.Count; i += 3)
  56. {
  57. var a = (int)pollyIndices[i + 0];
  58. var b = (int)pollyIndices[i + 1];
  59. var c = (int)pollyIndices[i + 2];
  60. var ap = pollyPositions[a];
  61. var bp = pollyPositions[b];
  62. var cp = pollyPositions[c];
  63. var an = pollyNormals[a];
  64. var bn = pollyNormals[b];
  65. var cn = pollyNormals[c];
  66. TestContext.Out.WriteLine($"Triangle {ap} {an} {bp} {bn} {cp} {cn}");
  67. }
  68. // create a clone and apply a global axis transform.
  69. var clonedModel = model.DeepClone();
  70. var basisTransform
  71. = Matrix4x4.CreateScale(1, 2, 1)
  72. * Matrix4x4.CreateFromYawPitchRoll(1, 2, 3)
  73. * Matrix4x4.CreateTranslation(10,5,2);
  74. clonedModel.ApplyBasisTransform(basisTransform);
  75. clonedModel.AttachToCurrentTest("polly_out_transformed.glb");
  76. var wsettings = new WriteSettings();
  77. wsettings.ImageWriting = ResourceWriteMode.BufferView;
  78. wsettings.MergeBuffers = true;
  79. wsettings.BuffersMaxSize = 1024 * 1024 * 10;
  80. clonedModel.AttachToCurrentTest("polly_out_merged_10mb.gltf", wsettings);
  81. }
  82. [Test]
  83. public void LoadUniVRM()
  84. {
  85. var path = TestFiles.GetUniVRMModelPath();
  86. var model = ModelRoot.Load(path);
  87. Assert.That(model, Is.Not.Null);
  88. var flattenExtensions = model.GatherUsedExtensions().ToArray();
  89. model.AttachToCurrentTest("AliceModel.glb");
  90. }
  91. // [Test]
  92. public void LoadShrekshaoModel()
  93. {
  94. var model = ModelRoot.Load(ResourceInfo.From("SpecialCases\\shrekshao.glb"));
  95. Assert.That(model, Is.Not.Null);
  96. }
  97. [Test]
  98. public void LoadMouseModel()
  99. {
  100. // this model has several nodes with curve animations containing a single animation key,
  101. // which is causing some problems to the interpolator.
  102. var model = ModelRoot.Load(ResourceInfo.From("SpecialCases\\mouse.glb"));
  103. var boundingSphere = Runtime.MeshDecoder.EvaluateBoundingSphere(model.DefaultScene);
  104. var sampler = model
  105. .LogicalNodes[5]
  106. .GetCurveSamplers(model.LogicalAnimations[1])
  107. .Rotation
  108. .CreateCurveSampler(true);
  109. var node5_R_00 = sampler.GetPoint(0);
  110. var node5_R_01 = sampler.GetPoint(1);
  111. Assert.That(node5_R_01, Is.EqualTo(node5_R_00));
  112. model.AttachToCurrentTest("mouse_00.obj", model.LogicalAnimations[1], 0f);
  113. model.AttachToCurrentTest("mouse_01.obj", model.LogicalAnimations[1], 1f);
  114. }
  115. [TestCase("SketchfabExport-WhatIsPBR.glb")] // model has exported tangents in the form <0,0,0,1>
  116. public void LoadSketchfabModels(string path)
  117. {
  118. // this model has several nodes with curve animations containing a single animation key,
  119. // which is causing some problems to the interpolator.
  120. var model = ModelRoot.Load(ResourceInfo.From($"SpecialCases\\{path}"), Validation.ValidationMode.TryFix);
  121. model.AttachToCurrentTest("output.glb");
  122. }
  123. // these models show normal mapping but lack tangents, which are expected to be
  124. // generated at runtime; These tests generate the tangents and check them against the baseline.
  125. [TestCase("NormalTangentTest.glb")]
  126. [TestCase("NormalTangentMirrorTest.glb")]
  127. public void LoadGeneratedTangetsTest(string fileName)
  128. {
  129. var path = TestFiles.GetSampleModelsPaths().FirstOrDefault(item => item.EndsWith(fileName));
  130. var model = ModelRoot.Load(path);
  131. var mesh = model.DefaultScene
  132. .EvaluateTriangles<Geometry.VertexTypes.VertexPositionNormalTangent, Geometry.VertexTypes.VertexTexture1>()
  133. .ToMeshBuilder();
  134. var editableScene = new Scenes.SceneBuilder();
  135. editableScene.AddRigidMesh(mesh, Matrix4x4.Identity);
  136. model.AttachToCurrentTest("original.glb");
  137. editableScene.ToGltf2().AttachToCurrentTest("WithTangents.glb");
  138. }
  139. [Test]
  140. public void LoadAndSaveToMemory()
  141. {
  142. var path = TestFiles.GetSampleModelsPaths().FirstOrDefault(item => item.EndsWith("Avocado.glb"));
  143. var model = ModelRoot.Load(path);
  144. // model.LogicalImages[0].TransferToSatelliteFile(); // TODO
  145. // we will use this dictionary as our in-memory model container.
  146. var dictionary = new Dictionary<string, ArraySegment<Byte>>();
  147. // write to dictionary
  148. var wcontext = WriteContext.CreateFromDictionary(dictionary);
  149. model.Save("avocado.gltf", wcontext);
  150. Assert.That(dictionary.ContainsKey("avocado.gltf"), Is.True);
  151. Assert.That(dictionary.ContainsKey("avocado.bin"), Is.True);
  152. // read back from dictionary
  153. var rcontext = ReadContext.CreateFromDictionary(dictionary);
  154. var model2 = ModelRoot.Load("avocado.gltf", rcontext);
  155. // TODO: verify
  156. }
  157. [Test]
  158. public void LoadInvalidModelWithJsonFix()
  159. {
  160. // try to load an invalid gltf with an empty array
  161. var xpath = ResourceInfo.From("SpecialCases\\Invalid_EmptyArray.gltf");
  162. Assert.Throws<Validation.SchemaException>(() => ModelRoot.Load(xpath));
  163. // try to load an invalid gltf with an empty array, using a hook to fix the json before running the parser.
  164. var rsettings = new ReadSettings();
  165. rsettings.JsonPreprocessor = _RemoveEmptyArrayJsonProcessor;
  166. var model = ModelRoot.Load(xpath, rsettings);
  167. Assert.That(model, Is.Not.Null);
  168. // save the model, using a hook to modify the json before writing it to the file.
  169. var wsettings = new WriteSettings();
  170. wsettings.JsonPostprocessor = json =>
  171. {
  172. json = json.Replace("glTF 2.0 Validator test suite", "postprocessed json"); return json;
  173. };
  174. var path = model.AttachToCurrentTest("modified.gltf", wsettings);
  175. model = ModelRoot.Load(path);
  176. Assert.That("postprocessed json", Is.EqualTo(model.Asset.Generator));
  177. }
  178. private string _RemoveEmptyArrayJsonProcessor(string json)
  179. {
  180. var obj = Newtonsoft.Json.Linq.JObject.Parse(json);
  181. var children = obj.Children().ToArray();
  182. children[1].Remove(); // remove the empty "meshes" array.
  183. json = obj.ToString();
  184. return json;
  185. }
  186. }
  187. }