Exemple #1
0
    private IEnumerator LoadGLB(byte[] bytes)
    {
        // Define the publiclyVisible=true, otherwise will get an error.
        // https://stackoverflow.com/questions/1646193/why-does-memorystream-getbuffer-always-throw

        Stream stream = new MemoryStream(bytes, 0, bytes.Length, false, true);

        GLTFRoot gLTFRoot;

        GLTFParser.ParseJson(stream, out gLTFRoot);

        Debug.Log("Successfully parsed INIT packet!");

        GLTFSceneImporter loader = new GLTFSceneImporter(gLTFRoot, null, null, stream);

        loader.Collider        = GLTFSceneImporter.ColliderType.Box;
        loader.IsMultithreaded = false;

        loader.LoadSceneAsync().Wait();

        GameObject obj = loader.LastLoadedScene;

        obj.transform.parent = hyperverseRoot.transform;

        Debug.Log("Loaded scene from INIT packet!");

        // TEST:
        ResetSceneGraph();

        yield return(null);
    }
        private GameObject CreateGLTFScene(string projectFilePath)
        {
            ILoader fileLoader = new FileLoader(Path.GetDirectoryName(projectFilePath));

            ;                       using (var stream = File.OpenRead(projectFilePath))
            {
                GLTFRoot gLTFRoot = GLTFParser.ParseJson(stream);
                var      loader   = new GLTFSceneImporter(gLTFRoot, fileLoader, stream);

                loader.MaximumLod = _maximumLod;

                // HACK: Force the coroutine to run synchronously in the editor
                var stack = new Stack <IEnumerator>();
                stack.Push(loader.LoadScene(isMultithreaded: true));

                while (stack.Count > 0)
                {
                    var enumerator = stack.Pop();
                    if (enumerator.MoveNext())
                    {
                        stack.Push(enumerator);
                        var subEnumerator = enumerator.Current as IEnumerator;
                        if (subEnumerator != null)
                        {
                            stack.Push(subEnumerator);
                        }
                    }
                }
                return(loader.LastLoadedScene);
            }
        }
        public async Task LoadKHRSpecGlossGLTFFromStreamUWP()
        {
            StorageFolder localFolder = ApplicationData.Current.LocalFolder;
            StorageFile   sampleFile  = await StorageFile.GetFileFromApplicationUriAsync(new Uri(GLTF_PBR_SPECGLOSS_PATH));


            IRandomAccessStream gltfStream = await sampleFile.OpenAsync(FileAccessMode.Read);

            var reader = new DataReader(gltfStream.GetInputStreamAt(0));
            var bytes  = new byte[gltfStream.Size];
            await reader.LoadAsync((uint)gltfStream.Size);

            reader.ReadBytes(bytes);
            GLTFRoot gltfRoot = GLTFParser.ParseJson(bytes);

            Assert.IsNotNull(gltfRoot.ExtensionsUsed);
            Assert.IsTrue(gltfRoot.ExtensionsUsed.Contains(KHR_materials_pbrSpecularGlossinessExtensionFactory.EXTENSION_NAME));

            Assert.IsNotNull(gltfRoot.Materials);
            Assert.AreEqual(1, gltfRoot.Materials.Count);
            Material materialDef = gltfRoot.Materials[0];
            KHR_materials_pbrSpecularGlossinessExtension specGloss = materialDef.Extensions[KHR_materials_pbrSpecularGlossinessExtensionFactory.EXTENSION_NAME] as KHR_materials_pbrSpecularGlossinessExtension;

            Assert.IsTrue(specGloss != null);

            Assert.AreEqual(Color.White, specGloss.DiffuseFactor);
            Assert.AreEqual(4, specGloss.DiffuseTexture.Index.Id);
            Assert.AreEqual(KHR_materials_pbrSpecularGlossinessExtension.SPEC_FACTOR_DEFAULT, specGloss.SpecularFactor);
            Assert.AreEqual(KHR_materials_pbrSpecularGlossinessExtension.GLOSS_FACTOR_DEFAULT, specGloss.GlossinessFactor);
            Assert.AreEqual(5, specGloss.SpecularGlossinessTexture.Index.Id);
        }
        /// <summary>
        /// Loads via a web call the gltf file and then constructs a scene
        /// </summary>
        /// <param name="sceneIndex">Index into scene to load. -1 means load default</param>
        /// <param name="isMultithreaded">Whether to do loading operation on a thread</param>
        /// <returns></returns>
        public IEnumerator Load(int sceneIndex = -1, bool isMultithreaded = false)
        {
            if (_loadType == LoadType.Uri)
            {
                var www = UnityWebRequest.Get(_gltfUrl);

                yield return(www.Send());

                if (www.responseCode >= 400 || www.responseCode == 0)
                {
                    throw new WebRequestException(www);
                }

                _gltfData = www.downloadHandler.data;
            }
            else if (_loadType == LoadType.Stream)
            {
                // todo optimization: add stream support to parsing layer
                int streamLength = (int)_gltfStream.Length;
                _gltfData = new byte[streamLength];
                _gltfStream.Read(_gltfData, 0, streamLength);
            }
            else
            {
                throw new Exception("Invalid load type specified: " + _loadType);
            }

            _root = GLTFParser.ParseJson(_gltfData);
            yield return(ImportScene(sceneIndex, isMultithreaded));
        }
        /// <summary>
        /// Loads via a web call the gltf file and then constructs a scene
        /// </summary>
        /// <param name="sceneIndex">Index into scene to load. -1 means load default</param>
        /// <param name="isMultithreaded">Whether to do loading operation on a thread</param>
        /// <returns></returns>
        public IEnumerator Load(int sceneIndex = -1, bool isMultithreaded = false)
        {
            if (_loadType == LoadType.Uri)
            {
                var www = UnityWebRequest.Get(_gltfUrl);

#if UNITY_2017_2_OR_NEWER
                yield return(www.SendWebRequest());
#else
                yield return(www.Send());
#endif

                if (www.responseCode >= 400 || www.responseCode == 0)
                {
                    throw new WebRequestException(www);
                }

                byte[] gltfData = www.downloadHandler.data;
                _gltfStream.Stream = new MemoryStream(gltfData, 0, gltfData.Length, false, true);
            }
            else if (_loadType == LoadType.Stream)
            {
                // Do nothing, since the stream was passed in via the constructor.
            }
            else
            {
                throw new Exception("Invalid load type specified: " + _loadType);
            }

            _root = GLTFParser.ParseJson(_gltfStream.Stream, _gltfStream.StartPosition);
            yield return(ImportScene(sceneIndex, isMultithreaded));
        }
Exemple #6
0
        public void CreateAndSaveFromEmptyStream()
        {
            string outPath =
                TestAssetPaths.GetOutPath(TestAssetPaths.GLB_BOX_OUT_PATH_TEMPLATE, 10, TestAssetPaths.GLB_EXTENSION);

            FileStream glbStream = new FileStream(outPath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
            GLBObject  glbObject = GLBBuilder.ConstructFromStream(glbStream);

            Assert.IsNull(glbObject.Root);

            MemoryStream stream = new MemoryStream();
            StreamWriter writer = new StreamWriter(stream);

            writer.Write(TestAssetPaths.MIN_GLTF_STR);
            writer.Flush();
            stream.Position = 0;

            GLTFRoot gltfRoot;

            GLTFParser.ParseJson(stream, out gltfRoot);
            GLBBuilder.SetRoot(glbObject, gltfRoot);

            GLBBuilder.UpdateStream(glbObject);

            glbStream.Close();
            glbStream = new FileStream(outPath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);

            glbObject = GLBBuilder.ConstructFromStream(glbStream);
            Assert.IsNotNull(glbObject.Root);
            glbStream.Close();
        }
Exemple #7
0
        public void GLBSaveWithoutBinary()
        {
            string outPath =
                TestAssetPaths.GetOutPath(TestAssetPaths.GLB_BOX_OUT_PATH_TEMPLATE, 15, TestAssetPaths.GLB_EXTENSION);
            FileStream glbOutStream = new FileStream(outPath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);

            // first create from empty stream
            GLBObject glbObject        = GLBBuilder.ConstructFromStream(glbOutStream);
            uint      initialGLBLength = glbObject.BinaryChunkInfo.Length;

            MemoryStream stream = new MemoryStream();
            StreamWriter writer = new StreamWriter(stream);

            writer.Write(TestAssetPaths.MIN_GLTF_STR);
            writer.Flush();
            stream.Position = 0;

            GLTFRoot newRoot;

            GLTFParser.ParseJson(stream, out newRoot);
            GLBBuilder.SetRoot(glbObject, newRoot);
            GLBBuilder.UpdateStream(glbObject);
            Assert.AreEqual(glbObject.Header.FileLength, glbObject.JsonChunkInfo.StartPosition + glbObject.JsonChunkInfo.Length + GLTFParser.CHUNK_HEADER_SIZE);
            glbOutStream.Close();
            glbOutStream = new FileStream(outPath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
            List <ChunkInfo> chunks = GLTFParser.FindChunks(glbOutStream);

            Assert.AreEqual(1, chunks.Count);

            glbOutStream.Position = 0;
            GLBObject testObject = GLBBuilder.ConstructFromStream(glbOutStream);

            Assert.AreEqual(glbObject.JsonChunkInfo.Length, testObject.JsonChunkInfo.Length);
            Assert.AreEqual(glbObject.BinaryChunkInfo.Length, testObject.BinaryChunkInfo.Length);
        }
Exemple #8
0
        public void LoadKHRSpecGlossGLTFFromStream()
        {
            Assert.IsTrue(File.Exists(GLTF_PBR_SPECGLOSS_PATH));
            FileStream gltfStream = File.OpenRead(GLTF_PBR_SPECGLOSS_PATH);

            GLTFRoot gltfRoot;

            GLTFParser.ParseJson(gltfStream, out gltfRoot);

            Assert.IsNotNull(gltfRoot.ExtensionsUsed);
            Assert.IsTrue(gltfRoot.ExtensionsUsed.Contains(KHR_materials_pbrSpecularGlossinessExtensionFactory.EXTENSION_NAME));

            Assert.IsNotNull(gltfRoot.Materials);
            Assert.AreEqual(1, gltfRoot.Materials.Count);
            GLTFMaterial materialDef = gltfRoot.Materials[0];
            KHR_materials_pbrSpecularGlossinessExtension specGloss = materialDef.Extensions[KHR_materials_pbrSpecularGlossinessExtensionFactory.EXTENSION_NAME] as KHR_materials_pbrSpecularGlossinessExtension;

            Assert.IsTrue(specGloss != null);

            Assert.AreEqual(Color.White, specGloss.DiffuseFactor);
            Assert.AreEqual(4, specGloss.DiffuseTexture.Index.Id);
            Assert.AreEqual(KHR_materials_pbrSpecularGlossinessExtension.SPEC_FACTOR_DEFAULT, specGloss.SpecularFactor);
            Assert.AreEqual(KHR_materials_pbrSpecularGlossinessExtension.GLOSS_FACTOR_DEFAULT, specGloss.GlossinessFactor);
            Assert.AreEqual(5, specGloss.SpecularGlossinessTexture.Index.Id);
        }
Exemple #9
0
        public void LoadGLBFromStream()
        {
            Assert.IsTrue(File.Exists(GLB_PATH));
            FileStream gltfStream = File.OpenRead(GLB_PATH);
            GLTFRoot   gltfRoot   = GLTFParser.ParseJson(gltfStream);

            GLTFJsonLoadTestHelper.TestGLB(gltfRoot);
        }
Exemple #10
0
        // todo undo
#if !WINDOWS_UWP
        IEnumerator Start()
        {
            var     fullPath0 = Application.streamingAssetsPath + Path.DirectorySeparatorChar + asset0Path;
            ILoader loader0   = new FileLoader(URIHelper.GetDirectoryName(fullPath0));

            var     fullPath1 = Application.streamingAssetsPath + Path.DirectorySeparatorChar + asset1Path;
            ILoader loader1   = new FileLoader(URIHelper.GetDirectoryName(fullPath1));

            yield return(loader0.LoadStream(Path.GetFileName(asset0Path)));

            var asset0Stream = loader0.LoadedStream;
            var asset0Root   = GLTFParser.ParseJson(asset0Stream);

            yield return(loader1.LoadStream(Path.GetFileName(asset1Path)));

            var asset1Stream = loader1.LoadedStream;
            var asset1Root   = GLTFParser.ParseJson(asset1Stream);

            string newPath = "../../" + URIHelper.GetDirectoryName(asset0Path);

            int previousBufferCount  = asset1Root.Buffers.Count;
            int previousImageCount   = asset1Root.Images.Count;
            int previousSceneCounter = asset1Root.Scenes.Count;

            GLTFHelpers.MergeGLTF(asset1Root, asset0Root);

            for (int i = previousBufferCount; i < asset1Root.Buffers.Count; ++i)
            {
                GLTF.Schema.Buffer buffer = asset1Root.Buffers[i];
                if (!URIHelper.IsBase64Uri(buffer.Uri))
                {
                    buffer.Uri = newPath + buffer.Uri;
                }
            }

            for (int i = previousImageCount; i < asset1Root.Images.Count; ++i)
            {
                Image image = asset1Root.Images[i];
                if (!URIHelper.IsBase64Uri(image.Uri))
                {
                    image.Uri = newPath + image.Uri;
                }
            }

            foreach (NodeId node in asset1Root.Scenes[asset0Root.Scene.Id + previousSceneCounter].Nodes)
            {
                node.Value.Translation.X += 5f;
                asset1Root.Scene.Value.Nodes.Add(node);
            }
            GLTFSceneImporter importer = new GLTFSceneImporter(
                asset1Root,
                loader1
                );

            importer.MaximumLod = MaximumLod;

            yield return(importer.LoadScene(-1, Multithreaded));
        }
    private void Load(Stream stream)
    {
        GLTFRoot gLTFRoot;

        GLTFParser.ParseJson(stream, out gLTFRoot);
        var loader = new GLTFSceneImporter(gLTFRoot, null, null, stream);

        loader.LoadSceneAsync();
    }
    IEnumerator Start()
    {
        var timer = new System.Diagnostics.Stopwatch();

        var csv = new StringBuilder();

        csv.AppendLine("Name, Time (ms)");

        Debug.Log("Start Parsing Benchmark.");

        foreach (var gltfUrl in GLTFUrls)
        {
            var www = UnityWebRequest.Get(gltfUrl);

#if UNITY_2017_2_OR_NEWER
            yield return(www.SendWebRequest());
#else
            yield return(www.Send());
#endif

            Debug.LogFormat("Benchmarking: {0}", gltfUrl);
            long totalTime = 0;
            for (var i = 0; i < NumberOfIterations; i++)
            {
                timer.Start();
                GLTFRoot gltfRoot = null;
                GLTFParser.ParseJson(new MemoryStream(www.downloadHandler.data), out gltfRoot);
                timer.Stop();

                Debug.LogFormat("Iteration {0} took: {1}ms", i, timer.ElapsedMilliseconds);
                totalTime += timer.ElapsedMilliseconds;
            }

            var avgTime = (float)totalTime / NumberOfIterations;
            Debug.LogFormat("Average parse time {0}ms", avgTime);
            csv.AppendFormat("{0}, {1}\n", gltfUrl, avgTime);
        }



        Debug.Log("End Parsing Benchmark.");

        Debug.Log("Done.");

        if (SaveCSV)
        {
            var fileName = string.Format("glTFBench_{0}iter", NumberOfIterations);
            var path     = EditorUtility.SaveFilePanel("Save GLTF Benchmark .csv", "", fileName, "csv");

            if (path != null)
            {
                File.WriteAllText(path, csv.ToString());
                Debug.LogFormat("Benchmark written to: {0}", path);
            }
        }
    }
Exemple #13
0
        public void LoadGLTFFromStream()
        {
            Assert.IsTrue(File.Exists(GLTF_PATH));
            FileStream gltfStream = File.OpenRead(GLTF_PATH);

            GLTFRoot.RegisterExtension(new TestExtensionFactory());
            GLTFRoot gltfRoot = GLTFParser.ParseJson(gltfStream);

            GLTFJsonLoadTestHelper.TestGLTF(gltfRoot);
        }
Exemple #14
0
        public void Initialize()
        {
            MemoryStream stream = new MemoryStream();
            StreamWriter writer = new StreamWriter(stream);

            writer.Write(testStr);
            writer.Flush();
            stream.Position = 0;

            _testRoot = GLTFParser.ParseJson(stream);
        }
Exemple #15
0
        public async Task LoadGLTFFromStreamUWP()
        {
            StorageFolder localFolder = ApplicationData.Current.LocalFolder;
            StorageFile   sampleFile  = await StorageFile.GetFileFromApplicationUriAsync(new Uri(GLTF_PATH));

            IRandomAccessStream gltfStream = await sampleFile.OpenAsync(FileAccessMode.Read);

            GLTFRoot gltfRoot = GLTFParser.ParseJson(gltfStream.AsStream());

            GLTFJsonLoadTestHelper.TestGLTF(gltfRoot);
        }
Exemple #16
0
        private GameObject CreateGLTFScene(string projectFilePath)
        {
            ILoader fileLoader = new FileLoader(Path.GetDirectoryName(projectFilePath));

            using (var stream = File.OpenRead(projectFilePath))
            {
                GLTFRoot gLTFRoot;
                GLTFParser.ParseJson(stream, out gLTFRoot);

                OnGLTFRootIsConstructed?.Invoke(gLTFRoot);

                var loader = new GLTFSceneImporter(Path.GetFullPath(projectFilePath), gLTFRoot, fileLoader, null, stream);
                GLTFSceneImporter.budgetPerFrameInMilliseconds = float.MaxValue;
                loader.addImagesToPersistentCaching            = false; // Since we control the PersistentAssetCache during AB Conversion, we don't want the importer to mess with that
                loader.addMaterialsToPersistentCaching         = false;
                loader.initialVisibility     = true;
                loader.useMaterialTransition = false;
                loader.maximumLod            = _maximumLod;
                loader.isMultithreaded       = true;

                OnGLTFWillLoad?.Invoke(loader);

                // HACK: Force the coroutine to run synchronously in the editor
                var stack = new Stack <IEnumerator>();
                stack.Push(loader.LoadScene());

                while (stack.Count > 0)
                {
                    var enumerator = stack.Pop();

                    try
                    {
                        if (enumerator.MoveNext())
                        {
                            stack.Push(enumerator);
                            var subEnumerator = enumerator.Current as IEnumerator;
                            if (subEnumerator != null)
                            {
                                stack.Push(subEnumerator);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Debug.Log("GLTFImporter - CreateGLTFScene Failed: " + e.Message + "\n" + e.StackTrace);
                    }
                }

                return(loader.lastLoadedScene);
            }
        }
        public void TestMinimumGLTF()
        {
            var testStr = @"
			{
				""asset"": {
					""version"": ""2.0""
				}
			}
		"        ;

            var testRoot = GLTFParser.ParseJson(Encoding.ASCII.GetBytes(testStr));

            Assert.AreEqual(testRoot.Asset.Version, "2.0");
        }
Exemple #18
0
        public void LoadGLBFromStream()
        {
            Assert.IsTrue(File.Exists(GLB_PATH));
            FileStream gltfStream = File.OpenRead(GLB_PATH);

            // todo: this code does not work if file is greater than 4 gb
            int streamLength = (int)gltfStream.Length;

            byte[] gltfData = new byte[streamLength];
            gltfStream.Read(gltfData, 0, streamLength);

            GLTFRoot gltfRoot = GLTFParser.ParseJson(gltfData);

            GLTFJsonLoadTestHelper.TestGLB(gltfRoot);
        }
        private GameObject CreateGLTFScene(string projectFilePath)
        {
            ILoader fileLoader = new FileLoader(Path.GetDirectoryName(projectFilePath));

            using (var stream = File.OpenRead(projectFilePath))
            {
                GLTFRoot gLTFRoot;
                GLTFParser.ParseJson(stream, out gLTFRoot);
                var loader = new GLTFSceneImporter(gLTFRoot, fileLoader, null, stream);
                loader.MaximumLod      = _maximumLod;
                loader.IsMultithreaded = true;

                loader.LoadSceneAsync().Wait();
                return(loader.LastLoadedScene);
            }
        }
        public void MergeNodes()
        {
            Assert.IsTrue(File.Exists(GLTF_BOOMBOX_PATH));
            Assert.IsTrue(File.Exists(GLTF_LANTERN_PATH));

            FileStream gltfBoomBoxStream = File.OpenRead(GLTF_BOOMBOX_PATH);
            GLTFRoot   boomBoxRoot;

            GLTFParser.ParseJson(gltfBoomBoxStream, out boomBoxRoot);

            FileStream gltfLanternStream = File.OpenRead(GLTF_LANTERN_PATH);
            GLTFRoot   lanternRoot;

            GLTFParser.ParseJson(gltfLanternStream, out lanternRoot);

            GLTFRoot boomBoxCopy = new GLTFRoot(boomBoxRoot);

            GLTFHelpers.MergeGLTF(boomBoxRoot, lanternRoot);

            Assert.AreNotEqual(boomBoxRoot.Nodes, boomBoxCopy.Nodes);

            Assert.AreNotEqual(boomBoxCopy.Accessors.Count, boomBoxRoot.Accessors.Count);
            Assert.AreNotEqual(boomBoxCopy.Meshes.Count, boomBoxRoot.Meshes.Count);
            Assert.AreNotEqual(boomBoxCopy.Nodes.Count, boomBoxRoot.Nodes.Count);
            Assert.AreNotEqual(boomBoxCopy.BufferViews.Count, boomBoxRoot.BufferViews.Count);
            Assert.AreNotEqual(boomBoxCopy.Buffers.Count, boomBoxRoot.Buffers.Count);
            Assert.AreNotEqual(boomBoxCopy.Images.Count, boomBoxRoot.Images.Count);
            Assert.AreNotEqual(boomBoxCopy.Materials.Count, boomBoxRoot.Materials.Count);
            Assert.AreNotEqual(boomBoxCopy.Textures.Count, boomBoxRoot.Textures.Count);
            Assert.AreNotEqual(boomBoxCopy.Scenes.Count, boomBoxRoot.Scenes.Count);

            Assert.AreEqual(boomBoxCopy.Accessors.Count + lanternRoot.Accessors.Count, boomBoxRoot.Accessors.Count);
            Assert.AreEqual(boomBoxCopy.Meshes.Count + lanternRoot.Meshes.Count, boomBoxRoot.Meshes.Count);
            Assert.AreEqual(boomBoxCopy.Nodes.Count + lanternRoot.Nodes.Count, boomBoxRoot.Nodes.Count);
            Assert.AreEqual(boomBoxCopy.BufferViews.Count + lanternRoot.BufferViews.Count, boomBoxRoot.BufferViews.Count);
            Assert.AreEqual(boomBoxCopy.Buffers.Count + lanternRoot.Buffers.Count, boomBoxRoot.Buffers.Count);
            Assert.AreEqual(boomBoxCopy.Images.Count + lanternRoot.Images.Count, boomBoxRoot.Images.Count);
            Assert.AreEqual(boomBoxCopy.Materials.Count + lanternRoot.Materials.Count, boomBoxRoot.Materials.Count);
            Assert.AreEqual(boomBoxCopy.Textures.Count + lanternRoot.Textures.Count, boomBoxRoot.Textures.Count);
            Assert.AreEqual(boomBoxCopy.Scenes.Count + lanternRoot.Scenes.Count, boomBoxRoot.Scenes.Count);

            // test no throw
            StringWriter stringWriter = new StringWriter();

            boomBoxRoot.Serialize(stringWriter);
        }
        public async Task LoadGLTFFromStreamUWP()
        {
            StorageFolder localFolder = ApplicationData.Current.LocalFolder;
            StorageFile   sampleFile  = await StorageFile.GetFileFromApplicationUriAsync(new Uri(GLTF_PATH));


            IRandomAccessStream gltfStream = await sampleFile.OpenAsync(FileAccessMode.Read);

            var reader = new DataReader(gltfStream.GetInputStreamAt(0));
            var bytes  = new byte[gltfStream.Size];
            await reader.LoadAsync((uint)gltfStream.Size);

            reader.ReadBytes(bytes);
            GLTFRoot gltfRoot = GLTFParser.ParseJson(bytes);

            GLTFJsonLoadTestHelper.TestGLTF(gltfRoot);
        }
Exemple #22
0
        static void Main(string[] args)
        {
            Console.WriteLine("GLTFSerialization CLI");
            if (args.Length == 0)
            {
                Console.WriteLine("Usage:");
                Console.WriteLine("  GLTFSerializationCLI [gltf_file]");

                goto exit;
            }

            Stream stream;

            try
            {
                stream = System.IO.File.OpenRead(args[0]);
            }
            catch (DirectoryNotFoundException)
            {
                Console.WriteLine("Directory not found");
                goto exit;
            }
            catch (FileNotFoundException)
            {
                Console.WriteLine("File not found");
                goto exit;
            }

            GLTFRoot root;

            GLTFParser.ParseJson(stream, out root);
            ExtTextureTransformExtension ext = (ExtTextureTransformExtension)
                                               root.Materials[1].PbrMetallicRoughness.BaseColorTexture.Extensions["EXT_texture_transform"];

            root.Serialize(Console.Out);
            Console.WriteLine();

exit:
            if (System.Diagnostics.Debugger.IsAttached)
            {
                Console.WriteLine("Press Enter to exit...");
                Console.ReadLine();
            }
        }
Exemple #23
0
        public void CreateGLBFromStream()
        {
            Assert.IsTrue(File.Exists(TestAssetPaths.GLB_BOOMBOX_PATH));
            FileStream glbStream    = File.OpenRead(TestAssetPaths.GLB_BOOMBOX_PATH);
            FileStream glbOutStream = File.Create(TestAssetPaths.GLB_BOOMBOX_OUT_PATH);
            GLBObject  glbObject    = GLBBuilder.ConstructFromStream(glbStream, glbOutStream);

            Assert.IsNotNull(glbObject.Root);
            Assert.IsNotNull(glbObject.Stream);
            Assert.AreEqual(0, glbObject.StreamStartPosition);
            Assert.AreEqual(GLTFParser.HEADER_SIZE, glbObject.JsonChunkInfo.StartPosition);
            Assert.AreEqual(glbStream.Length, glbObject.Header.FileLength);

            glbOutStream.Position = 0;
            GLTFRoot glbOutRoot;

            GLTFParser.ParseJson(glbOutStream, out glbOutRoot);
            GLTFJsonLoadTestHelper.TestGLB(glbOutRoot);
        }
Exemple #24
0
        private GameObject CreateGLTFScene(string projectFilePath)
        {
            var importOptions = new ImportOptions
            {
                DataLoader = new FileLoader(Path.GetDirectoryName(projectFilePath)),
            };

            using (var stream = File.OpenRead(projectFilePath))
            {
                GLTFRoot gLTFRoot;
                GLTFParser.ParseJson(stream, out gLTFRoot);
                stream.Position = 0;                 // Make sure the read position is changed back to the beginning of the file
                var loader = new GLTFSceneImporter(gLTFRoot, stream, importOptions);
                loader.MaximumLod      = _maximumLod;
                loader.IsMultithreaded = true;

                loader.LoadSceneAsync().Wait();
                return(loader.LastLoadedScene);
            }
        }
        private GameObject CreateGLTFScene(string projectFilePath)
        {
            ILoader fileLoader = new FileLoader(Path.GetDirectoryName(projectFilePath));

            using (var stream = File.OpenRead(projectFilePath))
            {
                GLTFRoot gLTFRoot;
                GLTFParser.ParseJson(stream, out gLTFRoot);

                OnGLTFRootIsConstructed?.Invoke(gLTFRoot);

                var loader = new GLTFSceneImporter(Path.GetFullPath(projectFilePath), gLTFRoot, fileLoader, null, stream);
                GLTFSceneImporter.budgetPerFrameInMilliseconds = float.MaxValue;
                loader.addImagesToPersistentCaching            = false;
                loader.addMaterialsToPersistentCaching         = false;
                loader.initialVisibility     = true;
                loader.useMaterialTransition = false;
                loader.maximumLod            = _maximumLod;
                loader.isMultithreaded       = true;

                // HACK: Force the coroutine to run synchronously in the editor
                var stack = new Stack <IEnumerator>();
                stack.Push(loader.LoadScene());

                while (stack.Count > 0)
                {
                    var enumerator = stack.Pop();
                    if (enumerator.MoveNext())
                    {
                        stack.Push(enumerator);
                        var subEnumerator = enumerator.Current as IEnumerator;
                        if (subEnumerator != null)
                        {
                            stack.Push(subEnumerator);
                        }
                    }
                }

                return(loader.lastLoadedScene);
            }
        }
Exemple #26
0
        public void UpdateStream()
        {
            Assert.IsTrue(File.Exists(TestAssetPaths.GLB_BOOMBOX_PATH));
            FileStream glbStream = File.OpenRead(TestAssetPaths.GLB_BOOMBOX_PATH);
            string     outPath   =
                TestAssetPaths.GetOutPath(TestAssetPaths.GLB_BOX_OUT_PATH_TEMPLATE, 0, TestAssetPaths.GLB_EXTENSION);
            FileStream glbOutStream = new FileStream(outPath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
            GLBObject  glbObject    = GLBBuilder.ConstructFromStream(glbStream, glbOutStream);

            for (int i = 0; i < 10; ++i)
            {
                glbObject.Root.Nodes.Add(new Node
                {
                    Mesh = new MeshId
                    {
                        Id   = 0,
                        Root = glbObject.Root
                    }
                });
            }

            GLBBuilder.UpdateStream(glbObject);
            glbOutStream.Position = 0;

            GLTFRoot glbOutRoot;

            GLTFParser.ParseJson(glbOutStream, out glbOutRoot);
            FileStream glbFileStream = glbObject.Stream as FileStream;

            Assert.AreEqual(glbFileStream, glbFileStream);
            glbOutStream.Position = 0;
            List <ChunkInfo> chunkInfo = GLTFParser.FindChunks(glbOutStream);

            Assert.AreEqual(2, chunkInfo.Count);
            CompareBinaryData(glbObject, glbStream);
        }
Exemple #27
0
        public void CreateEmptyStreamAndAppendGLB()
        {
            string outPath =
                TestAssetPaths.GetOutPath(TestAssetPaths.GLB_BOX_OUT_PATH_TEMPLATE, 11, TestAssetPaths.GLB_EXTENSION);

            FileStream glbStream = new FileStream(outPath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
            GLBObject  glbObject = GLBBuilder.ConstructFromStream(glbStream);

            Assert.IsNull(glbObject.Root);

            MemoryStream stream = new MemoryStream();
            StreamWriter writer = new StreamWriter(stream);

            writer.Write(TestAssetPaths.MIN_GLTF_STR);
            writer.Flush();
            stream.Position = 0;

            GLTFRoot gltfRoot;

            GLTFParser.ParseJson(stream, out gltfRoot);
            GLBBuilder.SetRoot(glbObject, gltfRoot);
            GLBBuilder.UpdateStream(glbObject);

            FileStream glbAppendStream = File.OpenRead(TestAssetPaths.GLB_BOOMBOX_PATH);
            GLBObject  glbAppendObject = GLBBuilder.ConstructFromStream(glbAppendStream);

            GLBBuilder.AddBinaryData(glbObject, glbAppendStream, false, glbAppendObject.BinaryChunkInfo.StartPosition + GLTFParser.CHUNK_HEADER_SIZE);

            glbStream.Close();
            glbStream = new FileStream(outPath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);

            glbObject = GLBBuilder.ConstructFromStream(glbStream);
            Assert.IsNotNull(glbObject.Root);
            Assert.AreEqual(glbAppendObject.BinaryChunkInfo.Length, glbObject.BinaryChunkInfo.Length);
            glbStream.Close();
        }
Exemple #28
0
        /// <summary>
        /// Loads via a web call the gltf file and then constructs a scene
        /// </summary>
        /// <param name="sceneIndex">Index into scene to load. -1 means load default</param>
        /// <param name="isMultithreaded">Whether to do loading operation on a thread</param>
        /// <returns></returns>
        public IEnumerator Load(int sceneIndex = -1, bool isMultithreaded = false)
        {
            if (_loadType == LoadType.Uri)
            {
                var www = UnityWebRequest.Get(_gltfUrl);

                yield return(www.Send());

                if (www.responseCode >= 400 || www.responseCode == 0)
                {
                    throw new WebRequestException(www);
                }

                byte[] gltfData = www.downloadHandler.data;
                _gltfStream.Stream = new MemoryStream(gltfData, 0, gltfData.Length, false, true);
            }
            else
            {
                throw new Exception("Invalid load type specified: " + _loadType);
            }

            _root = GLTFParser.ParseJson(_gltfStream.Stream, _gltfStream.StartPosition);
            yield return(ImportScene(sceneIndex, isMultithreaded));
        }
Exemple #29
0
        /// <summary>
        /// Parses a GLTF and populates a List<ContentServerUtils.MappingPair> with its dependencies
        /// </summary>
        /// <param name="assetHash">The asset's content server hash</param>
        /// <param name="assetFilename">The asset's content server file name</param>
        /// <param name="sceneCid">The asset scene ID</param>
        /// <param name="mappingPairsList">The reference of a list where the dependency mapping pairs will be added</param>
        public void GetAssetDependenciesMappingPairs(string assetHash, string assetFilename, string sceneCid, ref List <ContentServerUtils.MappingPair> mappingPairsList)
        {
            // 1. Get all dependencies
            List <AssetPath> gltfPaths = ABConverter.Utils.GetPathsFromPairs(finalDownloadedPath, new []
            {
                new ContentServerUtils.MappingPair
                {
                    file = assetFilename,
                    hash = assetHash
                }
            }, Config.gltfExtensions);

            // Disable editor assets auto-import temporarily to avoid Unity trying to import the GLTF on its own, when we know dependencies haven't been downloaded yet
            AssetDatabase.StartAssetEditing();

            string path = DownloadAsset(gltfPaths[0]);

            if (string.IsNullOrEmpty(path))
            {
                log.Error("Core - GetAssetDependenciesMappingPairs() - Invalid target asset data! aborting dependencies population");
                return;
            }

            log.Info($"Core - GetAssetDependenciesMappingPairs() -> path: {path}," +
                     $"\n file: {gltfPaths[0].file}," +
                     $"\n hash: {gltfPaths[0].hash}," +
                     $"\n pair: {gltfPaths[0].pair}, " +
                     $"\n basePath: {gltfPaths[0].basePath}," +
                     $"\n finalPath: {gltfPaths[0].finalPath}," +
                     $"\n finalMetaPath: {gltfPaths[0].finalMetaPath}");

            // 2. Search for dependencies hashes in scene mappings and add them to the collection
            using (var stream = File.OpenRead(path))
            {
                GLTFRoot gLTFRoot;
                GLTFParser.ParseJson(stream, out gLTFRoot);

                ContentServerUtils.MappingsAPIData parcelInfoApiData = ABConverter.Utils.GetSceneMappingsData(env.webRequest, settings.tld, sceneCid);

                if (gLTFRoot.Buffers != null)
                {
                    foreach (var asset in gLTFRoot.Buffers)
                    {
                        if (string.IsNullOrEmpty(asset.Uri))
                        {
                            continue;
                        }

                        mappingPairsList.AddRange(parcelInfoApiData.data[0].content.contents.Where(x => x.file.Contains(asset.Uri)).ToArray());

                        log.Info("Core - GetAssetDependenciesMappingPairs - Buffers -> Searching for... uri: " + asset.Uri + " -> name: " + asset.Name);
                    }
                }

                if (gLTFRoot.Images != null)
                {
                    foreach (var asset in gLTFRoot.Images)
                    {
                        if (string.IsNullOrEmpty(asset.Uri))
                        {
                            continue;
                        }
                        mappingPairsList.AddRange(parcelInfoApiData.data[0].content.contents.Where(x => x.file.Contains(asset.Uri)).ToArray());

                        log.Info("Core - GetAssetDependenciesMappingPairs - Images -> uri: " + asset.Uri + " -> name: " + asset.Name);
                    }
                }
            }

            // 3. Remove temporary GLTF file and re-enable editor assets auto-import
            File.Delete(path);
            AssetDatabase.StopAssetEditing();
        }
 private void LoadFile(int sceneIndex = -1)
 {
     _glTFData = File.ReadAllBytes(_glTFPath);
     _root     = GLTFParser.ParseJson(_glTFData);
 }