@galacean/engine-loader 2.0.0-alpha.29 → 2.0.0-alpha.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/module.js CHANGED
@@ -1,4 +1,4 @@
1
- import { Utils, AssetPromise, AnimationClip, AnimationEvent, Loader, AnimationStringCurve, Keyframe, AnimationBoolCurve, AnimationRefCurve, AnimationQuaternionCurve, AnimationColorCurve, AnimationVector4Curve, AnimationVector3Curve, AnimationVector2Curve, AnimationFloatArrayCurve, AnimationArrayCurve, AnimationFloatCurve, ModelMesh, BlendShape, Signal, Entity, Transform, TextureFormat, Texture2D, TextureCube, TextureCubeFace, ReferResource, DiffuseMode, BackgroundMode, resourceLoader, AssetType, AnimatorController, AnimatorControllerLayer, AnimatorStateTransition, BufferAsset, GLCapabilityType, Logger, ContentRestorer, AmbientLight, TextureFilterMode, Font, SystemInfo, Animator, IndexFormat, VertexElementFormat, request, InterpolationType, SkinnedMeshRenderer, PBRMaterial, TextureCoordinate, RenderFace, VertexElement, Buffer, BufferBindFlag, BufferUsage, Camera, MeshRenderer, Skin, TextureWrapMode as TextureWrapMode$1, TextureUtils, AnimatorStateMachine, JSONAsset, Shader, Material, PrimitiveMesh, SpriteAtlas, Sprite, TextAsset, AudioClip, AudioManager, ShaderFactory, ShaderLib, PhysicsMaterial, RenderTarget, Scene, DirectLight, PointLight, SpotLight, UnlitMaterial } from '@galacean/engine-core';
1
+ import { Utils, AssetPromise, AnimationClip, AnimationEvent, Loader, AnimationStringCurve, Keyframe, AnimationBoolCurve, AnimationRefCurve, AnimationQuaternionCurve, AnimationColorCurve, AnimationVector4Curve, AnimationVector3Curve, AnimationVector2Curve, AnimationFloatArrayCurve, AnimationArrayCurve, AnimationFloatCurve, ModelMesh, BlendShape, TextureFormat, Texture2D, TextureCube, TextureCubeFace, ReferResource, Entity, resourceLoader, AssetType, AnimatorController, AnimatorControllerLayer, AnimatorStateTransition, BufferAsset, GLCapabilityType, Logger, ContentRestorer, AmbientLight, DiffuseMode, TextureFilterMode, Font, SystemInfo, Animator, IndexFormat, VertexElementFormat, request, InterpolationType, SkinnedMeshRenderer, Transform, PBRMaterial, TextureCoordinate, RenderFace, VertexElement, Buffer, BufferBindFlag, BufferUsage, Camera, MeshRenderer, Skin, TextureWrapMode as TextureWrapMode$1, TextureUtils, AnimatorStateMachine, JSONAsset, Shader, Material, PrimitiveMesh, SpriteAtlas, Sprite, TextAsset, AudioClip, AudioManager, PhysicsMaterial, RenderTarget, Scene, BackgroundMode, DirectLight, PointLight, SpotLight, UnlitMaterial } from '@galacean/engine-core';
2
2
  import { Quaternion, Vector4, Color, Vector3, Vector2, MathUtil, SphericalHarmonics3, BoundingBox, Matrix, Rect } from '@galacean/engine-math';
3
3
  import { GLCompressedTextureInternalFormat } from '@galacean/engine-rhi-webgl';
4
4
 
@@ -639,37 +639,27 @@ function float32ArrayToVector2(float32Array, vertexCount) {
639
639
  return array;
640
640
  }
641
641
 
642
- function _is_native_reflect_construct() {
643
- // Since Reflect.construct can't be properly polyfilled, some
644
- // implementations (e.g. core-js@2) don't set the correct internal slots.
645
- // Those polyfills don't allow us to subclass built-ins, so we need to
646
- // use our fallback implementation.
647
- try {
648
- // If the internal slots aren't set, this throws an error similar to
649
- // TypeError: this is not a Boolean object.
650
- var result = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
651
- } catch (_) {}
652
- return (_is_native_reflect_construct = function() {
653
- return !!result;
654
- })();
655
- }
656
-
657
- function _construct(Parent, args, Class) {
658
- if (_is_native_reflect_construct()) _construct = Reflect.construct;
659
- else {
660
- _construct = function construct(Parent, args, Class) {
661
- var a = [null];
662
- a.push.apply(a, args);
663
- var Constructor = Function.bind.apply(Parent, a);
664
- var instance = new Constructor();
642
+ function _object_without_properties_loose(source, excluded) {
643
+ if (source == null) return {};
665
644
 
666
- if (Class) _set_prototype_of(instance, Class.prototype);
645
+ var target = {};
646
+ var sourceKeys = Object.keys(source);
647
+ var key, i;
667
648
 
668
- return instance;
669
- };
649
+ for (i = 0; i < sourceKeys.length; i++) {
650
+ key = sourceKeys[i];
651
+ if (excluded.indexOf(key) >= 0) continue;
652
+ target[key] = source[key];
670
653
  }
671
654
 
672
- return _construct.apply(null, arguments);
655
+ return target;
656
+ }
657
+
658
+ function resolveRefItem(refs, index, owner, label) {
659
+ if (!Number.isInteger(index) || index < 0 || index >= refs.length) {
660
+ throw new Error(owner + ": invalid ref index " + index + " for " + label);
661
+ }
662
+ return refs[index];
673
663
  }
674
664
 
675
665
  var ParserType = /*#__PURE__*/ function(ParserType) {
@@ -685,32 +675,20 @@ var ParserType = /*#__PURE__*/ function(ParserType) {
685
675
  this.engine = engine;
686
676
  this.type = type;
687
677
  this.resource = resource;
688
- this.entityMap = new Map();
689
- this.entityConfigMap = new Map();
690
- this.components = new Map();
691
- this.componentConfigMap = new Map();
692
- this.rootIds = [];
693
- this.strippedIds = [];
694
- this._tasks = new Set();
678
+ this./** Runtime Entity instances, indexed by the flat entities[] position. */ entityInstances = [];
679
+ this./** Components waiting for props/calls application (Stage 4). */ pendingComponents = [];
695
680
  this._loaded = 0;
696
681
  this._total = 0;
697
682
  this.resourceManager = engine.resourceManager;
698
683
  }
699
684
  var _proto = ParserContext.prototype;
700
685
  _proto.clear = function clear() {
701
- this.entityMap.clear();
702
- this.components.clear();
703
- this.componentConfigMap.clear();
704
- this.entityConfigMap.clear();
705
- this.rootIds.length = 0;
706
- this.strippedIds.length = 0;
707
- };
708
- /** @internal */ _proto._addDependentAsset = function _addDependentAsset(url, promise) {
686
+ this.entityInstances.length = 0;
687
+ this.pendingComponents.length = 0;
688
+ };
689
+ /** @internal */ _proto._addDependentAsset = function _addDependentAsset(promise) {
709
690
  var _this = this;
710
- var tasks = this._tasks;
711
- if (tasks.has(url)) return;
712
691
  ++this._total;
713
- tasks.add(url);
714
692
  promise.finally(function() {
715
693
  ++_this._loaded;
716
694
  _this._setTaskCompleteProgress(_this._loaded, _this._total);
@@ -720,230 +698,214 @@ var ParserType = /*#__PURE__*/ function(ParserType) {
720
698
  }();
721
699
 
722
700
  var ReflectionParser = /*#__PURE__*/ function() {
723
- function ReflectionParser(_context) {
701
+ function ReflectionParser(_context, _refs) {
724
702
  this._context = _context;
703
+ this._refs = _refs;
725
704
  }
726
705
  var _proto = ReflectionParser.prototype;
727
- _proto.parseEntity = function parseEntity(entityConfig) {
728
- var _this = this;
729
- return this._getEntityByConfig(entityConfig).then(function(entity) {
730
- var _entityConfig_isActive;
731
- entity.isActive = (_entityConfig_isActive = entityConfig.isActive) != null ? _entityConfig_isActive : true;
732
- var transform = entity.transform;
733
- var transformConfig = entityConfig.transform;
734
- if (transformConfig) {
735
- _this.parsePropsAndMethods(transform, transformConfig);
736
- } else {
737
- var position = entityConfig.position, rotation = entityConfig.rotation, scale = entityConfig.scale;
738
- if (position) transform.position.copyFrom(position);
739
- if (rotation) transform.rotation.copyFrom(rotation);
740
- if (scale) transform.scale.copyFrom(scale);
741
- }
742
- var _entityConfig_layer;
743
- entity.layer = (_entityConfig_layer = entityConfig.layer) != null ? _entityConfig_layer : entity.layer;
744
- // @ts-ignore
745
- _this._context.type === ParserType.Prefab && entity._markAsTemplate(_this._context.resource);
746
- return entity;
747
- });
748
- };
749
- _proto.parseClassObject = function parseClassObject(item) {
750
- var _this = this;
751
- var Class = Loader.getClass(item.class);
752
- var _item_constructParams;
753
- var params = (_item_constructParams = item.constructParams) != null ? _item_constructParams : [];
754
- return Promise.all(params.map(function(param) {
755
- return _this.parseBasicType(param);
756
- })).then(function(resultParams) {
757
- return _construct(Class, [].concat(resultParams));
758
- }).then(function(instance) {
759
- return _this.parsePropsAndMethods(instance, item);
760
- });
761
- };
762
- _proto.parsePropsAndMethods = function parsePropsAndMethods(instance, item) {
706
+ /**
707
+ * Apply v2 props to a component/object instance.
708
+ * Each prop value is resolved recursively (handling $ref, $type, $class, $entity, $component, $signal).
709
+ */ _proto.parseProps = function parseProps(instance, props) {
763
710
  var promises = [];
764
- if (item.methods) {
765
- for(var methodName in item.methods){
766
- var methodParams = item.methods[methodName];
767
- for(var i = 0, count = methodParams.length; i < count; i++){
768
- promises.push(this.parseMethod(instance, methodName, methodParams[i]));
769
- }
770
- }
771
- }
772
- if (item.props) {
711
+ if (props) {
773
712
  var _this, _loop = function(key) {
774
- var value = item.props[key];
775
- var promise = _this.parseBasicType(value, instance[key]).then(function(v) {
776
- return instance[key] = v;
713
+ var promise = _this._resolveValue(props[key], instance[key]).then(function(v) {
714
+ instance[key] = v;
777
715
  });
778
716
  promises.push(promise);
779
717
  };
780
- for(var key in item.props)_this = this, _loop(key);
718
+ for(var key in props)_this = this, _loop(key);
781
719
  }
782
720
  return Promise.all(promises).then(function() {
783
721
  return instance;
784
722
  });
785
723
  };
786
- _proto.parseMethod = function parseMethod(instance, methodName, methodParams) {
724
+ /**
725
+ * Execute calls sequentially on a target instance.
726
+ * Call args are resolved with the same v2 value rules as props.
727
+ */ _proto.parseCalls = function parseCalls(instance, calls) {
728
+ var _loop = function(i, n) {
729
+ var call = calls[i];
730
+ chain = chain.then(function() {
731
+ var method = instance == null ? void 0 : instance[call.method];
732
+ if (typeof method !== "function") {
733
+ return Promise.reject(new Error('Call target does not have method "' + call.method + '"'));
734
+ }
735
+ var _call_args;
736
+ return Promise.all(((_call_args = call.args) != null ? _call_args : []).map(function(arg) {
737
+ return _this._resolveValue(arg);
738
+ })).then(function(resolvedArgs) {
739
+ return Promise.resolve(method.apply(instance, resolvedArgs));
740
+ }).then(function(result) {
741
+ if (!call.result) return result;
742
+ if (result == null || (typeof result === "undefined" ? "undefined" : _type_of(result)) !== "object" && typeof result !== "function") {
743
+ return Promise.reject(new Error('Call "' + call.method + '" returned ' + result + " and cannot be mutated by result"));
744
+ }
745
+ return _this.parseMutationBlock(result, call.result);
746
+ });
747
+ });
748
+ };
787
749
  var _this = this;
788
- var isMethodObject = ReflectionParser._isMethodObject(methodParams);
789
- var params = isMethodObject ? methodParams.params : methodParams;
790
- return Promise.all(params.map(function(param) {
791
- return _this.parseBasicType(param);
792
- })).then(function(result) {
793
- var _instance;
794
- var methodResult = (_instance = instance)[methodName].apply(_instance, [].concat(result));
795
- if (isMethodObject && methodParams.result) {
796
- return _this.parsePropsAndMethods(methodResult, methodParams.result);
797
- } else {
798
- return methodResult;
799
- }
750
+ if (!(calls == null ? void 0 : calls.length)) return Promise.resolve(instance);
751
+ var chain = Promise.resolve();
752
+ for(var i = 0, n = calls.length; i < n; i++)_loop(i);
753
+ return chain.then(function() {
754
+ return instance;
800
755
  });
801
756
  };
802
- _proto.parseSignal = function parseSignal(signalRef) {
803
- var _this = this;
804
- var signal = new Signal();
805
- return Promise.all(signalRef.listeners.map(function(listener) {
806
- return Promise.all([
807
- _this.parseBasicType(listener.target),
808
- listener.arguments ? Promise.all(listener.arguments.map(function(a) {
809
- return _this.parseBasicType(a);
810
- })) : Promise.resolve([])
811
- ]).then(function(param) {
812
- var target = param[0], resolvedArgs = param[1];
813
- if (target) {
814
- var _signal;
815
- (_signal = signal).on.apply(_signal, [].concat([
816
- target,
817
- listener.methodName
818
- ], resolvedArgs));
819
- }
820
- });
821
- })).then(function() {
822
- return signal;
757
+ /**
758
+ * Apply props and calls from the same mutation block without imposing ordering between them.
759
+ */ _proto.parseMutationBlock = function parseMutationBlock(target, block) {
760
+ if (!block) return Promise.resolve(target);
761
+ return Promise.all([
762
+ this.parseProps(target, block.props),
763
+ this.parseCalls(target, block.calls)
764
+ ]).then(function() {
765
+ return target;
823
766
  });
824
767
  };
825
- _proto.parseBasicType = function parseBasicType(value, originValue) {
826
- var _this = this;
827
- if (Array.isArray(value)) {
828
- return Promise.all(value.map(function(item) {
829
- return _this.parseBasicType(item);
768
+ /**
769
+ * Resolve a v2 value with $ prefix detection.
770
+ *
771
+ * Priority:
772
+ * 1. null/undefined/primitive → passthrough
773
+ * 2. Array → recurse each element
774
+ * 3. { $ref } → asset reference
775
+ * 4. { $type } → polymorphic type construct
776
+ * 5. { $class } → registered class constructor
777
+ * 6. { $entity } → entity reference by path (flat index + optional children descent)
778
+ * 7. { $component } → component reference
779
+ * 8. { $signal } → signal binding
780
+ * 9. plain object → recurse values (modify originValue in place if exists)
781
+ */ _proto._resolveValue = function _resolveValue(value, originValue) {
782
+ var _this, _loop = function(key) {
783
+ promises.push(_this._resolveValue(obj[key], target[key]).then(function(v) {
784
+ return target[key] = v;
830
785
  }));
831
- } else if ((typeof value === "undefined" ? "undefined" : _type_of(value)) === "object" && value != null) {
832
- if (ReflectionParser._isClassType(value)) {
833
- return Promise.resolve(Loader.getClass(value["classType"]));
834
- } else if (ReflectionParser._isClass(value)) {
835
- // class object
836
- return this.parseClassObject(value);
837
- } else if (ReflectionParser._isAssetRef(value)) {
838
- var _this1 = this, context = _this1._context;
839
- // reference object
840
- // @ts-ignore
841
- return context.resourceManager.getResourceByRef(value).then(function(resource) {
842
- if (resource && context.type === ParserType.Prefab) {
843
- // @ts-ignore
844
- context.resource._addDependenceAsset(resource);
845
- }
846
- return resource;
847
- });
848
- } else if (ReflectionParser._isComponentRef(value)) {
849
- var entity = this._resolveEntityByPath(value.entityPath);
850
- if (!entity) return Promise.resolve(null);
851
- var type = Loader.getClass(value.componentType);
852
- if (!type) return Promise.resolve(null);
853
- var _entity_getComponents_value_componentIndex;
854
- return Promise.resolve((_entity_getComponents_value_componentIndex = entity.getComponents(type, [])[value.componentIndex]) != null ? _entity_getComponents_value_componentIndex : null);
855
- } else if (ReflectionParser._isEntityRef(value)) {
856
- return Promise.resolve(this._resolveEntityByPath(value.entityPath));
857
- } else if (ReflectionParser._isSignalRef(value)) {
858
- return this.parseSignal(value);
859
- } else if (originValue) {
860
- var _this2, _loop = function(key) {
861
- if (key === "methods") {
862
- var methods = value[key];
863
- for(var methodName in methods){
864
- var methodParams = methods[methodName];
865
- for(var i = 0, count = methodParams.length; i < count; i++){
866
- var params = methodParams[i];
867
- var promise = _this2.parseMethod(originValue, methodName, params);
868
- promises.push(promise);
869
- }
870
- }
871
- } else {
872
- promises.push(_this2.parseBasicType(value[key], originValue[key]).then(function(v) {
873
- return originValue[key] = v;
874
- }));
875
- }
876
- };
877
- var promises = [];
878
- for(var key in value)_this2 = this, _loop(key);
879
- return Promise.all(promises).then(function() {
880
- return originValue;
881
- });
786
+ };
787
+ var _this1 = this;
788
+ if (value == null || (typeof value === "undefined" ? "undefined" : _type_of(value)) !== "object") return Promise.resolve(value);
789
+ if (Array.isArray(value)) return Promise.all(value.map(function(v) {
790
+ return _this1._resolveValue(v);
791
+ }));
792
+ var obj = value;
793
+ // $ref asset reference (index into refs array)
794
+ if ("$ref" in obj) {
795
+ var _this2 = this, context = _this2._context;
796
+ var refItem;
797
+ try {
798
+ refItem = resolveRefItem(this._refs, obj.$ref, "ReflectionParser", "$ref");
799
+ } catch (error) {
800
+ return Promise.reject(error);
882
801
  }
883
- }
884
- // primitive type
885
- return Promise.resolve(value);
886
- };
887
- _proto._getEntityByConfig = function _getEntityByConfig(entityConfig) {
888
- var _this = this;
889
- // @ts-ignore
890
- var assetUrl = entityConfig.assetUrl;
891
- var engine = this._context.engine;
892
- if (assetUrl) {
893
- return engine.resourceManager// @ts-ignore
894
- .getResourceByRef({
895
- url: assetUrl,
896
- key: entityConfig.key,
897
- isClone: entityConfig.isClone
898
- }).then(function(entity) {
899
- // @ts-ignore
900
- var resource = engine.resourceManager._objectPool[assetUrl];
901
- if (resource && _this._context.type === ParserType.Prefab) {
802
+ // @ts-ignore
803
+ return context.resourceManager.getResourceByRef(refItem).then(function(resource) {
804
+ if (resource && context.type === ParserType.Prefab) {
902
805
  // @ts-ignore
903
- _this._context.resource._addDependenceAsset(resource);
806
+ context.resource._addDependenceAsset(resource);
904
807
  }
905
- entity.name = entityConfig.name;
906
- return entity;
808
+ return resource;
907
809
  });
908
- } else {
909
- var transform = entityConfig.transform;
910
- var entity = new Entity(engine, entityConfig.name, transform ? Loader.getClass(transform.class) : Transform);
911
- return Promise.resolve(entity);
912
810
  }
913
- };
914
- _proto._resolveEntityByPath = function _resolveEntityByPath(entityPath) {
915
- var _this__context = this._context, rootIds = _this__context.rootIds, entityMap = _this__context.entityMap;
916
- if (!entityPath.length || entityPath[0] >= rootIds.length) return null;
917
- var entity = entityMap.get(rootIds[entityPath[0]]);
918
- for(var i = 1; i < entityPath.length; i++){
919
- if (!entity || entityPath[i] >= entity.children.length) return null;
920
- entity = entity.children[entityPath[i]];
811
+ // $type — polymorphic type: construct instance and apply remaining props
812
+ if ("$type" in obj) {
813
+ var $type = obj.$type, rest = _object_without_properties_loose(obj, [
814
+ "$type"
815
+ ]);
816
+ return this._resolveRegisteredClass($type, "$type").then(function(Class) {
817
+ var instance = new Class();
818
+ return Object.keys(rest).length > 0 ? _this1.parseProps(instance, rest) : instance;
819
+ });
921
820
  }
922
- return entity;
923
- };
924
- ReflectionParser._isClass = function _isClass(value) {
925
- return value["class"] !== undefined;
926
- };
927
- ReflectionParser._isClassType = function _isClassType(value) {
928
- return value["classType"] !== undefined;
821
+ // $class — registered class constructor for factory-style methods.
822
+ if ("$class" in obj) {
823
+ return this._resolveRegisteredClass(obj.$class, "$class");
824
+ }
825
+ // $entity — entity reference by path (first element = flat index, subsequent = children indices)
826
+ if ("$entity" in obj) {
827
+ return Promise.resolve(this._resolveEntityRef(obj.$entity));
828
+ }
829
+ // $component — component reference: { entity, type, index }
830
+ if ("$component" in obj) {
831
+ return Promise.resolve(this._resolveComponent(obj.$component));
832
+ }
833
+ // $signal — signal binding: register listeners on the existing Signal instance
834
+ if ("$signal" in obj) {
835
+ return this._resolveSignal(originValue, obj.$signal);
836
+ }
837
+ // Plain object — recurse each value, modifying originValue in place or building a new object
838
+ var target = originValue && (typeof originValue === "undefined" ? "undefined" : _type_of(originValue)) === "object" && !Array.isArray(originValue) ? originValue : {};
839
+ var promises = [];
840
+ for(var key in obj)_this = this, _loop(key);
841
+ return Promise.all(promises).then(function() {
842
+ return target;
843
+ });
929
844
  };
930
- ReflectionParser._isAssetRef = function _isAssetRef(value) {
931
- return value["url"] !== undefined;
845
+ _proto._getRegisteredClass = function _getRegisteredClass(value, sentinel) {
846
+ if (typeof value !== "string" || value.length === 0) {
847
+ throw new Error("" + sentinel + " must be a non-empty registered class name string");
848
+ }
849
+ var Class = Loader.getClass(value);
850
+ if (!Class) throw new Error('Loader.getClass: class "' + value + '" is not registered');
851
+ return Class;
932
852
  };
933
- ReflectionParser._isEntityRef = function _isEntityRef(value) {
934
- return Array.isArray(value["entityPath"]) && value["componentType"] === undefined;
853
+ /** Promise-adapt {@link _getRegisteredClass} so $type/$class branches can fold into the resolver chain. */ _proto._resolveRegisteredClass = function _resolveRegisteredClass(value, sentinel) {
854
+ try {
855
+ return Promise.resolve(this._getRegisteredClass(value, sentinel));
856
+ } catch (error) {
857
+ return Promise.reject(error);
858
+ }
935
859
  };
936
- ReflectionParser._isComponentRef = function _isComponentRef(value) {
937
- return Array.isArray(value["entityPath"]) && value["componentType"] !== undefined;
860
+ _proto._resolveSignal = function _resolveSignal(signal, listeners) {
861
+ var _this = this;
862
+ if (!signal || typeof signal.on !== "function") {
863
+ return Promise.reject(new Error("$signal requires a pre-initialized Signal instance on the target property"));
864
+ }
865
+ var promises = listeners.map(function(listener) {
866
+ var targetComponent = _this._resolveComponent(listener.target.$component);
867
+ if (!targetComponent) return Promise.resolve();
868
+ var _listener_args;
869
+ return Promise.all(((_listener_args = listener.args) != null ? _listener_args : []).map(function(a) {
870
+ return _this._resolveValue(a);
871
+ })).then(function(resolvedArgs) {
872
+ var _signal;
873
+ (_signal = signal).on.apply(_signal, [].concat([
874
+ targetComponent,
875
+ listener.methodName
876
+ ], resolvedArgs));
877
+ });
878
+ });
879
+ return Promise.all(promises).then(function() {
880
+ return signal;
881
+ });
938
882
  };
939
- ReflectionParser._isSignalRef = function _isSignalRef(value) {
940
- return value["listeners"] !== undefined;
883
+ _proto._resolveComponent = function _resolveComponent(comp) {
884
+ var entity = this._resolveEntityRef(comp.entity);
885
+ if (!entity) return null;
886
+ var type = Loader.getClass(comp.type);
887
+ if (!type) return null;
888
+ var buffer = ReflectionParser._componentBuffer;
889
+ buffer.length = 0;
890
+ entity.getComponents(type, buffer);
891
+ var _buffer_comp_index;
892
+ var result = (_buffer_comp_index = buffer[comp.index]) != null ? _buffer_comp_index : null;
893
+ buffer.length = 0;
894
+ return result;
941
895
  };
942
- ReflectionParser._isMethodObject = function _isMethodObject(value) {
943
- return Array.isArray(value == null ? void 0 : value.params);
896
+ _proto._resolveEntityRef = function _resolveEntityRef(path) {
897
+ if (!path || path.length === 0) return null;
898
+ var _this__context_entityInstances_path_;
899
+ var entity = (_this__context_entityInstances_path_ = this._context.entityInstances[path[0]]) != null ? _this__context_entityInstances_path_ : null;
900
+ for(var i = 1, n = path.length; entity && i < n; i++){
901
+ var _entity_children_path_i;
902
+ entity = (_entity_children_path_i = entity.children[path[i]]) != null ? _entity_children_path_i : null;
903
+ }
904
+ return entity;
944
905
  };
945
906
  return ReflectionParser;
946
907
  }();
908
+ /** @internal shared with HierarchyParser; each use must length=0 -> getComponents -> read -> length=0 synchronously. */ ReflectionParser._componentBuffer = [];
947
909
 
948
910
  /**
949
911
  * HDR (Radiance RGBE) image decoder.
@@ -1245,45 +1207,6 @@ function _instanceof(left, right) {
1245
1207
  } else return left instanceof right;
1246
1208
  }
1247
1209
 
1248
- function _array_like_to_array(arr, len) {
1249
- if (len == null || len > arr.length) len = arr.length;
1250
-
1251
- for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
1252
-
1253
- return arr2;
1254
- }
1255
-
1256
- function _unsupported_iterable_to_array(o, minLen) {
1257
- if (!o) return;
1258
- if (typeof o === "string") return _array_like_to_array(o, minLen);
1259
-
1260
- var n = Object.prototype.toString.call(o).slice(8, -1);
1261
-
1262
- if (n === "Object" && o.constructor) n = o.constructor.name;
1263
- if (n === "Map" || n === "Set") return Array.from(n);
1264
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
1265
- }
1266
-
1267
- function _create_for_of_iterator_helper_loose(o, allowArrayLike) {
1268
- var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
1269
-
1270
- if (it) return (it = it.call(o)).next.bind(it);
1271
- // Fallback for engines without symbol support
1272
- if (Array.isArray(o) || (it = _unsupported_iterable_to_array(o)) || allowArrayLike && o && typeof o.length === "number") {
1273
- if (it) o = it;
1274
-
1275
- var i = 0;
1276
-
1277
- return function() {
1278
- if (i >= o.length) return { done: true };
1279
-
1280
- return { done: false, value: o[i++] };
1281
- };
1282
- }
1283
-
1284
- throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
1285
- }
1286
-
1287
1210
  /**
1288
1211
  * The Prefab resource.
1289
1212
  */ var PrefabResource = /*#__PURE__*/ function(ReferResource1) {
@@ -1315,8 +1238,9 @@ function _create_for_of_iterator_helper_loose(o, allowArrayLike) {
1315
1238
  };
1316
1239
  _proto._onDestroy = function _onDestroy() {
1317
1240
  var _this = this;
1241
+ var _this__root;
1318
1242
  ReferResource1.prototype._onDestroy.call(this);
1319
- this._root.destroy();
1243
+ (_this__root = this._root) == null ? void 0 : _this__root.destroy();
1320
1244
  this._dependenceAssets.forEach(function(asset) {
1321
1245
  if (_instanceof(asset, ReferResource)) {
1322
1246
  // @ts-ignore
@@ -1332,319 +1256,260 @@ function _create_for_of_iterator_helper_loose(o, allowArrayLike) {
1332
1256
  var _this = this;
1333
1257
  this.data = data;
1334
1258
  this.context = context;
1335
- this._prefabContextMap = new WeakMap();
1336
- this._prefabPromiseMap = new Map();
1259
+ if (data.version !== "2.0") {
1260
+ var resourceType = context.type === ParserType.Scene ? "scene" : "prefab";
1261
+ throw new Error("Unsupported " + resourceType + ' format version "' + data.version + '". Expected "2.0".');
1262
+ }
1337
1263
  this._engine = this.context.engine;
1338
- this._organizeEntities = this._organizeEntities.bind(this);
1339
- this._parseComponents = this._parseComponents.bind(this);
1340
- this._parsePrefabModification = this._parsePrefabModification.bind(this);
1341
- this._parseAddedComponents = this._parseAddedComponents.bind(this);
1342
- this._parseComponentsPropsAndMethods = this._parseComponentsPropsAndMethods.bind(this);
1343
- this._parsePrefabRemovedEntities = this._parsePrefabRemovedEntities.bind(this);
1344
- this._parsePrefabRemovedComponents = this._parsePrefabRemovedComponents.bind(this);
1345
- this._clearAndResolve = this._clearAndResolve.bind(this);
1346
1264
  this.promise = new Promise(function(resolve, reject) {
1347
1265
  _this._reject = reject;
1348
1266
  _this._resolve = resolve;
1349
1267
  });
1350
- this._reflectionParser = new ReflectionParser(context);
1268
+ this._reflectionParser = new ReflectionParser(context, data.refs);
1351
1269
  }
1352
1270
  var _proto = HierarchyParser.prototype;
1353
- /** start parse the scene or prefab or others */ _proto.start = function start() {
1354
- this._parseEntities().then(this._organizeEntities).then(this._parseComponents).then(this._parseAddedComponents).then(this._parseComponentsPropsAndMethods).then(this._parsePrefabModification).then(this._parsePrefabRemovedEntities).then(this._parsePrefabRemovedComponents).then(this._clearAndResolve).then(this._resolve).catch(this._reject);
1355
- };
1356
- _proto._applyEntityData = function _applyEntityData(entity, entityConfig) {
1357
- if (entityConfig === void 0) entityConfig = {};
1358
- var _entityConfig_isActive;
1359
- entity.isActive = (_entityConfig_isActive = entityConfig.isActive) != null ? _entityConfig_isActive : entity.isActive;
1360
- var _entityConfig_name;
1361
- entity.name = (_entityConfig_name = entityConfig.name) != null ? _entityConfig_name : entity.name;
1362
- var transform = entity.transform;
1363
- var transformConfig = entityConfig.transform;
1364
- if (transformConfig) {
1365
- this._reflectionParser.parsePropsAndMethods(transform, transformConfig);
1366
- } else {
1367
- var position = entityConfig.position, rotation = entityConfig.rotation, scale = entityConfig.scale;
1368
- if (position) transform.position.copyFrom(position);
1369
- if (rotation) transform.rotation.copyFrom(rotation);
1370
- if (scale) transform.scale.copyFrom(scale);
1371
- }
1372
- if (entityConfig.layer) entity.layer = entityConfig.layer;
1373
- return entity;
1374
- };
1375
- _proto._parseEntities = function _parseEntities() {
1271
+ _proto.start = function start() {
1376
1272
  var _this = this;
1377
- var entitiesConfig = this.data.entities;
1378
- var entityConfigMap = this.context.entityConfigMap;
1379
- var entityMap = this.context.entityMap;
1380
- var engine = this._engine;
1381
- var promises = entitiesConfig.map(function(entityConfig) {
1382
- var _entityConfig_strippedId;
1383
- var id = (_entityConfig_strippedId = entityConfig.strippedId) != null ? _entityConfig_strippedId : entityConfig.id;
1384
- entityConfig.id = id;
1385
- entityConfigMap.set(id, entityConfig);
1386
- return _this._getEntityByConfig(entityConfig, engine);
1387
- });
1388
- return Promise.all(promises).then(function(entities) {
1389
- for(var i = 0, l = entities.length; i < l; i++){
1390
- entityMap.set(entitiesConfig[i].id, entities[i]);
1391
- }
1392
- // Build rootIds in serialization order (not async completion order)
1393
- var rootIds = _this.context.rootIds;
1394
- for(var i1 = 0, l1 = entitiesConfig.length; i1 < l1; i1++){
1395
- if (!entitiesConfig[i1].parent && !entitiesConfig[i1].strippedId) {
1396
- rootIds.push(entitiesConfig[i1].id);
1397
- }
1398
- }
1399
- return entities;
1400
- });
1401
- };
1402
- _proto._parseComponents = function _parseComponents() {
1403
- var entitiesConfig = this.data.entities;
1404
- var entityMap = this.context.entityMap;
1405
- for(var i = 0, l = entitiesConfig.length; i < l; i++){
1406
- var entityConfig = entitiesConfig[i];
1407
- if (entityConfig.strippedId) {
1408
- continue;
1409
- }
1410
- var entity = entityMap.get(entityConfig.id);
1411
- this._addComponents(entity, entityConfig.components);
1412
- }
1413
- };
1414
- _proto._parsePrefabModification = function _parsePrefabModification() {
1415
- var _loop = function(i, l) {
1416
- var entityConfig = entitiesConfig[i];
1417
- var id = entityConfig.id, modifications = entityConfig.modifications;
1418
- if (modifications == null ? void 0 : modifications.length) {
1419
- var _promises;
1420
- var rootEntity = entityMap.get(id);
1421
- (_promises = promises).push.apply(_promises, [].concat(modifications.map(function(modification) {
1422
- var target = modification.target, props = modification.props, methods = modification.methods;
1423
- var entityId = target.entityId, componentId = target.componentId;
1424
- var context = _this._prefabContextMap.get(rootEntity);
1425
- var targetEntity = context.entityMap.get(entityId);
1426
- var targetComponent = context.components.get(componentId);
1427
- if (targetComponent) {
1428
- return _this._reflectionParser.parsePropsAndMethods(targetComponent, {
1429
- props: props,
1430
- methods: methods
1431
- });
1432
- } else if (targetEntity) {
1433
- return Promise.resolve(_this._applyEntityData(targetEntity, props));
1434
- }
1435
- })));
1273
+ this._parseEntities().then(function() {
1274
+ return _this._organizeEntities();
1275
+ }).then(function() {
1276
+ return _this._parseComponents();
1277
+ }).then(function() {
1278
+ return _this._parseComponentsPropsAndCalls();
1279
+ }).then(function() {
1280
+ return _this._parsePrefabOverrides();
1281
+ }).then(function() {
1282
+ return _this._clearAndResolve();
1283
+ }).then(this._resolve).catch(this._reject);
1284
+ };
1285
+ _proto._onEntityCreated = function _onEntityCreated(_entity) {};
1286
+ // ---------------------------------------------------------------------------
1287
+ // Stage 1: Create entity instances
1288
+ // ---------------------------------------------------------------------------
1289
+ _proto._parseEntities = function _parseEntities() {
1290
+ var _this, _loop = function(i, n) {
1291
+ var entityConfig = entities[i];
1292
+ if (HierarchyParser._isPrefabInstanceEntity(entityConfig)) {
1293
+ promises.push(_this._loadPrefabInstance(entityConfig, engine).then(function(entity) {
1294
+ entityInstances[i] = entity;
1295
+ }));
1296
+ } else {
1297
+ var entity = new Entity(engine, entityConfig.name);
1298
+ HierarchyParser._applyEntityProps(entity, entityConfig);
1299
+ _this._onEntityCreated(entity);
1300
+ entityInstances[i] = entity;
1436
1301
  }
1437
1302
  };
1438
- var _this = this;
1439
- var entitiesConfig = this.data.entities;
1440
- var entityMap = this.context.entityMap;
1303
+ var entities = this.data.entities;
1304
+ var entityInstances = this.context.entityInstances;
1305
+ var engine = this._engine;
1441
1306
  var promises = [];
1442
- for(var i = 0, l = entitiesConfig.length; i < l; i++)_loop(i);
1307
+ for(var i = 0, n = entities.length; i < n; i++)_this = this, _loop(i);
1443
1308
  return Promise.all(promises);
1444
1309
  };
1445
- _proto._parseAddedComponents = function _parseAddedComponents() {
1446
- var entityMap = this.context.entityMap;
1447
- var entityConfigMap = this.context.entityConfigMap;
1448
- var strippedIds = this.context.strippedIds;
1449
- for(var i = 0, n = strippedIds.length; i < n; i++){
1450
- var entityConfig = entityConfigMap.get(strippedIds[i]);
1451
- var prefabContext = this._prefabContextMap.get(entityMap.get(entityConfig.prefabInstanceId));
1452
- var entity = prefabContext.entityMap.get(entityConfig.prefabSource.entityId);
1453
- this._addComponents(entity, entityConfig.components);
1454
- }
1455
- };
1456
- _proto._parsePrefabRemovedEntities = function _parsePrefabRemovedEntities() {
1457
- var entitiesConfig = this.data.entities;
1458
- var entityMap = this.context.entityMap;
1459
- for(var i = 0, l = entitiesConfig.length; i < l; i++){
1460
- var entityConfig = entitiesConfig[i];
1461
- var id = entityConfig.id, removedEntities = entityConfig.removedEntities;
1462
- if (removedEntities == null ? void 0 : removedEntities.length) {
1463
- var rootEntity = entityMap.get(id);
1464
- for(var j = 0, m = removedEntities.length; j < m; j++){
1465
- var target = removedEntities[j];
1466
- var entityId = target.entityId;
1467
- var context = this._prefabContextMap.get(rootEntity);
1468
- var targetEntity = context.entityMap.get(entityId);
1469
- if (targetEntity) {
1470
- targetEntity.destroy();
1471
- }
1472
- }
1310
+ // ---------------------------------------------------------------------------
1311
+ // Stage 2: Build parent-child hierarchy
1312
+ // ---------------------------------------------------------------------------
1313
+ _proto._organizeEntities = function _organizeEntities() {
1314
+ var entities = this.data.entities;
1315
+ var entityInstances = this.context.entityInstances;
1316
+ for(var i = 0, n = entities.length; i < n; i++){
1317
+ var entityConfig = entities[i];
1318
+ // Prefab instance entities manage their own children.
1319
+ if (HierarchyParser._isPrefabInstanceEntity(entityConfig)) continue;
1320
+ var children = entityConfig.children;
1321
+ if (!children) continue;
1322
+ var parent = entityInstances[i];
1323
+ for(var j = 0, m = children.length; j < m; j++){
1324
+ parent.addChild(entityInstances[children[j]]);
1473
1325
  }
1474
1326
  }
1327
+ var rootIndices = this._getRootIndices();
1328
+ for(var i1 = 0, n1 = rootIndices.length; i1 < n1; i1++){
1329
+ this._handleRootEntity(rootIndices[i1]);
1330
+ }
1475
1331
  };
1476
- _proto._parsePrefabRemovedComponents = function _parsePrefabRemovedComponents() {
1477
- var entitiesConfig = this.data.entities;
1478
- var entityMap = this.context.entityMap;
1479
- var prefabContextMap = this._prefabContextMap;
1480
- for(var i = 0, l = entitiesConfig.length; i < l; i++){
1481
- var entityConfig = entitiesConfig[i];
1482
- var id = entityConfig.id, removedComponents = entityConfig.removedComponents;
1483
- if (removedComponents == null ? void 0 : removedComponents.length) {
1484
- var rootEntity = entityMap.get(id);
1485
- for(var j = 0, m = removedComponents.length; j < m; j++){
1486
- var target = removedComponents[j];
1487
- var componentId = target.componentId;
1488
- var context = prefabContextMap.get(rootEntity);
1489
- var targetComponent = context.components.get(componentId);
1490
- if (targetComponent) {
1491
- targetComponent.destroy();
1492
- }
1493
- }
1332
+ // ---------------------------------------------------------------------------
1333
+ // Stage 3: Add components to entities
1334
+ // ---------------------------------------------------------------------------
1335
+ _proto._parseComponents = function _parseComponents() {
1336
+ var entities = this.data.entities;
1337
+ var allComponents = this.data.components;
1338
+ var entityInstances = this.context.entityInstances;
1339
+ var pendingComponents = this.context.pendingComponents;
1340
+ var refs = this.data.refs;
1341
+ for(var i = 0, n = entities.length; i < n; i++){
1342
+ var entityConfig = entities[i];
1343
+ if (HierarchyParser._isPrefabInstanceEntity(entityConfig)) continue;
1344
+ var entity = entityInstances[i];
1345
+ var componentIndices = entityConfig.components;
1346
+ if (!componentIndices) continue;
1347
+ for(var j = 0, m = componentIndices.length; j < m; j++){
1348
+ var config = allComponents[componentIndices[j]];
1349
+ var instance = HierarchyParser._addComponentFromConfig(entity, config, refs);
1350
+ pendingComponents.push({
1351
+ instance: instance,
1352
+ config: config
1353
+ });
1494
1354
  }
1495
1355
  }
1496
1356
  };
1497
- _proto._organizeEntities = function _organizeEntities() {
1498
- var _this_context = this.context, rootIds = _this_context.rootIds, strippedIds = _this_context.strippedIds;
1499
- var parentIds = rootIds.concat(strippedIds);
1500
- for(var i = 0, l = parentIds.length; i < l; i++){
1501
- this._parseChildren(parentIds[i]);
1502
- }
1503
- for(var i1 = 0; i1 < rootIds.length; i1++){
1504
- this._handleRootEntity(rootIds[i1]);
1357
+ // ---------------------------------------------------------------------------
1358
+ // Stage 4: Apply props and execute calls on components
1359
+ // ---------------------------------------------------------------------------
1360
+ _proto._parseComponentsPropsAndCalls = function _parseComponentsPropsAndCalls() {
1361
+ var pendingComponents = this.context.pendingComponents;
1362
+ var reflectionParser = this._reflectionParser;
1363
+ var promises = [];
1364
+ for(var i = 0, n = pendingComponents.length; i < n; i++){
1365
+ var _pendingComponents_i = pendingComponents[i], instance = _pendingComponents_i.instance, config = _pendingComponents_i.config;
1366
+ promises.push(reflectionParser.parseMutationBlock(instance, config));
1505
1367
  }
1368
+ return Promise.all(promises);
1506
1369
  };
1507
- _proto._getEntityByConfig = function _getEntityByConfig(entityConfig, engine) {
1508
- var _this = this;
1509
- var entityPromise;
1510
- if (entityConfig.assetUrl) {
1511
- entityPromise = this._parsePrefab(entityConfig, engine);
1512
- } else if (entityConfig.strippedId) {
1513
- entityPromise = this._parseStrippedEntity(entityConfig);
1514
- } else {
1515
- entityPromise = this._parseEntity(entityConfig, engine);
1370
+ // ---------------------------------------------------------------------------
1371
+ // Stage 5: Apply prefab instance overrides
1372
+ // ---------------------------------------------------------------------------
1373
+ _proto._parsePrefabOverrides = function _parsePrefabOverrides() {
1374
+ var entities = this.data.entities;
1375
+ var entityInstances = this.context.entityInstances;
1376
+ var promises = [];
1377
+ for(var i = 0, n = entities.length; i < n; i++){
1378
+ var entityConfig = entities[i];
1379
+ if (!HierarchyParser._isPrefabInstanceEntity(entityConfig)) continue;
1380
+ var overrides = entityConfig.instance.overrides;
1381
+ if (!overrides) continue;
1382
+ this._applyOverrides(entityInstances[i], overrides, promises);
1516
1383
  }
1517
- return entityPromise.then(function(entity) {
1518
- return _this._applyEntityData(entity, entityConfig);
1519
- });
1384
+ return Promise.all(promises);
1520
1385
  };
1521
- _proto._parseEntity = function _parseEntity(entityConfig, engine) {
1522
- var transform = entityConfig.transform;
1523
- var entity = new Entity(engine, entityConfig.name, transform ? Loader.getClass(transform.class) : Transform);
1524
- this._addEntityPlugin(entityConfig.id, entity);
1525
- return Promise.resolve(entity);
1386
+ _proto._applyOverrides = function _applyOverrides(rootEntity, overrides, promises) {
1387
+ var refs = this.data.refs;
1388
+ var reflectionParser = this._reflectionParser;
1389
+ // entityProps — entity-level property overrides
1390
+ if (overrides.entityProps) {
1391
+ for(var j = 0, m = overrides.entityProps.length; j < m; j++){
1392
+ var override = overrides.entityProps[j];
1393
+ HierarchyParser._applyEntityProps(HierarchyParser._resolveEntity(rootEntity, override.path), override);
1394
+ }
1395
+ }
1396
+ // componentProps — component-level property overrides
1397
+ if (overrides.componentProps) {
1398
+ for(var j1 = 0, m1 = overrides.componentProps.length; j1 < m1; j1++){
1399
+ var override1 = overrides.componentProps[j1];
1400
+ var entity = HierarchyParser._resolveEntity(rootEntity, override1.path);
1401
+ var target = HierarchyParser._resolveComponent(entity, override1.selector);
1402
+ promises.push(reflectionParser.parseMutationBlock(target, override1));
1403
+ }
1404
+ }
1405
+ // addedComponents — attach top-level components[index] to a prefab entity and parse props
1406
+ if (overrides.addedComponents) {
1407
+ var allComponents = this.data.components;
1408
+ for(var j2 = 0, m2 = overrides.addedComponents.length; j2 < m2; j2++){
1409
+ var added = overrides.addedComponents[j2];
1410
+ var entity1 = HierarchyParser._resolveEntity(rootEntity, added.target);
1411
+ var config = allComponents[added.component];
1412
+ var component = HierarchyParser._addComponentFromConfig(entity1, config, refs);
1413
+ promises.push(reflectionParser.parseMutationBlock(component, config));
1414
+ }
1415
+ }
1416
+ // addedEntities — attach already-created top-level entityInstances[index] as a child
1417
+ if (overrides.addedEntities) {
1418
+ var entityInstances = this.context.entityInstances;
1419
+ for(var j3 = 0, m3 = overrides.addedEntities.length; j3 < m3; j3++){
1420
+ var added1 = overrides.addedEntities[j3];
1421
+ var parent = HierarchyParser._resolveEntity(rootEntity, added1.parent);
1422
+ parent.addChild(entityInstances[added1.entity]);
1423
+ }
1424
+ }
1425
+ // removedEntities — pre-resolve all targets then destroy (destroy shifts sibling indices)
1426
+ if (overrides.removedEntities) {
1427
+ var removed = overrides.removedEntities;
1428
+ var targets = new Array(removed.length);
1429
+ for(var j4 = 0, m4 = removed.length; j4 < m4; j4++){
1430
+ targets[j4] = HierarchyParser._resolveEntity(rootEntity, removed[j4]);
1431
+ }
1432
+ for(var j5 = 0, m5 = targets.length; j5 < m5; j5++){
1433
+ targets[j5].destroy();
1434
+ }
1435
+ }
1436
+ // removedComponents — pre-resolve all targets then destroy (destroy shifts component indices)
1437
+ if (overrides.removedComponents) {
1438
+ var targets1 = [];
1439
+ for(var j6 = 0, m6 = overrides.removedComponents.length; j6 < m6; j6++){
1440
+ var override2 = overrides.removedComponents[j6];
1441
+ var entity2 = HierarchyParser._resolveEntity(rootEntity, override2.path);
1442
+ var selectors = override2.selectors;
1443
+ for(var k = 0, p = selectors.length; k < p; k++){
1444
+ targets1.push(HierarchyParser._resolveComponent(entity2, selectors[k]));
1445
+ }
1446
+ }
1447
+ for(var j7 = 0, m7 = targets1.length; j7 < m7; j7++){
1448
+ targets1[j7].destroy();
1449
+ }
1450
+ }
1526
1451
  };
1527
- _proto._parsePrefab = function _parsePrefab(entityConfig, engine) {
1452
+ // ---------------------------------------------------------------------------
1453
+ // Prefab instance loading
1454
+ // ---------------------------------------------------------------------------
1455
+ _proto._loadPrefabInstance = function _loadPrefabInstance(entityConfig, engine) {
1528
1456
  var _this = this;
1529
- var assetUrl = entityConfig.assetUrl;
1457
+ var instance = entityConfig.instance;
1458
+ var refItem;
1459
+ try {
1460
+ refItem = resolveRefItem(this.data.refs, instance.asset, "HierarchyParser", "instance.asset");
1461
+ } catch (error) {
1462
+ return Promise.reject(error);
1463
+ }
1530
1464
  return engine.resourceManager// @ts-ignore
1531
- .getResourceByRef({
1532
- url: assetUrl
1533
- }).then(function(prefabResource) {
1465
+ .getResourceByRef(refItem).then(function(prefabResource) {
1534
1466
  var entity = _instanceof(prefabResource, PrefabResource) ? prefabResource.instantiate() : prefabResource.instantiateSceneRoot();
1535
- var instanceContext = new ParserContext(engine, ParserType.Prefab, null);
1536
- _this._generateInstanceContext(entity, instanceContext, "");
1537
- _this._prefabContextMap.set(entity, instanceContext);
1538
- var cbArray = _this._prefabPromiseMap.get(entityConfig.id);
1539
- if (cbArray) {
1540
- for(var i = 0, n = cbArray.length; i < n; i++){
1541
- cbArray[i].resolve(instanceContext);
1542
- }
1543
- }
1467
+ _this._onEntityCreated(entity);
1544
1468
  return entity;
1545
1469
  });
1546
1470
  };
1547
- _proto._parseStrippedEntity = function _parseStrippedEntity(entityConfig) {
1548
- var _this = this;
1549
- this.context.strippedIds.push(entityConfig.id);
1550
- return new Promise(function(resolve, reject) {
1551
- var _this__prefabPromiseMap_get;
1552
- var cbArray = (_this__prefabPromiseMap_get = _this._prefabPromiseMap.get(entityConfig.prefabInstanceId)) != null ? _this__prefabPromiseMap_get : [];
1553
- cbArray.push({
1554
- resolve: resolve,
1555
- reject: reject
1556
- });
1557
- _this._prefabPromiseMap.set(entityConfig.prefabInstanceId, cbArray);
1558
- }).then(function(context) {
1559
- var entityId = entityConfig.prefabSource.entityId;
1560
- return context.entityMap.get(entityId);
1561
- });
1562
- };
1563
- _proto._parseChildren = function _parseChildren(parentId) {
1564
- var _this_context = this.context, entityConfigMap = _this_context.entityConfigMap, entityMap = _this_context.entityMap;
1565
- var children = entityConfigMap.get(parentId).children;
1566
- if (children && children.length > 0) {
1567
- var parent = entityMap.get(parentId);
1568
- for(var i = 0; i < children.length; i++){
1569
- var childId = children[i];
1570
- var entity = entityMap.get(childId);
1571
- parent.addChild(entity);
1572
- this._parseChildren(childId);
1573
- }
1471
+ // ---------------------------------------------------------------------------
1472
+ // Utilities
1473
+ // ---------------------------------------------------------------------------
1474
+ /** Resolve an entity inside a prefab instance by walking the child-index path from root */ HierarchyParser._resolveEntity = function _resolveEntity(root, path) {
1475
+ var entity = root;
1476
+ for(var i = 0, n = path.length; i < n; i++){
1477
+ entity = entity.children[path[i]];
1478
+ if (!entity) throw new Error("HierarchyParser: override target entity not found at path [" + path + "], failed at depth " + i);
1574
1479
  }
1480
+ return entity;
1575
1481
  };
1576
- _proto._addComponents = function _addComponents(entity, components) {
1577
- var context = this.context;
1578
- var componentMap = context.components;
1579
- var componentConfigMap = context.componentConfigMap;
1580
- for(var i = 0, n = components.length; i < n; i++){
1581
- var componentConfig = components[i];
1582
- var key = !componentConfig.url ? componentConfig.class : componentConfig.url;
1583
- var componentId = componentConfig.id;
1584
- var component = entity.addComponent(Loader.getClass(key));
1585
- componentMap.set(componentId, component);
1586
- componentConfigMap.set(componentId, componentConfig);
1587
- this._addComponentPlugin(componentId, component);
1588
- }
1589
- };
1590
- _proto._generateInstanceContext = function _generateInstanceContext(entity, context, path) {
1591
- var entityMap = context.entityMap, components = context.components;
1592
- var componentsMap = {};
1593
- var componentIndexMap = {};
1594
- entityMap.set(path, entity);
1595
- // @ts-ignore
1596
- entity._components.forEach(function(component) {
1597
- // @ts-ignore
1598
- var name = Loader.getClassName(component.constructor);
1599
- if (!componentsMap[name]) {
1600
- componentsMap[name] = entity.getComponents(component.constructor, []);
1601
- componentIndexMap[name] = 0;
1602
- }
1603
- components.set(path + ":" + name + "/" + componentIndexMap[name]++, component);
1604
- });
1605
- for(var i = 0, n = entity.children.length; i < n; i++){
1606
- var child = entity.children[i];
1607
- var childPath = path ? path + "/" + i : "" + i;
1608
- this._generateInstanceContext(child, context, childPath);
1609
- }
1482
+ /** Resolve a component on an entity by type name + per-type index */ HierarchyParser._resolveComponent = function _resolveComponent(entity, selector) {
1483
+ var type = Loader.getClass(selector.type);
1484
+ if (!type) throw new Error('HierarchyParser: override target component type "' + selector.type + '" is not registered');
1485
+ var buffer = ReflectionParser._componentBuffer;
1486
+ buffer.length = 0;
1487
+ entity.getComponents(type, buffer);
1488
+ var result = buffer[selector.index];
1489
+ buffer.length = 0;
1490
+ if (!result) throw new Error("HierarchyParser: override target component not found: " + selector.type + "/" + selector.index);
1491
+ return result;
1610
1492
  };
1611
- _proto._parseComponentsPropsAndMethods = function _parseComponentsPropsAndMethods() {
1612
- var context = this.context;
1613
- var componentConfigMap = context.componentConfigMap;
1614
- var reflectionParser = this._reflectionParser;
1615
- var promises = [];
1616
- for(var _iterator = _create_for_of_iterator_helper_loose(context.components), _step; !(_step = _iterator()).done;){
1617
- var _step_value = _step.value, componentId = _step_value[0], component = _step_value[1];
1618
- var componentConfig = componentConfigMap.get(componentId);
1619
- if (componentConfig) {
1620
- promises.push(reflectionParser.parsePropsAndMethods(component, componentConfig));
1621
- }
1622
- }
1623
- return Promise.all(promises);
1493
+ /** Resolve component class from config and add to entity. Throws if class is not registered. */ HierarchyParser._addComponentFromConfig = function _addComponentFromConfig(entity, config, refs) {
1494
+ var key = config.script != null ? resolveRefItem(refs, config.script, "HierarchyParser", "component.script").url : config.type;
1495
+ var Class = Loader.getClass(key);
1496
+ if (!Class) throw new Error('Loader.getClass: class "' + key + '" is not registered');
1497
+ return entity.addComponent(Class);
1498
+ };
1499
+ HierarchyParser._isPrefabInstanceEntity = function _isPrefabInstanceEntity(entityConfig) {
1500
+ return "instance" in entityConfig;
1501
+ };
1502
+ /** Apply entity-level props (name, isActive, layer, transform) to an entity. */ HierarchyParser._applyEntityProps = function _applyEntityProps(entity, props) {
1503
+ if (props.name != null) entity.name = props.name;
1504
+ if (props.isActive != null) entity.isActive = props.isActive;
1505
+ if (props.layer != null) entity.layer = props.layer;
1506
+ if (props.position) entity.transform.position.set(props.position[0], props.position[1], props.position[2]);
1507
+ if (props.rotation) entity.transform.rotation.set(props.rotation[0], props.rotation[1], props.rotation[2]);
1508
+ if (props.scale) entity.transform.scale.set(props.scale[0], props.scale[1], props.scale[2]);
1624
1509
  };
1625
- _proto._addComponentPlugin = function _addComponentPlugin(componentId, component) {};
1626
- _proto._addEntityPlugin = function _addEntityPlugin(entityId, entity) {};
1627
1510
  return HierarchyParser;
1628
1511
  }();
1629
1512
 
1630
- var MaterialLoaderType = /*#__PURE__*/ function(MaterialLoaderType) {
1631
- MaterialLoaderType["Vector2"] = "Vector2";
1632
- MaterialLoaderType["Vector3"] = "Vector3";
1633
- MaterialLoaderType["Vector4"] = "Vector4";
1634
- MaterialLoaderType["Color"] = "Color";
1635
- MaterialLoaderType["Float"] = "Float";
1636
- MaterialLoaderType["Texture"] = "Texture";
1637
- MaterialLoaderType["Boolean"] = "Boolean";
1638
- MaterialLoaderType["Integer"] = "Integer";
1639
- return MaterialLoaderType;
1640
- }({});
1641
-
1642
- var SpecularMode = /*#__PURE__*/ function(SpecularMode) {
1643
- SpecularMode["Sky"] = "Sky";
1644
- SpecularMode["Custom"] = "Custom";
1645
- return SpecularMode;
1646
- }({});
1647
-
1648
1513
  /** @Internal */ var SceneParser = /*#__PURE__*/ function(HierarchyParser) {
1649
1514
  _inherits(SceneParser, HierarchyParser);
1650
1515
  function SceneParser(data, context, scene) {
@@ -1658,91 +1523,43 @@ var SpecularMode = /*#__PURE__*/ function(SpecularMode) {
1658
1523
  */ _proto._collectDependentAssets = function _collectDependentAssets(data) {
1659
1524
  var context = this.context;
1660
1525
  var resourceManager = context.resourceManager;
1661
- this._parseDependentAssets(data);
1662
- var scene = data.scene;
1663
- var ambient = scene.ambient;
1664
- if (ambient) {
1665
- var useCustomAmbient = ambient.specularMode === SpecularMode.Custom;
1666
- var useSH = ambient.diffuseMode === DiffuseMode.SphericalHarmonics;
1667
- var customAmbientLight = ambient.customAmbientLight, ambientLight = ambient.ambientLight;
1668
- if (useCustomAmbient && customAmbientLight) {
1669
- // @ts-ignore
1670
- context._addDependentAsset(customAmbientLight.url, resourceManager.getResourceByRef(customAmbientLight));
1671
- }
1672
- if (ambientLight && (!useCustomAmbient || useSH)) {
1673
- // @ts-ignore
1674
- context._addDependentAsset(ambientLight.url, resourceManager.getResourceByRef(ambientLight));
1675
- }
1676
- }
1677
- var background = scene.background;
1678
- var backgroundMode = background.mode;
1679
- if (backgroundMode === BackgroundMode.Texture) {
1680
- var texture = background.texture;
1526
+ var refs = data.refs;
1527
+ for(var i = 0, n = refs.length; i < n; i++){
1681
1528
  // @ts-ignore
1682
- texture && context._addDependentAsset(texture.url, resourceManager.getResourceByRef(texture));
1683
- } else if (backgroundMode === BackgroundMode.Sky) {
1684
- var skyMesh = background.skyMesh, skyMaterial = background.skyMaterial;
1685
- if (skyMesh && skyMaterial) {
1686
- // @ts-ignore
1687
- context._addDependentAsset(skyMesh.url, resourceManager.getResourceByRef(skyMesh));
1688
- // @ts-ignore
1689
- context._addDependentAsset(skyMaterial.url, resourceManager.getResourceByRef(skyMaterial));
1690
- }
1529
+ context._addDependentAsset(resourceManager.getResourceByRef(refs[i]));
1691
1530
  }
1692
1531
  };
1693
- _proto._handleRootEntity = function _handleRootEntity(id) {
1694
- var entityMap = this.context.entityMap;
1695
- this.scene.addRootEntity(entityMap.get(id));
1532
+ _proto._getRootIndices = function _getRootIndices() {
1533
+ return this.data.scene.entities;
1534
+ };
1535
+ _proto._handleRootEntity = function _handleRootEntity(index) {
1536
+ this.scene.addRootEntity(this.context.entityInstances[index]);
1696
1537
  };
1697
1538
  _proto._clearAndResolve = function _clearAndResolve() {
1698
1539
  this.context.clear();
1699
1540
  return this.scene;
1700
1541
  };
1701
- _proto._parseDependentAssets = function _parseDependentAssets(file) {
1702
- var entities = file.entities;
1703
- for(var i = 0, n = entities.length; i < n; i++){
1704
- var entity = entities[i];
1705
- if (!!entity.assetUrl) {
1706
- var context = this.context;
1707
- var url = entity.assetUrl, key = entity.key;
1708
- // @ts-ignore
1709
- context._addDependentAsset(url, context.resourceManager.getResourceByRef({
1710
- url: url,
1711
- key: key
1712
- }));
1713
- } else if (entity.strippedId) {
1714
- continue;
1715
- } else {
1716
- var components = entity.components;
1717
- for(var j = 0, m = components.length; j < m; j++){
1718
- var component = components[j];
1719
- this._searchDependentAssets(component.methods);
1720
- this._searchDependentAssets(component.props);
1721
- }
1722
- }
1723
- }
1724
- };
1725
- _proto._searchDependentAssets = function _searchDependentAssets(value) {
1726
- if (Array.isArray(value)) {
1727
- for(var i = 0, n = value.length; i < n; i++){
1728
- this._searchDependentAssets(value[i]);
1729
- }
1730
- } else if (!!value && (typeof value === "undefined" ? "undefined" : _type_of(value)) === "object") {
1731
- // @ts-ignore
1732
- if (ReflectionParser._isAssetRef(value)) {
1733
- var context = this.context;
1734
- // @ts-ignore
1735
- context._addDependentAsset(value.url, context.resourceManager.getResourceByRef(value));
1736
- } else {
1737
- for(var key in value){
1738
- this._searchDependentAssets(value[key]);
1739
- }
1740
- }
1741
- }
1742
- };
1743
1542
  return SceneParser;
1744
1543
  }(HierarchyParser);
1745
1544
 
1545
+ var SpecularMode = /*#__PURE__*/ function(SpecularMode) {
1546
+ SpecularMode[SpecularMode["Sky"] = 0] = "Sky";
1547
+ SpecularMode[SpecularMode["Custom"] = 1] = "Custom";
1548
+ return SpecularMode;
1549
+ }({});
1550
+
1551
+ var MaterialLoaderType = /*#__PURE__*/ function(MaterialLoaderType) {
1552
+ MaterialLoaderType["Vector2"] = "Vector2";
1553
+ MaterialLoaderType["Vector3"] = "Vector3";
1554
+ MaterialLoaderType["Vector4"] = "Vector4";
1555
+ MaterialLoaderType["Color"] = "Color";
1556
+ MaterialLoaderType["Float"] = "Float";
1557
+ MaterialLoaderType["Texture"] = "Texture";
1558
+ MaterialLoaderType["Boolean"] = "Boolean";
1559
+ MaterialLoaderType["Integer"] = "Integer";
1560
+ return MaterialLoaderType;
1561
+ }({});
1562
+
1746
1563
  /**
1747
1564
  * Decode engine binary resource.
1748
1565
  * @param arrayBuffer - array buffer of decode binary file
@@ -3224,6 +3041,45 @@ function getMeshoptDecoder() {
3224
3041
  return GLTFResource;
3225
3042
  }(ReferResource);
3226
3043
 
3044
+ function _array_like_to_array(arr, len) {
3045
+ if (len == null || len > arr.length) len = arr.length;
3046
+
3047
+ for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
3048
+
3049
+ return arr2;
3050
+ }
3051
+
3052
+ function _unsupported_iterable_to_array(o, minLen) {
3053
+ if (!o) return;
3054
+ if (typeof o === "string") return _array_like_to_array(o, minLen);
3055
+
3056
+ var n = Object.prototype.toString.call(o).slice(8, -1);
3057
+
3058
+ if (n === "Object" && o.constructor) n = o.constructor.name;
3059
+ if (n === "Map" || n === "Set") return Array.from(n);
3060
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
3061
+ }
3062
+
3063
+ function _create_for_of_iterator_helper_loose(o, allowArrayLike) {
3064
+ var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
3065
+
3066
+ if (it) return (it = it.call(o)).next.bind(it);
3067
+ // Fallback for engines without symbol support
3068
+ if (Array.isArray(o) || (it = _unsupported_iterable_to_array(o)) || allowArrayLike && o && typeof o.length === "number") {
3069
+ if (it) o = it;
3070
+
3071
+ var i = 0;
3072
+
3073
+ return function() {
3074
+ if (i >= o.length) return { done: true };
3075
+
3076
+ return { done: false, value: o[i++] };
3077
+ };
3078
+ }
3079
+
3080
+ throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
3081
+ }
3082
+
3227
3083
  /**
3228
3084
  * Module for glTF 2.0 Interface
3229
3085
  */ /**
@@ -5493,15 +5349,17 @@ var PrefabParser = /*#__PURE__*/ function(HierarchyParser) {
5493
5349
  return _this;
5494
5350
  }
5495
5351
  var _proto = PrefabParser.prototype;
5496
- _proto._applyEntityData = function _applyEntityData(entity, entityConfig) {
5497
- if (entityConfig === void 0) entityConfig = {};
5498
- HierarchyParser.prototype._applyEntityData.call(this, entity, entityConfig);
5352
+ _proto._onEntityCreated = function _onEntityCreated(entity) {
5499
5353
  // @ts-ignore
5500
5354
  entity._markAsTemplate(this.context.resource);
5501
- return entity;
5502
5355
  };
5503
- _proto._handleRootEntity = function _handleRootEntity(id) {
5504
- this.prefabResource._root = this.context.entityMap.get(id);
5356
+ _proto._getRootIndices = function _getRootIndices() {
5357
+ return [
5358
+ this.data.root
5359
+ ];
5360
+ };
5361
+ _proto._handleRootEntity = function _handleRootEntity(index) {
5362
+ this.prefabResource._root = this.context.entityInstances[index];
5505
5363
  };
5506
5364
  _proto._clearAndResolve = function _clearAndResolve() {
5507
5365
  this.context.clear();
@@ -5512,9 +5370,7 @@ var PrefabParser = /*#__PURE__*/ function(HierarchyParser) {
5512
5370
  var context = new ParserContext(engine, ParserType.Prefab, prefabResource);
5513
5371
  var parser = new PrefabParser(data, context, prefabResource);
5514
5372
  parser.start();
5515
- return parser.promise.then(function() {
5516
- return prefabResource;
5517
- });
5373
+ return parser.promise;
5518
5374
  };
5519
5375
  return PrefabParser;
5520
5376
  }(HierarchyParser);
@@ -5854,15 +5710,6 @@ var KTXContentRestorer = /*#__PURE__*/ function(ContentRestorer) {
5854
5710
  return KTXContentRestorer;
5855
5711
  }(ContentRestorer);
5856
5712
 
5857
- function parseProperty(object, key, value) {
5858
- if ((typeof value === "undefined" ? "undefined" : _type_of(value)) === "object") {
5859
- for(var subKey in value){
5860
- parseProperty(object[key], subKey, value[subKey]);
5861
- }
5862
- } else {
5863
- object[key] = value;
5864
- }
5865
- }
5866
5713
  var MaterialLoader = /*#__PURE__*/ function(Loader) {
5867
5714
  _inherits(MaterialLoader, Loader);
5868
5715
  function MaterialLoader() {
@@ -5923,7 +5770,7 @@ var MaterialLoader = /*#__PURE__*/ function(Loader) {
5923
5770
  break;
5924
5771
  }
5925
5772
  };
5926
- var name = materialSchema.name, shaderData = materialSchema.shaderData, macros = materialSchema.macros, renderState = materialSchema.renderState;
5773
+ var name = materialSchema.name, shaderData = materialSchema.shaderData, macros = materialSchema.macros;
5927
5774
  var material = new Material(engine, shader);
5928
5775
  material.name = name;
5929
5776
  var texturePromises = new Array();
@@ -5937,7 +5784,6 @@ var MaterialLoader = /*#__PURE__*/ function(Loader) {
5937
5784
  materialShaderData.enableMacro(name1, value);
5938
5785
  }
5939
5786
  }
5940
- parseProperty(material, "renderState", renderState);
5941
5787
  return Promise.all(texturePromises).then(function() {
5942
5788
  return material;
5943
5789
  });
@@ -6479,51 +6325,6 @@ AudioLoader = __decorate([
6479
6325
  ])
6480
6326
  ], AudioLoader);
6481
6327
 
6482
- var ShaderChunkLoader = /*#__PURE__*/ function(Loader) {
6483
- _inherits(ShaderChunkLoader, Loader);
6484
- function ShaderChunkLoader() {
6485
- return Loader.apply(this, arguments) || this;
6486
- }
6487
- var _proto = ShaderChunkLoader.prototype;
6488
- _proto.load = function load(item, resourceManager) {
6489
- var url = item.url;
6490
- // @ts-ignore
6491
- return resourceManager._request(url, _extends({}, item, {
6492
- type: "text"
6493
- })).then(function(code) {
6494
- ShaderFactory.registerInclude(url.substring(1), code);
6495
- return ShaderChunkLoader._loadChunksInCode(code, url, resourceManager);
6496
- });
6497
- };
6498
- /**
6499
- * @internal
6500
- */ ShaderChunkLoader._loadChunksInCode = function _loadChunksInCode(code, basePath, resourceManager) {
6501
- var shaderChunkPaths = new Array();
6502
- var matches = code.matchAll(ShaderChunkLoader._shaderIncludeRegex);
6503
- for(var _iterator = _create_for_of_iterator_helper_loose(matches), _step; !(_step = _iterator()).done;){
6504
- var match = _step.value;
6505
- var chunkPath = Utils.resolveAbsoluteUrl(basePath, match[1]);
6506
- if (!ShaderLib[chunkPath.substring(1)]) {
6507
- shaderChunkPaths.push(chunkPath);
6508
- }
6509
- }
6510
- return Promise.all(shaderChunkPaths.map(function(chunkPath) {
6511
- // @ts-ignore
6512
- return resourceManager.load({
6513
- type: "ShaderChunk",
6514
- url: chunkPath
6515
- });
6516
- }));
6517
- };
6518
- return ShaderChunkLoader;
6519
- }(Loader);
6520
- ShaderChunkLoader._shaderIncludeRegex = /#include\s+"([./][^\\"]+)"/gm;
6521
- ShaderChunkLoader = __decorate([
6522
- resourceLoader("ShaderChunk", [
6523
- "glsl"
6524
- ])
6525
- ], ShaderChunkLoader);
6526
-
6527
6328
  var ShaderLoader = /*#__PURE__*/ function(Loader) {
6528
6329
  _inherits(ShaderLoader, Loader);
6529
6330
  function ShaderLoader() {
@@ -6533,7 +6334,7 @@ var ShaderLoader = /*#__PURE__*/ function(Loader) {
6533
6334
  _proto.load = function load(item, resourceManager) {
6534
6335
  var _this = this;
6535
6336
  var url = item.url;
6536
- if (url.endsWith(".gsp")) {
6337
+ if (url.endsWith(".shaderc")) {
6537
6338
  // @ts-ignore
6538
6339
  return resourceManager._request(url, _extends({}, item, {
6539
6340
  type: "json"
@@ -6550,10 +6351,7 @@ var ShaderLoader = /*#__PURE__*/ function(Loader) {
6550
6351
  if (builtinShader) {
6551
6352
  return Shader.find(builtinShader);
6552
6353
  }
6553
- return ShaderChunkLoader._loadChunksInCode(code, url, resourceManager).then(function() {
6554
- var shader = Shader.create(code, undefined, url);
6555
- return shader;
6556
- });
6354
+ return Shader.create(code, undefined, url);
6557
6355
  });
6558
6356
  };
6559
6357
  _proto._getBuiltinShader = function _getBuiltinShader(code) {
@@ -6565,7 +6363,8 @@ var ShaderLoader = /*#__PURE__*/ function(Loader) {
6565
6363
  ShaderLoader._builtinRegex = /^\s*\/\/\s*@builtin\s+(\w+)/;
6566
6364
  ShaderLoader = __decorate([
6567
6365
  resourceLoader(AssetType.Shader, [
6568
- "shader"
6366
+ "shader",
6367
+ "shaderc"
6569
6368
  ])
6570
6369
  ], ShaderLoader);
6571
6370
 
@@ -6645,6 +6444,122 @@ RenderTargetLoader = __decorate([
6645
6444
  ])
6646
6445
  ], RenderTargetLoader);
6647
6446
 
6447
+ function loadRef(refs, index, resourceManager, label) {
6448
+ var ref = resolveRefItem(refs, index, "SceneLoader", label);
6449
+ // @ts-ignore
6450
+ return resourceManager.getResourceByRef(ref);
6451
+ }
6452
+ /**
6453
+ * Apply scene-level data (ambient, background, shadow, fog, AO) to a Scene.
6454
+ * @internal
6455
+ */ function applySceneData(scene, sceneData, resourceManager, refs) {
6456
+ var promises = [];
6457
+ try {
6458
+ // parse ambient light
6459
+ var ambient = sceneData.ambient;
6460
+ if (ambient) {
6461
+ var useCustomAmbient = ambient.specularMode === SpecularMode.Custom;
6462
+ var useSH = ambient.diffuseMode === DiffuseMode.SphericalHarmonics;
6463
+ scene.ambientLight.diffuseIntensity = ambient.diffuseIntensity;
6464
+ scene.ambientLight.specularIntensity = ambient.specularIntensity;
6465
+ scene.ambientLight.diffuseMode = ambient.diffuseMode;
6466
+ var solidColor = ambient.diffuseSolidColor;
6467
+ if (solidColor) {
6468
+ scene.ambientLight.diffuseSolidColor.set(solidColor[0], solidColor[1], solidColor[2], solidColor[3]);
6469
+ }
6470
+ if (useCustomAmbient && ambient.customAmbientLight != null) {
6471
+ promises.push(loadRef(refs, ambient.customAmbientLight, resourceManager, "scene.ambient.customAmbientLight").then(function(ambientLight) {
6472
+ scene.ambientLight.specularTexture = ambientLight == null ? void 0 : ambientLight.specularTexture;
6473
+ }));
6474
+ }
6475
+ if (ambient.ambientLight != null && (!useCustomAmbient || useSH)) {
6476
+ promises.push(loadRef(refs, ambient.ambientLight, resourceManager, "scene.ambient.ambientLight").then(function(ambientLight) {
6477
+ if (!useCustomAmbient) {
6478
+ scene.ambientLight.specularTexture = ambientLight == null ? void 0 : ambientLight.specularTexture;
6479
+ }
6480
+ if (useSH) {
6481
+ scene.ambientLight.diffuseSphericalHarmonics = ambientLight == null ? void 0 : ambientLight.diffuseSphericalHarmonics;
6482
+ }
6483
+ }));
6484
+ }
6485
+ }
6486
+ // parse background
6487
+ var background = sceneData.background;
6488
+ scene.background.mode = background.mode;
6489
+ switch(scene.background.mode){
6490
+ case BackgroundMode.SolidColor:
6491
+ {
6492
+ var color = background.color;
6493
+ scene.background.solidColor.set(color[0], color[1], color[2], color[3]);
6494
+ break;
6495
+ }
6496
+ case BackgroundMode.Sky:
6497
+ if (background.skyMesh != null && background.skyMaterial != null) {
6498
+ promises.push(loadRef(refs, background.skyMesh, resourceManager, "scene.background.skyMesh").then(function(mesh) {
6499
+ scene.background.sky.mesh = mesh;
6500
+ }), loadRef(refs, background.skyMaterial, resourceManager, "scene.background.skyMaterial").then(function(material) {
6501
+ scene.background.sky.material = material;
6502
+ }));
6503
+ } else {
6504
+ Logger.warn("Sky background mode requires skyMesh and skyMaterial");
6505
+ }
6506
+ break;
6507
+ case BackgroundMode.Texture:
6508
+ if (background.texture != null) {
6509
+ promises.push(loadRef(refs, background.texture, resourceManager, "scene.background.texture").then(function(texture) {
6510
+ scene.background.texture = texture;
6511
+ }));
6512
+ var _background_textureFillMode;
6513
+ scene.background.textureFillMode = (_background_textureFillMode = background.textureFillMode) != null ? _background_textureFillMode : scene.background.textureFillMode;
6514
+ }
6515
+ break;
6516
+ }
6517
+ } catch (error) {
6518
+ return Promise.reject(error);
6519
+ }
6520
+ // parse shadow
6521
+ var shadow = sceneData.shadow;
6522
+ if (shadow) {
6523
+ if (shadow.castShadows != undefined) scene.castShadows = shadow.castShadows;
6524
+ if (shadow.shadowResolution != undefined) scene.shadowResolution = shadow.shadowResolution;
6525
+ if (shadow.shadowDistance != undefined) scene.shadowDistance = shadow.shadowDistance;
6526
+ if (shadow.shadowCascades != undefined) scene.shadowCascades = shadow.shadowCascades;
6527
+ if (shadow.enableTransparentShadow != undefined) scene.enableTransparentShadow = shadow.enableTransparentShadow;
6528
+ if (shadow.shadowTwoCascadeSplits != undefined) scene.shadowTwoCascadeSplits = shadow.shadowTwoCascadeSplits;
6529
+ if (shadow.shadowFourCascadeSplits) {
6530
+ var splits = shadow.shadowFourCascadeSplits;
6531
+ scene.shadowFourCascadeSplits.set(splits[0], splits[1], splits[2]);
6532
+ }
6533
+ if (shadow.shadowFadeBorder != undefined) scene.shadowFadeBorder = shadow.shadowFadeBorder;
6534
+ }
6535
+ // parse fog
6536
+ var fog = sceneData.fog;
6537
+ if (fog) {
6538
+ if (fog.fogMode != undefined) scene.fogMode = fog.fogMode;
6539
+ if (fog.fogStart != undefined) scene.fogStart = fog.fogStart;
6540
+ if (fog.fogEnd != undefined) scene.fogEnd = fog.fogEnd;
6541
+ if (fog.fogDensity != undefined) scene.fogDensity = fog.fogDensity;
6542
+ if (fog.fogColor) scene.fogColor.set(fog.fogColor[0], fog.fogColor[1], fog.fogColor[2], fog.fogColor[3]);
6543
+ }
6544
+ // Post Process
6545
+ if (sceneData.postProcess) {
6546
+ Logger.warn("Post Process is not supported in scene yet, please add PostProcess component in entity instead.");
6547
+ }
6548
+ // Ambient Occlusion
6549
+ var ambientOcclusion = sceneData.ambientOcclusion;
6550
+ if (ambientOcclusion) {
6551
+ var sceneAO = scene.ambientOcclusion;
6552
+ if (ambientOcclusion.enabledAmbientOcclusion != undefined) sceneAO.enabled = ambientOcclusion.enabledAmbientOcclusion;
6553
+ if (ambientOcclusion.quality != undefined) sceneAO.quality = ambientOcclusion.quality;
6554
+ if (ambientOcclusion.intensity != undefined) sceneAO.intensity = ambientOcclusion.intensity;
6555
+ if (ambientOcclusion.radius != undefined) sceneAO.radius = ambientOcclusion.radius;
6556
+ if (ambientOcclusion.bias != undefined) sceneAO.bias = ambientOcclusion.bias;
6557
+ if (ambientOcclusion.power != undefined) sceneAO.power = ambientOcclusion.power;
6558
+ if (ambientOcclusion.bilateralThreshold != undefined) sceneAO.bilateralThreshold = ambientOcclusion.bilateralThreshold;
6559
+ if (ambientOcclusion.minHorizonAngle != undefined) sceneAO.minHorizonAngle = ambientOcclusion.minHorizonAngle;
6560
+ }
6561
+ return Promise.all(promises).then(function() {});
6562
+ }
6648
6563
  var SceneLoader = /*#__PURE__*/ function(Loader) {
6649
6564
  _inherits(SceneLoader, Loader);
6650
6565
  function SceneLoader() {
@@ -6658,122 +6573,15 @@ var SceneLoader = /*#__PURE__*/ function(Loader) {
6658
6573
  ._request(item.url, _extends({}, item, {
6659
6574
  type: "json"
6660
6575
  })).then(function(data) {
6661
- var _data_name;
6662
- var scene = new Scene(engine, (_data_name = data.name) != null ? _data_name : "");
6576
+ var _data_scene_name;
6577
+ var scene = new Scene(engine, (_data_scene_name = data.scene.name) != null ? _data_scene_name : "");
6663
6578
  var context = new ParserContext(engine, ParserType.Scene, scene);
6664
6579
  var parser = new SceneParser(data, context, scene);
6665
6580
  parser._collectDependentAssets(data);
6666
6581
  context._setTaskCompleteProgress = setTaskCompleteProgress;
6667
6582
  parser.start();
6668
6583
  return parser.promise.then(function() {
6669
- var promises = [];
6670
- // parse ambient light
6671
- var ambient = data.scene.ambient;
6672
- if (ambient) {
6673
- var useCustomAmbient = ambient.specularMode === SpecularMode.Custom;
6674
- var useSH = ambient.diffuseMode === DiffuseMode.SphericalHarmonics;
6675
- scene.ambientLight.diffuseIntensity = ambient.diffuseIntensity;
6676
- scene.ambientLight.specularIntensity = ambient.specularIntensity;
6677
- scene.ambientLight.diffuseMode = ambient.diffuseMode;
6678
- scene.ambientLight.diffuseSolidColor.copyFrom(ambient.diffuseSolidColor);
6679
- if (useCustomAmbient && ambient.customAmbientLight) {
6680
- promises.push(// @ts-ignore
6681
- resourceManager.getResourceByRef(ambient.customAmbientLight).then(function(ambientLight) {
6682
- scene.ambientLight.specularTexture = ambientLight == null ? void 0 : ambientLight.specularTexture;
6683
- }));
6684
- }
6685
- if (ambient.ambientLight && (!useCustomAmbient || useSH)) {
6686
- promises.push(// @ts-ignore
6687
- resourceManager.getResourceByRef(ambient.ambientLight).then(function(ambientLight) {
6688
- if (!useCustomAmbient) {
6689
- scene.ambientLight.specularTexture = ambientLight == null ? void 0 : ambientLight.specularTexture;
6690
- }
6691
- if (useSH) {
6692
- scene.ambientLight.diffuseSphericalHarmonics = ambientLight == null ? void 0 : ambientLight.diffuseSphericalHarmonics;
6693
- }
6694
- }));
6695
- }
6696
- }
6697
- // parse background
6698
- var background = data.scene.background;
6699
- scene.background.mode = background.mode;
6700
- switch(scene.background.mode){
6701
- case BackgroundMode.SolidColor:
6702
- scene.background.solidColor.copyFrom(background.color);
6703
- break;
6704
- case BackgroundMode.Sky:
6705
- if (background.skyMesh && background.skyMaterial) {
6706
- // @ts-ignore
6707
- var skyMeshPromise = resourceManager.getResourceByRef(background.skyMesh).then(function(mesh) {
6708
- scene.background.sky.mesh = mesh;
6709
- });
6710
- // @ts-ignore
6711
- // prettier-ignore
6712
- var skyMaterialPromise = resourceManager.getResourceByRef(background.skyMaterial).then(function(material) {
6713
- scene.background.sky.material = material;
6714
- });
6715
- promises.push(skyMeshPromise, skyMaterialPromise);
6716
- } else {
6717
- Logger.warn("Sky background mode requires skyMesh and skyMaterial");
6718
- }
6719
- break;
6720
- case BackgroundMode.Texture:
6721
- if (background.texture) {
6722
- // @ts-ignore
6723
- // prettier-ignore
6724
- var backgroundPromise = resourceManager.getResourceByRef(background.texture).then(function(texture) {
6725
- scene.background.texture = texture;
6726
- });
6727
- promises.push(backgroundPromise);
6728
- var _background_textureFillMode;
6729
- scene.background.textureFillMode = (_background_textureFillMode = background.textureFillMode) != null ? _background_textureFillMode : scene.background.textureFillMode;
6730
- }
6731
- break;
6732
- }
6733
- // parse shadow
6734
- var shadow = data.scene.shadow;
6735
- if (shadow) {
6736
- if (shadow.castShadows != undefined) scene.castShadows = shadow.castShadows;
6737
- if (shadow.shadowResolution != undefined) scene.shadowResolution = shadow.shadowResolution;
6738
- if (shadow.shadowDistance != undefined) scene.shadowDistance = shadow.shadowDistance;
6739
- if (shadow.shadowCascades != undefined) scene.shadowCascades = shadow.shadowCascades;
6740
- if (shadow.enableTransparentShadow != undefined) {
6741
- scene.enableTransparentShadow = shadow.enableTransparentShadow;
6742
- }
6743
- var _shadow_shadowTwoCascadeSplits;
6744
- scene.shadowTwoCascadeSplits = (_shadow_shadowTwoCascadeSplits = shadow.shadowTwoCascadeSplits) != null ? _shadow_shadowTwoCascadeSplits : scene.shadowTwoCascadeSplits;
6745
- shadow.shadowFourCascadeSplits && scene.shadowFourCascadeSplits.copyFrom(shadow.shadowFourCascadeSplits);
6746
- var _shadow_shadowFadeBorder;
6747
- scene.shadowFadeBorder = (_shadow_shadowFadeBorder = shadow.shadowFadeBorder) != null ? _shadow_shadowFadeBorder : scene.shadowFadeBorder;
6748
- }
6749
- // parse fog
6750
- var fog = data.scene.fog;
6751
- if (fog) {
6752
- if (fog.fogMode != undefined) scene.fogMode = fog.fogMode;
6753
- if (fog.fogStart != undefined) scene.fogStart = fog.fogStart;
6754
- if (fog.fogEnd != undefined) scene.fogEnd = fog.fogEnd;
6755
- if (fog.fogDensity != undefined) scene.fogDensity = fog.fogDensity;
6756
- if (fog.fogColor != undefined) scene.fogColor.copyFrom(fog.fogColor);
6757
- }
6758
- // Post Process
6759
- var postProcessData = data.scene.postProcess;
6760
- if (postProcessData) {
6761
- Logger.warn("Post Process is not supported in scene yet, please add PostProcess component in entity instead.");
6762
- }
6763
- // Ambient Occlusion
6764
- var ambientOcclusion = data.scene.ambientOcclusion;
6765
- if (ambientOcclusion) {
6766
- var sceneAmbientOcclusion = scene.ambientOcclusion;
6767
- sceneAmbientOcclusion.enabled = ambientOcclusion.enabledAmbientOcclusion;
6768
- sceneAmbientOcclusion.intensity = ambientOcclusion.intensity;
6769
- sceneAmbientOcclusion.radius = ambientOcclusion.radius;
6770
- sceneAmbientOcclusion.bias = ambientOcclusion.bias;
6771
- sceneAmbientOcclusion.power = ambientOcclusion.power;
6772
- sceneAmbientOcclusion.quality = ambientOcclusion.quality;
6773
- sceneAmbientOcclusion.bilateralThreshold = ambientOcclusion.bilateralThreshold;
6774
- sceneAmbientOcclusion.minHorizonAngle = ambientOcclusion.minHorizonAngle;
6775
- }
6776
- return Promise.all(promises).then(function() {
6584
+ return applySceneData(scene, data.scene, resourceManager, data.refs).then(function() {
6777
6585
  resolve(scene);
6778
6586
  });
6779
6587
  });