소스 검색

Merge pull request #3494 from TrevorDev/sceneAssetContainer

Create SceneAssetContainer class and new fileLoader loadAssets method
David Catuhe 7 년 전
부모
커밋
54d67e3f86

+ 1 - 0
Tools/Gulp/config.json

@@ -192,6 +192,7 @@
                 "../../src/Rendering/babylon.renderingManager.js",
                 "../../src/Rendering/babylon.renderingGroup.js",
                 "../../src/babylon.scene.js",
+                "../../src/babylon.assetContainer.js",
                 "../../src/Mesh/babylon.buffer.js",
                 "../../src/Mesh/babylon.vertexBuffer.js",
                 "../../src/Materials/Textures/babylon.internalTexture.js",

+ 10 - 0
loaders/src/OBJ/babylon.objFileLoader.ts

@@ -264,6 +264,16 @@ module BABYLON {
             return this.importMesh(null, scene, data, rootUrl, null, null, null);
         }
 
+        public loadAssets(scene: Scene, data: string, rootUrl: string, onError?: (message: string, exception?: any) => void):Nullable<AssetContainer>{
+            var container = new AssetContainer(scene);
+            var result = this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
+            if(result){
+                container.removeAllFromScene();
+                return container;
+            }
+            return null;
+        }
+
         /**
          * Read the OBJ file and create an Array of meshes.
          * Each mesh contains all information given by the OBJ and the MTL file.

+ 10 - 0
loaders/src/STL/babylon.stlFileLoader.ts

@@ -86,6 +86,16 @@ module BABYLON {
             return result;
         }
 
+        public loadAssets(scene: Scene, data: string, rootUrl: string, onError?: (message: string, exception?: any) => void):Nullable<AssetContainer>{
+            var container = new AssetContainer(scene);
+            var result = this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
+            if(result){
+                container.removeAllFromScene();
+                return container;
+            }
+            return null;
+        }
+
         private isBinary (data: any) {
 
             // check if file size is correct for binary stl

+ 23 - 0
loaders/src/glTF/babylon.glTFFileLoader.ts

@@ -239,6 +239,29 @@ module BABYLON {
             }
         }
 
+        public loadAssetsAsync(scene: Scene, data: string | ArrayBuffer, rootUrl: string, onSuccess: (assets:AssetContainer) => void, onProgress?: (event: SceneLoaderProgressEvent) => void, onError?: (message: string, exception?: any) => void): void {
+            try {
+                const loaderData = this._parse(data);
+                this._loader = this._getLoader(loaderData);
+                this._loader.importMeshAsync(null, scene, loaderData, rootUrl,  (meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[]) => {
+                    var container = new AssetContainer(scene);
+                    Array.prototype.push.apply(container.meshes, meshes)
+                    Array.prototype.push.apply(container.particleSystems, particleSystems)
+                    Array.prototype.push.apply(container.skeletons, skeletons)
+                    container.removeAllFromScene();
+                    onSuccess(container)
+                }, onProgress, onError);
+            }
+            catch (e) {
+                if (onError) {
+                    onError(e.message, e);
+                }
+                else {
+                    Tools.Error(e.message);
+                }
+            }
+        }
+
         public canDirectLoad(data: string): boolean {
             return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
         }

+ 480 - 418
src/Loading/Plugins/babylon.babylonFileLoader.ts

@@ -28,6 +28,357 @@
         return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
     }
 
+    var loadAssets = (scene: Scene, data: string, rootUrl: string, onError?: (message: string, exception?: any) => void, addToScene = false):Nullable<AssetContainer> => {
+        var container = new AssetContainer(scene);
+
+            // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
+            // when SceneLoader.debugLogging = true (default), or exception encountered.
+            // Everything stored in var log instead of writing separate lines to support only writing in exception,
+            // and avoid problems with multiple concurrent .babylon loads.
+            var log = "importScene has failed JSON parse";
+            try {
+                var parsedData = JSON.parse(data);
+                log = "";
+                var fullDetails = SceneLoader.loggingLevel === SceneLoader.DETAILED_LOGGING;               
+
+                var index: number;
+                var cache: number;
+                // Lights
+                if (parsedData.lights !== undefined && parsedData.lights !== null) {
+                    for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
+                        var parsedLight = parsedData.lights[index];
+                        var light = Light.Parse(parsedLight, scene);
+                        if (light) {
+                            container.lights.push(light);
+                            log += (index === 0 ? "\n\tLights:" : "");
+                            log += "\n\t\t" + light.toString(fullDetails);
+                        }
+                    }
+                }
+
+                // Animations
+                if (parsedData.animations !== undefined && parsedData.animations !== null) {
+                    for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
+                        var parsedAnimation = parsedData.animations[index];
+                        var animation = Animation.Parse(parsedAnimation);
+                        scene.animations.push(animation);
+                        container.animations.push(animation);
+                        log += (index === 0 ? "\n\tAnimations:" : "");
+                        log += "\n\t\t" + animation.toString(fullDetails);
+                    }
+                }
+
+                // Materials
+                if (parsedData.materials !== undefined && parsedData.materials !== null) {
+                    for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
+                        var parsedMaterial = parsedData.materials[index];
+                        var mat = Material.Parse(parsedMaterial, scene, rootUrl);
+                        container.materials.push(mat);
+                        log += (index === 0 ? "\n\tMaterials:" : "");
+                        log += "\n\t\t" + mat.toString(fullDetails);
+                    }
+                }
+
+                if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
+                    for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
+                        var parsedMultiMaterial = parsedData.multiMaterials[index];
+                        var mmat = Material.ParseMultiMaterial(parsedMultiMaterial, scene);
+                        container.multiMaterials.push(mmat);
+                        log += (index === 0 ? "\n\tMultiMaterials:" : "");
+                        log += "\n\t\t" + mmat.toString(fullDetails);
+                    }
+                }
+
+                // Morph targets
+                if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
+                    for (var managerData of parsedData.morphTargetManagers) {
+                        container.morphTargetManagers.push(MorphTargetManager.Parse(managerData, scene));
+                    }
+                }
+
+                // Skeletons
+                if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
+                    for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
+                        var parsedSkeleton = parsedData.skeletons[index];
+                        var skeleton = Skeleton.Parse(parsedSkeleton, scene);
+                        container.skeletons.push(skeleton);
+                        log += (index === 0 ? "\n\tSkeletons:" : "");
+                        log += "\n\t\t" + skeleton.toString(fullDetails);
+                    }
+                }
+
+                // Geometries
+                var geometries = parsedData.geometries;
+                if (geometries !== undefined && geometries !== null) {
+                    var addedGeometry = new Array<Nullable<Geometry>>();
+                    // Boxes
+                    var boxes = geometries.boxes;
+                    if (boxes !== undefined && boxes !== null) {
+                        for (index = 0, cache = boxes.length; index < cache; index++) {
+                            var parsedBox = boxes[index];
+                            addedGeometry.push(BoxGeometry.Parse(parsedBox, scene));
+                        }
+                    }
+
+                    // Spheres
+                    var spheres = geometries.spheres;
+                    if (spheres !== undefined && spheres !== null) {
+                        for (index = 0, cache = spheres.length; index < cache; index++) {
+                            var parsedSphere = spheres[index];
+                            addedGeometry.push(SphereGeometry.Parse(parsedSphere, scene));
+                        }
+                    }
+
+                    // Cylinders
+                    var cylinders = geometries.cylinders;
+                    if (cylinders !== undefined && cylinders !== null) {
+                        for (index = 0, cache = cylinders.length; index < cache; index++) {
+                            var parsedCylinder = cylinders[index];
+                            addedGeometry.push(CylinderGeometry.Parse(parsedCylinder, scene));
+                        }
+                    }
+
+                    // Toruses
+                    var toruses = geometries.toruses;
+                    if (toruses !== undefined && toruses !== null) {
+                        for (index = 0, cache = toruses.length; index < cache; index++) {
+                            var parsedTorus = toruses[index];
+                            addedGeometry.push(TorusGeometry.Parse(parsedTorus, scene));
+                        }
+                    }
+
+                    // Grounds
+                    var grounds = geometries.grounds;
+                    if (grounds !== undefined && grounds !== null) {
+                        for (index = 0, cache = grounds.length; index < cache; index++) {
+                            var parsedGround = grounds[index];
+                            addedGeometry.push(GroundGeometry.Parse(parsedGround, scene));
+                        }
+                    }
+
+                    // Planes
+                    var planes = geometries.planes;
+                    if (planes !== undefined && planes !== null) {
+                        for (index = 0, cache = planes.length; index < cache; index++) {
+                            var parsedPlane = planes[index];
+                            addedGeometry.push(PlaneGeometry.Parse(parsedPlane, scene));
+                        }
+                    }
+
+                    // TorusKnots
+                    var torusKnots = geometries.torusKnots;
+                    if (torusKnots !== undefined && torusKnots !== null) {
+                        for (index = 0, cache = torusKnots.length; index < cache; index++) {
+                            var parsedTorusKnot = torusKnots[index];
+                            addedGeometry.push(TorusKnotGeometry.Parse(parsedTorusKnot, scene));
+                        }
+                    }
+
+                    // VertexData
+                    var vertexData = geometries.vertexData;
+                    if (vertexData !== undefined && vertexData !== null) {
+                        for (index = 0, cache = vertexData.length; index < cache; index++) {
+                            var parsedVertexData = vertexData[index];
+                            addedGeometry.push(Geometry.Parse(parsedVertexData, scene, rootUrl));
+                        }
+                    }
+
+                    addedGeometry.forEach((g)=>{
+                        if(g){
+                            container.geometries.push(g);
+                        }
+                    })
+                }
+                
+                // Transform nodes
+                if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
+                    for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
+                        var parsedTransformNode = parsedData.transformNodes[index];
+                        var node = TransformNode.Parse(parsedTransformNode, scene, rootUrl);
+                        container.transformNodes.push(node);
+                    }
+                }                
+
+                // Meshes
+                if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
+                    for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
+                        var parsedMesh = parsedData.meshes[index];
+                        var mesh = <AbstractMesh>Mesh.Parse(parsedMesh, scene, rootUrl);
+                        container.meshes.push(mesh);
+                        log += (index === 0 ? "\n\tMeshes:" : "");
+                        log += "\n\t\t" + mesh.toString(fullDetails);
+                    }
+                }
+
+                // Cameras
+                if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
+                    for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
+                        var parsedCamera = parsedData.cameras[index];
+                        var camera = Camera.Parse(parsedCamera, scene);
+                        container.cameras.push(camera);
+                        log += (index === 0 ? "\n\tCameras:" : "");
+                        log += "\n\t\t" + camera.toString(fullDetails);
+                    }
+                }
+
+                // Browsing all the graph to connect the dots
+                for (index = 0, cache = scene.cameras.length; index < cache; index++) {
+                    var camera = scene.cameras[index];
+                    if (camera._waitingParentId) {
+                        camera.parent = scene.getLastEntryByID(camera._waitingParentId);
+                        camera._waitingParentId = null;
+                    }
+                }
+
+                for (index = 0, cache = scene.lights.length; index < cache; index++) {
+                    let light = scene.lights[index];
+                    if (light && light._waitingParentId) {
+                        light.parent = scene.getLastEntryByID(light._waitingParentId);
+                        light._waitingParentId = null;
+                    }
+                }
+
+                // Sounds
+                // TODO: add sound
+                var loadedSounds: Sound[] = [];
+                var loadedSound: Sound;
+                if (AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
+                    for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
+                        var parsedSound = parsedData.sounds[index];
+                        if (Engine.audioEngine.canUseWebAudio) {
+                            if (!parsedSound.url) parsedSound.url = parsedSound.name;
+                            if (!loadedSounds[parsedSound.url]) {
+                                loadedSound = Sound.Parse(parsedSound, scene, rootUrl);
+                                loadedSounds[parsedSound.url] = loadedSound;
+                                container.sounds.push(loadedSound);
+                            }
+                            else {
+                                container.sounds.push(Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
+                            }
+                        } else {
+                            container.sounds.push(new Sound(parsedSound.name, null, scene));
+                        }
+                    }
+                }
+
+                loadedSounds = [];
+
+                // Connect parents & children and parse actions
+                for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
+                    var transformNode = scene.transformNodes[index];
+                    if (transformNode._waitingParentId) {
+                        transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
+                        transformNode._waitingParentId = null;
+                    }
+                }                
+                for (index = 0, cache = scene.meshes.length; index < cache; index++) {
+                    var mesh = scene.meshes[index];
+                    if (mesh._waitingParentId) {
+                        mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
+                        mesh._waitingParentId = null;
+                    }
+                    if (mesh._waitingActions) {
+                        ActionManager.Parse(mesh._waitingActions, mesh, scene);
+                        mesh._waitingActions = null;
+                    }
+                }
+
+                // freeze world matrix application
+                for (index = 0, cache = scene.meshes.length; index < cache; index++) {
+                    var currentMesh = scene.meshes[index];
+                    if (currentMesh._waitingFreezeWorldMatrix) {
+                        currentMesh.freezeWorldMatrix();
+                        currentMesh._waitingFreezeWorldMatrix = null;
+                    } else {
+                        currentMesh.computeWorldMatrix(true);
+                    }
+                }
+
+                // Particles Systems
+                if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
+                    for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
+                        var parsedParticleSystem = parsedData.particleSystems[index];
+                        var ps = ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
+                        container.particleSystems.push(ps);
+                    }
+                }
+
+                // Lens flares
+                if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
+                    for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
+                        var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
+                        var lf = LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
+                        container.lensFlareSystems.push(lf);
+                    }
+                }
+
+                // Shadows
+                if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
+                    for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
+                        var parsedShadowGenerator = parsedData.shadowGenerators[index];
+                        var sg = ShadowGenerator.Parse(parsedShadowGenerator, scene);
+                        container.shadowGenerators.push(sg);
+                    }
+                }
+
+                // Lights exclusions / inclusions
+                for (index = 0, cache = scene.lights.length; index < cache; index++) {
+                    let light = scene.lights[index];
+                    // Excluded check
+                    if (light._excludedMeshesIds.length > 0) {
+                        for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
+                            var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
+
+                            if (excludedMesh) {
+                                light.excludedMeshes.push(excludedMesh);
+                            }
+                        }
+
+                        light._excludedMeshesIds = [];
+                    }
+
+                    // Included check
+                    if (light._includedOnlyMeshesIds.length > 0) {
+                        for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
+                            var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
+
+                            if (includedOnlyMesh) {
+                                light.includedOnlyMeshes.push(includedOnlyMesh);
+                            }
+                        }
+
+                        light._includedOnlyMeshesIds = [];
+                    }
+                }
+
+                // Actions (scene)
+                if (parsedData.actions !== undefined && parsedData.actions !== null) {
+                    ActionManager.Parse(parsedData.actions, null, scene);
+                }
+                
+                if(!addToScene){
+                    container.removeAllFromScene();
+                }
+
+                return container;
+
+            } catch (err) {
+                let msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
+                if (onError) {
+                    onError(msg, err);
+                } else {
+                    Tools.Log(msg);
+                    throw err;
+                }
+            } finally {
+                if (log !== null && SceneLoader.loggingLevel !== SceneLoader.NO_LOGGING) {
+                    Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (SceneLoader.loggingLevel !== SceneLoader.MINIMAL_LOGGING ? log : ""));
+                }
+            }
+
+            return null;
+    }
+
     SceneLoader.RegisterPlugin({
         name: "babylon.js",
         extensions: ".babylon",
@@ -150,464 +501,172 @@
                                         log += "\n\tMaterial " + mat.toString(fullDetails);
                                     }
                                 }
-                            }
-
-                            // Skeleton ?
-                            if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
-                                var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
-                                if (skeletonAlreadyLoaded === false) {
-                                    for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
-                                        var parsedSkeleton = parsedData.skeletons[skeletonIndex];
-                                        if (parsedSkeleton.id === parsedMesh.skeletonId) {
-                                            var skeleton = Skeleton.Parse(parsedSkeleton, scene);
-                                            skeletons.push(skeleton);
-                                            loadedSkeletonsIds.push(parsedSkeleton.id);
-                                            log += "\n\tSkeleton " + skeleton.toString(fullDetails);
-                                        }
-                                    }
-                                }
-                            }
-
-                            var mesh = Mesh.Parse(parsedMesh, scene, rootUrl);
-                            meshes.push(mesh);
-                            log += "\n\tMesh " + mesh.toString(fullDetails);
-                        }
-                    }
-
-                    // Connecting parents
-                    var currentMesh: AbstractMesh;
-                    for (index = 0, cache = scene.meshes.length; index < cache; index++) {
-                        currentMesh = scene.meshes[index];
-                        if (currentMesh._waitingParentId) {
-                            currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
-                            currentMesh._waitingParentId = null;
-                        }
-                    }
-
-                    // freeze and compute world matrix application
-                    for (index = 0, cache = scene.meshes.length; index < cache; index++) {
-                        currentMesh = scene.meshes[index];
-                        if (currentMesh._waitingFreezeWorldMatrix) {
-                            currentMesh.freezeWorldMatrix();
-                            currentMesh._waitingFreezeWorldMatrix = null;
-                        } else {
-                            currentMesh.computeWorldMatrix(true);
-                        }
-                    }
-                }
-
-                // Particles
-                if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
-                    for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
-                        var parsedParticleSystem = parsedData.particleSystems[index];
-                        if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
-                            particleSystems.push(ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
-                        }
-                    }
-                }
-
-                return true;
-
-            } catch (err) {
-                let msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
-                if (onError) {
-                    onError(msg, err);
-                } else {
-                    Tools.Log(msg);
-                    throw err;
-                }
-            } finally {
-                if (log !== null && SceneLoader.loggingLevel !== SceneLoader.NO_LOGGING) {
-                    Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (SceneLoader.loggingLevel !== SceneLoader.MINIMAL_LOGGING ? log : ""));
-                }
-            }
-
-            return false;
-        },
-        load: (scene: Scene, data: string, rootUrl: string, onError?: (message: string, exception?: any) => void): boolean => {
-            // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
-            // when SceneLoader.debugLogging = true (default), or exception encountered.
-            // Everything stored in var log instead of writing separate lines to support only writing in exception,
-            // and avoid problems with multiple concurrent .babylon loads.
-            var log = "importScene has failed JSON parse";
-            try {
-                var parsedData = JSON.parse(data);
-                log = "";
-                var fullDetails = SceneLoader.loggingLevel === SceneLoader.DETAILED_LOGGING;
-
-                // Scene
-                if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
-                    scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !SceneLoader.ForceFullSceneLoadingForIncremental;
-                }
-                if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
-                    scene.autoClear = parsedData.autoClear;
-                }
-                if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
-                    scene.clearColor = Color4.FromArray(parsedData.clearColor);
-                }
-                if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
-                    scene.ambientColor = Color3.FromArray(parsedData.ambientColor);
-                }
-                if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
-                    scene.gravity = Vector3.FromArray(parsedData.gravity);
-                }
-
-                // Fog
-                if (parsedData.fogMode && parsedData.fogMode !== 0) {
-                    scene.fogMode = parsedData.fogMode;
-                    scene.fogColor = Color3.FromArray(parsedData.fogColor);
-                    scene.fogStart = parsedData.fogStart;
-                    scene.fogEnd = parsedData.fogEnd;
-                    scene.fogDensity = parsedData.fogDensity;
-                    log += "\tFog mode for scene:  ";
-                    switch (scene.fogMode) {
-                        // getters not compiling, so using hardcoded
-                        case 1: log += "exp\n"; break;
-                        case 2: log += "exp2\n"; break;
-                        case 3: log += "linear\n"; break;
-                    }
-                }
-
-                //Physics
-                if (parsedData.physicsEnabled) {
-                    var physicsPlugin;
-                    if (parsedData.physicsEngine === "cannon") {
-                        physicsPlugin = new CannonJSPlugin();
-                    } else if (parsedData.physicsEngine === "oimo") {
-                        physicsPlugin = new OimoJSPlugin();
-                    }
-                    log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
-                    //else - default engine, which is currently oimo
-                    var physicsGravity = parsedData.physicsGravity ? Vector3.FromArray(parsedData.physicsGravity) : null;
-                    scene.enablePhysics(physicsGravity, physicsPlugin);
-                }
-
-                // Metadata
-                if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
-                    scene.metadata = parsedData.metadata;
-                }
-
-                //collisions, if defined. otherwise, default is true
-                if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
-                    scene.collisionsEnabled = parsedData.collisionsEnabled;
-                }
-                scene.workerCollisions = !!parsedData.workerCollisions;
-
-                var index: number;
-                var cache: number;
-                // Lights
-                if (parsedData.lights !== undefined && parsedData.lights !== null) {
-                    for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
-                        var parsedLight = parsedData.lights[index];
-                        var light = Light.Parse(parsedLight, scene);
-                        if (light) {
-                            log += (index === 0 ? "\n\tLights:" : "");
-                            log += "\n\t\t" + light.toString(fullDetails);
-                        }
-                    }
-                }
-
-                // Animations
-                if (parsedData.animations !== undefined && parsedData.animations !== null) {
-                    for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
-                        var parsedAnimation = parsedData.animations[index];
-                        var animation = Animation.Parse(parsedAnimation);
-                        scene.animations.push(animation);
-                        log += (index === 0 ? "\n\tAnimations:" : "");
-                        log += "\n\t\t" + animation.toString(fullDetails);
-                    }
-                }
-
-                if (parsedData.autoAnimate) {
-                    scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
-                }
-
-                // Materials
-                if (parsedData.materials !== undefined && parsedData.materials !== null) {
-                    for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
-                        var parsedMaterial = parsedData.materials[index];
-                        var mat = Material.Parse(parsedMaterial, scene, rootUrl);
-                        log += (index === 0 ? "\n\tMaterials:" : "");
-                        log += "\n\t\t" + mat.toString(fullDetails);
-                    }
-                }
-
-                if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
-                    for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
-                        var parsedMultiMaterial = parsedData.multiMaterials[index];
-                        var mmat = Material.ParseMultiMaterial(parsedMultiMaterial, scene);
-                        log += (index === 0 ? "\n\tMultiMaterials:" : "");
-                        log += "\n\t\t" + mmat.toString(fullDetails);
-                    }
-                }
-
-                // Morph targets
-                if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
-                    for (var managerData of parsedData.morphTargetManagers) {
-                        MorphTargetManager.Parse(managerData, scene);
-                    }
-                }
-
-                // Skeletons
-                if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
-                    for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
-                        var parsedSkeleton = parsedData.skeletons[index];
-                        var skeleton = Skeleton.Parse(parsedSkeleton, scene);
-                        log += (index === 0 ? "\n\tSkeletons:" : "");
-                        log += "\n\t\t" + skeleton.toString(fullDetails);
-                    }
-                }
-
-                // Geometries
-                var geometries = parsedData.geometries;
-                if (geometries !== undefined && geometries !== null) {
-                    // Boxes
-                    var boxes = geometries.boxes;
-                    if (boxes !== undefined && boxes !== null) {
-                        for (index = 0, cache = boxes.length; index < cache; index++) {
-                            var parsedBox = boxes[index];
-                            BoxGeometry.Parse(parsedBox, scene);
-                        }
-                    }
-
-                    // Spheres
-                    var spheres = geometries.spheres;
-                    if (spheres !== undefined && spheres !== null) {
-                        for (index = 0, cache = spheres.length; index < cache; index++) {
-                            var parsedSphere = spheres[index];
-                            SphereGeometry.Parse(parsedSphere, scene);
-                        }
-                    }
-
-                    // Cylinders
-                    var cylinders = geometries.cylinders;
-                    if (cylinders !== undefined && cylinders !== null) {
-                        for (index = 0, cache = cylinders.length; index < cache; index++) {
-                            var parsedCylinder = cylinders[index];
-                            CylinderGeometry.Parse(parsedCylinder, scene);
-                        }
-                    }
-
-                    // Toruses
-                    var toruses = geometries.toruses;
-                    if (toruses !== undefined && toruses !== null) {
-                        for (index = 0, cache = toruses.length; index < cache; index++) {
-                            var parsedTorus = toruses[index];
-                            TorusGeometry.Parse(parsedTorus, scene);
-                        }
-                    }
-
-                    // Grounds
-                    var grounds = geometries.grounds;
-                    if (grounds !== undefined && grounds !== null) {
-                        for (index = 0, cache = grounds.length; index < cache; index++) {
-                            var parsedGround = grounds[index];
-                            GroundGeometry.Parse(parsedGround, scene);
-                        }
-                    }
+                            }
 
-                    // Planes
-                    var planes = geometries.planes;
-                    if (planes !== undefined && planes !== null) {
-                        for (index = 0, cache = planes.length; index < cache; index++) {
-                            var parsedPlane = planes[index];
-                            PlaneGeometry.Parse(parsedPlane, scene);
+                            // Skeleton ?
+                            if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
+                                var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
+                                if (skeletonAlreadyLoaded === false) {
+                                    for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
+                                        var parsedSkeleton = parsedData.skeletons[skeletonIndex];
+                                        if (parsedSkeleton.id === parsedMesh.skeletonId) {
+                                            var skeleton = Skeleton.Parse(parsedSkeleton, scene);
+                                            skeletons.push(skeleton);
+                                            loadedSkeletonsIds.push(parsedSkeleton.id);
+                                            log += "\n\tSkeleton " + skeleton.toString(fullDetails);
+                                        }
+                                    }
+                                }
+                            }
+
+                            var mesh = Mesh.Parse(parsedMesh, scene, rootUrl);
+                            meshes.push(mesh);
+                            log += "\n\tMesh " + mesh.toString(fullDetails);
                         }
                     }
 
-                    // TorusKnots
-                    var torusKnots = geometries.torusKnots;
-                    if (torusKnots !== undefined && torusKnots !== null) {
-                        for (index = 0, cache = torusKnots.length; index < cache; index++) {
-                            var parsedTorusKnot = torusKnots[index];
-                            TorusKnotGeometry.Parse(parsedTorusKnot, scene);
+                    // Connecting parents
+                    var currentMesh: AbstractMesh;
+                    for (index = 0, cache = scene.meshes.length; index < cache; index++) {
+                        currentMesh = scene.meshes[index];
+                        if (currentMesh._waitingParentId) {
+                            currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
+                            currentMesh._waitingParentId = null;
                         }
                     }
 
-                    // VertexData
-                    var vertexData = geometries.vertexData;
-                    if (vertexData !== undefined && vertexData !== null) {
-                        for (index = 0, cache = vertexData.length; index < cache; index++) {
-                            var parsedVertexData = vertexData[index];
-                            Geometry.Parse(parsedVertexData, scene, rootUrl);
+                    // freeze and compute world matrix application
+                    for (index = 0, cache = scene.meshes.length; index < cache; index++) {
+                        currentMesh = scene.meshes[index];
+                        if (currentMesh._waitingFreezeWorldMatrix) {
+                            currentMesh.freezeWorldMatrix();
+                            currentMesh._waitingFreezeWorldMatrix = null;
+                        } else {
+                            currentMesh.computeWorldMatrix(true);
                         }
                     }
                 }
 
-                // Transform nodes
-                if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
-                    for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
-                        var parsedTransformNode = parsedData.transformNodes[index];
-                        TransformNode.Parse(parsedTransformNode, scene, rootUrl);
+                // Particles
+                if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
+                    for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
+                        var parsedParticleSystem = parsedData.particleSystems[index];
+                        if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
+                            particleSystems.push(ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
+                        }
                     }
                 }
 
-                // Meshes
-                if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
-                    for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
-                        var parsedMesh = parsedData.meshes[index];
-                        var mesh = <AbstractMesh>Mesh.Parse(parsedMesh, scene, rootUrl);
-                        log += (index === 0 ? "\n\tMeshes:" : "");
-                        log += "\n\t\t" + mesh.toString(fullDetails);
-                    }
-                }
+                return true;
 
-                // Cameras
-                if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
-                    for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
-                        var parsedCamera = parsedData.cameras[index];
-                        var camera = Camera.Parse(parsedCamera, scene);
-                        log += (index === 0 ? "\n\tCameras:" : "");
-                        log += "\n\t\t" + camera.toString(fullDetails);
-                    }
+            } catch (err) {
+                let msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
+                if (onError) {
+                    onError(msg, err);
+                } else {
+                    Tools.Log(msg);
+                    throw err;
                 }
-                if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
-                    scene.setActiveCameraByID(parsedData.activeCameraID);
+            } finally {
+                if (log !== null && SceneLoader.loggingLevel !== SceneLoader.NO_LOGGING) {
+                    Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (SceneLoader.loggingLevel !== SceneLoader.MINIMAL_LOGGING ? log : ""));
                 }
+            }
 
-                // Browsing all the graph to connect the dots
-                for (index = 0, cache = scene.cameras.length; index < cache; index++) {
-                    var camera = scene.cameras[index];
-                    if (camera._waitingParentId) {
-                        camera.parent = scene.getLastEntryByID(camera._waitingParentId);
-                        camera._waitingParentId = null;
-                    }
-                }
+            return false;
+        },
+        load: (scene: Scene, data: string, rootUrl: string, onError?: (message: string, exception?: any) => void): boolean => {
+            // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
+            // when SceneLoader.debugLogging = true (default), or exception encountered.
+            // Everything stored in var log instead of writing separate lines to support only writing in exception,
+            // and avoid problems with multiple concurrent .babylon loads.
+            var log = "importScene has failed JSON parse";
+            try {
+                var parsedData = JSON.parse(data);
+                log = "";
 
-                for (index = 0, cache = scene.lights.length; index < cache; index++) {
-                    let light = scene.lights[index];
-                    if (light && light._waitingParentId) {
-                        light.parent = scene.getLastEntryByID(light._waitingParentId);
-                        light._waitingParentId = null;
-                    }
+                // Scene
+                if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
+                    scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !SceneLoader.ForceFullSceneLoadingForIncremental;
                 }
-
-                // Sounds
-                var loadedSounds: Sound[] = [];
-                var loadedSound: Sound;
-                if (AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
-                    for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
-                        var parsedSound = parsedData.sounds[index];
-                        if (Engine.audioEngine.canUseWebAudio) {
-                            if (!parsedSound.url) parsedSound.url = parsedSound.name;
-                            if (!loadedSounds[parsedSound.url]) {
-                                loadedSound = Sound.Parse(parsedSound, scene, rootUrl);
-                                loadedSounds[parsedSound.url] = loadedSound;
-                            }
-                            else {
-                                Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
-                            }
-                        } else {
-                            new Sound(parsedSound.name, null, scene);
-                        }
-                    }
+                if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
+                    scene.autoClear = parsedData.autoClear;
                 }
-
-                loadedSounds = [];
-
-                // Connect parents & children and parse actions
-                for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
-                    var transformNode = scene.transformNodes[index];
-                    if (transformNode._waitingParentId) {
-                        transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
-                        transformNode._waitingParentId = null;
-                    }
+                if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
+                    scene.clearColor = Color4.FromArray(parsedData.clearColor);
                 }
-                for (index = 0, cache = scene.meshes.length; index < cache; index++) {
-                    var mesh = scene.meshes[index];
-                    if (mesh._waitingParentId) {
-                        mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
-                        mesh._waitingParentId = null;
-                    }
-                    if (mesh._waitingActions) {
-                        ActionManager.Parse(mesh._waitingActions, mesh, scene);
-                        mesh._waitingActions = null;
-                    }
+                if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
+                    scene.ambientColor = Color3.FromArray(parsedData.ambientColor);
                 }
-
-                // freeze world matrix application
-                for (index = 0, cache = scene.meshes.length; index < cache; index++) {
-                    var currentMesh = scene.meshes[index];
-                    if (currentMesh._waitingFreezeWorldMatrix) {
-                        currentMesh.freezeWorldMatrix();
-                        currentMesh._waitingFreezeWorldMatrix = null;
-                    } else {
-                        currentMesh.computeWorldMatrix(true);
-                    }
+                if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
+                    scene.gravity = Vector3.FromArray(parsedData.gravity);
                 }
 
-                // Particles Systems
-                if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
-                    for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
-                        var parsedParticleSystem = parsedData.particleSystems[index];
-                        ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
+                // Fog
+                if (parsedData.fogMode && parsedData.fogMode !== 0) {
+                    scene.fogMode = parsedData.fogMode;
+                    scene.fogColor = Color3.FromArray(parsedData.fogColor);
+                    scene.fogStart = parsedData.fogStart;
+                    scene.fogEnd = parsedData.fogEnd;
+                    scene.fogDensity = parsedData.fogDensity;
+                    log += "\tFog mode for scene:  ";
+                    switch (scene.fogMode) {
+                        // getters not compiling, so using hardcoded
+                        case 1: log += "exp\n"; break;
+                        case 2: log += "exp2\n"; break;
+                        case 3: log += "linear\n"; break;
                     }
                 }
 
-                // Environment texture
-                if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
-                    scene.environmentTexture = CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
-                    if (parsedData.createDefaultSkybox === true) {
-                        var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
-                        var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
-                        scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
+                //Physics
+                if (parsedData.physicsEnabled) {
+                    var physicsPlugin;
+                    if (parsedData.physicsEngine === "cannon") {
+                        physicsPlugin = new CannonJSPlugin();
+                    } else if (parsedData.physicsEngine === "oimo") {
+                        physicsPlugin = new OimoJSPlugin();
                     }
+                    log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
+                    //else - default engine, which is currently oimo
+                    var physicsGravity = parsedData.physicsGravity ? Vector3.FromArray(parsedData.physicsGravity) : null;
+                    scene.enablePhysics(physicsGravity, physicsPlugin);
                 }
 
-                // Lens flares
-                if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
-                    for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
-                        var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
-                        LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
-                    }
+                // Metadata
+                if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
+                    scene.metadata = parsedData.metadata;
                 }
 
-                // Shadows
-                if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
-                    for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
-                        var parsedShadowGenerator = parsedData.shadowGenerators[index];
-                        ShadowGenerator.Parse(parsedShadowGenerator, scene);
-                    }
+                //collisions, if defined. otherwise, default is true
+                if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
+                    scene.collisionsEnabled = parsedData.collisionsEnabled;
                 }
+                scene.workerCollisions = !!parsedData.workerCollisions;
 
-                // Lights exclusions / inclusions
-                for (index = 0, cache = scene.lights.length; index < cache; index++) {
-                    let light = scene.lights[index];
-                    // Excluded check
-                    if (light._excludedMeshesIds.length > 0) {
-                        for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
-                            var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
-
-                            if (excludedMesh) {
-                                light.excludedMeshes.push(excludedMesh);
-                            }
-                        }
-
-                        light._excludedMeshesIds = [];
-                    }
-
-                    // Included check
-                    if (light._includedOnlyMeshesIds.length > 0) {
-                        for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
-                            var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
-
-                            if (includedOnlyMesh) {
-                                light.includedOnlyMeshes.push(includedOnlyMesh);
-                            }
-                        }
-
-                        light._includedOnlyMeshesIds = [];
-                    }
+                var container = loadAssets(scene, data, rootUrl, onerror, true);
+                if(!container){
+                    return false;
+                }
+                
+                if (parsedData.autoAnimate) {		
+                    scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);		
                 }
 
-                // Actions (scene)
-                if (parsedData.actions !== undefined && parsedData.actions !== null) {
-                    ActionManager.Parse(parsedData.actions, null, scene);
+                if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {		
+                    scene.setActiveCameraByID(parsedData.activeCameraID);		
                 }
 
+                // Environment texture		
+                if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {		
+                    scene.environmentTexture = CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);		
+                    if (parsedData.createDefaultSkybox === true) {		
+                        var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;		
+                        var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;		
+                        scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);		
+                    }
+                }
                 // Finish
                 return true;
-
             } catch (err) {
                 let msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
                 if (onError) {
@@ -621,8 +680,11 @@
                     Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (SceneLoader.loggingLevel !== SceneLoader.MINIMAL_LOGGING ? log : ""));
                 }
             }
-
             return false;
+        },
+        loadAssets: (scene: Scene, data: string, rootUrl: string, onError?: (message: string, exception?: any) => void): Nullable<AssetContainer> =>{
+            var container = loadAssets(scene, data, rootUrl, onerror);
+            return container;
         }
     });
 }

+ 87 - 0
src/Loading/babylon.sceneLoader.ts

@@ -27,6 +27,7 @@
         load: (scene: Scene, data: string, rootUrl: string, onError?: (message: string, exception?: any) => void) => boolean;
         canDirectLoad?: (data: string) => boolean;
         rewriteRootURL?: (rootUrl: string, responseURL?: string) => string;
+        loadAssets: (scene: Scene, data: string, rootUrl: string, onError?: (message: string, exception?: any) => void) => Nullable<AssetContainer>;
     }
 
     export interface ISceneLoaderPluginAsync {
@@ -36,6 +37,7 @@
         loadAsync: (scene: Scene, data: string, rootUrl: string, onSuccess?: () => void, onProgress?: (event: SceneLoaderProgressEvent) => void, onError?: (message: string, exception?: any) => void) => void;
         canDirectLoad?: (data: string) => boolean;
         rewriteRootURL?: (rootUrl: string, responseURL?: string) => string;
+        loadAssetsAsync: (scene: Scene, data: string, rootUrl: string, onSuccess?: (assets: Nullable<AssetContainer>) => void, onProgress?: (event: SceneLoaderProgressEvent) => void, onError?: (message: string, exception?: any) => void) => void;
     }
 
     interface IRegisteredPlugin {
@@ -455,5 +457,90 @@
                 }
             }, progressHandler, errorHandler, disposeHandler, pluginExtension);
         }
+        
+        public static LoadAssetContainer(
+            rootUrl: string,
+            sceneFilename: any,
+            scene: Scene,
+            onSuccess: Nullable<(assets: AssetContainer) => void> = null,
+            onProgress: Nullable<(event: SceneLoaderProgressEvent) => void> = null,
+            onError: Nullable<(scene: Scene, message: string, exception?: any) => void> = null,
+            pluginExtension: Nullable<string> = null
+        ): Nullable<ISceneLoaderPlugin | ISceneLoaderPluginAsync> {
+            if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
+                Tools.Error("Wrong sceneFilename parameter");
+                return null;
+            }
+
+            var loadingToken = {};
+            scene._addPendingData(loadingToken);
+
+            var disposeHandler = () => {
+                scene._removePendingData(loadingToken);
+            };
+
+            var errorHandler = (message: Nullable<string>, exception?: any) => {
+                let errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
+                if (onError) {
+                    onError(scene, errorMessage, exception);
+                } else {
+                    Tools.Error(errorMessage);
+                    // should the exception be thrown?
+                }
+
+                disposeHandler();
+            };
+
+            var progressHandler = onProgress ? (event: SceneLoaderProgressEvent) => {
+                try {
+                    onProgress(event);
+                }
+                catch (e) {
+                    errorHandler("Error in onProgress callback", e);
+                }
+            } : undefined;
+
+            var successHandler = (assets: AssetContainer) => {
+                if (onSuccess) {
+                    try {
+                        onSuccess(assets);
+                    }
+                    catch (e) {
+                        errorHandler("Error in onSuccess callback", e);
+                    }
+                }
+
+                scene._removePendingData(loadingToken);
+            };
+
+            return SceneLoader._loadData(rootUrl, sceneFilename, scene, (plugin, data, responseURL) => {
+                if ((<any>plugin).loadAssets) {
+                    var syncedPlugin = <ISceneLoaderPlugin>plugin;
+                    var assetContainer = syncedPlugin.loadAssets(scene, data, rootUrl, errorHandler);
+                    if (!assetContainer) {
+                        return;
+                    }
+
+                    scene.loadingPluginName = plugin.name;
+                    successHandler(assetContainer);
+                } else if ((<any>plugin).loadAssetsAsync) {
+                    var asyncedPlugin = <ISceneLoaderPluginAsync>plugin;
+                    asyncedPlugin.loadAssetsAsync(scene, data, rootUrl, (assetContainer) => {
+                        if(assetContainer){
+                            scene.loadingPluginName = plugin.name;
+                            successHandler(assetContainer);
+                        }
+                    }, progressHandler, errorHandler);
+                }else{
+                    errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssets or loadAssetsAsync method.")
+                }
+
+                if (SceneLoader.ShowLoadingScreen) {
+                    scene.executeWhenReady(() => {
+                        scene.getEngine().hideLoadingUI();
+                    });
+                }
+            }, progressHandler, errorHandler, disposeHandler, pluginExtension);
+        }
     };
 }

+ 119 - 0
src/babylon.assetContainer.ts

@@ -0,0 +1,119 @@
+module BABYLON {
+    export class AssetContainer {
+        public scene: Scene;
+
+        // Objects
+        public cameras = new Array<Camera>();
+        public lights = new Array<Light>();
+        public meshes = new Array<AbstractMesh>();
+        public skeletons = new Array<Skeleton>();
+        public particleSystems = new Array<ParticleSystem>();
+        public animations = new Array<Animation>();
+        public multiMaterials = new Array<MultiMaterial>();
+        public materials = new Array<Material>();
+        public morphTargetManagers = new Array<MorphTargetManager>();
+        public geometries = new Array<Geometry>();
+        public transformNodes = new Array<TransformNode>();
+        public lensFlareSystems = new Array<LensFlareSystem>();
+        public shadowGenerators = new Array<ShadowGenerator>();
+        public actionManagers = new Array<ActionManager>();
+        public sounds = new Array<Sound>();
+        
+        constructor(scene:Scene){
+            this.scene = scene;
+        }
+        
+        addAllToScene(){
+            this.cameras.forEach((o)=>{
+                this.scene.addCamera(o);
+            });
+            this.lights.forEach((o)=>{
+                this.scene.addLight(o);
+            });
+            this.meshes.forEach((o)=>{
+                this.scene.addMesh(o);
+            });
+            this.skeletons.forEach((o)=>{
+                this.scene.addSkeleton(o);
+            });
+            this.particleSystems.forEach((o)=>{
+                this.scene.addParticleSystem(o);
+            });
+            this.animations.forEach((o)=>{
+                this.scene.addAnimation(o);
+            });
+            this.multiMaterials.forEach((o)=>{
+                this.scene.addMultiMaterial(o);
+            });
+            this.materials.forEach((o)=>{
+                this.scene.addMaterial(o);
+            });
+            this.morphTargetManagers.forEach((o)=>{
+                this.scene.addMorphTargetManager(o);
+            });
+            this.geometries.forEach((o)=>{
+                this.scene.addGeometry(o);
+            });
+            this.transformNodes.forEach((o)=>{
+                this.scene.addTransformNode(o);
+            });
+            this.lensFlareSystems.forEach((o)=>{
+                this.scene.addLensFlareSystem(o);
+            });
+            this.actionManagers.forEach((o)=>{
+                this.scene.addActionManager(o);
+            });
+            this.sounds.forEach((o)=>{
+                o.play();
+                o.autoplay=true;
+                this.scene.mainSoundTrack.AddSound(o);
+            })
+        }
+        removeAllFromScene(){
+            this.cameras.forEach((o)=>{
+                this.scene.removeCamera(o);
+            });
+            this.lights.forEach((o)=>{
+                this.scene.removeLight(o);
+            });
+            this.meshes.forEach((o)=>{
+                this.scene.removeMesh(o);
+            });
+            this.skeletons.forEach((o)=>{
+                this.scene.removeSkeleton(o);
+            });
+            this.particleSystems.forEach((o)=>{
+                this.scene.removeParticleSystem(o);
+            });
+            this.animations.forEach((o)=>{
+                this.scene.removeAnimation(o);
+            });
+            this.multiMaterials.forEach((o)=>{
+                this.scene.removeMultiMaterial(o);
+            });
+            this.materials.forEach((o)=>{
+                this.scene.removeMaterial(o);
+            });
+            this.morphTargetManagers.forEach((o)=>{
+                this.scene.removeMorphTargetManager(o);
+            });
+            this.geometries.forEach((o)=>{
+                this.scene.removeGeometry(o);
+            });
+            this.transformNodes.forEach((o)=>{
+                this.scene.removeTransformNode(o);
+            });
+            this.lensFlareSystems.forEach((o)=>{
+                this.scene.removeLensFlareSystem(o);
+            });
+            this.actionManagers.forEach((o)=>{
+                this.scene.removeActionManager(o);
+            });
+            this.sounds.forEach((o)=>{
+                o.stop();
+                o.autoplay = false;
+                this.scene.mainSoundTrack.RemoveSound(o);
+            })
+        }
+    }
+}

+ 81 - 0
src/babylon.scene.ts

@@ -2248,6 +2248,7 @@
             if (this.collisionCoordinator) {
                 this.collisionCoordinator.onMeshAdded(newMesh);
             }
+            newMesh._resyncLightSources();
 
             this.onNewMeshAddedObservable.notifyObservers(newMesh);
         }
@@ -2342,6 +2343,50 @@
             return index;
         }
 
+        
+        public removeParticleSystem(toRemove: ParticleSystem): number {
+            var index = this.particleSystems.indexOf(toRemove);
+            if (index !== -1) {
+                this.particleSystems.splice(index, 1);
+            }
+            return index;
+        };
+        public removeAnimation(toRemove: Animation): number {
+            var index = this.animations.indexOf(toRemove);
+            if (index !== -1) {
+                this.animations.splice(index, 1);
+            }
+            return index;
+        };
+        public removeMultiMaterial(toRemove: MultiMaterial): number {
+            var index = this.multiMaterials.indexOf(toRemove);
+            if (index !== -1) {
+                this.multiMaterials.splice(index, 1);
+            }
+            return index;
+        };
+        public removeMaterial(toRemove: Material): number {
+            var index = this.materials.indexOf(toRemove);
+            if (index !== -1) {
+                this.materials.splice(index, 1);
+            }
+            return index;
+        };
+        public removeLensFlareSystem(toRemove:LensFlareSystem){
+            var index = this.lensFlareSystems.indexOf(toRemove);
+            if (index !== -1) {
+                this.lensFlareSystems.splice(index, 1);
+            }
+            return index;
+        };
+        public removeActionManager(toRemove:ActionManager){
+            var index = this._actionManagers.indexOf(toRemove);
+            if (index !== -1) {
+                this._actionManagers.splice(index, 1);
+            }
+            return index;
+        };
+
         public addLight(newLight: Light) {
             this.lights.push(newLight);
             this.sortLightsByPriority();
@@ -2368,6 +2413,42 @@
             this.onNewCameraAddedObservable.notifyObservers(newCamera);
         }
 
+        public addSkeleton(newSkeleton:Skeleton){
+            this.skeletons.push(newSkeleton)
+        }
+
+        public addParticleSystem(newParticleSystem:ParticleSystem){
+            this.particleSystems.push(newParticleSystem)
+        }
+
+        public addAnimation(newAnimation:Animation){
+            this.animations.push(newAnimation)
+        }
+
+        public addMultiMaterial(newMultiMaterial:MultiMaterial){
+            this.multiMaterials.push(newMultiMaterial)
+        }
+
+        public addMaterial(newMaterial:Material){
+            this.materials.push(newMaterial)
+        }
+
+        public addMorphTargetManager(newMorphTargetManager:MorphTargetManager){
+            this.morphTargetManagers.push(newMorphTargetManager)
+        }
+
+        public addGeometry(newGeometrie:Geometry){
+            this._geometries.push(newGeometrie)
+        }
+
+        public addLensFlareSystem(newLensFlareSystem:LensFlareSystem){
+            this.lensFlareSystems.push(newLensFlareSystem)
+        }
+
+        public addActionManager(newActionManager:ActionManager){
+            this._actionManagers.push(newActionManager)
+        }
+
         /**
          * Switch active camera
          * @param {Camera} newCamera - new active camera

BIN
tests/validation/ReferenceImages/assetContainer.png


+ 6 - 0
tests/validation/config.json

@@ -245,6 +245,12 @@
       "excludeFromAutomaticTesting": true
     },
     {
+      "title": "Asset Containers",
+      "playgroundId": "#P3U079#19",
+      "renderCount": 20,
+      "referenceImage": "assetContainer.png"
+    },   
+    {
       "title": "GLTF Mesh Primitive Attribute Test",
       "renderCount": 20,
       "scriptToRun": "/Demos/GLTFMeshPrimitiveAttributeTest/index.js",