Explorar el Código

Add animationStartMode and update documentation for glTF loader

Gary Hsu hace 7 años
padre
commit
9c24a5c7c2

+ 28 - 22
loaders/src/glTF/2.0/babylon.glTFLoader.ts

@@ -272,22 +272,36 @@ module BABYLON.GLTF2 {
             return skeletons;
         }
 
-        private _getAnimationTargets(): any[] {
-            const targets = new Array();
-
+        private _startAnimations(): void {
             const animations = this._gltf.animations;
-            if (animations) {
-                for (const animation of animations) {
-                    targets.push(...animation.targets);
-                }
+            if (!animations) {
+                return;
             }
 
-            return targets;
-        }
-
-        private _startAnimations(): void {
-            for (const target of this._getAnimationTargets()) { 
-                this._babylonScene.beginAnimation(target, 0, Number.MAX_VALUE, true);
+            switch (this._parent.animationStartMode) {
+                case GLTFLoaderAnimationStartMode.NONE: {
+                    // do nothing
+                    break;
+                }
+                case GLTFLoaderAnimationStartMode.FIRST: {
+                    const animation = animations[0];
+                    for (const target of animation.targets) {
+                        this._babylonScene.beginAnimation(target, 0, Number.MAX_VALUE, true);
+                    }
+                    break;
+                }
+                case GLTFLoaderAnimationStartMode.ALL: {
+                    for (const animation of animations) {
+                        for (const target of animation.targets) {
+                            this._babylonScene.beginAnimation(target, 0, Number.MAX_VALUE, true);
+                        }
+                    }
+                    break;
+                }
+                default: {
+                    Tools.Error("Invalid animation start mode " + this._parent.animationStartMode);
+                    return;
+                }
             }
         }
 
@@ -312,10 +326,6 @@ module BABYLON.GLTF2 {
                     }
                     break;
                 }
-                case GLTFLoaderCoordinateSystemMode.PASS_THROUGH: {
-                    // do nothing
-                    break;
-                }
                 case GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
                     this._babylonScene.useRightHandedSystem = true;
                     break;
@@ -346,6 +356,7 @@ module BABYLON.GLTF2 {
                 this._traverseNodes(context, nodeIndices, node => {
                     if (nodeNames.indexOf(node.name) !== -1) {
                         filteredNodeIndices.push(node.index);
+                        node.parent = this._rootNode;
                         return false;
                     }
 
@@ -1703,11 +1714,6 @@ module BABYLON.GLTF2 {
         }
 
         private _compileMaterialAsync(babylonMaterial: Material, babylonMesh: AbstractMesh, onSuccess: () => void): void {
-            if (!this._parent.compileMaterials) {
-                onSuccess();
-                return;
-            }
-
             if (this._parent.useClipPlane) {
                 babylonMaterial.forceCompilation(babylonMesh, () => {
                     babylonMaterial.forceCompilation(babylonMesh, () => {

+ 131 - 52
loaders/src/glTF/README.md

@@ -1,17 +1,16 @@
 # Babylon.js glTF File Loader
 
-# Usage
 The glTF file loader is a SceneLoader plugin.
 
-[glTF2 Playground example](http://www.babylonjs-playground.com/#6MZV8R)
+[Simple Playground Example](http://www.babylonjs-playground.com/#2IK4U7)
 
-## Step 1 - Include the glTF File Loader
+## Setup
 
 **Full Version**
 
 This loader supports both glTF 1.0 and 2.0 and will use the correct loader based on the glTF version string.
 
-```
+```HTML
 <script src="babylon.js"></script>
 <script src="babylon.glTFFileLoader.js"></script>
 ```
@@ -20,7 +19,7 @@ This loader supports both glTF 1.0 and 2.0 and will use the correct loader based
 
 This loader supports only glTF 1.0 and will fail to load glTF 2.0.
 
-```
+```HTML
 <script src="babylon.js"></script>
 <script src="babylon.glTF1FileLoader.js"></script>
 ```
@@ -29,75 +28,155 @@ This loader supports only glTF 1.0 and will fail to load glTF 2.0.
 
 This loader supports only glTF 2.0 and will fail to load glTF 1.0.
 
-```
+```HTML
 <script src="babylon.js"></script>
 <script src="babylon.glTF2FileLoader.js"></script>
 ```
 
-## Step 2 - Call the Scene Loader
+## Loading the Scene
+The Load function loads a glTF asset into a new scene.
+```JavaScript
+BABYLON.SceneLoader.Load("./", "duck.gltf", engine, function (scene) {
+    // do something with the scene
+});
 ```
-BABYLON.SceneLoader.Load("./", "duck.gltf", engine, function (scene) { 
-   // do somethings with the scene
+
+The Append function appends a glTF file to an existing scene.
+```JavaScript
+BABYLON.SceneLoader.Append("./", "duck.gltf", scene, function (scene) {
+    // do something with the scene
 });
 ```
 
-You can also call the ImportMesh function and import specific meshes
+The ImportMesh function imports specific meshes from a glTF asset to an existing scene and returns the imported meshes and skeletons.
+```JavaScript
+// The first parameter can be set to null to load all meshes and skeletons
+BABYLON.SceneLoader.ImportMesh(["myMesh1", "myMesh2"], "./", "duck.gltf", scene, function (meshes, particleSystems, skeletons) {
+    // do something with the meshes and skeletons
+    // particleSystems are always null for glTF assets
+});
 ```
-// meshesNames can be set to "null" to load all meshes and skeletons
-BABYLON.SceneLoader.ImportMesh(["myMesh1", "myMesh2", "..."], "./", "duck.gltf", scene, function (meshes, particleSystems, skeletons) { 
-   // do somethings with the meshes, particleSystems (not handled in glTF files) and skeletons
+
+## Advanced
+
+The SceneLoader returns the glTF loader instance to enable setting properties per instance.
+
+```JavaScript
+var loader = BABYLON.SceneLoader.Load("./", "duck.gltf", engine, function (scene) {
+    // do something with the scene
 });
+
+// do something with the loader
+// loader.<option1> = <...>
+// loader.<option2> = <...>
+// loader.dispose();
 ```
 
-You can also append a glTF file to a scene. When using `SceneLoader.Append`, configure the scene to use right handed system by setting the property `useRightHandedSystem` to true. 
+#### onParsed
+Raised when the asset has been parsed. The `data.json` property stores the glTF JSON. The `data.bin` property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
 
+```JavaScript
+loader.onParsed = function (data) {
+    // do something with the data
+};
 ```
-// glTF Files use right handed system 
-scene.useRightHandedSystem = true;
 
-// Append sample glTF model to scene
-BABYLON.SceneLoader.Append("https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Models/master/2.0/BoomBox/glTF/", "BoomBox.gltf", scene, function (scene) {
-}, null, function (scene) {
-    alert("error");
-});
+### Version 1 Only
+
+#### IncrementalLoading
+Set this property to false to disable incremental loading which delays the loader from calling the success callback until after loading the meshes and shaders. Textures always loads asynchronously. For example, the success callback can compute the bounding information of the loaded meshes when incremental loading is disabled. Defaults to true.
+
+```JavaScript
+BABYLON.GLTFFileLoader.IncrementalLoading = false;
+```
+
+#### HomogeneousCoordinates
+Set this property to true in order to work with homogeneous coordinates, available with some converters and exporters. Defaults to false.
+
+```JavaScript
+BABYLON.GLTFFileLoader.HomogeneousCoordinates = true;
+```
+
+### Version 2 Only
+
+#### coordinateSystemMode
+The coordinate system mode (AUTO, FORCE_RIGHT_HANDED). Defaults to AUTO.
+
+```JavaScript
+loader.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED;
 ```
 
-## Step 3 (V1 Only) - Optionally Specify Flags
+#### animationStartMode
+The animation start mode (NONE, FIRST, ALL). Defaults to FIRST.
 
-If you want to disable incremental loading, you can set the property `IncrementalLoading` to false.
-Then, you'll be able to be called back with all geometries and shaders loaded. Textures are always loaded asynchronously. For example, you can retrieve the real bounding infos of a mesh loaded when incremental loading is disabled.
+```JavaScript
+loader.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.NONE;
 ```
-BABYLON.GLTFFileLoader.IncrementalLoading = false; // true by default
+
+#### compileMaterials
+Set to true to compile materials before raising the success callback. Defaults to false.
+
+```JavaScript
+loader.compileMaterials = true;
+```
+
+#### useClipPlane
+Set to true to also compile materials with clip planes. Defaults to false.
+
+```JavaScript
+loader.useClipPlane = true;
 ```
 
-In order to work with homogeneous coordinates (that can be available with some converters and exporters):
+#### compileShadowGenerators
+Set to true to compile shadow generators before raising the success callback. Defaults to false.
+
+```JavaScript
+loader.compileShadowGenerators = true;
 ```
-BABYLON.GLTFFileLoader.HomogeneousCoordinates = true; // false by default
+
+#### onMeshLoaded
+Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
+
+```JavaScript
+loader.onMeshLoaded = function (mesh) {
+    // do something with the mesh
+};
 ```
 
-# Supported Features
-* Load scenes (SceneLoader.Load and SceneLoader.Append)
-* Support of ImportMesh function
-* Import geometries
-    * From binary files
-    * From base64 buffers
-* Import lights (V1 only)
-* Import cameras
-* Import and set custom shaders (V1 only)
-    * Automatically bind attributes
-    * Automatically bind matrices
-    * Set uniforms
-* Import and set animations
-* Skinning (BETA, sometimes wrong on tricky models)
-    * Skeletons
-    * Hardware skinning (shaders support)
-    * Bones import
-* Handle dummy nodes (empty nodes)
-* PBR materials (V2 only)
+#### onTextureLoaded
+Raised when the loader creates a texture 
+after parsing the glTF properties of the texture.
 
-# Future Improvements
-* Test on more geometries
-* Test on more animated models
-* Test on more skinned models
-* Improve shaders support (V1 only) (glitches with samplers can appear in particular configurations)
-* Add support for morph targets (V2 only)
+```JavaScript
+loader.onTextureLoaded = function (texture) {
+    // do something with the texture
+};
+```
+
+#### onMaterialLoaded
+Raised when the loader creates a material after parsing the glTF properties of the material.
+
+```JavaScript
+loader.onMaterialLoaded = function (material) {
+    // do something with the material
+};
+```
+
+#### onComplete
+Raised when the asset is completely loaded, immediately before the loader is disposed.
+For assets with LODs, raised when all of the LODs are complete.
+For assets without LODs, raised when the model is complete, immediately after onSuccess.
+
+```JavaScript
+loader.onComplete = function () {
+    // do something when loading is complete
+};
+```
+
+#### dispose
+Disposes the loader, releases resources during load, and cancels any outstanding requests.
+
+```JavaScript
+// Cancel loading of the current glTF asset.
+loader.dispose();
+```

+ 80 - 13
loaders/src/glTF/babylon.glTFFileLoader.ts

@@ -2,17 +2,34 @@
 
 module BABYLON {
     export enum GLTFLoaderCoordinateSystemMode {
-        // Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene (scene.useRightHandedSystem).
-        // NOTE: When scene.useRightHandedSystem is false, an additional transform will be added to the root to transform the data from right-handed to left-handed.
+        /**
+         * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
+         */
         AUTO,
 
-        // The glTF right-handed data is not transformed in any form and is loaded directly.
-        PASS_THROUGH,
-
-        // Sets the useRightHandedSystem flag on the scene.
+        /**
+         * Sets the useRightHandedSystem flag on the scene.
+         */
         FORCE_RIGHT_HANDED,
     }
 
+    export enum GLTFLoaderAnimationStartMode {
+        /**
+         * No animation will start.
+         */
+        NONE,
+
+        /**
+         * The first animation will start.
+         */
+        FIRST,
+
+        /**
+         * All animations will start.
+         */
+        ALL,
+    }
+
     export interface IGLTFLoaderData {
         json: Object;
         bin: Nullable<ArrayBufferView>;
@@ -27,29 +44,76 @@ module BABYLON {
         public static CreateGLTFLoaderV1: (parent: GLTFFileLoader) => IGLTFLoader;
         public static CreateGLTFLoaderV2: (parent: GLTFFileLoader) => IGLTFLoader;
 
-        // Common options
+        // #region Common options
+
+        /**
+         * Raised when the asset has been parsed.
+         * The data.json property stores the glTF JSON.
+         * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
+         */
         public onParsed: (data: IGLTFLoaderData) => void;
 
-        // V1 options
-        public static HomogeneousCoordinates = false;
+        // #endregion
+
+        // #region V1 options
+
         public static IncrementalLoading = true;
 
-        // V2 options
+        public static HomogeneousCoordinates = false;
+
+        // #endregion
+
+        // #region V2 options
+
+        /**
+         * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
+         */
         public coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
+
+        /**
+         * The animation start mode (NONE, FIRST, ALL).
+         */
+        public animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
+
+        /**
+         * Set to true to compile materials before raising the success callback.
+         */
         public compileMaterials = false;
-        public compileShadowGenerators = false;
+
+        /**
+         * Set to true to also compile materials with clip planes.
+         */
         public useClipPlane = false;
+
+        /**
+         * Set to true to compile shadow generators before raising the success callback.
+         */
+        public compileShadowGenerators = false;
+
+        /**
+         * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
+         */
         public onMeshLoaded: (mesh: AbstractMesh) => void;
+
+        /**
+         * Raised when the loader creates a texture after parsing the glTF properties of the texture.
+         */
         public onTextureLoaded: (texture: BaseTexture) => void;
+
+        /**
+         * Raised when the loader creates a material after parsing the glTF properties of the material.
+         */
         public onMaterialLoaded: (material: Material) => void;
 
         /**
-         * Raised when the asset is completely loaded, just before the loader is disposed.
+         * Raised when the asset is completely loaded, immediately before the loader is disposed.
          * For assets with LODs, raised when all of the LODs are complete.
-         * For assets without LODs, raised when the model is complete just after onSuccess.
+         * For assets without LODs, raised when the model is complete, immediately after onSuccess.
          */
         public onComplete: () => void;
 
+        // #endregion
+
         private _loader: IGLTFLoader;
 
         public name = "gltf";
@@ -59,6 +123,9 @@ module BABYLON {
             ".glb": { isBinary: true }
         };
 
+        /**
+         * Disposes the loader, releases resources during load, and cancels any outstanding requests.
+         */
         public dispose(): void {
             if (this._loader) {
                 this._loader.dispose();

+ 6 - 6
sandbox/index.js

@@ -1,4 +1,5 @@
 /// <reference path="../dist/preview release/babylon.d.ts" />
+/// <reference path="../dist/preview release/loaders/babylon.glTFFileLoader.d.ts" />
 
 if (BABYLON.Engine.isSupported()) {
     var canvas = document.getElementById("renderCanvas");
@@ -21,7 +22,7 @@ if (BABYLON.Engine.isSupported()) {
     var currentPluginName;
     var toExecuteAfterSceneCreation;
 
-    canvas.addEventListener("contextmenu", function(evt) {
+    canvas.addEventListener("contextmenu", function (evt) {
         evt.preventDefault();
     }, false);
 
@@ -33,14 +34,13 @@ if (BABYLON.Engine.isSupported()) {
 
     // Setting up some GLTF values
     BABYLON.GLTFFileLoader.IncrementalLoading = false;
-    BABYLON.SceneLoader.OnPluginActivatedObservable.add(function(plugin) {
+    BABYLON.SceneLoader.OnPluginActivatedObservable.add(function (plugin) {
         currentPluginName = plugin.name;
 
-        if (plugin.name !== "gltf") {
-            return;
+        if (plugin.name === "gltf" && plugin instanceof BABYLON.GLTFFileLoader) {
+            plugin.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.ALL;
+            plugin.compileMaterials = true;
         }
-
-        plugin.compileMaterials = true;
     });
 
     // Resize