LoadSampleTests.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using NUnit.Framework;
  6. namespace SharpGLTF.Schema2.LoadAndSave
  7. {
  8. /// <summary>
  9. /// Test cases for models found in <see href="https://github.com/KhronosGroup/glTF-Sample-Models"/> and more....
  10. /// </summary>
  11. [TestFixture]
  12. [AttachmentPathFormat("*/TestResults/LoadAndSave/?", true)]
  13. [Category("Model Load and Save")]
  14. public class LoadSampleTests
  15. {
  16. #region setup
  17. [OneTimeSetUp]
  18. public void Setup()
  19. {
  20. // TestFiles.DownloadReferenceModels();
  21. }
  22. #endregion
  23. #region helpers
  24. private static ModelRoot _LoadModel(string f, bool tryFix = false)
  25. {
  26. var settings = tryFix
  27. ? Validation.ValidationMode.TryFix
  28. : Validation.ValidationMode.Strict;
  29. ModelRoot model = null;
  30. var perf = System.Diagnostics.Stopwatch.StartNew();
  31. try
  32. {
  33. model = ModelRoot.Load(f, settings);
  34. Assert.That(model, Is.Not.Null);
  35. }
  36. catch (Exception ex)
  37. {
  38. TestContext.Progress.WriteLine($"Failed {f.ToShortDisplayPath()}");
  39. Assert.Fail(ex.Message);
  40. }
  41. var perf_load = perf.ElapsedMilliseconds;
  42. // do a model clone and compare it
  43. _AssertAreEqual(model, model.DeepClone());
  44. var perf_clone = perf.ElapsedMilliseconds;
  45. if (!f.Contains("Iridescence")) // the iridescence sample models declares using IOR but it's not actually used
  46. {
  47. var unsupportedExtensions = new[] { "MSFT_lod", "EXT_lights_image_based" };
  48. // check extensions used
  49. if (unsupportedExtensions.All(uex => !model.ExtensionsUsed.Contains(uex)))
  50. {
  51. var detectedExtensions = model.GatherUsedExtensions().ToArray();
  52. Assert.That(detectedExtensions, Is.EquivalentTo(model.ExtensionsUsed));
  53. }
  54. }
  55. // Save models
  56. model.AttachToCurrentTest(System.IO.Path.ChangeExtension(System.IO.Path.GetFileName(f), ".obj"));
  57. var perf_wavefront = perf.ElapsedMilliseconds;
  58. model.AttachToCurrentTest(System.IO.Path.ChangeExtension(System.IO.Path.GetFileName(f), ".glb"));
  59. var perf_glb = perf.ElapsedMilliseconds;
  60. TestContext.Progress.WriteLine($"processed {f.ToShortDisplayPath()} - Load:{perf_load}ms Clone:{perf_clone}ms S.obj:{perf_wavefront}ms S.glb:{perf_glb}ms");
  61. return model;
  62. }
  63. private static void _AssertAreEqual(ModelRoot a, ModelRoot b)
  64. {
  65. var aa = a.GetLogicalChildrenFlattened().ToList();
  66. var bb = b.GetLogicalChildrenFlattened().ToList();
  67. Assert.That(bb, Has.Count.EqualTo(aa.Count));
  68. Assert.That
  69. (
  70. aa.Select(item => item.GetType()),
  71. Is.EqualTo(bb.Select(item => item.GetType()))
  72. );
  73. }
  74. #endregion
  75. [TestCase("\\glTF\\")]
  76. // [TestCase("\\glTF-Draco\\")] // Not supported
  77. [TestCase("\\glTF-IBL\\")]
  78. [TestCase("\\glTF-Binary\\")]
  79. [TestCase("\\glTF-Embedded\\")]
  80. [TestCase("\\glTF-Quantized\\")]
  81. // [TestCase("\\glTF-Meshopt\\")] // not supported
  82. public void LoadModelsFromKhronosSamples(string section)
  83. {
  84. TestContext.CurrentContext.AttachGltfValidatorLinks();
  85. Assert.Multiple( () =>
  86. {
  87. foreach (var f in TestFiles.GetSampleModelsPaths())
  88. {
  89. if (f.Contains("SuzanneMorphSparse")) continue; // temporarily skipping due to empty BufferView issue
  90. if (!f.Contains(section)) continue;
  91. _LoadModel(f);
  92. }
  93. } );
  94. }
  95. [Test]
  96. public void LoadModelsFromBabylonJs()
  97. {
  98. TestContext.CurrentContext.AttachGltfValidatorLinks();
  99. foreach (var f in TestFiles.GetBabylonJSModelsPaths())
  100. {
  101. _LoadModel(f, true);
  102. }
  103. }
  104. [TestCase("TeapotsGalore.gltf")]
  105. [TestCase("GrassFieldInstanced.glb")]
  106. [TestCase("InstanceTest.glb")]
  107. public void LoadModelsWithGpuMeshInstancingExtension(string fileFilter)
  108. {
  109. TestContext.CurrentContext.AttachGltfValidatorLinks();
  110. var f = TestFiles.GetMeshIntancingModelPaths().FirstOrDefault(item => item.Contains(fileFilter));
  111. var model = _LoadModel(f, false);
  112. var ff = System.IO.Path.GetFileNameWithoutExtension(f);
  113. model.AttachToCurrentTest($"{ff}.loaded.glb");
  114. // perform roundtrip
  115. var roundtripDefault = model.DefaultScene
  116. .ToSceneBuilder() // glTF to SceneBuilder
  117. .ToGltf2(Scenes.SceneBuilderSchema2Settings.Default); // SceneBuilder to glTF
  118. var roundtripInstanced = model.DefaultScene
  119. .ToSceneBuilder() // glTF to SceneBuilder
  120. .ToGltf2(Scenes.SceneBuilderSchema2Settings.WithGpuInstancing); // SceneBuilder to glTF
  121. // compare bounding spheres
  122. var modelBounds = Runtime.MeshDecoder.EvaluateBoundingBox(model.DefaultScene);
  123. var rtripDefBounds = Runtime.MeshDecoder.EvaluateBoundingBox(roundtripDefault.DefaultScene);
  124. var rtripGpuBounds = Runtime.MeshDecoder.EvaluateBoundingBox(roundtripInstanced.DefaultScene);
  125. Assert.That(rtripDefBounds, Is.EqualTo(modelBounds));
  126. Assert.That(rtripGpuBounds, Is.EqualTo(modelBounds));
  127. // save results
  128. roundtripDefault.AttachToCurrentTest($"{ff}.roundtrip.default.glb");
  129. roundtripInstanced.AttachToCurrentTest($"{ff}.roundtrip.instancing.glb");
  130. }
  131. [TestCase("IridescenceMetallicSpheres.gltf")]
  132. [TestCase("SpecGlossVsMetalRough.gltf")]
  133. [TestCase(@"TextureTransformTest.gltf")]
  134. [TestCase(@"UnlitTest\glTF-Binary\UnlitTest.glb")]
  135. [TestCase(@"glTF-Quantized\Avocado.gltf")]
  136. [TestCase(@"glTF-Quantized\AnimatedMorphCube.gltf")]
  137. [TestCase(@"glTF-Quantized\AnimatedMorphCube.gltf")]
  138. [TestCase(@"glTF-Quantized\Duck.gltf")]
  139. [TestCase(@"glTF-Quantized\Lantern.gltf")]
  140. [TestCase(@"MosquitoInAmber.glb")]
  141. public void LoadModelsWithExtensions(string filePath)
  142. {
  143. TestContext.CurrentContext.AttachGltfValidatorLinks();
  144. filePath = TestFiles
  145. .GetSampleModelsPaths()
  146. .FirstOrDefault(item => item.EndsWith(filePath));
  147. _LoadModel(filePath);
  148. }
  149. [Test]
  150. public void LoadModelWithUnlitMaterial()
  151. {
  152. var f = TestFiles
  153. .GetSampleModelsPaths()
  154. .FirstOrDefault(item => item.EndsWith(@"UnlitTest\glTF-Binary\UnlitTest.glb"));
  155. var model = ModelRoot.Load(f);
  156. Assert.That(model, Is.Not.Null);
  157. Assert.That(model.LogicalMaterials[0].Unlit, Is.True);
  158. // do a model roundtrip
  159. var modelBis = ModelRoot.ParseGLB(model.WriteGLB());
  160. Assert.That(modelBis, Is.Not.Null);
  161. Assert.That(modelBis.LogicalMaterials[0].Unlit, Is.True);
  162. }
  163. [Test]
  164. public void LoadModelWithLights()
  165. {
  166. var f = TestFiles
  167. .GetSchemaExtensionsModelsPaths()
  168. .FirstOrDefault(item => item.EndsWith("lights.gltf"));
  169. var model = ModelRoot.Load(f);
  170. Assert.That(model, Is.Not.Null);
  171. Assert.That(model.LogicalPunctualLights, Has.Count.EqualTo(3));
  172. Assert.That(model.DefaultScene.VisualChildren.ElementAt(0).PunctualLight.LogicalIndex, Is.EqualTo(1));
  173. Assert.That(model.DefaultScene.VisualChildren.ElementAt(1).PunctualLight.LogicalIndex, Is.EqualTo(0));
  174. }
  175. [TestCase("SimpleSparseAccessor.gltf")]
  176. // [TestCase("SuzanneMorphSparse.gltf")] requires supporting empty BufferView
  177. public void LoadModelWithSparseAccessor(string fileName)
  178. {
  179. var path = TestFiles
  180. .GetSampleModelsPaths()
  181. .FirstOrDefault(item => item.Contains(fileName));
  182. var model = ModelRoot.Load(path);
  183. Assert.That(model, Is.Not.Null);
  184. var primitive = model.LogicalMeshes[0].Primitives[0];
  185. var accessor = primitive.GetVertexAccessor("POSITION");
  186. var basePositions = accessor._GetMemoryAccessor().AsVector3Array();
  187. var positions = accessor.AsVector3Array();
  188. }
  189. [Test]
  190. public void LoadModelWithMorphTargets()
  191. {
  192. var path = TestFiles
  193. .GetSampleModelsPaths()
  194. .FirstOrDefault(item => item.Contains("MorphPrimitivesTest.glb"));
  195. var model = ModelRoot.Load(path);
  196. Assert.That(model, Is.Not.Null);
  197. var triangles = model.DefaultScene
  198. .EvaluateTriangles<Geometry.VertexTypes.VertexPosition, Geometry.VertexTypes.VertexEmpty>(null, null, 0)
  199. .ToArray();
  200. model.AttachToCurrentTest(System.IO.Path.ChangeExtension(System.IO.Path.GetFileName(path), ".obj"));
  201. model.AttachToCurrentTest(System.IO.Path.ChangeExtension(System.IO.Path.GetFileName(path), ".glb"));
  202. }
  203. [TestCase("RiggedFigure.glb")]
  204. [TestCase("RiggedSimple.glb")]
  205. [TestCase("BoxAnimated.glb")]
  206. [TestCase("AnimatedMorphCube.glb")]
  207. [TestCase("AnimatedMorphSphere.glb")]
  208. [TestCase("CesiumMan.glb")]
  209. //[TestCase("Monster.glb")] // temporarily removed from khronos repo
  210. [TestCase("BrainStem.glb")]
  211. [TestCase("Fox.glb")]
  212. public void LoadModelsWithAnimations(string path)
  213. {
  214. path = TestFiles
  215. .GetSampleModelsPaths()
  216. .FirstOrDefault(item => item.Contains(path));
  217. var model = ModelRoot.Load(path);
  218. Assert.That(model, Is.Not.Null);
  219. path = System.IO.Path.GetFileNameWithoutExtension(path);
  220. model.AttachToCurrentTest(path + ".glb");
  221. var triangles = model.DefaultScene
  222. .EvaluateTriangles<Geometry.VertexTypes.VertexPosition, Geometry.VertexTypes.VertexEmpty>()
  223. .ToArray();
  224. var anim = model.LogicalAnimations[0];
  225. var duration = anim.Duration;
  226. for(int i=0; i < 10; ++i)
  227. {
  228. var t = duration * i / 10;
  229. int tt = (int)(t * 1000.0f);
  230. model.AttachToCurrentTest($"{path} at {tt}.obj",anim, t);
  231. }
  232. }
  233. [Test]
  234. public void LoadAnimatedMorphCube()
  235. {
  236. var path = TestFiles
  237. .GetSampleModelsPaths()
  238. .FirstOrDefault(item => item.Contains("AnimatedMorphCube.glb"));
  239. var model = ModelRoot.Load(path);
  240. Assert.That(model, Is.Not.Null);
  241. var anim = model.LogicalAnimations[0];
  242. var node = model.LogicalNodes[0];
  243. var acc_master = node.Mesh.Primitives[0].GetVertexAccessor("POSITION");
  244. var acc_morph0 = node.Mesh.Primitives[0].GetMorphTargetAccessors(0)["POSITION"];
  245. var acc_morph1 = node.Mesh.Primitives[0].GetMorphTargetAccessors(1)["POSITION"];
  246. var pos_master = acc_master.AsVector3Array();
  247. var pos_morph0 = acc_morph0.AsVector3Array();
  248. var pos_morph1 = acc_morph1.AsVector3Array();
  249. // pos_master
  250. var instance = Runtime.SceneTemplate
  251. .Create(model.DefaultScene)
  252. .CreateInstance();
  253. var pvrt = node.Mesh.Primitives[0].GetVertexColumns();
  254. for (float t = 0; t < 5; t+=0.25f)
  255. {
  256. instance.Armature.SetAnimationFrame(anim.LogicalIndex, t);
  257. var nodexform = instance.GetDrawableInstance(0).Transform;
  258. TestContext.WriteLine($"Animation at {t}");
  259. var curves = node.GetCurveSamplers(anim);
  260. if (t < anim.Duration)
  261. {
  262. var mw = curves.GetMorphingSampler<float[]>()
  263. .CreateCurveSampler()
  264. .GetPoint(t);
  265. TestContext.WriteLine($" Morph Weights: {mw[0]} {mw[1]}");
  266. }
  267. var msw = curves.GetMorphingSampler<Transforms.SparseWeight8>()
  268. .CreateCurveSampler()
  269. .GetPoint(t);
  270. TestContext.WriteLine($" Morph Sparse : {msw.Weight0} {msw.Weight1}");
  271. var triangles = model.DefaultScene
  272. .EvaluateTriangles<Geometry.VertexTypes.VertexPosition, Geometry.VertexTypes.VertexEmpty>(null, anim, t)
  273. .ToList();
  274. var vertices = triangles
  275. .SelectMany(item => new[] { item.A.Position, item.B.Position, item.C.Position })
  276. .Distinct()
  277. .ToList();
  278. foreach (var v in vertices) TestContext.WriteLine($"{v}");
  279. TestContext.WriteLine();
  280. }
  281. }
  282. [Test]
  283. public void LoadMultiUVTexture()
  284. {
  285. var path = TestFiles
  286. .GetSampleModelsPaths()
  287. .FirstOrDefault(item => item.Contains("TextureTransformMultiTest.glb"));
  288. var model = ModelRoot.Load(path);
  289. Assert.That(model, Is.Not.Null);
  290. var materials = model.LogicalMaterials;
  291. var normalTest0Mat = materials.FirstOrDefault(item => item.Name == "NormalTest0Mat");
  292. var normalTest0Mat_normal = normalTest0Mat.FindChannel("Normal").Value;
  293. var normalTest0Mat_normal_xform = normalTest0Mat_normal.TextureTransform;
  294. Assert.That(normalTest0Mat_normal_xform, Is.Not.Null);
  295. }
  296. [Test]
  297. public void FindDependencyFiles()
  298. {
  299. TestContext.CurrentContext.AttachGltfValidatorLinks();
  300. foreach (var f in TestFiles.GetBabylonJSModelsPaths())
  301. {
  302. TestContext.WriteLine(f);
  303. var dependencies = ModelRoot.GetSatellitePaths(f);
  304. foreach(var d in dependencies)
  305. {
  306. TestContext.WriteLine($" {d}");
  307. }
  308. TestContext.WriteLine();
  309. }
  310. }
  311. }
  312. }