@hology/core 0.0.271 → 0.0.273
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/effects/vfx/gpu-sprite-compiler.js +1 -1
- package/dist/effects/vfx/gpu-sprite-runtime.js +1 -1
- package/dist/effects/vfx/gpu-vfx-world-service.js +1 -1
- package/dist/effects/vfx/rates.d.ts +2 -0
- package/dist/effects/vfx/rates.js +1 -1
- package/dist/effects/vfx/vfx-actor.d.ts +2 -1
- package/dist/effects/vfx/vfx-actor.js +1 -1
- package/dist/effects/vfx/vfx-asset.d.ts +10 -1
- package/dist/effects/vfx/vfx-backend-partition.d.ts +8 -0
- package/dist/effects/vfx/vfx-backend-partition.js +4 -0
- package/dist/effects/vfx/vfx-materializer.js +1 -1
- package/dist/effects/vfx/vfx-render-preparation.js +1 -1
- package/dist/effects/vfx/vfx-renderers.d.ts +27 -2
- package/dist/effects/vfx/vfx-renderers.js +1 -1
- package/dist/gameplay/actors/builtin/components/character/character-animation.d.ts +2 -0
- package/dist/gameplay/actors/builtin/components/character/character-animation.js +1 -1
- package/dist/gameplay/initiate.js +1 -1
- package/dist/scene/asset-resource-loader.d.ts +5 -1
- package/dist/scene/asset-resource-loader.js +1 -1
- package/dist/scene/materializer.d.ts +1 -1
- package/dist/scene/materializer.js +1 -1
- package/dist/scene/model.d.ts +4 -0
- package/dist/scene/native-texture.d.ts +13 -0
- package/dist/scene/native-texture.js +4 -0
- package/dist/shader-nodes/particle-parameter.d.ts +4 -0
- package/dist/shader-nodes/particle-parameter.js +4 -0
- package/dist/test/asset-resource-loader-texture-array.test.js +1 -1
- package/dist/test/gpu-sprite-compiler.test.js +1 -1
- package/dist/test/gpu-sprite-pipeline-cache.test.js +1 -1
- package/dist/test/native-texture.test.d.ts +2 -0
- package/dist/test/native-texture.test.js +4 -0
- package/dist/test/shader-graph.test.js +1 -1
- package/dist/test/vfx-backend-partition.test.d.ts +2 -0
- package/dist/test/vfx-backend-partition.test.js +4 -0
- package/dist/test/vfx-playback-transform.test.js +1 -1
- package/dist/test/vfx-render-preparation.test.js +1 -1
- package/dist/utils/mesh.d.ts +1 -1
- package/dist/utils/mesh.js +1 -1
- package/package.json +1 -1
- package/tsconfig.tsbuildinfo +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate as e,__metadata as t}from"tslib";import{LatticeGeometryCache as a,setLatticeGeometrySourceIdentity as s}from"./lattice-deformation.js";export{createLatticeDeformation,latticePoint,isValidLattice,deformLatticeGeometry,LatticeGeometryCache}from"./lattice-deformation.js";import{ConvexPolyhedronCollisionShape as r}from"./collision/collision-shape.js";import{SpriteShader as i}from"../shader/sprite-shader.js";import{Observable as n,Subject as o}from"rxjs";import*as l from"three";import{BoxGeometry as c,BufferGeometry as u,Color as d,Euler as h,Fog as p,FogExp2 as f,Group as m,Material as g,Matrix4 as y,Mesh as w,MeshLambertMaterial as S,MeshPhongMaterial as b,MeshStandardMaterial as v,Matrix3 as M,Object3D as A,PointLight as x,Quaternion as j,Scene as P,Texture as I,Vector2 as D,Vector3 as C,Vector4 as O}from"three";import{attributes as E,batchingUniformFloat as k,batchingUniformVec2 as T,batchingUniformVec3 as B,batchingUniformVec4 as V,bool as N,BooleanExpression as z,BooleanNode as $,colorToNormal as U,float as F,deriveNodeShaderMaterial as R,FloatNode as W,ifDefApply as _,mix as G,NodeShaderMaterial as L,rgb as q,rgba as J,RgbNode as Y,select as Q,standardMaterial as H,Texture2dLookupNode as Z,textureSampler2d as X,textureSampler2dArray as K,UniformBoolNode as ee,UniformFloatNode as te,UniformSampler2dArraySlice as ae,UniformVec2Node as se,UniformVec3Node as re,UniformVec4Node as ie,varying as ne,varyingAttributes as oe,varyingTransformed as le,vec2 as ce,Vec2Node as ue,vec3 as de,Vec3Node as he,vec4 as pe,Vec4Node as fe}from"three-shader-graph";import{Service as me}from"typedi";import{VfxActor as ge}from"../effects/vfx/vfx-actor.js";import{VisualEffect as ye}from"../effects/vfx/vfx-param.js";import{Prefab as we,PrefabOf as Se}from"./objects/prefab.js";import{DataAssetRef as be}from"./objects/data-asset.js";import{SceneRef as ve}from"./scene-ref.js";import{ModelRef as Me}from"./model-ref.js";import{BaseActor as Ae,getActorOptions as xe}from"../gameplay/actors/actor.js";import je from"../gameplay/actors/builtin/index.js";import{ActorComponent as Pe}from"../gameplay/actors/component.js";import{PhysicsBodyType as Ie}from"../gameplay/services/physics/physics-system.js";import{NetMode as De}from"../gameplay/net/net-session.js";import{NetRole as Ce}from"../gameplay/net/service/net-actor-role.js";import{ThreeBlendingMode as Oe}from"../effects/vfx/vfx-asset.js";import{withInjectionContext as Ee}from"../gameplay/inject.js";import{RenderingView as ke}from"../rendering.js";import{markMaterialUniformValuesNeedUpdate as Te,setMaterialUniformValuesAutoUpdate as Be}from"../rendering/node-material-webgpu-resolver.js";import{curveSampler as Ve,oneMinus as Ne,particleUniforms as ze,Sampler2DNode as $e}from"../shader-nodes/index.js";import{LambertShader as Ue}from"../shader/builtin/lambert-shader.js";import{LandscapeCompositeShader as Fe}from"../shader/builtin/landscape-composite-shader.js";import{LandscapeShader as Re}from"../shader/builtin/landscape-shader.js";import{StandardShader as We}from"../shader/builtin/standard-shader.js";import{UnlitShader as _e}from"../shader/builtin/unlit-shader.js";import{extractShaderParameters as Ge,getDataAssetDefinitionType as Le,getParameterDefinitionId as qe,getParameterDefinitionType as Je,isDataAssetDefinitionAbstract as Ye,isParameterDefinitionAbstract as Qe,isParameterDefinitionAssignableTo as He,isParameterDefinitionStructAssignableTo as Ze,shaderParameterUniformName as Xe}from"../shader/parameter.js";import{ArrayMap as Ke,DefaultMap as et,groupBy as tt}from"../utils/collections.js";import{iterateMaterials as at}from"../utils/materials.js";import{filterChildrenShallow as st,filterSceneShallow as rt,findFirstVisibleMesh as it,findFirstVisibleObject as nt,traverseAsync as ot}from"../utils/three/traverse.js";import{AssetMeshInstance as lt,AssetResourceLoader as ct}from"./asset-resource-loader.js";import{AssetsProvider as ut}from"./assets-provider.js";import{isCollisionMesh as dt}from"./collision/collision-shape-import.js";import{BoxCollisionShape as ht,PhysicalShapeMesh as pt}from"./collision/collision-shape.js";import{LandscapeManager as ft}from"./landscape/landscape-manager.js";import{initLandscape as mt}from"./landscape/landscape.js";import{SectionGrid as gt,smoothNormalsCrossMeshes as yt}from"./landscape/utils.js";import{createGrassFoliageMaterial as wt}from"./materials/grass-foliage.js";import{createGrassMaterial as St}from"./materials/grass.js";import{getMaterialAttribute as bt}from"./materials/utils/material-painting.js";import{PaintedScatterManager as vt}from"./scatter/painted-scatter-manager.js";import{SurfaceScatterManager as Mt}from"./scatter/surface-scatter-manager.js";import{createWaterMaterial as At}from"./materials/water.js";import{SerializedParamType as xt}from"./model.js";import{applyRuntimeParamTypeInference as jt,convertConfiguredParamsToRuntimeTypes as Pt,convertConfiguredParamValueToRuntimeType as It,inferRuntimeSerializedParamTypeHint as Dt}from"./custom-param-runtime-types.js";import{ShapeLibrary as Ct,ShapeLibraryKeys as Ot}from"./objects/shapes.js";import{ambientLightName as Et,createSky as kt,defaultSkyMaterial as Tt}from"./sky.js";import{Curve2 as Bt}from"../utils/curve.js";import{DecalUnlitShader as Vt}from"../shader/builtin/decal-unlit-shader.js";import{DecalStandardShader as Nt}from"../shader/builtin/decal-standard-shader.js";import{ClusterGenerator as zt}from"../rendering/cluster-generator.js";import{ColorLayer as $t,defaultValueColorLayer as Ut,defaultValueMaskLayer as Ft,MaskLayer as Rt}from"../shader/color-layer.js";import{LayeredShader as Wt}from"../shader/builtin/layered-shader.js";import{isColorLayerSerialized as _t}from"../shader/color-layer.js";import{FogVolume as Gt}from"../rendering/fog/fog-volume-actor.js";import{UnscaledSprite as Lt}from"../utils/three/unscaled-sprite.js";import{ToonShader as qt}from"../shader/builtin/toon-shader.js";import{BatchedMesh2 as Jt}from"./batched-mesh-2.js";import{ParallaxStandardMaterial as Yt}from"../shader/builtin/standard-shader.js";import{parallaxOcclusionMapping as Qt}from"../shader-nodes/pom.js";import{traverseVisibleEvery as Ht}from"../utils/three/traverse.js";import{BufferGeometryUtils as Zt,RectAreaLightHelper as Xt}from"three/examples/jsm/Addons.js";import{createSequenceData as Kt,isSequenceData as ea,Sequence as ta}from"../effects/sequence/sequence-data.js";import{applyUvTiling as aa}from"./../shader/uv-nodes.js";import{buildShaderGraphMaterial as sa,shaderGraphMaterialSideToThree as ra}from"../shader/graph/index.js";import{hasExecutableEventGraphDocument as ia}from"../gameplay/event-graph/model.js";import{depthUniformName as na}from"../shader-nodes/depth.js";export{jt as applyRuntimeParamTypeInference,Pt as convertConfiguredParamsToRuntimeTypes,It as convertConfiguredParamValueToRuntimeType,Dt as inferRuntimeSerializedParamTypeHint};const oa={},la=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),ca=/^((?!chrome|android).)*safari/i.test(navigator.userAgent)||(navigator.userAgent.includes("iPhone")||navigator.userAgent.includes("iPad"))&&!!navigator.userAgent.match(/AppleWebKit/)&&!navigator.userAgent.match(/CriOS/);export const shapeDefaultColor="#aaaaaa";export class SceneMaterializerLoader{constructor(e,t,a){this.dataProvider=e,this.assetsService=t,this.assetManagerService=a}get(e,t){return new ua(e,this.dataProvider,this.assetsService,this.assetManagerService,t,[],[],{create:()=>null,initActor:async()=>{}})}}let ua=class{async preparePersistence(e,t,a){this.persistence=e,this.persistenceSceneId=t;const s=async(e,t,a,r)=>{for(const i of e){const e=t+i.id;if(a.length&&this.authoredPersistenceParents.set(e,a[a.length-1]),i.children&&await s(i.children,t,[...a,e],r),"prefab"!==i.type||null==i.assetId||r.includes(i.assetId))continue;const n=await this.assetsService.getAsset(i.assetId);null!=n?.prefab&&(null!=n.prefab.mainActorId&&this.prefabInstanceExposedActorMap.set(e,e+"/"+n.prefab.mainActorId),await s(n.prefab.objects,e+"/",[...a,e],[...r,i.assetId]))}};await s(a,"",[],[]);for(const e of this.prefabInstanceExposedActorMap.keys()){const t=this.persistenceActorPath(e),a=this.authoredPersistenceTargets.get(t);(null==a||e.length<a.length)&&this.authoredPersistenceTargets.set(t,e)}const r=e=>e.filter(e=>!this.isPersistenceRemoved(e.id)).map(e=>null==e.children?e:{...e,children:r(e.children)});return r(a)}persistenceActorPath(e){const t=new Set;for(;this.prefabInstanceExposedActorMap.has(e)&&!t.has(e);)t.add(e),e=this.prefabInstanceExposedActorMap.get(e);return e}isPersistenceRemoved(e){if(null==this.persistence)return!1;for(let t=e;null!=t;t=this.authoredPersistenceParents.get(t))if(this.persistence.isRemoved({sceneId:this.persistenceSceneId,path:t}))return!0;return!1}registerPersistentActors(){const e=[];if(null==this.persistence)return e;for(const[t,a]of this.materializedActors){const s={sceneId:this.persistenceSceneId,path:t},r={sceneId:this.persistenceSceneId,path:this.authoredPersistenceTargets.get(t)??t};this.persistence.register(a,s,r)&&e.push(a)}return e}get prefabEventGraphInstances(){return[...this.materializedPrefabEventGraphs.values()]}resolveSceneActor(e){const t=this.persistenceActorPath(e);if(!this.isPersistenceRemoved(t))return this.materializedActors.get(t)}constructor(e,t,s,r,i,n,c,u,d=[]){this.scene=e,this.dataProvider=t,this.assetsService=s,this.assetManagerService=r,this.renderingView=i,this.shaders=n,this.actorTypes=c,this.actorProvider=u,this.componentTypes=d,this.navigationBakes={},this.navigationRevision=0,this.objectMap=new Map,this.sceneObjectMap=new Map,this.components=[],this.landscapeManagers=[],this.materializedActors=new Map,this.authoredPersistenceTargets=new Map,this.authoredPersistenceParents=new Map,this.idToSceneObject=new Map,this.inEditor=!0,this.netMode=De.none,this.updated$=new o,this.removed$=new o,this.prefabEventGraphAdded$=new o,this.prefabEventGraphRemoved$=new o,this.error$=new o,this.materializedPrefabEventGraphs=new Map,this.announcedPrefabEventGraphs=new Set,this.editorActorParamSnapshot=new Map,this.editorAttachedActorComponents=new WeakMap,this.livePrefabInstances=new Map,this.sceneSettingsActive=!1,this.assets=new Map,this.vfxPreloads=new WeakMap,this.latticeGeometries=new a,this._canBeInstancedCache=new Map,this.editorStaticDrawChunks=[],this.editorStaticChunkBySource=new WeakMap,this.editorStaticSnapshotBySource=new WeakMap,this.dirtyEditorStaticDrawChunks=new Set,this.editorStaticEditingObjects=new Set,this.editorMatrixWorldEditingObjects=new Set,this.editorStaticSelectedObjects=new Set,this.editorStaticDrawSetSuspended=!1,this.editorStaticDrawSetRebuildQueued=!1,this.editorStaticFullRebuildQueued=!1,this._editorStaticDrawSetsEnabled=!0,this.editorStaticInitialized=!1,this.editorStaticDisposed=!1,this.editorStaticObjectsToRebuild=new Map,this.editorStaticDrawSetUpdated$=new o,this._originalMaterials=new Map,this.worldEnvironmentRequest=0,this.prefabInstanceChain=[],this.prefabInstanceExposedActorMap=new Map,this.geometryCache=new Map,this.collisionShapeCache=new Map,this.modelImageBitmaps=new WeakMap,this.assetManagerService.materialProvider=async e=>materialFromAsset(this.assets.get(e)??await this.assetsService.getAsset(e),this.renderingView,this.assetsService,this.assetManagerService,this.shaders),this.originalFog=e.fog,null!=this.renderingView.csm&&(this.originalGlobalLight={direction:this.renderingView.csm.lightDirection.clone(),intensity:this.renderingView.csm.lightIntensity,lights:this.renderingView.csm.lights.map(e=>({intensity:e.intensity,color:e.color.clone(),castShadow:e.castShadow,src:e.userData.src,volumetricIntensity:e.userData.volumetricIntensity}))}),t.onCreate(e=>{this.navigationRevision++,this.update(e).finally(()=>this.scheduleEditorStaticDrawSetRebuild()),this.handlePaintedScatterSceneMutation(e),this.handleSurfaceScatterSceneMutation(e)}),t.onUpdate(e=>{this.navigationRevision++,this.prepareEditorStaticObjectForMutation(e),this.update(e).finally(()=>this.scheduleEditorStaticDrawSetRebuild(e)),this.handlePaintedScatterSceneMutation(e),this.handleSurfaceScatterSceneMutation(e)}),t.onRemove(e=>{this.navigationRevision++,this.prepareEditorStaticObjectForMutation(e),this.remove(e),this.scheduleEditorStaticDrawSetRebuild(),this.handlePaintedScatterSceneMutation(e),this.handleSurfaceScatterSceneMutation(e)}),this.createAssetSubscription=s.onCreate.subscribe(e=>{this.navigationRevision++,this.assets.set(e.id,e)}),this.updateSubscription=s.onUpdate.subscribe(async t=>{this.navigationRevision++;const a=this.assets.get(t.id);if(this.assets.set(t.id,t),"material"==t.type){const a=[];e.traverse(e=>{if(e instanceof l.Mesh)if(Array.isArray(e.material))for(let s=0;s<e.material.length;s++)a.push(this.refreshMaterial(e,e.material[s],t,s));else a.push(this.refreshMaterial(e,e.material,t))}),await Promise.all(a)}else if("mesh"==t.type){this.findByAssetId(t.id).forEach(async e=>{this.remove(e.userData.src);const t=await this.materializeAndInitActor(e.userData.src);this.updated$.next({object:t,source:e.userData.src}),this.scheduleEditorStaticDrawSetRebuild()});for(const e of this.assets.values())if("prefab"==e.type){if(!e.prefab.objects.some(e=>Vs(e,e=>e.assetId==t.id,this.assets)))continue;this.findByAssetId(e.id).forEach(e=>{this.remove(e.userData.src),this.materializeAndInitActor(e.userData.src).finally(()=>this.scheduleEditorStaticDrawSetRebuild())})}this.landscapeManagers.forEach(e=>{const a=e.source?.grass?.layers?.some(e=>e.meshes.some(e=>e.assetId===t.id));a&&e.queueRefreshScatter(this.renderingView?.camera.position??new C,!0)}),null!=this.surfaceScatterManager&&(this.surfaceScatterManager.usesSourceAsset(t.id)||this.surfaceScatterManager.usesScatterAsset(t.id))&&this.surfaceScatterManager.queueRefresh(!0),this.paintedScatterManager?.usesScatterAsset(t.id)&&this.paintedScatterManager.queueRefresh(!0)}else if("prefab"===t.type){if("prefab"===a?.type&&await this.applyLivePrefabParameterUpdate(a,t))return;if(!this.inEditor)return void console.warn(`Prefab ${t.name??t.id} changed in a way that cannot be applied to its running instances. Respawn or restart to use the saved data.`);this.findByAssetId(t.id).forEach(e=>{const t=e.userData.src;this.remove(t),this.materializeAndInitActor(t).finally(()=>this.scheduleEditorStaticDrawSetRebuild())}),(this.surfaceScatterManager?.usesPrefabAsset(t.id)||this.sceneReferencesPrefabAsset(t.id)&&await this.prefabAssetContainsSurfaceScatter(t))&&await this.refreshSurfaceScatterPresence(!0),(this.paintedScatterManager?.usesPrefabAsset(t.id)||this.sceneReferencesPrefabAsset(t.id)&&await this.prefabAssetContainsPaintedScatter(t))&&await this.refreshPaintedScatterPresence(!0)}else if("vfx"===t.type)for(const e of this.dataProvider.getObjects())await Ea(e,async e=>{"vfx"===e.type&&e.assetId===t.id&&(this.remove(e),await this.materializeAndInitActor(e))});else if("texture"===t.type)await this.refreshMaterialTextures(t);else if("shaderGraph"===t.type){this.scene.traverse(e=>{if(e instanceof w)if(Array.isArray(e.material))for(let a=0;a<e.material.length;a++)this.refreshMaterial(e,e.material[a],t,a);else this.refreshMaterial(e,e.material,t)});for(const e of this.dataProvider.getObjects())await Ea(e,async e=>{if("vfx"===e.type&&null!=e.assetId){const a=this.assets.get(e.assetId);null!=a&&this.vfxAssetUsesShaderGraph(a,t.id)&&(this.remove(e),await this.materializeAndInitActor(e))}})}this.scheduleEditorStaticDrawSetRebuild()})}async refreshMaterialTextures(e){if("texture"!==e.type)return void console.error("Can not refresh material textures. Asset is not a texture",e);const t=new Set,a=new Set,s=[],r=s=>{t.has(s)||(t.add(s),this.materialUsesTexture(s,e.id)&&a.add(s))};if(this.scene.traverse(t=>{t instanceof l.SpotLight&&"spot"===t.userData?.src?.light?.type&&t.userData.src.light.spot.mapTextureId===e.id&&s.push(t),t instanceof w&&(Array.isArray(t.material)?t.material.forEach(r):r(t.material))}),0===a.size&&0===s.length)return;const i=await this.assetManagerService.getTexture(e);if(null!=i){for(const t of a)this.replaceMaterialTextureReferences(t,e.id,i);for(const e of s)e.map=i}else console.error("Can not refresh material textures. Texture not found",e)}materialUsesTexture(e,t){if(e instanceof l.ShaderMaterial){for(const a of Object.values(e.uniforms))if(a.value instanceof l.Texture&&a.value.userData.assetId===t)return!0}else for(const a of Object.values(e))if(a instanceof l.Texture&&a.userData.assetId===t)return!0;return!1}replaceMaterialTextureReferences(e,t,a){let s=!1;if(e instanceof l.ShaderMaterial)for(const[r,i]of Object.entries(e.uniforms))i.value instanceof l.Texture&&i.value.userData.assetId===t&&(e.uniforms[r].value=a,s=!0);else for(const[r,i]of Object.entries(e))i instanceof l.Texture&&i.userData.assetId===t&&(e[r]=a,s=!0);s&&(e.needsUpdate=!0,Te(e))}async getAsset(e){let t=this.assets.get(e);return null==t&&(t=await this.assetsService.getAsset(e),null!=t&&this.assets.set(e,t)),t}async refreshMaterial(e,t,a,s){const r=t?.userData?.assetId;if(r!==a.id){const e=this.assets.get(r);let t=!1;if(null!=e&&("shaderGraph"===a.type&&"asset"===e.material?.shaderGraph?.source&&e.material.shaderGraph.assetId===a.id&&(t=!0),!t&&null!=e.material?.shaderParams))for(const s of Object.values(e.material.shaderParams)){if(s.type===xt.Material&&s.value===a.id){t=!0;break}if(s.type===xt.Array&&"element"in s&&s.element===xt.Material&&s.value.includes(a.id)){t=!0;break}}if(!t)return}const i=await materialFromAsset(this.assets.get(r),this.renderingView,this.assetsService,this.assetManagerService,this.shaders,!1),n=i.userData,o=t.userData.receiveDecals!==n.receiveDecals;i.userData=t.userData,i.userData.hasBloom=n.hasBloom,i.userData.reflective=n.reflective,i.userData.outlineParameters=n.outlineParameters,i.userData.receiveDecals=n.receiveDecals,o&&(t.needsUpdate=!0),null!=s?Ka(e.material[s],i)||(e.material[s]=i):Ka(e.material,i)||(e.material=i,e===this.sky&&this.applySkySettings(e.material))}vfxAssetUsesShaderGraph(e,t){return null!=e.vfx&&e.vfx.emitters.some(e=>this.emitterUsesShaderGraph(e,t))}emitterUsesShaderGraph(e,t){const a=e.output;return"shaderGraph"===a.materialSource&&"asset"===a.shaderGraph?.source&&a.shaderGraph.assetId===t||!!e.children&&e.children.some(e=>this.emitterUsesShaderGraph(e,t))}getTopLevelActors(){return Array.from(this.materializedActors.entries()).filter(([e,t])=>!e.includes("/")).map(([,e])=>e)}get actorInstances(){return Array.from(this.materializedActors.values())}async initTextures(){const e="webgpu"===this.renderingView?.requestedBackend,t=e?this.renderingView.initializeBackend().catch(e=>{console.warn("Could not prepare WebGPU texture uploads before compilation",e)}):void 0,a=new Map,s=new Map,r=[];for(const e of this.collectMaterialAssignments(this.dataProvider.getObjects())){const t=this.assets.get(e.materialId);if(null!=t?.material)for(const e of Object.values(t.material.shaderParams??{}))if(e.type===xt.Texture&&"string"==typeof e.value){const t=this.assets.get(e.value);if(null==t)continue;const r=t.texture?.textureArrayFileKey;null==r?a.set(t.id,t):s.set(r,t)}}const i=[...Array.from(a.values(),e=>({asset:e,array:!1})),...Array.from(s.values(),e=>({asset:e,array:!0}))];let n=0;if(await Promise.all(Array.from({length:Math.min(16,i.length)},async()=>{for(;n<i.length;){const{asset:a,array:s}=i[n++],o=s?(await this.assetManagerService.getTextureArray(a))?.texture:await this.assetManagerService.getTexture(a);null!=o&&(e&&(await t,this.renderingView.initTexture(o)),r.push(o))}})),0!==r.length&&this.renderingView&&"webgpu"!==this.renderingView.requestedBackend){console.log(`Initializing ${r.length} textures`),console.time("Init textures");for(const e of r)this.renderingView.initTexture(e);console.timeEnd("Init textures")}}async prefetchAssets(){this.texturePrefetch=this.initTextures().catch(e=>{console.warn("Could not prefetch scene textures",e)});const e=this.collectAssetMeshIds(this.dataProvider.getObjects());await Promise.all(Array.from(e).map(async e=>{const t=this.assets.get(e);if("mesh"===t?.type)return this.assetManagerService.getMesh(t,{mergeGeomtries:!0,clone:!1})}))}collectAssetMeshIds(e,t=[],a=new Set){for(const s of e??[])this.collectObjectAssetMeshIds(s,t,a);return a}collectObjectAssetMeshIds(e,t,a){if(this.shouldBeMaterialized(e)&&("asset_mesh"===e.type&&null!=e.assetId&&a.add(e.assetId),null!=e.children&&this.collectAssetMeshIds(e.children,t,a),"prefab"===e.type&&null!=e.assetId&&!t.includes(e.assetId))){const s=this.assets.get(e.assetId);null!=s?.prefab?.objects&&this.collectAssetMeshIds(s.prefab.objects,[...t,e.assetId],a)}}collectMaterialAssignments(e,t=[],a=[]){for(const s of e??[])this.collectObjectMaterialAssignments(s,t,a);return a}collectObjectMaterialAssignments(e,t,a){if(this.shouldBeMaterialized(e)&&("shape_mesh"!==e.type&&"asset_mesh"!==e.type||null==e.materialAssignments||a.push(...e.materialAssignments),null!=e.children&&this.collectMaterialAssignments(e.children,t,a),"prefab"===e.type&&null!=e.assetId&&!t.includes(e.assetId))){const s=this.assets.get(e.assetId);null!=s?.prefab?.objects&&this.collectMaterialAssignments(s.prefab.objects,[...t,e.assetId],a)}}async init(){await this.preInit(),ha.clear(),pa.clear(),await this.prefetchAssets(),await Promise.all(this.dataProvider.getObjects().map(e=>this.materialize(e))),await this.initActorsPostInit(),this.generateOcclusionClusters(),this.announcePrefabEventGraphs(),await this.refreshPaintedScatterPresence(!0),await this.refreshSurfaceScatterPresence(!0),this.editorStaticInitialized=!0,this.rebuildEditorStaticDrawSet(),"webgpu"===this.renderingView.requestedBackend&&await this.texturePrefetch}get editorStaticDrawSetsEnabled(){return this._editorStaticDrawSetsEnabled}set editorStaticDrawSetsEnabled(e){this._editorStaticDrawSetsEnabled!==e&&(this._editorStaticDrawSetsEnabled=e,this.editorStaticInitialized&&!this.editorStaticDisposed&&(e?this.rebuildEditorStaticDrawSet():(this.editorStaticDrawSetSuspended=!1,this.editorStaticEditingObjects.clear(),this.editorStaticFullRebuildQueued=!1,this.editorStaticObjectsToRebuild.clear(),this.disposeEditorStaticDrawSet(),this.editorStaticDrawSetUpdated$.next())))}beginEditorStaticSceneEdit(e=[]){for(const e of this.editorMatrixWorldEditingObjects)Aa(e,!1);this.editorMatrixWorldEditingObjects.clear();for(const t of e)this.editorMatrixWorldEditingObjects.add(t),Aa(t,!0);if(!this._editorStaticDrawSetsEnabled||!this.inEditor||this.editorStaticDrawSetSuspended)return;this.editorStaticDrawSetSuspended=!0,this.editorStaticEditingObjects.clear();const t=new Set;for(const a of e){this.editorStaticEditingObjects.add(a);const e=this.editorStaticChunkBySource.get(a);null!=e&&t.add(e)}for(const e of t)this.disposeEditorStaticDrawChunk(e),this.dirtyEditorStaticDrawChunks.add(e),this.buildEditorStaticDrawChunk(e);this.editorStaticDrawSetUpdated$.next()}setEditorStaticSelectedObjects(e){if(!this.inEditor)return;const t=new Set(e),a=new Set;for(const e of this.editorStaticSelectedObjects)if(!t.has(e)){const t=this.editorStaticChunkBySource.get(e);null!=t&&a.add(t)}for(const e of t)if(!this.editorStaticSelectedObjects.has(e)){const t=this.editorStaticChunkBySource.get(e);null!=t&&a.add(t)}this.editorStaticSelectedObjects.clear();for(const e of t)this.editorStaticSelectedObjects.add(e);if(!this.editorStaticDrawSetSuspended&&"webgpu"===this.renderingView?.requestedBackend){for(const e of a)this.disposeEditorStaticDrawChunk(e),this.buildEditorStaticDrawChunk(e);a.size>0&&this.editorStaticDrawSetUpdated$.next()}}endEditorStaticSceneEdit(){for(const e of this.editorMatrixWorldEditingObjects)Aa(e,!1);if(this.editorMatrixWorldEditingObjects.clear(),this.editorStaticDrawSetSuspended){this.editorStaticDrawSetSuspended=!1,this.editorStaticEditingObjects.clear();for(const e of this.dirtyEditorStaticDrawChunks)this.disposeEditorStaticDrawChunk(e),this.buildEditorStaticDrawChunk(e);this.dirtyEditorStaticDrawChunks.clear(),this.editorStaticDrawSetUpdated$.next()}}getEditorRenderObject(e){const t=e.userData?.src,a=null!=t?.id?this.sceneObjectMap.get(t.id)??e:e;if(this.editorStaticEditingObjects.has(a)||this.editorStaticSelectedObjects.has(a))return a;const s=this.editorStaticSnapshotBySource.get(a);return!0===s?.chunk.active?s.object:e}scheduleEditorStaticDrawSetRebuild(e){!this.editorStaticDisposed&&this._editorStaticDrawSetsEnabled&&this.inEditor&&!this.editorStaticDrawSetSuspended&&"webgpu"===this.renderingView?.requestedBackend&&(null==e?(this.editorStaticFullRebuildQueued=!0,this.editorStaticObjectsToRebuild.clear()):this.editorStaticFullRebuildQueued||this.editorStaticObjectsToRebuild.set(e.id,e),this.editorStaticDrawSetRebuildQueued||(this.editorStaticDrawSetRebuildQueued=!0,queueMicrotask(()=>{if(this.editorStaticDrawSetRebuildQueued=!1,this.editorStaticDisposed||this.editorStaticDrawSetSuspended)return;if(this.editorStaticFullRebuildQueued)return this.editorStaticFullRebuildQueued=!1,void this.rebuildEditorStaticDrawSet();const e=new Set;for(const t of this.editorStaticObjectsToRebuild.values()){const a=this.sceneObjectMap.get(t.id),s=null==a?null:this.editorStaticChunkBySource.get(a);if(null==s){this.editorStaticFullRebuildQueued=!0;break}e.add(s)}if(this.editorStaticObjectsToRebuild.clear(),this.editorStaticFullRebuildQueued)return this.editorStaticFullRebuildQueued=!1,void this.rebuildEditorStaticDrawSet();for(const t of e)this.disposeEditorStaticDrawChunk(t),this.buildEditorStaticDrawChunk(t);this.editorStaticDrawSetUpdated$.next()})))}prepareEditorStaticObjectForMutation(e){const t=this.sceneObjectMap.get(e.id);if(null==t)return;const a=this.editorStaticChunkBySource.get(t);!0===a?.active&&this.disposeEditorStaticDrawChunk(a)}rebuildEditorStaticDrawSet(){if(this.disposeEditorStaticDrawSet(),!this._editorStaticDrawSetsEnabled||!this.inEditor||this.editorStaticDrawSetSuspended||"webgpu"!==this.renderingView?.requestedBackend)return;const e=[];for(const t of this.idToSceneObject.values()){if("asset_mesh"!==t.type||null!=t.latticeDeformation||!0===t.hidden||t.physics?.type===Ie.dynamic)continue;const a=this.sceneObjectMap.get(t.id);null!=a&&this.canUseEditorStaticDrawSet(a)&&e.push(a)}const t=new m;t.name="Hology WebGPU editor static authored objects",t.visible=!1,t.userData.hologyEditorStaticAuthoredRoot=!0,this.scene.add(t),this.editorStaticAuthoredRoot=t,e.sort((e,t)=>{const a=e.userData?.src,s=t.userData?.src,r="asset_mesh"===a?.type?`${a.assetId}:${JSON.stringify(a.materialAssignments??[])}`:"",i="asset_mesh"===s?.type?`${s.assetId}:${JSON.stringify(s.materialAssignments??[])}`:"";return r.localeCompare(i)});for(let t=0;t<e.length;t+=32){const a={sources:e.slice(t,t+32),sourceVisibility:new Map,sourceUpdateMatrixWorld:new Map,sourceParents:new Map,active:!1};this.editorStaticDrawChunks.push(a);for(const e of a.sources)this.editorStaticChunkBySource.set(e,a);this.buildEditorStaticDrawChunk(a)}this.editorStaticDrawSetUpdated$.next()}buildEditorStaticDrawChunk(e){const t=new m;t.name="Hology WebGPU editor static asset mesh chunk",t.userData.hologyEditorStaticSnapshotRoot=!0,e.sourceVisibility.clear(),e.sourceUpdateMatrixWorld.clear(),e.sourceParents.clear();for(const a of e.sources){if(this.editorStaticEditingObjects.has(a)||this.editorStaticSelectedObjects.has(a)){this.editorStaticSnapshotBySource.delete(a);continue}a.updateWorldMatrix(!0,!0);const s=new m;s.name=a.name;const r=a.userData?.src;for(const e of a.children){const t=e.clone(!0),a=[];t.traverse(e=>{const t=e.userData?.src;(dt(e)||null!=t?.id&&null!=r?.id&&t.id!==r.id)&&a.push(e)});for(const e of a)e.removeFromParent();a.includes(t)||s.add(t)}s.matrix.copy(a.matrixWorld),s.matrix.decompose(s.position,s.quaternion,s.scale),s.matrixAutoUpdate=!1,t.add(s),this.editorStaticSnapshotBySource.set(a,{object:s,chunk:e}),e.sourceVisibility.set(a,a.visible),e.sourceParents.set(a,a.parent),a.visible=!1,this.editorStaticAuthoredRoot?.attach(a),e.sourceUpdateMatrixWorld.set(a,a.updateMatrixWorld),a.updateMatrixWorld=va}0!==t.children.length&&(ba(t),this.scene.add(t),e.root=t,e.disposer=this.renderingView.registerExperimentalStaticDrawSet(t,`hology-editor-static-asset-meshes-${this.editorStaticDrawChunks.indexOf(e)}`),e.active=!0)}canUseEditorStaticDrawSet(e){let t=!1,a=!0;return e.traverseVisible(e=>{e instanceof w&&!dt(e)&&(t=!0,null!=e.geometry?.index&&null==e.customDepthMaterial&&ja(e.material)||(a=!1))}),t&&a}disposeEditorStaticDrawSet(){for(const e of this.editorStaticDrawChunks)this.disposeEditorStaticDrawChunk(e);this.editorStaticDrawChunks.length=0,this.dirtyEditorStaticDrawChunks.clear(),this.editorStaticChunkBySource=new WeakMap,this.editorStaticSnapshotBySource=new WeakMap,this.editorStaticAuthoredRoot?.removeFromParent(),this.editorStaticAuthoredRoot=void 0}disposeEditorStaticDrawChunk(e){e.disposer?.(),e.disposer=void 0,e.root?.removeFromParent(),e.root=void 0,e.active=!1;for(const[t,a]of e.sourceParents){const e=t.userData?.src,s=null==e?.id||this.sceneObjectMap.get(e.id)===t;(null!=a&&null==t.parent&&s||null!=a&&t.parent===this.editorStaticAuthoredRoot&&s)&&a.attach(t)}e.sourceParents.clear();for(const[t,a]of e.sourceVisibility)t.visible=a;e.sourceVisibility.clear();for(const[t,a]of e.sourceUpdateMatrixWorld)t.updateMatrixWorld=a;e.sourceUpdateMatrixWorld.clear()}async preloadVisualEffects(e){const t=[],a=new Set;for(const s of e){const e=s.asset;if(a.has(e))continue;a.add(e);let r=this.inEditor?void 0:this.vfxPreloads.get(e);null==r&&(r=this.preloadVisualEffect(s).catch(t=>{throw this.vfxPreloads.get(e)===r&&this.vfxPreloads.delete(e),t}),this.inEditor||this.vfxPreloads.set(e,r)),t.push(r)}await Promise.all(t)}async preloadVisualEffect(e){const t=new Set;!function(e,t){const a=e=>{const s=e.output;switch(s.type){case"sprite":case"stretchedSprite":t.add(s.texture);break;case"trail":null!=s.texture&&t.add(s.texture);break;case"decal":t.add(s.colorMap),t.add(s.alphaMap)}e.children?.forEach(a)};e.vfx.emitters.forEach(a)}(e.asset,t),await Promise.all([this.initVfxTextures(t),(async()=>{const t=await e.create(new P);try{await t.prepareRendering()}finally{t.onEndPlay(),t.disposed.next(!0),t.object.removeFromParent()}})()])}async initVfxTextures(e){const t=await Promise.all(Array.from(e,async e=>{const t=await this.assetsService.getAsset(e);return null==t?null:this.assetManagerService.getTexture(t)}));for(const e of t)null!=e&&this.renderingView.initTexture(e)}async initVfx(){await this.preloadVisualEffects(this.actorInstances.flatMap(e=>Ds(e)))}async initActorsPostInit(e=Array.from(this.materializedActors.entries())){const t=e.map(async([e,t])=>{if(t.__isInitialised)return;const a=t.object.userData.src??t.object.userData._src;if("vfx"===a.type)return Promise.resolve();const s="prefab"===a.type?await this.assetsService.getAsset(a.assetId):null,r=e.split("/"),i=r.slice(0,-1),n=i.join("/"),o=(r[r.length-1],new Map);for(const[e,t]of this.materializedActors)if(o.set(e,t),0===n.length)e.includes("/")||o.set(e,t);else if(e.startsWith(n+"/")){const a=e.slice(n.length+1);a.includes("/")||o.set(a,t)}const l={...s?.actor?.params??{},...a.actor?.params??{}},c=[...a.actor?.innerParams??[]];for(let t=i.length-1;t>=0;t--){const a=i.slice(0,t+1).join("/"),s=this.idToSceneObject.get(a);if("prefab"===s?.type&&null!=s.prefab){const i=await this.assetsService.getAsset(s.assetId);if(null!=i){let n=!1,o=a+"/"+i.prefab?.mainActorId;for(;null!=o;){if(o===e){n=!0;break}o=this.prefabInstanceExposedActorMap.get(o)}if(n&&null!=s.prefab.params&&Object.assign(l,Ua(s.prefab.params)),null!=s.prefab.innerParams){const e=r.slice(t+1);for(const t of s.prefab.innerParams){const a=Ua(t.params);0!==Object.keys(a).length&&(n?c.push({path:Fa(t.path,e)?t.path.slice(e.length):t.path,params:a}):Fa(t.path,e)&&c.push({path:t.path.slice(e.length),params:a}))}}}}}this.rememberLivePrefabActorSettings(e,{...a.actor,params:l,innerParams:c});for(const e of c)await this.applyActorComponentParams(t,e.path.slice(),e.params,o);await this.attachEditorComponents(t,a,o);const u=await prepareClassParameters(l,t.constructor,this.assetsService,this.assetManagerService,o,this.renderingView,this.shaders,this.actorProvider,e=>{const t=n.length>0?n+"/"+e:e;return this.prefabInstanceExposedActorMap.has(t)?this.persistenceActorPath(t):null},t);Object.assign(t,u);try{return await this.actorProvider.initActor(t)}catch(e){console.error(`Failed to initiate actor (name="${a.name}", id=${a.id})`,e)}});return Promise.all(t)}async attachEditorComponents(e,t,a){const s=t.actor?.components??[],r=new Array(s.length).fill(null);this.editorAttachedActorComponents.set(e,r);for(const[i,n]of s.entries()){const s=this.componentTypes.find(e=>e.name===n.type);if(null==s){console.warn(`Component type '${n.type}' not found for actor ${t.id}`);continue}const o=e.attach(s.type);if(r[i]=o,null!=n.params){const e=await prepareClassParameters(n.params,null,this.assetsService,this.assetManagerService,a,this.renderingView,this.shaders,this.actorProvider,e=>this.prefabInstanceExposedActorMap.get(e)??null,o);Object.assign(o,e)}for(const e of n.innerParams??[])await this.applyActorComponentParams(o,e.path.slice(),e.params,a)}}addVfxChildActors(e,t=e){}async applyActorComponentParams(e,t,a,s){const r=t.length,i=t.shift();if(0==r){const t=await prepareClassParameters(a,null,this.assetsService,this.assetManagerService,s,this.renderingView,this.shaders,this.actorProvider,e=>this.prefabInstanceExposedActorMap.get(e)??null,e);for(const[a,s]of Object.entries(t))null!=s&&(e[a]=s)}else null!=e[i]&&await this.applyActorComponentParams(e[i],t,a,s)}previewLatticeDeformation(e,t){this.latticeGeometries.apply(e,t,JSON.stringify(e.userData.src?.vertexMaterials??[]))}canObjectBeInstanced(e){return null==e.latticeDeformation&&e.physics?.type!==Ie.dynamic&&"sky"!==e.type&&"global_fog"!==e.type&&"world_env"!==e.type}async canAssetBeInstanced(e){let t=this._canBeInstancedCache.get(e.assetId);if(null==t){const a=await this.createFromAsset(e);if(null==a)return!1;const s=[];a.traverse(e=>{!dt(e)&&e.isMesh&&s.push(e)});const r=1==s.length&&0==s[0].children.length,i=!ca,n=s.every(e=>!Array.isArray(e.material)||1===e.material.length),o=s.some(e=>e instanceof w&&null!=e.geometry.morphAttributes&&Object.keys(e.geometry.morphAttributes).length>0),l=!0;t=s.length>0&&(r||n&&i)&&l&&!o,this._canBeInstancedCache.set(e.assetId,t)}return t}async preInit(){this.renderingView?.onLoop(()=>{null!=this.sky&&this.renderingView.camera.getWorldPosition(this.sky.position)}),await this.preloadAssets()}async preloadAssets(){const e=await this.assetsService.getAssets();for(const t of e)this.assets.set(t.id,t)}shouldBeMaterialized(e){if(!1===e.enabled)return!1;if(null!=this.detailTier&&"asset_mesh"===e.type&&null!=e.assetId){const t=this.assets.get(e.assetId);if(null!=t){const e=t.mesh?.detailTier;if(null!=e)return e<=this.detailTier}}return!0}async initWithInstancing(){this.sceneSettingsActive=!0,await this.preInit(),await this.prefetchAssets(),this.experimentalStaticDrawSetDisposer?.(),this.experimentalStaticDrawSetDisposer=void 0,ha.clear(),pa.clear();const e=[],t=new Ke,a=new Ke,s=new Ke;let r=0,i=0,n=0;const o=new Map,c=new et(()=>new Map),u="webgpu"===this.renderingView?.requestedBackend?new m:null,p=null!=u?new m:null;null!=u&&(u.name="Hology WebGPU static scene objects",p.name="Hology WebGPU unsorted late static scene objects");const f=(e,t)=>{if(null!=u&&function(e){return e.visible&&null!=e.geometry.index&&null==e.customDepthMaterial&&ja(e.material,!0)}(t)){((Array.isArray(t.material)?t.material:[t.material]).some(e=>e.transparent||Pa(e))?p:u).add(e)}else this.scene.add(e)};for(const l of this.dataProvider.getObjects())await Ea(l,async(l,u,h)=>{if(!this.shouldBeMaterialized(l))return;const p="asset_mesh"==l.type&&this.canObjectBeInstanced(l)&&await this.canAssetBeInstanced(l),f="shape_mesh"===l.type&&"landscape"!==l.shape&&l.physics?.type!==Ie.dynamic;if(p||f){if(u&&u.children?.length>0){const e=u.children.findIndex(e=>e.id===l.id);e>=0&&u.children.splice(e,1)}if(f){let e=l.shape+JSON.stringify(l.shapeParams??{})+l.castShadow+l.receiveShadow;const t=l.materialAssignments?.at(0)?.materialId,a=null!=t?this.assets.get(t):null;let r=null;if(!1&&null!=a&&"shader"!==a.material.type){if(e+=a.material.type+a.material.shader,null!=a.material.shaderParams){if(e+=Object.entries(a.material.shaderParams).filter(([e,t])=>"color"!=e).map(e=>JSON.stringify(e)).join(),null!=a.material.shaderParams.color){const e=a.material.shaderParams.color;e.type===xt.Color&&null!=e.value&&(r=new d(e.value))}}e+=a.material.outlines,null!=a.material.outlineParams&&(e+=JSON.stringify(a.material.outlineParams)),e+=a.material.reflective,e+=a.material.bloom,e+=a.material.side,e+=a.material.side,e+=a.material.transparent,e+=a.material.alphaTest}else e+=t;s.push(e,{object:{...l,parentTransform:h},color:r}),n++}else{const e=this.assets.get(l.assetId);null==e&&console.log("Can't find asset with id "+l.assetId);let s=o.get(l.assetId);if(null==s){const e=await this.createFromAsset(l,{assignMaterials:!1});if(null==e)return;if(s=o.get(l.assetId),null==s){s={useBatchedMesh:null!=it(e)&&Ht(e,e=>!(e instanceof w)||this.testCanBatch(e.material,e.geometry)),assetMesh:e},o.set(l.assetId,s)}}const n=_a(l.materialAssignments,e.materialAssignments);if(s.useBatchedMesh)await ot(s.assetMesh,async t=>{if(!(t instanceof w))return;const s=Array.isArray(t.material)?t.material[0]:t.material,i=await this.resolveMaterialForAssignments(s,n,e);if(null!=i){Be(i,!1),c.get(l.id).set(t.uuid,i);let s=ts(t,i);if(s+=cs(i),"webgpu"===this.renderingView?.requestedBackend){const t=l.castShadow??e.castShadow??!1,a=l.receiveShadow??e.receiveShadow??!1;s+=`|detailCulling:${JSON.stringify(l.detailCulling??null)}`,s+=`|castShadow:${t?1:0}|receiveShadow:${a?1:0}`}a.push(s,{...l,parentTransform:h,meshUUID:t.uuid}),r++}else console.warn("Can not materialize mesh because missing material",l)});else{const e=l.assetId+JSON.stringify(l.materialAssignments??[]);t.push(e,{...l,parentTransform:h}),i++}}}else null==u&&e.push({...l,parentTransform:h})});console.log(`Scene init stats: \n Batched Assets: ${a.size} groups containing in total ${r} objects.\n Instanced Assets: ${t.size} groups containing in total ${i} objects.\n Shapes: ${s.size} batch groups containing in total ${n} objects. \n ${e.length} objects can not be batched. \n `),console.time("materialize batches");for(const[e,t]of a.entries()){if(0==t.length)continue;let e;o.get(t[0].assetId).assetMesh;e=this.createBatchedMesh(t,c,o);const a=this.assets.get(t[0].assetId);"webgl"===this.renderingView?.activeBackend?(e instanceof Jt&&e.perInstanceCastShadow||(e.castShadow=Js(t,a?.castShadow??!1)),e.receiveShadow=Ys(t,a?.receiveShadow??!1)):(e.castShadow=t[0].castShadow??a?.castShadow??!1,e.receiveShadow=t[0].receiveShadow??a?.receiveShadow??!1);const s=new lt;s.add(e),s.userData.src=t[0],s.userData.detailCulling=t[0].detailCulling,s.castShadow=!1,s.receiveShadow=!1,f(s,e)}for(const e of t.values()){if(0==e.length)continue;let t;const a=o.get(e[0].assetId).assetMesh;t=await this.createInstancedMesh(e,a);const s=this.assets.get(e[0].assetId);t.castShadow=Js(e,s?.castShadow??!1),t.receiveShadow=Ys(e,s?.receiveShadow??!1);const r=new lt;r.add(t),r.userData.src=e[0],r.userData.detailCulling=e[0].detailCulling,a instanceof lt&&(r.collisionShapes=a.collisionShapes),this.prepareCollisionShapesForInstanced(r),r.castShadow=!1,r.receiveShadow=!1,f(r,t)}console.timeEnd("materialize batches");for(const e of s.values()){if(0==e.length)continue;const t=e[0].object,a=await this.createFromShape(t),s=nt(a,e=>!dt(e)&&null!=e.geometry),r=Ha(s.material);null!=e[0].color&&null!=r.color&&(r.color=new d(16777215));const i=null==s.geometry.index?Zt.mergeVertices(s.geometry):s.geometry;let n,o;!(ca||r instanceof L)?(n=new l.BatchedMesh(e.length,i.getAttribute("position").count,i.index.count,r),n.perObjectFrustumCulled=!0,o=n.addGeometry(i)):n=new l.InstancedMesh(i,r,e.length),n.castShadow=a.castShadow??!0,n.receiveShadow=s.receiveShadow??!1;for(let t=0;t<e.length;t++){const a=e[t],s=(new l.Matrix4).compose((new C).fromArray(a.object.position),(new j).setFromEuler((new h).fromArray(a.object.rotation)),(new C).fromArray(a.object.scale)),r=(new y).copy(a.object.parentTransform).multiply(s);let i;i=n instanceof l.BatchedMesh?n.addInstance(o):t,n.setMatrixAt(i,r),a.color}for(let t=0;t<e.length;t++){const s=e[t],r=new lt;r.userData.src=e[0],r.userData.detailCulling=e[0].object.detailCulling,a instanceof pt&&(r.collisionShapes=[a.collisionShape]),r.castShadow=!0,r.receiveShadow=!0,f(r,n),r.add(n),null==n.userData.hasCollision&&(n.userData.hasCollision=[]),n.userData.hasCollision[t]=!1!==s.object.collisionDetection}}if(null!=u&&u.children.length>0&&(ba(u),this.scene.add(u),this.experimentalStaticDrawSetDisposer=this.renderingView.registerExperimentalStaticDrawSet(u,"hology-materialized-static-scene")),null!=p&&p.children.length>0){ba(p),this.scene.add(p);const e=this.experimentalStaticDrawSetDisposer,t=this.renderingView.registerExperimentalStaticDrawSet(p,"hology-materialized-unsorted-late-static-scene",!0);this.experimentalStaticDrawSetDisposer=()=>{e?.(),t()}}await Promise.all(e.map(e=>this.materialize(e))),await this.initActorsPostInit(),this.announcePrefabEventGraphs(),await this.initVfx(),this.generateOcclusionClusters(),await this.refreshPaintedScatterPresence(!0),await this.refreshSurfaceScatterPresence(!0),"webgpu"===this.renderingView.requestedBackend&&await this.texturePrefetch}generateOcclusionClusters(){const e=new zt;e.initScene(this.scene),e.clusters.forEach(e=>{this.renderingView.addCluster(e)})}prepareCollisionShapesForInstanced(e){e instanceof lt&&e.collisionShapes.forEach(e=>{e instanceof r&&e.mesh instanceof w&&(e.mesh=e.mesh.geometry)})}setScene(e){this.scene=e}testCanBatch(e,t){return!ca&&(!Array.isArray(e)||1==e.length)&&this.testCanBatchMaterial(e)}testCanBatchMaterial(e){return null!=(Array.isArray(e)?e[0]:e)}createBatchedMesh(e,t,a){const s=new Ke;for(const t of e)null!=t.meshUUID?s.push(t.meshUUID??t.assetId,t):console.warn("Missing mesh uuid for batching");let r=0,i=0,n=0;const o=new Map;for(const[e,t]of s.entries()){const s=t[0].assetId,l=a.get(s);if(null==l){console.warn("Missing batching info for asset id "+s);continue}const c=nt(l.assetMesh,t=>t instanceof w&&t.uuid===e);if(null==c){console.warn("Missing mesh in batched asset");continue}o.set(e,c);const u=c.geometry.getAttribute("position");null==u&&console.warn("Missing position attribute for batched mesh"),r+=c.geometry.index.count*t.length,i+=u.count*t.length,n+=t.length}const c=["color","map","roughness","roughnessMap","metalness","metalnessMap","opacity","alphaMap","aoMap","aoMapIntensity","normalMap","normalScale","emissive","emissiveIntensity","emissiveMap"],u=new Map,h=new Map,p=[];let f=new l.MeshStandardMaterial({color:"white"});const m=t.get(e[0].id).get(e[0].meshUUID);if(null==m)throw"missing source material";if(m instanceof v&&!(m instanceof l.MeshPhysicalMaterial)){const a=new Set,s=new Map;for(const r of e){const e=t.get(r.id).get(r.meshUUID);if(null==e)throw"missing mat";for(const t of c){let r=e[t];r instanceof l.CompressedArrayTexture&&null!=r.userData.index&&(r=r.userData.index);const i=s.get(t);void 0===i||Is(r,i)?s.set(t,r):a.add(t)}}for(const e of a){let t;const a=m[e];let s=e;if("number"==typeof a){let a=p.find(e=>e.params.length<4);if(null==a){const t="vp"+p.length;a={name:t,params:[e],node:V(t)},p.push(a)}else a.params.push(e);s=a.name,t=js(a.node,a.params.length-1)}else if(a instanceof O)t=V(s);else if(a instanceof C||a instanceof d)t=B(s);else if(a instanceof D)t=T(s);else if(a instanceof l.CompressedArrayTexture)s=e+"_i",t=k(s);else if(a instanceof I)continue;u.set(e,t),h.set(e,s)}let r=oe.uv;m instanceof Yt&&null!=m.heightMap&&(r=Qt(r,X(m.heightMap),F(m.heightScale)));let i=vs(u.get("opacity"),W)??F(m.opacity??1);if(null!=m.alphaMap){let e;if(m.alphaMap instanceof l.CompressedArrayTexture){const t=K(m.alphaMap),a=vs(u.get("alphaMap"),W)??F(m.alphaMap.userData.index??0);e=t.sample(de(r.x,r.y,a))}else e=X(m.alphaMap).sample(r);i=i.multiply(e.r)}let n=J(vs(u.get("color"),he)??m.color,i);if(null!=m.map){let e;if(m.map instanceof l.CompressedArrayTexture){const t=K(m.map),a=vs(u.get("map"),W)??F(m.map.userData.index??0);e=t.sample(de(r.x,r.y,a))}else e=X(m.map).sample(aa(r,m.map));n=n.multiply(e),i=i.multiply(e.a)}m.vertexColors&&(n=n.multiply(pe(ne(E.color.rgb),1)));let o=J(vs(u.get("emissive"),he)??m.emissive,i);if(null!=m.emissiveMap){let e;if(m.emissiveMap instanceof l.CompressedArrayTexture){const t=K(m.emissiveMap),a=vs(u.get("emissiveMap"),W)??F(m.emissiveMap.userData.index??0);e=t.sample(de(r.x,r.y,a))}else e=X(m.emissiveMap).sample(aa(r,m.emissiveMap));o=o.multiply(e)}const g=vs(u.get("emissiveIntensity"),W)??F(m.emissiveIntensity??1),y=vs(u.get("normalScale"),ue)??ce(m.normalScale??new D(1,1));let w=le.normal;if(null!=m.normalMap){let e;if(m.normalMap instanceof l.CompressedArrayTexture){const t=K(m.normalMap),a=vs(u.get("normalMap"),W)??F(m.normalMap.userData.index??0);e=t.sample(de(r.x,r.y,a))}else e=X(m.normalMap).sample(aa(r,m.normalMap));w=U(e.rgb,y.x)}let S=vs(u.get("roughness"),W)??F(m.roughness??1);if(null!=m.roughnessMap){let e;if(m.roughnessMap instanceof l.CompressedArrayTexture){const t=K(m.roughnessMap),a=vs(u.get("roughnessMap"),W)??F(m.roughnessMap.userData.index??0);e=t.sample(de(r.x,r.y,a))}else e=X(m.roughnessMap).sample(aa(r,m.roughnessMap));S=S.multiply(e.g)}let b=vs(u.get("metalness"),W)??F(m.metalness??0);if(null!=m.metalnessMap){let e;if(m.metalnessMap instanceof l.CompressedArrayTexture){const t=K(m.metalnessMap),a=vs(u.get("metalnessMap"),W)??F(m.metalnessMap.userData.index??0);e=t.sample(de(r.x,r.y,a))}else e=X(m.metalnessMap).sample(aa(r,m.metalnessMap));b=b.multiply(e.b)}let v=F(1);if(null!=m.aoMap){let e;if(m.aoMap instanceof l.CompressedArrayTexture){const t=K(m.aoMap),a=vs(u.get("aoMap"),W)??F(m.aoMap.userData.index??0);e=t.sample(de(r.x,r.y,a))}else e=X(m.aoMap).sample(aa(r,m.aoMap));v=v.multiply(e.r)}const M=vs(u.get("aoMapIntensity"),W)??F(m.aoMapIntensity??0);let A=w;!0!==m.userData.disableAO&&(A=_("DOUBLE_SIDED",A,e=>Q(new z("gl_FrontFacing"),e,e.multiplyScalar(-1))));const x=new L({color:H({color:n,roughness:S,metalness:b,ambientOcclusion:v,ambientOcclusionIntensity:M,emissive:o,emissiveIntensity:g,normal:A}),normal:w,roughness:S,emissive:o.rgb,transparent:m.transparent,alphaTest:m.alphaTest,envMap:m.envMap,opacity:i});null!=m.envMap&&(x.uniforms.envMapIntensity={value:m.envMapIntensity},x.uniforms.envMapRotation={value:xs(m.envMapRotation,m.envMap)}),x.envMap=m.envMap,x.side=m.side,f=x}else if(m instanceof L){const a=new Set,s=new Map,r=Object.keys(m.uniforms).filter(e=>!hs(e));for(const i of e){const e=t.get(i.id).get(i.meshUUID);if(!(e instanceof L))throw new Error("Expected NodeShaderMaterial in node material batch");for(const t of r){const r=e.uniforms[t]?.value,i=s.get(t);void 0===i||Is(r,i)?s.set(t,r):fs(r)&&fs(i)&&ms(r)===ms(i)&&a.add(t)}}const i=new Set(Object.keys(m.uniforms)),n={};for(const e of a){let t,a;const s=m.uniforms[e]?.value;if("number"==typeof s){let s=p.find(e=>e.params.length<4);if(null==s){const t=gs("vp"+p.length,i);s={name:t,params:[e],node:V(t)},p.push(s)}else s.params.push(e);a=s.name,t=js(s.node,s.params.length-1)}else if(s instanceof O)a=gs(e,i),t=V(a);else if(s instanceof C||s instanceof d)a=gs(e,i),t=B(a);else{if(!(s instanceof D))continue;a=gs(e,i),t=T(a)}u.set(e,t),h.set(e,a),n[e]=t}if(0===u.size)f=m;else{const e=R(m,{color:m.outputColor,transform:m.outputTransform??null,position:null==m.outputTransform?m.outputPosition:void 0,normal:m.outputNormal??null,roughness:m.outputRoughness??null,opacity:m.outputOpacity??null,emissive:m.outputEmissive??null,uniforms:ys(m,new Set(u.keys())),uniformNodes:n});e.uniformNodes=n,g=m,(y=e).name=g.name,y.side=g.side,y.blending=g.blending,y.depthWrite=g.depthWrite,y.depthTest=g.depthTest,y.colorWrite=g.colorWrite,y.toneMapped=g.toneMapped,y.visible=g.visible,y.opacity=g.opacity,y.forceSinglePass=g.forceSinglePass,y.premultipliedAlpha=g.premultipliedAlpha,y.polygonOffset=g.polygonOffset,y.polygonOffsetFactor=g.polygonOffsetFactor,y.polygonOffsetUnits=g.polygonOffsetUnits,y.shadowSide=g.shadowSide,Object.assign(y.defines,g.defines),Object.assign(y.userData,g.userData),y.needsUpdate=!0,f=e}}else{f=m;for(const a of e){const e=t.get(a.id).get(a.meshUUID);if(e!=f){console.error(`Different materials in group for object ${a.id} and mesh uuid ${a.meshUUID}`,{objectMaterial:e,sourceMaterial:m});break}}}var g,y;const S=new Jt(n,i,r,f);for(const e of p)S.initUniform(e.name,4);for(const[e,t]of u.entries()){if(p.some(t=>t.params.includes(e)))continue;let a=1;t instanceof fe||t instanceof he?a=4:t instanceof ue&&(a=2),S.initUniform(h.get(e)??e,a,0)}for(const[e,r]of s.entries()){const s=r[0].assetId,i=o.get(e);if(null==i){console.error(`Missing single asset mesh for mesh uuid ${e} and asset id ${s}`);continue}if(null==i.geometry){console.error("Missing geometry on mesh mesh");continue}const n=S.addGeometry(as(i.geometry,m)),c=this.assets.get(s),f=a.get(s);if(null==f){console.warn("Missing batching info when configuring for asset id "+s);continue}const g=it(f.assetMesh)?.uuid===e,y=f.assetMesh instanceof lt&&g?f.assetMesh.collisionShapes:void 0,w=this.configureBatchedInstancedMesh(r,S,i,n,y);for(let e=0;e<w.length;e++){const a=r[e],s=w[e];"webgpu"!==this.renderingView?.requestedBackend&&S.setCastShadowAt(s,a.castShadow??c?.castShadow??!1);const i=t.get(a.id).get(a.meshUUID),n=i.userData.surface;null!=n&&(S.surfaceByInstance[s]=n);for(const e of p){let t=Ps.set(0,0,0,0);for(let a=0;a<e.params.length;a++){const s=ps(i,e.params[a]);"number"==typeof s&&t.setComponent(a,s)}S.setUniformAt(e.name,s,t)}for(let e of u.keys()){if(p.some(t=>t.params.includes(e)))continue;const t=h.get(e)??e;let a=ps(i,e);if(a instanceof d&&(a=new C(a.r,a.g,a.b)),a instanceof l.CompressedArrayTexture)a=a.userData.index??0;else if(a instanceof I||null==a)continue;S.setUniformAt(t,s,a)}}}return S}async createInstancedMesh(e,t){const a=nt(t,e=>!dt(e)&&null!=e.geometry),s=await this.assetsService.getAsset(e[0].assetId);await this.applyMaterials(t,_a(e[0].materialAssignments,s.materialAssignments),s),a.updateMatrix();const r=a.geometry.clone(),i=a.material;let n;if(n=new l.InstancedMesh(r,i,e.length),this.configureBatchedInstancedMesh(e,n,a),a.material instanceof g&&n.castShadow&&n.receiveShadow&&Array.isArray(i))for(const e of i);return n}configureBatchedInstancedMesh(e,t,a,s,r){const i=[];a.updateWorldMatrix(!0,!0);for(let n=0;n<e.length;n++){let o=n;t instanceof l.BatchedMesh&&(o=t.addInstance(s)),i.push(o);const c=(new l.Matrix4).compose((new C).fromArray(e[n].position),(new j).setFromEuler((new h).fromArray(e[n].rotation)),(new C).fromArray(e[n].scale)),u=(new y).copy(e[n].parentTransform).multiply(c),d=(new y).copy(u).multiply(a.matrixWorld);t.setMatrixAt(o,d),null==t.userData.hasCollision&&(t.userData.hasCollision=[]);const p=this.assets.get(e[n].assetId);t.userData.hasCollision[o]=!1!==e[n].collisionDetection||!1!==p?.collisionDetection,null!=r&&(null==t.userData.collisionShapes&&(t.userData.collisionShapes=[]),t.userData.collisionShapes[o]=r,null==t.userData.collisionMatrices&&(t.userData.collisionMatrices=[]),t.userData.collisionMatrices[o]=u)}return i}remove(e){if(console.log("Remove scene object",e),"global_fog"==e.type)return void(this.scene.fog=this.originalFog);if("world_env"===e.type)this.resetWorldEnv(),this.worldEnvObj=null;else if("actor"==e.type||"vfx"===e.type){const t=this.materializedActors.get(e.id);null!=t?(t.disposed.next(!0),t.onEndPlay()):console.warn("Failed to remove actor",e)}else if("prefab"===e.type){this.unregisterLivePrefabInstance(e.id);const t=new Set(this.removePrefabEventGraphs(e.id).flatMap(e=>e.actors));this.materializedActors.forEach((a,s)=>{(s===e.id||s.startsWith(e.id+"/"))&&(t.has(a)||(a.disposed.next(!0),a.onEndPlay()),this.materializedActors.delete(s))})}const t=this.sceneObjectMap.get(e.id);t&&this.latticeGeometries.release(t),t?.parent.remove(t),this.sceneObjectMap.delete(e.id),this.components.filter(t=>t.object.userData.src?.id===e.id).forEach(e=>this.components.splice(this.components.indexOf(e,1))),this.landscapeManagers.filter(t=>t.source.id===e.id).forEach(e=>{e.clear(),e.stop(),this.landscapeManagers.splice(this.landscapeManagers.indexOf(e,1))}),this.removed$.next({object:t,source:e})}deleteSceneObject(e){const t=this.sceneObjectMap.get(e.id);if(this.scene.remove(t),"landscape"==e.type){const t=this.landscapeManagers.findIndex(t=>t.source.id===e.id);if(t>-1){const e=this.landscapeManagers.splice(t,1)[0];e.clear(),e.stop()}}}findByAssetId(e){return rt(this.scene,t=>t.userData.src?.assetId==e,e=>null!=e.userData.src)}applyMaterials(e,t,a){return null==t?Promise.resolve([]):Promise.all(t.filter(e=>"null"!==e.materialId).map(t=>this.applyMaterial(e,t,a)))}async applyMaterial(e,t,a){await applyMaterial(e,t,async e=>{const t=await this.getAsset(e);if(null!=t)try{return materialFromAsset(t,this.renderingView,this.assetsService,this.assetManagerService,this.shaders)}catch(e){console.error("Failed to apply material",e)}else console.warn("Missing material with id "+e)},this._originalMaterials,{textureFlipY:getConvertedFbxToGlbAssignedMaterialTextureFlipY(a)})}async resolveMaterialForAssignments(e,t,a){let s=e,r=null,i=null;const n=getConvertedFbxToGlbAssignedMaterialTextureFlipY(a);for(const e of t??[]){if(!Ja(s,e,r,i))continue;const t=await this.getAsset(e.materialId);if(null==t){console.warn("Missing material with id "+e.materialId);continue}let a=await materialFromAsset(t,this.renderingView,this.assetsService,this.assetManagerService,this.shaders,!0);null!=a&&(a=Qa(a,n)),null!=a&&s.id!==a.id&&(r=r??qa(s),i=i??s.name,s=a);break}return s}unapplyMaterials(e){e.traverse(async e=>{if(e instanceof w)if(e.material instanceof Array)for(let t=0;t<e.material.length;t++)e.material[t]=this._originalMaterials.get(e.id+"#"+t)??e.material[t];else e.material=this._originalMaterials.get(e.id)??e.material})}updateActors(e){this.navigationRevision++;const t=new Map(this.actorTypes.map(e=>[e.name,e.type])),a=new Map(e.map(e=>[e.name,e.type])),s=new Set;for(const e of new Set([...t.keys(),...a.keys()]))(t.get(e)??je[e])!==(a.get(e)??je[e])&&s.add(e);this.actorTypes=e,0!==s.size&&rt(this.scene,e=>e.userData.src?.id&&"actor"===e.userData.src.type&&this.materializedActors.has(e.userData.src?.id)&&s.has(e.userData.src.actor.type)).forEach(async e=>{this.remove(e.userData.src),await this.materializeAndInitActor(e.userData.src)})}updateComponents(e){this.componentTypes=e,rt(this.scene,e=>e.userData.src?.id&&"actor"===e.userData.src.type&&this.materializedActors.has(e.userData.src?.id)&&(e.userData.src.actor?.components?.length??0)>0).forEach(async e=>{this.remove(e.userData.src),await this.materializeAndInitActor(e.userData.src)})}updateShaders(e){this.shaders=e;for(const[e,t]of ha.entries())t.userData.customShaderName&&ha.delete(e);pa.clear(),this.landscapeManagers.forEach(t=>t.updateShaders(e)),rt(this.scene,e=>!0).forEach(e=>{e.traverse(async e=>{if(e instanceof w)if(Array.isArray(e.material))for(let t=0;t<e.material.length;t++){const a=e.material[t].userData?.customShaderName;if(null!=a){const a=e.material[t].userData.assetId,s=await this.getAsset(a);null!=s&&this.refreshMaterial(e,e.material[t],s,t)}}else{const t=e.material.userData?.customShaderName;if(null!=t){const t=e.material.userData.assetId,a=await this.getAsset(t);null!=a&&this.refreshMaterial(e,e.material,a)}}})})}async update(e){if("sky"===e.type&&null!=this.sky&&null!=this.sky.parent)return void this.updateSky(e);if("world_env"===e.type&&null!=this.worldEnvObj)return void this.updateWorldEnv(e);const t=this.sceneObjectMap.get(e.id);if(t){let i=!1;if(t.traverseAncestors(e=>{"_hology_transform_group"===e.name&&(i=!0)}),!i){const a=this.findParent(e);null!=a&&a.uuid!=t.uuid?a.attach(t):console.error("Parent is wrong")}if(!("shape_mesh"!==e.type&&"asset_mesh"!==e.type||null==e.renderOrder&&0===t.renderOrder||e.renderOrder===t.renderOrder))return void(t.renderOrder=e.renderOrder??0);if("prefab"!==e.type&&"group"!==e.type){this.unapplyMaterials(t);this.inEditor&&e.hidden&&!1?t.traverse(e=>{e instanceof w&&(e.material.wireframe=!0)}):t.traverse(e=>{e instanceof w&&(e.material.wireframe=!1)})}if("asset_mesh"===e.type&&t.userData.assetId!==e.assetId){this.remove(e);const t=await this.materializeAndInitActor(e);return void this.updated$.next({object:t,source:e})}if("asset_mesh"===e.type&&this.latticeGeometries.apply(t,e.latticeDeformation,JSON.stringify(e.vertexMaterials??[])),"asset_mesh"===e.type){const a=this.assets.get(e.assetId);_a(e.materialAssignments,a.materialAssignments).forEach(e=>this.applyMaterial(t,e,a))}else"shape_mesh"===e.type&&this.applyMaterials(t,e.materialAssignments);if(i||(null!=e.position&&t.position.fromArray(e.position),null!=e.scale&&t.scale.fromArray(e.scale),null!=e.rotation&&t.rotation.fromArray(e.rotation),this.inEditor&&("asset_mesh"===e.type||"shape_mesh"===e.type&&"landscape"!==e.shape)&&e.physics?.type!==Ie.dynamic?Aa(t,!1):this.inEditor&&function(e){let t=!1;if(e.traverse(e=>{Ma.has(e)&&(t=!0)}),!t)return;e.updateWorldMatrix(!0,!0),e.traverse(e=>{Ma.has(e)&&(e.matrixWorldNeedsUpdate=!1)})}(t)),this.applyVertexMaterials(e,t),"light"==e.type){if("point"==e.light.type){const a=t;a.color=new d(e.light.point.color),a.intensity=e.light.point.intensity,a.decay=e.light.point.decay,a.castShadow=e.light.point.castShadow,a.distance=Math.max(e.light.point.distance,0),a.userData.volumetricIntensity=e.light.point.volumetricIntensity}else if("spot"==e.light.type){const a=t;a.color=new d(e.light.spot.color),a.intensity=e.light.spot.intensity,a.decay=e.light.spot.decay,a.angle=e.light.spot.angle,a.penumbra=e.light.spot.penumbra,a.castShadow=e.light.spot.castShadow,a.distance=Math.max(e.light.spot.distance,0),a.userData.volumetricIntensity=e.light.spot.volumetricIntensity,a.map=await this.loadSpotLightMap(e.light.spot.mapTextureId)}else if("directional"===e.light.type)this.applyDirectionalLight(e.light.directional,e);else if("ambient"===e.light.type)this.applyDirectionalAmbientLight(t,e.light.ambient,e);else if("rectArea"===e.light.type){const a=t;a.color=new d(e.light.rectArea.color),a.intensity=e.light.rectArea.intensity,null!=e.scale&&(a.width=e.scale[0],a.height=e.scale[1]),a.children.forEach(e=>{e instanceof Xt&&e.update()})}}else if("landscape"===e.shape){const a=this.landscapeManagers.find(t=>t.source.id===e.id),i=null==a||(s=a.source.landscape.options,r=e.landscape.options,s.density!==r.density||s.sections.x!==r.sections.x||s.sections.y!==r.sections.y);if(this.inEditor&&i){this.remove(e);const t=await this.materializeAndInitActor(e);return void this.updated$.next({object:t,source:e})}this.applyHeightMaps(t,e.landscape.heightMaps),this.inEditor&&this.landscapeManagers.filter(t=>t.source.id===e.id).forEach(t=>{t.updateSource(e),t.queueRefreshScatter(this.renderingView.camera.position,!0,e=>!0)})}else if("global_fog"===e.type){const t=(this.scene.fog instanceof f?"density":"linear")!==e.fog.type;this.scene.fog=Ia(e.fog),t&&(a=this.scene).traverse(e=>{if(e instanceof w){const t=e.material;t instanceof L&&(a.fog instanceof p?(t.uniforms.fogFar.value=a.fog.far,t.uniforms.fogNear.value=a.fog.near):a.fog instanceof f&&(t.uniforms.density={value:a.fog.density}),t.needsUpdate=!0,t.uniformsNeedUpdate=!0)}}),this.fixFogColor()}else if("actor"===e.type){if(this.materializedActors.has(e.id)){const t=this.materializedActors.get(e.id);if(t instanceof Gt){const a=await prepareClassParameters(e.actor.params,null,this.assetsService,this.assetManagerService,this.materializedActors,this.renderingView,[],this.actorProvider,e=>this.prefabInstanceExposedActorMap.get(e)??null,t);return void Object.assign(t,a)}const a=this.editorActorParamSnapshot.get(e.id);if((null==a||a!==JSON.stringify(e.actor))&&!i){if(null!=t&&null!=a&&await this.tryApplyLiveActorParameterUpdate(t,e,a))return void this.updated$.next({object:t.object,source:e});this.remove(e),await this.materializeAndInitActor(e)}}}else if("shape_mesh"===e.type){const a=await this.createMeshByShape(e.shape,t.material,e.shapeParams);t instanceof pt&&(t.geometry=a.geometry,t.collisionShape=a.collisionShape)}if("shape_mesh"===e.type&&"landscape"!==e.shape)da(t,e.castShadow,e.receiveShadow);else if("asset_mesh"===e.type){const a=this.assets.get(e.assetId);if(null==a)return void console.error("Asset not found",e.assetId);const s=e.receiveShadow??!!a.receiveShadow,r=e.castShadow??!!a.castShadow;da(t,r,s)}e.name&&e.name.length>0&&(t.name=e.name),this.updated$.next({object:t,source:e})}else{const t=await this.materializeAndInitActor(e);this.updated$.next({object:t,source:e})}var a,s,r;this.renderingView.invalidateShadows()}async materializeAndInitActor(e,t=this.findParent(e)){const a=await this.materialize(e,t),s=Array.from(this.materializedActors.entries()).filter(([t])=>t===e.id||t.startsWith(e.id+"/"));return await this.initActorsPostInit(s),this.announcePrefabEventGraphs(e.id),a}async tryApplyLiveActorParameterUpdate(e,t,a){let s;try{s=JSON.parse(a)}catch{return!1}const r=await this.tryApplyLiveActorSettingsUpdate(e,s,t.actor);return r&&this.editorActorParamSnapshot.set(t.id,JSON.stringify(t.actor)),r}async tryApplyLiveActorSettingsUpdate(e,t,a){const s=await this.applyLiveActorSettingsUpdate(e,t,a);return s.hasChanges&&!s.rejected}async applyLiveActorSettingsUpdate(e,t,a){const s=t?.components??[],r=a?.components??[];if(t?.type!==a?.type||s.length!==r.length||s.some((e,t)=>e.type!==r[t]?.type))return{applied:t,hasChanges:!0,rejected:!0};let i=!1,n=!1;const o=await this.tryApplyLiveParameterUpdate(e,t?.params??{},a?.params??{});!1===o&&(n=!0),i||(i=!0===o);const l=await this.applyLiveInnerParameterUpdates(e,t?.innerParams??[],a?.innerParams??[]);n||(n=l.rejected),i||(i=l.hasChanges);const c=this.editorAttachedActorComponents.get(e),u=[];for(let e=0;e<r.length;e++){const t=s[e],a=r[e];if(JSON.stringify(t)===JSON.stringify(a)){u.push(a);continue}const o=c?.[e];if(null==o){n=!0,u.push(t);continue}const l=await this.tryApplyLiveParameterUpdate(o,t?.params??{},a?.params??{});!1===l&&(n=!0),i||(i=!0===l);const d=await this.applyLiveInnerParameterUpdates(o,t?.innerParams??[],a?.innerParams??[]);n||(n=d.rejected),i||(i=d.hasChanges),u.push({...a,params:!1===l?t?.params:a?.params,innerParams:d.applied})}return{applied:{...a,params:!1===o?t?.params:a?.params,innerParams:l.applied,components:u},hasChanges:i,rejected:n}}async applyLivePrefabParameterUpdate(e,t){if(!this.assetsService.supportsLivePrefabParameters)return!1;const a=this.livePrefabInstances.get(t.id);if(null==a||0===a.size)return!0;const s=Ba(e.prefab?.objects??[]),r=Ba(t.prefab?.objects??[]);if(s.size!==r.size||[...s.keys()].some(e=>!r.has(e)))return!1;const i=[];await this.applyLiveNestedPrefabOverrideUpdates(e,t,a,i);for(const n of a.values())for(const[a,o]of s){const s=r.get(a),l=n.actorsById.get(a);if(null==s||null==l){i.push(`${n.prefix}/${a}`);continue}const c=n.actorSettingsById.get(a)??Na(o,n.source,e.prefab?.mainActorId===a),u=Na(o,n.source,e.prefab?.mainActorId===a),d=za(u,Na(s,n.source,t.prefab?.mainActorId===a),n.desiredActorSettingsById.get(a)??u);if(n.desiredActorSettingsById.set(a,d),JSON.stringify(c)===JSON.stringify(d))continue;const h=await this.applyLiveActorSettingsUpdate(l,c,d);n.actorSettingsById.set(a,h.applied),h.rejected&&i.push(`${n.prefix}/${a}`)}return i.length>0&&console.warn(`Some live parameters for prefab ${t.name??t.id} were not applied. The running instances were preserved: ${i.join(", ")}`),!0}async applyLiveNestedPrefabOverrideUpdates(e,t,a,s){const r=Va(e.prefab?.objects??[]),i=Va(t.prefab?.objects??[]);for(const[e,t]of r){const r=i.get(e);if(null==r||t.assetId!==r.assetId||JSON.stringify(t.prefab)===JSON.stringify(r.prefab))continue;const n=this.assets.get(r.assetId),o=this.livePrefabInstances.get(r.assetId);if("prefab"!==n?.type||null==n.prefab||null==o)continue;const l=Ba(n.prefab.objects);for(const i of a.values()){const a=`${i.prefix}/${e}`,c=o.get(a);if(null!=c){for(const[e,i]of l){const o=c.actorsById.get(e);if(null==o){s.push(`${a}/${e}`);continue}const l=Na(i,t,n.prefab.mainActorId===e),u=Na(i,r,n.prefab.mainActorId===e),d=c.desiredActorSettingsById.get(e)??l,h=za(l,u,d);c.desiredActorSettingsById.set(e,h);const p=c.actorSettingsById.get(e)??d;if(JSON.stringify(p)!==JSON.stringify(h)){const t=await this.applyLiveActorSettingsUpdate(o,p,h);c.actorSettingsById.set(e,t.applied),t.rejected&&s.push(`${a}/${e}`)}}c.source=r}}}}unregisterLivePrefabInstance(e){if(0!==e.length)for(const[t,a]of this.livePrefabInstances){for(const t of[...a.keys()])(t===e||t.startsWith(e+"/"))&&a.delete(t);0===a.size&&this.livePrefabInstances.delete(t)}}rememberLivePrefabActorSettings(e,t){if(this.assetsService.supportsLivePrefabParameters)for(const a of this.livePrefabInstances.values())for(const s of a.values()){if(!e.startsWith(s.prefix+"/"))continue;const a=e.slice(s.prefix.length+1);s.actorsById.has(a)&&(s.actorSettingsById.set(a,t),s.desiredActorSettingsById.set(a,t))}}async tryApplyLiveParameterUpdate(e,t,a){const s=new Set([...new Set([...Object.keys(t),...Object.keys(a)])].filter(e=>JSON.stringify(t[e])!==JSON.stringify(a[e])));if(0===s.size)return null;const r=await prepareClassParameters(a,null,this.assetsService,this.assetManagerService,this.materializedActors,this.renderingView,this.shaders,this.actorProvider,e=>this.prefabInstanceExposedActorMap.get(e)??null,e);return await e.applySceneParameters(r,s)}async applyLiveInnerParameterUpdates(e,t,a){const s=new Map(t.map(e=>[JSON.stringify(e.path),e])),r=new Map(a.map(e=>[JSON.stringify(e.path),e]));if(s.size!==t.length||r.size!==a.length)return{applied:t,hasChanges:!0,rejected:!0};let i=!1,n=!1;const o=[];for(const t of new Set([...s.keys(),...r.keys()])){const a=s.get(t),l=r.get(t);if(JSON.stringify(a?.params??{})===JSON.stringify(l?.params??{})){null!=l&&o.push(l);continue}const c=l?.path??a?.path,u=this.resolveActorComponent(e,c);if(null==u){n=!0,null!=a&&o.push(a);continue}!0===await this.tryApplyLiveParameterUpdate(u,a?.params??{},l?.params??{})?(null!=l&&o.push(l),i=!0):(n=!0,null!=a&&o.push(a))}return{applied:o,hasChanges:i,rejected:n}}resolveActorComponent(e,t){if(null==t||0===t.length)return null;let a=e;for(const e of t){const t=a[e];if(!(t instanceof Pe))return null;a=t}return a instanceof Pe?a:null}findParent(e){const t=this.dataProvider.getObjects().flatMap(t=>t.id===e.id?null:st(t,t=>t.children?.some(t=>t.id===e.id),()=>!0))[0];return null==t?this.scene:null!=t?rt(this.scene,e=>e.userData?.src?.id===t.id,e=>null!=e.userData?.src)[0]:void 0}fixFogColor(){!0===this.renderingView.options.enableOutlines&&(this.scene.fog.color=new d(this.scene.fog.color))}findMeshWithGeometry(e){let t;return e.traverse(e=>{e instanceof w&&e.geometry&&(t=e)}),t}applyVertexMaterials(e,t){if(null==e.vertexMaterials||0===e.vertexMaterials.length)return;let a=1;for(const t of e.vertexMaterials)a=Math.max(t.w.length,a);const s=tt(e.vertexMaterials,e=>e.m);t.traverse(e=>{if(e instanceof w){if(null==e.geometry)return;if(es(bt(e,0,!1)),a>0){es(bt(e,0,!1))}}});const r=new Set;for(const[e,i]of s.entries()){const s=null!=e?t.getObjectByName(e):this.findMeshWithGeometry(t);let n=!1;if(null==s||null==s.geometry)return void console.warn(`Failed to apply vertex materials on mesh with name "${e}"`);const o=bt(s,0,!0);es(o);for(const e of i)o.setX(e.i,e.w[0]??0),o.setY(e.i,e.w[1]??0),o.setZ(e.i,e.w[2]??0),o.setW(e.i,e.w[3]??0),n=!0;if(a>0){const e=bt(s,4,!0);es(e);for(const t of i)e.setX(t.i,t.w[4]??0),e.setY(t.i,t.w[5]??0),e.setZ(t.i,t.w[6]??0),e.setW(t.i,t.w[7]??0),e.needsUpdate=!0,n=!0}n&&r.add(e)}this.inEditor&&this.landscapeManagers.filter(t=>t.source.id===e.id).forEach(e=>e.queueRefreshScatter(this.renderingView.camera.position,!0,e=>r.has(e.name)))}async materialize(e,t,a=!1,s){const r=this.getNestedActorId(e.id,s);if(null!=this.persistence&&!0!==s?.runtimeSpawn){if(this.isPersistenceRemoved(r))return;if("actor"===e.type){const e=this.persistence.resolve({sceneId:this.persistenceSceneId,path:r});if(null!=e)return void this.materializedActors.set(r,e)}}if(this.idToSceneObject.set(r,e),!this.shouldBeMaterialized(e))return;let i,n;switch(e.type){case"asset_mesh":i=await this.createFromAsset(e),e.latticeDeformation||(i=freezeSkinnedMeshes(i));break;case"shape_mesh":i=await this.createFromShape(e);break;case"light":i=await this.createLight(e);break;case"particles":i=await this.createParticleSystem(e),e.collisionDetection=!1;break;case"global_fog":this.scene.fog=Ia(e.fog),this.fixFogColor(),i=new m;break;case"sky":this.sky=kt(),this.updateSky(e),i=this.sky;break;case"world_env":this.updateWorldEnv(e),i=new m,this.worldEnvObj=i;break;case"actor":({object:i,actor:n}=await this.createFromActor(e,s));break;case"group":case"scatter":i=new m;break;case"prefab":i=await this.createFromPrefab(e,s,t);break;case"vfx":i=await this.createFromVfx(e,s);break;default:console.warn(`Failed to materialize object. Unknown type '${e.type}'. This might be because the hology/core library is not compatible with the editor version or because of an error in the scene data. Scene object: id=${e.id}, name=${e.name}`)}if(null==i)return;e.name&&e.name.length>0&&(i.name=e.name),i.userData.detailCulling=e.detailCulling,this.applyTransform(e,i),a?i.userData._src=e:i.userData.src=e,null!=n&&(i.userData.actor=n,["NavMesh","NavMeshActor"].includes(e.actor?.type)&&(i.userData.navigationBake=this.navigationBakes[r]??this.navigationBakes[r.replace(/^\//,"")],this.inEditor&&(i.userData.navigationBakeSource=async()=>({objects:this.dataProvider.getObjects(),assets:await this.assetsService.getAssets(),loadCollisionShapes:async e=>(await this.assetManagerService.getMesh(e)).scene.collisionShapes??[]})),this.inEditor&&(i.userData.navigationBakeRevision=()=>this.navigationRevision))),this.inEditor,this.inEditor,this.objectMap.set(i.uuid,e),this.sceneObjectMap.set(e.id,i),e.physics?.type!==Ie.dynamic||null==t||this.inEditor?null==t?this.scene.add(i):null==t||"actor"!==e.type||this.inEditor?t?.add(i):(t.add(i),this.scene?.attach(i),console.log(i)):(t.add(i),i.getWorldPosition(Da),i.getWorldQuaternion(Ca),i.getWorldScale(Oa),this.scene.add(i),i.position.copy(Da),i.quaternion.copy(Ca),i.scale.copy(Oa)),null!=e.children&&await Promise.all(e.children?.map(e=>this.materialize(e,i,a,null==s?void 0:structuredClone(s))));const o=("asset_mesh"===e.type||"shape_mesh"===e.type&&"landscape"!==e.shape)&&e.physics?.type!==Ie.dynamic;if(this.inEditor&&o&&!function(e){for(let t=e;null!=t;t=t.parent)if(!0===t.userData.hologyEditorMatrixWorldAutoUpdate)return!0;return!1}(t)?Aa(i,!1):this.inEditor||null!=t||"asset_mesh"!=e.type&&"shape_mesh"!==e.type&&"prefab"!==e.type&&"group"!==e.type||"landscape"===e.shape||null!=e.physics?.type&&e.physics.type==Ie.dynamic||ba(i),null!=this.renderingView)return this.renderingView.invalidateShadows(),i;console.warn("RenderingView not found in materializer")}async handlePaintedScatterSceneMutation(e){const t=this.paintedScatterManager?.referencesSceneObject(e.id)??!1,a=await this.sceneObjectContainsPaintedScatter(e);(t||a)&&await this.refreshPaintedScatterPresence(!1)}async refreshPaintedScatterPresence(e=!1){return await this.sceneContainsPaintedScatter()?(null==this.paintedScatterManager&&(this.paintedScatterManager=new vt(this.scene,this.dataProvider,this.renderingView,this.assetManagerService,this.assetsService)),this.paintedScatterManager.queueRefresh(e),!0):(this.disposePaintedScatterManager(),!1)}disposePaintedScatterManager(){null!=this.paintedScatterManager&&(this.paintedScatterManager.clear(),this.paintedScatterManager.stop(),this.paintedScatterManager=void 0)}async sceneContainsPaintedScatter(){return this.sceneObjectsContainPaintedScatter(this.dataProvider.getObjects())}async sceneObjectsContainPaintedScatter(e,t=[]){for(const a of e??[])if(await this.sceneObjectContainsPaintedScatter(a,t))return!0;return!1}async sceneObjectContainsPaintedScatter(e,t=[]){if("scatter"===e.type&&(e.paintedScatter?.cells?.some(e=>(e.instances?.length??0)>0)||(e.paintedScatter?.palette?.length??0)>0))return!0;if(null!=e.children&&await this.sceneObjectsContainPaintedScatter(e.children,t))return!0;if("prefab"===e.type&&null!=e.assetId){if(t.includes(e.assetId))return!1;const a=this.assets.get(e.assetId)??await this.assetsService.getAsset(e.assetId),s=a?.prefab?.objects;if(null!=s)return this.sceneObjectsContainPaintedScatter(s,[...t,e.assetId])}return!1}async handleSurfaceScatterSceneMutation(e){const t=this.surfaceScatterManager?.referencesSceneObject(e.id)??!1,a=await this.sceneObjectContainsSurfaceScatter(e);(t||a)&&await this.refreshSurfaceScatterPresence(!0)}async refreshSurfaceScatterPresence(e=!1){return await this.sceneContainsSurfaceScatter()?(null==this.surfaceScatterManager&&(this.surfaceScatterManager=new Mt(this.scene,this.dataProvider,this.renderingView,this.assetManagerService,this.assetsService)),this.surfaceScatterManager.queueRefresh(e),!0):(this.disposeSurfaceScatterManager(),!1)}disposeSurfaceScatterManager(){null!=this.surfaceScatterManager&&(this.surfaceScatterManager.clear(),this.surfaceScatterManager.stop(),this.surfaceScatterManager=void 0)}async sceneContainsSurfaceScatter(){return this.sceneObjectsContainSurfaceScatter(this.dataProvider.getObjects())}async sceneObjectsContainSurfaceScatter(e,t=[]){for(const a of e??[])if(await this.sceneObjectContainsSurfaceScatter(a,t))return!0;return!1}async sceneObjectContainsSurfaceScatter(e,t=[]){if("asset_mesh"===e.type&&(e.surfaceScatter?.meshes?.length??0)>0)return!0;if(null!=e.children&&await this.sceneObjectsContainSurfaceScatter(e.children,t))return!0;if("prefab"===e.type&&null!=e.assetId){if(t.includes(e.assetId))return!1;const a=this.assets.get(e.assetId)??await this.assetsService.getAsset(e.assetId),s=a?.prefab?.objects;if(null!=s)return this.sceneObjectsContainSurfaceScatter(s,[...t,e.assetId])}return!1}sceneReferencesPrefabAsset(e){const t=(a=[])=>{for(const s of a??[]){if("prefab"===s.type&&s.assetId===e)return!0;if(t(s.children))return!0}return!1};return t(this.dataProvider.getObjects())}async prefabAssetContainsSurfaceScatter(e){return"prefab"===e.type&&null!=e.prefab?.objects&&this.sceneObjectsContainSurfaceScatter(e.prefab.objects,[e.id])}async prefabAssetContainsPaintedScatter(e){return"prefab"===e.type&&null!=e.prefab?.objects&&this.sceneObjectsContainPaintedScatter(e.prefab.objects,[e.id])}applyTransform(e,t){null!=e.position&&t.position.fromArray(e.position),null!=e.scale&&t.scale.fromArray(e.scale),null!=e.rotation&&t.rotation.fromArray(e.rotation)}updateWorldEnv(e){this.renderingView.configureAmbientOcclusion(e.worldEnv.ao.enabled,e.worldEnv.ao.blendIntensity,e.worldEnv.ao);const t=e.worldEnv.toneMapping;null!=t&&this.renderingView.setBaseToneMapping(t.mapping??0,t.exposure??1);const a=e.worldEnv.environment,s=++this.worldEnvironmentRequest;null!=a&&null!=a.textureId?this.assetManagerService.getTexture(this.assets.get(a.textureId)).then(e=>{s===this.worldEnvironmentRequest&&(null!=e?this.renderingView.setWorldEnvironment({source:e,intensity:a.intensity??1}):console.error("Failed to load environment texture with id "+a.textureId))}):this.renderingView.setWorldEnvironment(null)}resetWorldEnv(){this.worldEnvironmentRequest++,this.renderingView.setWorldEnvironment(null),this.renderingView.configureAmbientOcclusion(!1),this.renderingView.setBaseToneMapping(l.NoToneMapping,1)}async updateSky(e){null!=this.sky&&(null==e?.sky?.materialId&&this.sky.material!==Tt?(this.sky.material=Tt,this.applySkySettings(this.sky.material)):this.sky.material.userData?.assetId!==e.sky.materialId&&this.updateSkyMaterial(e),null!=e.rotation&&this.sky.rotation.fromArray(e.rotation))}async updateSkyMaterial(e){const t=await this.assetsService.getAsset(e.sky.materialId);if(null==t)return void console.warn(`No material asset found for sky with id ${e.sky.materialId}`);const a=await materialFromAsset(t,this.renderingView,this.assetsService,this.assetManagerService,this.shaders,!1);this.applySkySettings(a),null!=this.sky?this.sky.material=a:console.warn("No sky has been created")}applySkySettings(e){e.side=l.BackSide,(e instanceof v||e instanceof l.MeshBasicMaterial||e instanceof l.ShaderMaterial)&&(e.fog=!1),e.depthTest=!0,e.depthWrite=!1,e.transparent=!0}async createComponent(e,t,a,s){const r=new oa[a.path+"/"+a.className],i=t.id+s;r.id=i,r.object=e;for(const e of a.params)null!=e.value&&(r[e.name]=e.value);return this.components.push(r),i}async createFromActor(e,t){const a=this.actorTypes.find(t=>t.name===e.actor?.type)?.type??je[e.actor?.type];if(null==a)return console.warn(`Failed to materialize actor. No actor class found for type '${e.actor?.type}'.`),{object:null,actor:null};this.inEditor&&this.editorActorParamSnapshot.set(e.id,JSON.stringify(e.actor));const s=await this.actorProvider.create(a,(new C).fromArray(e.position),(new h).fromArray(e.rotation),!0),r=this.getNestedActorId(e.id,t);return s.__netSceneId=r,this.applyInitialMaterializedNetRole(s),this.materializedActors.set(r,s),{object:s?.object,actor:s}}applyInitialMaterializedNetRole(e){if(this.inEditor||this.netMode===De.none)return;const t=xe(e.constructor);!0!==t?.replicate?this.netMode===De.client&&(e.netRole=Ce.none):e.netRole=this.netMode===De.client?Ce.simulatedProxy:Ce.authority}getNestedActorId(e,t){return null!=t?t.sceneObjectChain.join("/")+"/"+e:e}async createFromVfx(e,t){const a=await this.assetsService.getAsset(e.assetId);null==a&&console.error("Could not find asset",e);const s=await this.actorProvider.create(ge,(new C).fromArray(e.position),(new h).fromArray(e.rotation),!1);try{await s.fromAsset(a)}catch(e){return console.error("Failed to create VFX asset",e),null}return s.play(),this.materializedActors.set(this.getNestedActorId(e.id,t),s),null!=s&&(s.object.userData.actor=s),s?.object}async createFromShape(e){const t=this.inEditor&&e.hidden;let a;if("landscape"==e.shape)a=this.createLandscape(e),a.traverse(e=>{e instanceof w&&this._originalMaterials.set(e.id,e.material)});else{let s=new v({name:"Default",color:new d("#aaaaaa"),visible:this.inEditor||!e.hidden,wireframe:!!t});!0===e.collider&&(s.opacity=.3,s.color.set(2517460),s.transparent=!0);const r=await this.createMeshByShape(e.shape,s,e.shapeParams);r.castShadow=e.castShadow??!0,r.receiveShadow=e.receiveShadow??!1,!1===e.collisionDetection&&(r.collisionShape=null),r.physics=e.physics,a=r,this._originalMaterials.set(a.id,r.material),a.traverse(e=>{})}return t||(await Promise.all((e.materialAssignments??[]).filter(e=>null!=e.materialId).map(e=>this.applyMaterial(a,e))),this.applyVertexMaterials(e,a)),a}createLandscape(e){const t=e.landscape?.options;if(null==t)return console.error(`No landscape options exist on scene object ${e.id} ${e.name}`),new m;const a=mt(e.landscape.options);this.applyHeightMaps(a,e.landscape.heightMaps,!0);const s=new ft(e,this.renderingView,a,this.assetManagerService,this.assetsService,this.shaders,async t=>{await Promise.all((e.materialAssignments??[]).filter(e=>null!=e.materialId).map(e=>this.applyMaterial(t,e))),this.inEditor||this.applyVertexMaterials({...e,vertexMaterials:e.vertexMaterials?.filter(e=>e.m===t.name)},t)},!this.inEditor&&!1!==e.landscape.staticDrawSets);return this.landscapeManagers.push(s),s.refreshGeometry(),a}applyHeightMaps(e,t,a=!1){const s=new gt(e.sections);for(const e of t??[]){const t=s.find(e.x,e.y);if(!t)return;const a=t.geometry.getAttribute("position");for(const t of e.points)a.setY(t.i,t.y);a.needsUpdate=!0}const r=e.sections;r.forEach(e=>{e.geometry.computeBoundsTree(),e.geometry.computeVertexNormals()}),this.inEditor&&!a||setTimeout(()=>yt(r),50)}async createMeshByShape(e,t,a={}){if("landscape"!==e&&Ot.includes(e)){const s=await prepareShapeParameters(a??{}),r=e+JSON.stringify(a);if(!this.geometryCache.has(r)){const t=Ct[e].geometry(s);(function(e){return null!=e.index&&e.hasAttribute("position")&&e.hasAttribute("normal")&&e.hasAttribute("uv")})(t)&&t.computeTangents(),this.geometryCache.set(r,t)}this.collisionShapeCache.has(r)||this.collisionShapeCache.set(r,Ct[e].collision(s));return new pt(this.geometryCache.get(r),t,this.collisionShapeCache.get(r))}if(this.inEditor)throw new Error(`Unsupported shape '${e}'`);console.warn(`Failed to create shape. Unsupported shape '${e}'. This might be because the hology/core library is not compatible with the editor version.`)}async decodeModelImage(e){const t=e.image;if("function"!=typeof createImageBitmap||"undefined"==typeof HTMLImageElement||!(t instanceof HTMLImageElement))return;const a=e.source;let s=this.modelImageBitmaps.get(a);if(null==s){const e=()=>createImageBitmap(t,{imageOrientation:"none",premultiplyAlpha:"none",colorSpaceConversion:"none"}),r=t.currentSrc||t.src,i=/^(blob:|data:)/.test(r)?this.assetManagerService.decodeImageBitmap(r):void 0;s=(i?.catch(t=>(console.warn("Worker model image decode failed; decoding locally",t),e()))??e()).then(e=>{a.data===t?a.data=e:e.close()}).catch(e=>{console.warn("Could not decode model image before upload",e)}),this.modelImageBitmaps.set(a,s)}await s,a.data!==t&&(e.needsUpdate=!0)}async createFromAsset(e,t){const a=this.assets.get(e.assetId)??await this.assetsService.getAsset(e.assetId);if(null==a)return void console.warn(`Can not find asset with id ${e.assetId} and name ${e.name}`);let{scene:s}=await this.assetManagerService.getMesh(a,{mergeGeomtries:!0});if(e.latticeDeformation&&(s=freezeSkinnedMeshes(s,!0),this.latticeGeometries.apply(s,e.latticeDeformation,JSON.stringify(e.vertexMaterials??[]))),!1!==t?.assignMaterials)try{await Promise.all(_a(e.materialAssignments,a.materialAssignments).map(e=>this.applyMaterial(s,e,a)))}catch(t){console.error("Failed to apply material"+t,e)}const r=e.receiveShadow??!!a.receiveShadow,i=e.castShadow??!!a.castShadow;if(s.receiveShadow=r,da(s,i,r),!1!==e.collisionDetection&&!1!==a.collisionDetection||(s.collisionShapes=[]),null!=e.physics&&!0!==this.inEditor&&(s.physics=e.physics),this.applyVertexMaterials(e,s),s.traverse(e=>{e instanceof w&&"computeBoundsTree"in e.geometry&&null==e.geometry.boundsTree&&e.geometry.computeBoundsTree()}),s.userData.assetId=e.assetId,s.traverse(e=>{if(e instanceof w)for(const t of at(e.material))Be(t,!1)}),"webgpu"===this.renderingView.requestedBackend){await this.renderingView.initializeBackend();const e=new Set;s.traverse(t=>{if(t instanceof w)for(const a of at(t.material))if(a instanceof l.ShaderMaterial)for(const t of Object.values(a.uniforms)){const a=t.value;a instanceof I&&null!=a.image&&e.add(a)}else for(const t of Object.values(a))t instanceof I&&null!=t.image&&e.add(t)}),await Promise.all(Array.from(e,async e=>{await this.decodeModelImage(e),this.renderingView.initTexture(e)}))}return s}async createFromPrefab(e,t,a){const s=await this.assetsService.getAsset(e.assetId);if(null==s)return void console.warn(`Can not find asset with id ${e.assetId} and name ${e.name}`);null==t&&(t={sceneObjectChain:[]}),t.sceneObjectChain.push(e.id);const{object:r}=await this.createFromPrefabAsset(s,t,a,e);return t.sceneObjectChain.pop(),r}async createFromPrefabAsset(e,t,a,s,r=!0){this.assets.set(e.id,e);const i=new m;null!=s&&this.applyTransform(s,i),null!=a&&a.add(i),await Promise.all(e.prefab.objects.filter(e=>"global_fog"!==e.type&&"world_env"!==e.type).map(e=>this.materialize(e,i,!0,structuredClone(t))));const n=t.sceneObjectChain.join("/"),o=Array.from(this.materializedActors.entries()).filter(([e,t])=>e.startsWith(n+"/")&&!t.__isInitialised);o.forEach(e=>{});let l=null;if(null!=e.prefab?.mainActorId){const a=t.sceneObjectChain.join("/")+"/"+e.prefab.mainActorId;l=this.materializedActors.get(this.persistenceActorPath(a))??null}r||await this.initActorsPostInit(o);const c=Array.from(this.materializedActors.entries()).filter(([e])=>e.startsWith(n+"/")),u=c.map(([,e])=>e),d=new Map(c.map(([e,t])=>[e.slice(n.length+1),t]));if(this.assetsService.supportsLivePrefabParameters){let t=this.livePrefabInstances.get(e.id);null==t&&(t=new Map,this.livePrefabInstances.set(e.id,t));const a=new Map([...Ba(e.prefab?.objects??[])].map(([t,a])=>[t,Na(a,s,e.prefab?.mainActorId===t)]));t.set(n,{prefix:n,source:s,actorsById:d,actorSettingsById:a,desiredActorSettingsById:new Map(a)})}if(!this.inEditor&&!0!==t.runtimeSpawn&&ia(e.prefab?.eventGraph)&&this.materializedPrefabEventGraphs.set(n,{id:n,graph:e.prefab.eventGraph,object:i,actors:u,actorsById:d,mainActor:l}),null!=e.prefab?.mainActorId&&null!=s){const a=t.sceneObjectChain.join("/"),s=a+"/"+e.prefab.mainActorId;this.prefabInstanceExposedActorMap.set(a,s)}return{object:i,actors:u,actorsById:d,mainActor:l,instanceId:n}}async createParticleSystem(e){await this.assetsService.getAsset(e.assetId);return new A}async createLight(e){if("point"===e.light.type){const t=new x(e.light.point.color,e.light.point.intensity,Math.max(e.light.point.distance,0),e.light.point.decay);if(t.castShadow=e.light.point.castShadow??!0,t.userData.volumetricIntensity=e.light.point.volumetricIntensity,this.inEditor){const e=(new l.TextureLoader).load("assets/light-bulb-icon.webp"),a=new l.SpriteMaterial({map:e,alphaTest:.5}),s=new Lt(a);s.scale.multiplyScalar(.6),t.add(s)}return t}if("spot"===e.light.type){const t=new l.SpotLight(e.light.spot.color,e.light.spot.intensity,Math.max(e.light.spot.distance,0),e.light.spot.angle,e.light.spot.penumbra,e.light.spot.decay);if(t.castShadow=e.light.spot.castShadow??!0,t.userData.volumetricIntensity=e.light.spot.volumetricIntensity,t.map=await this.loadSpotLightMap(e.light.spot.mapTextureId),t.target=new A,t.target.position.set(0,-1,0),t.add(t.target),this.inEditor){const e=(new l.TextureLoader).load("assets/light-bulb-icon.webp"),a=new l.SpriteMaterial({map:e,alphaTest:.5}),s=new Lt(a);s.scale.multiplyScalar(.6),t.add(s),t.add(new l.SpotLightHelper(t))}return t}if("rectArea"===e.light.type){const t=new l.RectAreaLight(e.light.rectArea.color,e.light.rectArea.intensity,e.scale?e.scale[0]:1,e.scale?e.scale[1]:1);if(this.inEditor){const e=(new l.TextureLoader).load("assets/light-bulb-icon.webp"),a=new l.SpriteMaterial({map:e,alphaTest:.5}),s=new Lt(a);s.scale.multiplyScalar(.6),t.add(s);const r=new Xt(t);t.add(r)}return t}return"directional"===e.light.type?(this.applyDirectionalLight(e.light.directional,e),new m):"ambient"===e.light.type?(this.applyDirectionalAmbientLight(null,e.light.ambient,e),new m):void 0}async loadSpotLightMap(e){if(null==e)return null;const t=this.assets.get(e);return null==t||"texture"!==t.type?null:await this.assetManagerService.getTexture(t)}applyDirectionalAmbientLight(e,t,a){const s=this.scene.children.find(e=>e.name===Et);null!=s?(s.intensity=t.intensity,s.color.set(t.color),s.groundColor.set(t.color),s.userData.src=a,s.userData.volumetricIntensity=t.volumetricIntensity):console.warn("Couldn't find ambient light")}applyDirectionalLight(e,t){this.renderingView.csm.lightIntensity=e.intensity;for(const a of this.renderingView.csm.lights)a.intensity=e.intensity,a.color.set(e.color),a.castShadow=e.castShadow,a.userData.src=t,a.userData.volumetricIntensity=e.volumetricIntensity;this.renderingView.csm.lightDirection.fromArray(e.direction).normalize()}dispose(e){for(const e of this.landscapeManagers)e.stop();if(this.landscapeManagers.length=0,this.latticeGeometries.dispose(),this.editorStaticDisposed=!0,this.disposeEditorStaticDrawSet(),this.editorStaticEditingObjects.clear(),this.editorStaticSelectedObjects.clear(),this.editorStaticObjectsToRebuild.clear(),this.editorStaticDrawSetUpdated$.complete(),this.experimentalStaticDrawSetDisposer?.(),this.experimentalStaticDrawSetDisposer=void 0,this.removePrefabEventGraphs(),this.livePrefabInstances.clear(),this.updateSubscription.unsubscribe(),this.createAssetSubscription.unsubscribe(),this.disposePaintedScatterManager(),this.disposeSurfaceScatterManager(),this.sceneSettingsActive){this.worldEnvironmentRequest++,this.renderingView.setWorldEnvironment(null),this.renderingView.configureAmbientOcclusion(!1),this.renderingView.setBaseToneMapping(l.NoToneMapping,1),this.scene.fog=this.originalFog;const e=this.renderingView.csm,t=this.originalGlobalLight;if(null!=e&&null!=t){e.lightDirection.copy(t.direction),e.lightIntensity=t.intensity;for(let a=0;a<e.lights.length&&a<t.lights.length;a++){const s=e.lights[a],r=t.lights[a];s.intensity=r.intensity,s.color.copy(r.color),s.castShadow=r.castShadow,s.userData.src=r.src,s.userData.volumetricIntensity=r.volumetricIntensity}}this.sceneSettingsActive=!1}this.materializedActors.forEach(t=>{e?.has(t)||t.disposed.next(!0)}),this.materializedActors.clear()}announcePrefabEventGraphs(e){for(const[t,a]of this.materializedPrefabEventGraphs)(null==e||t===e||t.startsWith(e+"/"))&&(this.announcedPrefabEventGraphs.has(t)||(this.announcedPrefabEventGraphs.add(t),this.prefabEventGraphAdded$.next(a)))}removePrefabEventGraphs(e){const t=[];for(const[a,s]of[...this.materializedPrefabEventGraphs])(null==e||a===e||a.startsWith(e+"/"))&&(t.push(s),this.prefabEventGraphRemoved$.next(s),this.materializedPrefabEventGraphs.delete(a),this.announcedPrefabEventGraphs.delete(a));return t}};ua=e([me(),t("design:paramtypes",[P,Object,ut,ct,ke,Array,Array,Object,Array])],ua);export{ua as SceneMaterializer};function da(e,t,a){e.castShadow=t,e.receiveShadow=a,e.traverse(e=>{e.castShadow=t,e.receiveShadow=a})}const ha=new Map,pa=new Map,fa=new S({color:16711935}),ma=new Map;export async function materialFromAsset(e,t,a,s,r,i=!0){if(null==e||null==e.material)return console.error("Asset or asset material is null",e),fa;const n=JSON.stringify(e.material)+t?._id,o=i&&!("shaderGraph"===e.material.type&&"asset"===e.material.shaderGraph?.source);if(o&&ha.has(n))return ha.get(n);if(o&&pa.has(n))return await pa.get(n);const l=_materialFromAsset(n,e,t,a,s,r,o);return o?pa.set(n,l).get(n):l}export async function _materialFromAsset(e,t,a,s,r,n,o=!0){const c={opacity:t.material.params?.opacity??1,map:null,emissive:t.material.params?.emissive??null,metalness:t.material.params?.metalness??0,flatShading:t.material.params?.flatShading??!1,color:new d(t.material.params?.color),transparent:null!=t.material.params?.opacity&&t.material.params?.opacity<1},u={};if(null!=t.material.params?.map){const e=t.material.params.map,a=await s.getAsset(e);null!=a&&(c.map=await r.getTexture(a))}let h,p,f;switch(t.material.type){case"phong":h=new b({...c,...u});break;case"water":h=At(c,a);break;case"grassFoliage":h=wt({color:c.color,map:c.map},a);break;case"grass":h=St({...c,colorTwo:new d(t.material.params.colorTwo),colorThree:new d(t.material.params.colorThree)},a);break;case"shaderGraph":{const e=await async function(e,t){const a=e.material?.shaderGraph;if("local"===a?.source)return a.graph;if("asset"===a?.source){const e=await t.getAsset(a.assetId);return e?.shaderGraph??null}return e.shaderGraph??null}(t,s);if(null==e){console.warn("Missing shader graph for material "+t.name),h=fa;break}"surface"===e.target&&null!=e.materialOptions?.side&&(p=ra(e.materialOptions.side)),"decal"===e.target?f=!1:null!=e.materialOptions?.transparent&&(f=e.materialOptions.transparent);try{const i=await prepareShaderGraphParameters(t.material?.shaderParams??{},e,s,r,a,n),o=t.shaderGraphPreviewNodeId,l=t.trailBillboard;h=sa(e,{parameters:i,previewNodeId:o,trailBillboard:l,alphaTest:t.material.alphaTest}),h.userData.customShaderName="asset"===t.material.shaderGraph?.source?`shaderGraph:${t.material.shaderGraph.assetId}`:`shaderGraph:${t.id}`}catch(e){console.warn("Shader graph runtime error: "+e,e),h=fa}break}case"standard":case"unlit":case"toon":case"layered":case"lambert":case"shader":case"landscape":case"landscape-composite":case"decal-unlit":case"decal-standard":case"sprite":const e={standard:la?Ue:We,lambert:Ue,unlit:_e,toon:qt,layered:Wt,landscape:Re,"landscape-composite":Fe,"decal-unlit":Vt,"decal-standard":Nt,sprite:i}[t.material.type]??n.find(e=>e.name==t.material.shader)?.type;if(e){try{let i=new e;const o=await prepareClassParameters(t.material?.shaderParams??{},e,s,r,null,a,n,void 0,void 0,i);Object.assign(i,o),i.alphaTest=t.material.alphaTest??i.alphaTest,h=i.build()}catch(e){console.log("Shader runtime error: "+e,e),ma.has(t.material.shader)||ma.set(t.material.shader,fa.clone()),h=ma.get(t.material.shader)}h.userData.customShaderName=t.material.shader}else console.warn("Missing shader implementation with name "+t.material.shader),h=fa;break;default:throw new Error("Unsupported material type "+t.material.type)}if(a?.csm.setupMaterial(h),h.side=p??t.material.side??h.side??l.FrontSide,h.transparent=(f??t.material.transparent??c.transparent??!1)||h.transparent,h.alphaTest=t.material.alphaTest??h.alphaTest??0,h.userData.receiveDecals=t.material.receiveDecals??!0,null!=t.material.blending&&(h.blending=Oe[t.material.blending]??l.NormalBlending),!0===t.material.transparent&&(h.depthWrite=!1),t.material.bloom&&(h.userData.hasBloom=!0),t.material.reflective&&(h.userData.reflective=!0),!0===t.material.outlines&&(h.userData.outlineParameters={},null!=t.material.outlineParams&&(null!=t.material.outlineParams.color&&(h.userData.outlineParameters.color=new d(t.material.outlineParams.color).toArray()),null!=t.material.outlineParams.thickness&&(h.userData.outlineParameters.thickness=t.material.outlineParams.thickness),null!=t.material.outlineParams.opacity&&(h.userData.outlineParameters.alpha=t.material.outlineParams.opacity),null!=t.material.outlineParams.colorMode&&(h.userData.outlineParameters.colorMode=t.material.outlineParams.colorMode),null!=t.material.outlineParams.darkening&&(h.userData.outlineParameters.darkening=t.material.outlineParams.darkening))),null!=t.material.surfaceAssetId&&""!==t.material.surfaceAssetId){const e=await materializeDataAssetRef(t.material.surfaceAssetId,s,r,void 0,a,n);null!=e&&(h.userData.surface=e.value)}return h.userData.assetId=t.id,o&&null!=a&&ha.set(e,h),o&&pa.delete(e),h}export function prepareCustomParamsFromShaderGraph(e,t={}){return Object.fromEntries((e.parameters??[]).map(e=>{const a=function(e){switch(e){case"float":return xt.FloatNode;case"boolean":return xt.BooleanNode;case"texture":return xt.Sampler2DNode;case"vec2":return xt.Vec2Node;case"vec3":return xt.Vec3Node;case"vec4":return xt.Vec4Node;case"color":return xt.RgbNode}}(e.type),s=t[e.name],r=s?.override??null!=s,i=void 0!==e.defaultValue?e.defaultValue:customParameterDefaultValueByType.get(a),n=!1===r?Wa(i):s?.value??Wa(i);return[e.name,{type:a,value:n,override:r}]}))}export async function prepareShaderGraphParameters(e,t,a,s,r,i){const n={},o=prepareCustomParamsFromShaderGraph(t,e),l=Object.entries(o),c=await Promise.all(l.map(([e,t])=>ya(e,t,a,s,null,r,i)));for(let e=0;e<l.length;e++){const[t]=l[e],a=c[e];null!=a&&(n[t]=a)}return n}export async function prepareClassParameters(e,t,a,s,r,i,n,o,l,c){const u={},{params:d,skipped:h}=Pt(e,{parameterType:t,parameterTarget:c,extractPropertyParameters:Ge,toSerializedParamType:toSerializedParamType});for(const e of h)console.warn(`Skipping stored parameter "${e.key}" because it could not be converted from ${xt[e.sourceType]} to ${xt[e.targetType]}`);for(const[e,t]of Object.entries(d)){if(!1===t.override)continue;const c=await ya(e,t,a,s,r,i,n,o,void 0,void 0,l);null!=c&&(u[e]=c)}return u}export async function prepareShapeParameters(e,t,a){const s={};for(const[r,i]of Object.entries(e)){const e=await ya(r,i,t,a,null,void 0,void 0,void 0,void 0,void 0);null!=e&&(s[r]=e)}return s}const ga=new Map;async function ya(e,t,a,s,r,i,n,o,l=t.value,c=t.type,u,p=(t.type===xt.Struct?t.struct:void 0)){if(null==t||null==l||""===l)return null;switch(c){case xt.Array:if(Array.isArray(l)&&"element"in t)return await Promise.all(l.map(l=>ya(e,t,a,s,r,i,n,o,l,t.element,u,t.elementStruct)));break;case xt.Number:case xt.FloatNode:let f;if("string"==typeof l?f=parseFloat(l):"number"==typeof l&&(f=l),c===xt.FloatNode){if("object"==typeof l&&"a"in l&&"b"in l){const e=l;if(null==e.a)return null;const t="string"==typeof e.a?parseFloat(e.a):e.a;if(null==e.b)return t;const a="string"==typeof e.b?parseFloat(e.b):e.b,s=function(e){let t=ga.get(e);return null==t&&(t=Ve(Bt.decode(e)),ga.set(e,t)),t}(e.easing),r=s.sample(Ne(ze.energy));return G(F(t),F(a),r)}return new te(Xe(e),f,void 0,!1)}return f;case xt.Texture:let m=await s.getTexture(await a.getAsset(l));return"envmap"===e.toLowerCase()&&null!=i&&(m=i.getEnvTexture(m)),m;case xt.Sampler2DNode:const g=await a.getAsset(l);if(null!=g?.texture?.textureArrayFileKey){const{texture:t,layerIndex:a}=await s.getTextureArray(g);if(t&&null!=a)return new ae(null,t,new te(Xe(e)+"_i",a,void 0,!1))}const y=await s.getTexture(g);return y?X(y):null;case xt.Boolean:return l;case xt.BooleanNode:return new ee(Xe(e),l,void 0,!1);case xt.Vector2:case xt.Vec2Node:if("object"==typeof l){const t=l instanceof Array?(new D).fromArray(l):new D(l.x,l.y);return c===xt.Vec2Node?new se(Xe(e),t,void 0,!1):t}return null;case xt.Vector3:case xt.Vec3Node:if("object"==typeof l){const t=l instanceof Array?(new C).fromArray(l):new C(l.x,l.y,l.z);return c===xt.Vec3Node?new re(Xe(e),t,void 0,!1):t}return null;case xt.Vector4:case xt.Vec4Node:if("object"==typeof l){const t=l instanceof Array?(new O).fromArray(l):new O(l.x,l.y,l.z,l.w);return c===xt.Vec4Node?new ie(Xe(e),t,void 0,!1):t}return null;case xt.Color:case xt.RgbNode:const w=new d(l);return c===xt.RgbNode?new re(Xe(e),new C(w.r,w.g,w.b),void 0,!1).rgb:w;case xt.String:return l;case xt.Scene:return"string"==typeof l?new ve(l):"object"==typeof l&&null!=l&&"string"==typeof l.id?new ve(l.id,"string"==typeof l.name?l.name:void 0):null;case xt.ModelRef:return"string"==typeof l?new Me(l):null;case xt.BaseActor:const S=l;if(null==r&&console.warn("Class parameters can not be prepared as actors are not passed in"),null==S)return null;if("object"==typeof S&&null!=S.type&&null!=S.id){if("actor"===S.type)return r?.get(S.id)??null;if("prefab"===S.type){const e=u?u(S.id):null;if(null!=e)return r?.get(e)??null;const t=[];for(const[e,a]of r?.entries()??[])e.startsWith(S.id+"/")&&t.push(a);return 1===t.length?t[0]:null}}if("string"==typeof S){const e=r?.get(S);if(null!=e)return e;const t=u?u(S):null;if(null!=t)return r?.get(t)??null;const a=[];for(const[e,t]of r?.entries()??[])e.startsWith(S+"/")&&a.push(t);return 1===a.length?a[0]:null}return null;case xt.Euler:const b=l;return(new h).fromArray(b);case xt.Object3D:{const e=await a.getAsset(l),t=(await s.getMesh(e,{applyMaterials:!0,rescale:!0,mergeGeomtries:!0})).scene;return t.userData.vfxIncludeRootTransform=!0,t}case xt.Material:{if(null==l)return null;const e=await a.getAsset(l);if(null==e)return console.warn("Material asset not found for material parameter",l),null;if("shaderGraph"===e.type&&null!=e.shaderGraph){const t=`shaderGraphParameter:${e.id}:${JSON.stringify(e.shaderGraph)}:${i?._id??"none"}`,r=ha.get(t);if(null!=r)return r;const o=await prepareShaderGraphParameters({},e.shaderGraph,a,s,i,n),l=sa(e.shaderGraph,{parameters:o});return l.userData.assetId=e.id,l.userData.assetName=e.name,ha.set(t,l),l}return null==e.material?(console.warn("Using a non-material asset for material parameter"),null):await materialFromAsset(e,i,a,s,n)}case xt.AudioBuffer:return await s.getAudio(await a.getAsset(l));case xt.VisualEffect:const v=await a.getAsset(l);if(null==o){console.error("Can not create instance of visual effect because missing actor provider");break}if("vfx"in v)return new ye(o,v);console.error("Using a non-vfx asset for visual effect parameter");break;case xt.Prefab:{const e=await a.getAsset(l);return null==e?(console.error("Using a non-prefab asset for prefab parameter",l),null):new we(e)}case xt.PrefabActor:{const e=await a.getAsset(l);return null==e?(console.error("Using a non-prefab asset for prefab parameter",l),null):new Se(new we(e))}case xt.DataAsset:return materializeDataAssetRef(l,a,s,r,i,n,o,u);case xt.Sequence:{if("string"!=typeof l)return console.warn("Invalid sequence parameter value",l),null;const e=await a.getAsset(l);if("sequence"===e?.type&&"sequence"in e)return new ta(e.sequence);console.error("Using a non-sequence asset for sequence parameter");break}case xt.SequenceData:return ea(l)?l:(console.warn("Invalid inline sequence data parameter value",l),null);case xt.Struct:return async function(e,t,a,s,r,i,n,o,l){const c=wa(e),u=c?.struct??t;if(null==u)return console.warn("Missing parameter definition id for struct parameter"),null;const d=Je(u);if(null==d)return console.warn(`Unknown parameter definition "${u}"`),null;if(Qe(u))return console.warn(`Can not instantiate abstract parameter definition "${u}"`),null;if(null!=t&&u!==t&&!Ze(u,t))return console.warn(`Parameter definition "${u}" is not assignable to "${t}"`),null;let h;try{h=new d}catch(e){return console.warn(`Failed to instantiate parameter definition "${u}"`,e),null}const p=function(e){const t=wa(e);if(null!=t)return t.value;if(Sa(e))return e;if(null!=e&&"object"==typeof e&&Sa(e.params))return e.params;return{}}(c?.value??e),f=await prepareClassParameters(p,null,a,s,r,i,n,o,l,h);return Object.assign(h,f),h}(l,p,a,s,r,i,n,o,u);case xt.Curve:return Bt.decode(l);case xt.ColorLayer:case xt.MaskLayer:if(_t(l)){const e=await $t.decode(l,async e=>await s.getTexture(await a.getAsset(e))),t=await prepareClassParameters(l.params,null,a,s,void 0,void 0,void 0,void 0,void 0,e);return Object.assign(e,t),e}return console.warn("Expecting color layer but got",l),null;case xt.AnimationClip:{const e="string"==typeof l?l:"object"==typeof l&&null!=l?l.assetId:null;if(null==e)return console.warn("Invalid animation clip asset id value",l),null;return await s.getAnimationClip(await a.getAsset(e))}}return null}export async function materializeDataAssetRef(e,t,a,s,r,i,o,l){const c="string"==typeof e?e:null!=e&&"object"==typeof e?e.assetId??e.id:null;if(null==c||""===c)return null;const u=await t.getAsset(c);if(null==u)return console.warn(`Data asset "${c}" was not found`),null;if("data"!==u.type||null==u.dataAsset)return console.warn("Using a non-data asset for data asset parameter",c),null;const d=u.dataAsset.definition;if(null==d||""===d)return console.warn(`Missing data asset definition id for asset "${u.id}"`),null;if(Ye(d))return console.warn(`Can not instantiate abstract data asset definition "${d}"`),null;const h=Le(d);if(null==h)return console.warn(`Unknown data asset definition "${d}"`),null;let p;try{p=new h}catch(e){return console.warn(`Failed to instantiate data asset definition "${d}"`,e),null}const f=u.dataAsset.params??{};if("object"!=typeof f||Array.isArray(f))return console.warn(`Invalid data asset params for asset "${u.id}"`),null;try{const e=await prepareClassParameters(f,null,t,a,s,r,i,o,l,p);Object.assign(p,e)}catch(e){return console.warn(`Failed to materialize data asset "${u.id}"`,e),null}const m=t.supportsLiveDataAssets?new n(e=>{let n=0;const c=t.onUpdate.subscribe(c=>{if(c.id!==u.id||"data"!==c.type)return;const d=++n;materializeDataAssetRef(u.id,t,a,s,r,i,o,l).then(t=>{e.closed||d!==n||null==t||e.next(t)}).catch(e=>console.warn(`Failed to reload data asset "${u.id}"`,e))});return()=>c.unsubscribe()}):void 0;return new be(u,p,m)}function wa(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&"string"==typeof e.struct&&Sa(e.value)?e:null}function Sa(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&Object.values(e).every(e=>null!=e&&"object"==typeof e&&"type"in e)}function ba(e){e.updateWorldMatrix(!0,!0),e.updateMatrix(),e.traverse(e=>{e.matrixAutoUpdate=!1,e.matrixWorldNeedsUpdate=!1});const t=e.updateMatrixWorld;e.updateMatrixWorld=function(){t.apply(e),e.updateMatrixWorld=function(){}}}function va(){}const Ma=new WeakMap;function Aa(e,t){if(t)return e.userData.hologyEditorMatrixWorldAutoUpdate=!0,void e.traverse(e=>{const t=Ma.get(e);if(null!=t){e.updateMatrixWorld=t.updateMatrixWorld;for(const[e,a]of t.matrixAutoUpdate)e.matrixAutoUpdate=a}});const a=!0===e.userData.hologyEditorMatrixWorldAutoUpdate,s=[];e.traverse(e=>{Ma.has(e)&&s.push(e)}),0!==s.length||a||s.push(e);for(const e of s)xa(e);delete e.userData.hologyEditorMatrixWorldAutoUpdate}function xa(e){const t=Ma.get(e);if(e.updateMatrix(),e.updateWorldMatrix(!0,!0),null==t){const t=new Map;e.traverse(e=>{t.set(e,e.matrixAutoUpdate)}),Ma.set(e,{updateMatrixWorld:e.updateMatrixWorld,matrixAutoUpdate:t})}e.traverse(e=>{e.matrixAutoUpdate=!1,e.matrixWorldNeedsUpdate=!1}),e.updateMatrixWorld=va}function ja(e,t=!1){return Array.isArray(e)?e.every(e=>ja(e,t)):t||!e.transparent&&!Pa(e)}function Pa(e){return e instanceof L&&(null!=e.uniforms[na]||null!=e.uniforms.hology_scene_map)}function Ia(e){return"linear"===e.type?new p(new d(e.color),e.near??100,e.far??1e3):"density"===e.type?new f(e.color,e.density):void console.warn("Invalid fog type",e)}const Da=new C,Ca=new j,Oa=new C;new v({color:4229780});async function Ea(e,t,a,s){null==s&&(s=(new y).identity());const r=s.clone().multiply(ka(e,new l.Matrix4));if(null!=e.children&&e.children.length>0)for(let a=e.children.length-1;a>=0;a--)await Ea(e.children[a],t,e,r);await t(e,a,s)}function ka(e,t){return null==e.position||null==e.rotation||null==e.scale?t.identity():t.compose((new C).fromArray(e.position),(new j).setFromEuler((new h).fromArray(e.rotation)),(new C).fromArray(e.scale))}export function toSerializedParamType(e){if(null==e)return;const t=e.constructor.prototype;return t instanceof Number||e===Number?xt.Number:t instanceof W||"function"==typeof e.prototype.isFloat?xt.FloatNode:t instanceof I||e===I||e.isTexture?xt.Texture:t instanceof $e||e===$e||e===Z||"function"==typeof e.prototype?.isSampler2D||!0===e.prototype?.isSampler2D?xt.Sampler2DNode:t instanceof Boolean||e===Boolean?xt.Boolean:t instanceof $?xt.BooleanNode:t instanceof d||e==d?xt.Color:t instanceof Y||"function"==typeof e.prototype.isRgb?xt.RgbNode:t instanceof D||e==D?xt.Vector2:t instanceof ue||"function"==typeof e.prototype.isVec2?xt.Vec2Node:t instanceof C||e==C?xt.Vector3:t instanceof he||"function"==typeof e.prototype.isVec3?xt.Vec3Node:t instanceof O||e==O?xt.Vector4:t instanceof fe||"function"==typeof e.prototype.isVec4?xt.Vec4Node:t instanceof String||e===String?xt.String:t instanceof ve||e===ve?xt.Scene:t instanceof Me||e===Me?xt.ModelRef:t instanceof Ae||e==Ae||e.prototype instanceof Ae||e.prototype==Ae?xt.BaseActor:t instanceof h||e==h?xt.Euler:t instanceof A||e==A?xt.Object3D:t instanceof g||e==g?xt.Material:t instanceof AudioBuffer||e==AudioBuffer?xt.AudioBuffer:t instanceof ye||e==ye?xt.VisualEffect:t instanceof we||e==we?xt.Prefab:t instanceof Se||e==Se?xt.PrefabActor:t instanceof be||e==be?xt.DataAsset:t instanceof Bt||e==Bt?xt.Curve:t instanceof $t||e==$t?xt.ColorLayer:t instanceof Rt||e==Rt?xt.MaskLayer:t instanceof l.AnimationClip||e==l.AnimationClip?xt.AnimationClip:t instanceof ta||e==ta?xt.Sequence:"SequenceData"===e.name||e.prototype&&"tracks"in e.prototype?xt.SequenceData:null!=qe(e)?xt.Struct:void console.warn("Failed to map parameter type to serialized version",{type:e})}export function getCustomParamTypeInfo(e){const t=e.type===Object?void 0:toSerializedParamType(e.type),a=t===xt.Struct?qe(e.type):void 0;return!0===e.options.array?{type:xt.Array,element:t,...null!=a?{elementStruct:a}:{}}:{type:t,...null!=a?{struct:a}:{}}}export function prepareCustomParams(e,t,a={},s={}){return Object.fromEntries(e.map(e=>{const r=getCustomParamTypeInfo(e);let i=r;const n=t[e.name],o=Ta(n)?n:void 0,l=!0===s.treatAllAsOptional||!0===e.options.optional,c=s.missingOverrideDefaultsToOverride??!0;let u=o?.override;void 0===u&&null!=n&&l&&c&&(u=!0),void 0===u&&l&&(u=!1);const d=void 0!==a[e.name]||void 0!==e.options.defaultValue,h=function(e,t){if(null==e.type){const a=function(e){return ea(e)?{type:xt.SequenceData}:void 0}(t);null!=a&&(e=a)}if(e.type!==xt.Struct)return{typeInfo:e,value:t};const a=wa(t);if(null==a)return{typeInfo:e,value:t};return{typeInfo:{...e,struct:a.struct},value:a.value}}(i,function(e,t){if(void 0!==t[e.name])return t[e.name];if(void 0!==e.options.defaultValue){const t=serializeCustomParameter(e.type,e.options.defaultValue);return void 0!==t?t:e.options.defaultValue}const a=toSerializedParamType(e.type);if(a===xt.Struct)return Qe(e.type)?{}:prepareCustomParamsFromType(e.type,{});return customParameterDefaultValueByType.get(a)}(e,a)),p=function(e,t){if(Ta(e))return e;if(null!=e&&"object"==typeof e&&!Array.isArray(e)&&"value"in e){const a=e;return{...t,value:a.value,..."boolean"==typeof a.override?{override:a.override}:{}}}if(t.type!==xt.SequenceData||!ea(e))return;return{type:xt.SequenceData,value:e}}(n,h.typeInfo);i=function(e,t,a){if(e.type!==xt.Struct||a?.type!==xt.Struct||null==a.struct)return e;const s=t.struct??e.struct;if(null==s||a.struct===s||Ze(a.struct,s)||null==Je(a.struct))return{...e,struct:a.struct};return e}(h.typeInfo,r,p);const f=!1!==u||e.options.array?p?.value??function(e,t,a){if(!0===e.options.array)return a?Wa(t):[];return Wa(t)}(e,h.value,d):Wa(h.value),m=function(e,t,a){if(t.type===xt.Struct){if(null!=t.struct&&Qe(t.struct))return a;const s=null!=t.struct?Je(t.struct):e.type;return null!=s&&Sa(a)?prepareCustomParamsFromType(s,a):a}if(t.type!==xt.Array||t.element!==xt.Struct||!Array.isArray(a))return a;const s=null!=t.elementStruct?Je(t.elementStruct):e.type;return a.map(e=>{const a=wa(e),r=a?.struct??t.elementStruct;if(null!=r&&Qe(r))return e;const i=null!=a?Je(a.struct):s,n=a?.value??(Sa(e)?e:null);if(null==i||null==n)return e;const o=prepareCustomParamsFromType(i,n);return null!=a?{struct:a.struct,value:o}:o})}(e,i,f);return[e.name,{...i,value:m,override:u}]}))}function Ta(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&"number"==typeof e.type&&"value"in e}function Ba(e){const t=new Map,a=e=>{for(const s of e)"actor"===s.type&&null!=s.actor&&t.set(s.id,s.actor),null!=s.children&&a(s.children)};return a(e),t}function Va(e){const t=new Map,a=e=>{for(const s of e)"prefab"===s.type&&t.set(s.id,s),null!=s.children&&a(s.children)};return a(e),t}function Na(e,t,a){if(!a||"prefab"!==t?.type||null==t.prefab)return e;const s=new Map((e.innerParams??[]).map(e=>[JSON.stringify(e.path),{path:e.path,params:{...e.params}}]));for(const e of t.prefab.innerParams??[]){const t=JSON.stringify(e.path),a=s.get(t);s.set(t,{path:e.path,params:{...a?.params??{},...Ua(e.params)}})}return{...e,params:{...e.params??{},...Ua(t.prefab.params)},innerParams:[...s.values()]}}function za(e,t,a){const s=new Map((e.innerParams??[]).map(e=>[JSON.stringify(e.path),e])),r=new Map((t.innerParams??[]).map(e=>[JSON.stringify(e.path),e])),i=new Map((a.innerParams??[]).map(e=>[JSON.stringify(e.path),e])),n=[];for(const e of new Set([...s.keys(),...r.keys(),...i.keys()])){const t=s.get(e),a=r.get(e),o=i.get(e),l=$a(t?.params??{},a?.params??{},o?.params??{});Object.keys(l).length>0&&n.push({path:a?.path??o?.path??t.path,params:l})}return{...t,params:$a(e.params??{},t.params??{},a.params??{}),innerParams:n}}function $a(e,t,a){const s={};for(const r of new Set([...Object.keys(e),...Object.keys(t),...Object.keys(a)]))JSON.stringify(a[r])!==JSON.stringify(e[r])?null!=a[r]&&(s[r]=a[r]):null!=t[r]&&(s[r]=t[r]);return s}function Ua(e){return null==e?{}:Object.fromEntries(Object.entries(e).filter(([,e])=>function(e){return!0===e?.override}(e)))}function Fa(e,t){return e.length>=t.length&&t.every((t,a)=>e[a]===t)}export function prepareCustomParamsFromType(e,t,a=null,s={}){const r=Ge(e);if(0===r.length)return{};let i;null!=a?Ee(a,()=>{i=a.get(e)}):i=new e;const n={};for(const e of r){const t=i[e.name];if(null!=t){const a=Ra(e,t);void 0!==a&&(n[e.name]=a)}}return prepareCustomParams(r,t,n,s)}function Ra(e,t){return!0===e.options.array?Array.isArray(t)?t.map(t=>serializeCustomParameter(e.type,t)??t):[]:serializeCustomParameter(e.type,t)}function Wa(e){return null==e?e:Array.isArray(e)?e.map(e=>Wa(e)):"object"==typeof e?"function"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e)):e}export function serializeCustomParameter(e,t){function a(){console.error("Failed to serialize value",{type:e,value:t})}switch(e){case Number:case Boolean:return t;case D:return t instanceof D?t.toArray():void a();case C:return t instanceof C?t.toArray():void a();case O:return t instanceof O?t.toArray():void a();case d:return t instanceof d?"#"+t.getHexString():"string"==typeof t?t:"number"==typeof t?"#"+new d(t).getHexString():void a();case String:return t;case h:return t instanceof h?t.toArray():void a();case we:return t instanceof we?t.asset?.id??null:void a();case be:return t instanceof be?t.id:"string"==typeof t?t:void a();case ve:return t instanceof ve?{id:t.id,...null!=t.name?{name:t.name}:{}}:void a();case Me:return t instanceof Me?t.id:"string"==typeof t?t:void a()}const s=qe(e);if(null!=s){const r=wa(t);if(null!=r)return r.struct===s?r.value:r;const i=function(e,t){if(null==t||"object"!=typeof t)return e;const a=t.constructor;return null!=qe(a)&&He(a,e)?a:e}(e,t),n=qe(i),o=function(e,t){if(null==t)return null;if(Sa(t))return t;if(null!=t&&"object"==typeof t&&Sa(t.params))return t.params;if("object"!=typeof t)return;const a=Ge(e),s={};for(const e of a){const a=t[e.name];if(void 0===a)continue;const r=Ra(e,a);void 0!==r&&(s[e.name]=r)}return prepareCustomParams(a,{},s)}(i,t);return void 0!==o?null!=o&&null!=n&&n!==s?{struct:n,value:o}:o:void a()}if(ea(t))return t}function _a(e,t){return function(e,t,a){const s=[],r=new Set;for(const i of[...e??[],...t??[]]){const e=a(i);r.has(e)||(r.add(e),s.push(i))}return s}((e??[]).filter(e=>Ga(e.materialId)),(t??[]).filter(e=>Ga(e.materialId)),e=>e.name?`name:${e.name}`:`color:${e.color}`)}function Ga(e){return"null"!=e&&null!=e}export const customParameterDefaultValueByType=new Map([[xt.RgbNode,"#000000"],[xt.Color,"#000000"],[xt.String,""],[xt.Scene,null],[xt.ModelRef,null],[xt.Vector4,[0,0,0,0]],[xt.Vec4Node,[0,0,0,0]],[xt.Vector3,[0,0,0]],[xt.Vec3Node,[0,0,0]],[xt.Vector2,[0,0]],[xt.Vec2Node,[0,0]],[xt.Euler,[0,0,0,"XYZ"]],[xt.Array,[]],[xt.DataAsset,null],[xt.SequenceData,Kt()],[xt.ColorLayer,Ut],[xt.MaskLayer,Ft]]);let La=new d;new d;function qa(e){return null==e?.color?null:(La.set(e.color),"#"+La.getHexString())}function Ja(e,t,a,s){const r="string"==typeof t.name&&""!==t.name?t.name:null;if(null!=r)return e.name===r||s===r;const i=qa(e);return null!=i&&(i===t.color||a===t.color)}export function applyMaterial(e,t,a,s,r={}){const i=[];return e.traverse(async e=>{if(e instanceof w||e.isMesh||e instanceof l.SkinnedMesh||e.isSkinnedMesh)for(const t of at(e.material))t.hasOwnProperty("color")&&i.push(e)}),Promise.all(i.map(async e=>{if(e.material instanceof Array)for(let i=0;i<e.material.length;i++){const n=e.material[i];if(null==n.color||!(n.color instanceof d))continue;const o=qa(n),l=n.name;if(Ja(n,t,e.userData["originalColor_"+i],e.userData["originalMaterialName_"+i])){const n=Qa(await a(t.materialId),r.textureFlipY),c=e.material[i];null!=n&&c.id!=n.id&&(e.material[i]=n,e.userData["originalColor_"+i]=e.userData["originalColor_"+i]??o,e.userData["originalMaterialName_"+i]=e.userData["originalMaterialName_"+i]??l,null!=s&&s.set(e.id+"#"+i,c))}}else if("color"in e.material){const i=e.material,n=qa(i),o=i.name;if(Ja(i,t,e.userData.originalColor,e.userData.originalMaterialName)){const i=Qa(await a(t.materialId),r.textureFlipY),l=e.material;null!=i&&(e.material=i,e.userData.originalColor=e.userData.originalColor??n,e.userData.originalMaterialName=e.userData.originalMaterialName??o,null!=s&&(s.has(e.id)||s.set(e.id,l)))}}}))}const Ya=new WeakMap;export function getConvertedFbxToGlbAssignedMaterialTextureFlipY(e){const t=e?.mesh?.uvConversion;return"fbx2gltf"===t?.source?!0!==t.flipV&&void 0:!function(e){return"glb"===e?.fileFormat&&!0===e.originalFileKey?.toLowerCase().endsWith(".fbx")}(e)&&void 0}function Qa(e,t){if(null==e||null==t||!function(e,t){return function(e){const t=[];for(const[a,s]of Object.entries(e))Za(a,s)&&t.push(s);if(e instanceof l.ShaderMaterial)for(const[a,s]of Object.entries(e.uniforms))Za(a,s.value)&&t.push(s.value);return t}(e).some(e=>e.flipY!==t)}(e,t))return e;let a=Ya.get(e);null==a&&(a=new Map,Ya.set(e,a));const s=a.get(t);if(null!=s)return s;const r=Ha(e);if(function(e,t){for(const a of Object.keys(e)){const s=e[a];Za(a,s)&&(e[a]=Xa(s,t))}}(r,t),r instanceof l.ShaderMaterial){for(const[e,a]of Object.entries(r.uniforms))Za(e,a.value)&&(a.value=Xa(a.value,t));r.uniformsNeedUpdate=!0}return r.needsUpdate=!0,a.set(t,r),r}function Ha(e){const t=e.clone();return t.userData={...e.userData??{}},t}function Za(e,t){const a=t;return(t instanceof I||!0===a?.isTexture)&&!e.toLowerCase().includes("envmap")&&!0!==a.isCompressedTexture&&!0!==a.isCompressedArrayTexture}function Xa(e,t){if(e.flipY===t)return e;const a=e.clone();return a.flipY=t,a.userData={...e.userData??{}},a.needsUpdate=!0,a}function Ka(e,t){if(e instanceof l.ShaderMaterial&&t instanceof l.ShaderMaterial){return e.fragmentShader+e.vertexShader==t.fragmentShader+t.vertexShader&&function(e,t){if(e instanceof l.ShaderMaterial&&t instanceof l.ShaderMaterial){for(const a in e.uniforms){if(null==t.uniforms[a])return!1;if(t.uniforms[a].value!==e.uniforms[a].value)return!1}return!0}return!1}(e,t)}return!1}function es(e){if(null!=e){for(let t=0;t<e.array.length;t++)e.setX(t,0);e.needsUpdate=!0}}function ts(e,t){const a=it(e);return null==a?"":function(e,t){const a=Os(e,t),s=a.sort().map(t=>{const a=e.getAttribute(t);if(null!=a){const e=a.array??a.data?.array,s=e?.constructor?.name??"";return`${t}:${a.itemSize}:${a.normalized?1:0}:${s}`}const s=function(e,t){if("uv"===t&&is(e))return{itemSize:2,normalized:!1,arrayType:"Float32Array"};throw new Error(`Unsupported synthetic batching geometry attribute: ${t}`)}(e,t);return`${t}:${s.itemSize}:${s.normalized?1:0}:${s.arrayType}`}).join(",");return`${null!=e.index?"indexed":"nonindexed"}|${s}`}(a.geometry,t)}function as(e,t){const a=Os(e,t);if(a.length===Object.keys(e.attributes).length)return e;const s=new u;s.name=e.name;const r=e.getIndex();null!=r&&s.setIndex(r);for(const t of a)s.setAttribute(t,rs(e,t));for(const t of e.groups)s.addGroup(t.start,t.count,t.materialIndex);return s.setDrawRange(e.drawRange.start,e.drawRange.count),null!=e.boundingBox&&(s.boundingBox=e.boundingBox.clone()),null!=e.boundingSphere&&(s.boundingSphere=e.boundingSphere.clone()),s.userData=e.userData,s}const ss=new WeakMap;function rs(e,t){return e.getAttribute(t)??function(e,t){if("uv"===t)return function(e){let t=ss.get(e);const a=e.getAttribute("position");if(null==a)throw new Error("Can not create synthetic batching UVs without a position attribute");null!=t&&t.count===a.count||(t=new l.Float32BufferAttribute(new Float32Array(2*a.count),2),ss.set(e,t));return t}(e);throw new Error(`Unsupported synthetic batching geometry attribute: ${t}`)}(e,t)}function is(e){return null!=e.getAttribute("position")}const ns=new WeakMap,os="hbat_",ls=new Set(["ambientLightColor","cameraNear","directionalLightShadows","directionalLights","directionalShadowMap","directionalShadowMatrix","fogColor","fogDensity","fogFar","fogNear","hemisphereLights","lightProbe","ltc_1","ltc_2","pointLightShadows","pointLights","pointShadowMap","pointShadowMatrix","receiveShadow","rectAreaLights","shadowFar","spotLightMap","spotLightMatrix","spotLightShadows","spotLights","spotShadowMap"]);function cs(e){let t=ns.get(e);return null==t&&(t=function(e){let t=e.type;if(e instanceof L)t+=function(e){let t="nodeShader";t+=function(e){if(null==e)return"";let t="";for(const a of Object.keys(e).sort())t+=`${a}:${String(e[a])};`;return t}(e.defines),t+=e.lights?"lights":"",t+=e.fog?"fog":"";for(const a of Object.keys(e.uniforms).sort()){if(hs(a))continue;const s=e.uniforms[a]?.value;fs(s)||(t+=`u:${a}:${bs(s)};`)}return t+=ds(e.vertexShader),t+=ds(e.fragmentShader),t}(e);else if(e instanceof l.MeshStandardMaterial&&!(e instanceof l.MeshPhysicalMaterial)||(t+=e.id+""),(e instanceof l.MeshBasicMaterial||e instanceof l.MeshLambertMaterial||e instanceof v||e instanceof b)&&(null!=e.map&&(t+="c"+e.map?.id),null!=e.aoMap&&(t+="o"+e.aoMap?.id),null!=e.lightMap&&(t+="l"+e.lightMap?.id),null!=e.envMap&&(t+="v"+e.envMap?.id),null!=e.alphaMap&&(t+="a"+e.alphaMap?.id)),e instanceof v&&(null!=e.normalMap&&(t+="n"+e.normalMap?.id),null!=e.roughnessMap&&(t+="r"+e.roughnessMap?.id),null!=e.metalnessMap&&(t+="m"+e.metalnessMap?.id),null!=e.emissiveMap&&(t+="e"+e.emissiveMap?.id)),e instanceof l.MeshPhysicalMaterial&&(null!=e.sheenColorMap&&(t+="sc"+e.sheenColorMap?.id),null!=e.sheenRoughnessMap&&(t+="sr"+e.sheenRoughnessMap?.id)),(e instanceof S||e instanceof b)&&null!=e.specularMap&&(t+="s"+e.specularMap?.id),e instanceof l.MeshToonMaterial&&(null!=e.map&&(t+="c"+e.map?.id),null!=e.aoMap&&(t+="o"+e.aoMap?.id),null!=e.lightMap&&(t+="l"+e.lightMap?.id),null!=e.alphaMap&&(t+="a"+e.alphaMap?.id)),e instanceof Yt&&null!=e.heightMap&&(t+="h"+e.heightMap?.id),e instanceof l.ShaderMaterial){t+=e.vertexShader,t+=e.fragmentShader;for(const a in e.uniforms){const s=e.uniforms[a];s&&s.value&&s.value.isTexture&&null!=s.value.id&&(t+="t:"+a+":"+s.value.id)}}null!=e.userData.outlineParameters&&(t+=e.userData.outlineParameters.color,t+=e.userData.outlineParameters.thickness,t+=e.userData.outlineParameters.alpha,t+=e.userData.outlineParameters.colorMode,t+=e.userData.outlineParameters.darkening);return t+=`side:${e.side};shadowSide:${e.shadowSide??"auto"};`,t+=e.transparent?"t":"",t+=e.vertexColors?"vc":"",t+=e.depthWrite?"dw":"",t+=e.depthTest?"dt":"",t+=`alphaTest:${e.alphaTest>0};`,t}(e),ns.set(e,t)),t}const us=new Map;function ds(e){return us.has(e)||us.set(e,`shader_${us.size}`),us.get(e)}function hs(e){return ls.has(e)||e.startsWith("hology_")}function ps(e,t){return e instanceof L?e.uniforms[t]?.value:e[t]}function fs(e){return"number"==typeof e||e instanceof D||e instanceof C||e instanceof O||e instanceof d}function ms(e){return"number"==typeof e?1:e instanceof D?2:4}function gs(e,t){const a=e.replace(/[^A-Za-z0-9_]/g,"_");let s=os+a;for(;t.has(s);)s=os+s;return t.add(s),s}function ys(e,t){const a={};for(const[s,r]of Object.entries(e.uniforms))t.has(s)||(a[s]={value:r.value});return a}const ws=new WeakMap;let Ss=1;function bs(e){if(null==e)return"null";if(e instanceof I||!0===e?.isTexture)return`texture:${e.id}`;if(e instanceof l.Matrix3||e instanceof l.Matrix4)return e.toArray().join(",");if("boolean"==typeof e||"number"==typeof e||"string"==typeof e)return String(e);if(Array.isArray(e)&&e.every(e=>null==e||["boolean","number","string"].includes(typeof e)))return JSON.stringify(e);if("object"==typeof e){let t=ws.get(e);return null==t&&(t=Ss++,ws.set(e,t)),`object:${t}`}return String(e)}function vs(e,t){if(null==e)return null;if(!(e instanceof t))throw new Error(`Value is not an instance of ${t.name}`);return e}const Ms=new y,As=new h;function xs(e,t){return As.copy(e),As.x*=-1,As.y*=-1,As.z*=-1,t.isCubeTexture&&!1===t.isRenderTargetTexture&&(As.y*=-1,As.z*=-1),(new l.Matrix3).setFromMatrix4(Ms.makeRotationFromEuler(As))}function js(e,t){switch(t){case 0:return e.x;case 1:return e.y;case 2:return e.z;case 3:return e.w}}const Ps=new O;function Is(e,t){return e===t||null==e==(null==t)&&("number"==typeof e&&"number"==typeof t?e===t||isNaN(e)&&isNaN(t):e instanceof l.Color&&t instanceof l.Color?e.r===t.r&&e.g===t.g&&e.b===t.b:e instanceof D&&t instanceof D?e.x===t.x&&e.y===t.y:e instanceof C&&t instanceof C?e.x===t.x&&e.y===t.y&&e.z===t.z:e instanceof O&&t instanceof O&&(e.x===t.x&&e.y===t.y&&e.z===t.z&&e.w===t.w))}function Ds(e){const t=[];for(const[a,s]of Object.entries(e))s instanceof ye?t.push(s):s instanceof Pe&&t.push(...Ds(s));return t}const Cs=new WeakMap;function Os(e,t){const a=Object.keys(e.attributes).filter(a=>Es(e,t,a));return!e.hasAttribute("uv")&&is(e)&&Es(e,t,"uv")&&a.push("uv"),a}function Es(e,t,a){return"position"===a||("uv"===a?function(e){if(e instanceof L)return Ts(e,"uv");if(e instanceof l.ShaderMaterial)return Bs(e.vertexShader,"uv");if(e instanceof Yt&&null!=e.heightMap)return!0;return ks.some(t=>e[t]?.isTexture)}(t):t instanceof L?Ts(t,a):t instanceof l.ShaderMaterial?function(e,t){if("uv1"===t||"uv2"===t||"uv3"===t)return Bs(e.vertexShader,t);return!0}(t,a):"uv1"!==a&&(("color"!==a||!function(e){let t=Cs.get(e);if(null!=t)return t;const a=e.getAttribute("color");if(null==a)t=!1;else{t=!0;for(let e=0;e<a.count;e++){for(let s=0;s<3;s++)if(1!==a.getComponent(e,s)){t=!1;break}if(!t)break}}return Cs.set(e,t),t}(e))&&("uv2"!==a||(null!=t.lightMap||null!=t.aoMap))))}const ks=["map","alphaMap","emissiveMap","normalMap","bumpMap","displacementMap","roughnessMap","metalnessMap","aoMap","specularMap","gradientMap","clearcoatMap","clearcoatNormalMap","clearcoatRoughnessMap","iridescenceMap","iridescenceThicknessMap","sheenColorMap","sheenRoughnessMap","transmissionMap","thicknessMap","anisotropyMap"];function Ts(e,t){return Bs(e.vertexShader,t)}function Bs(e,t){return new RegExp(`(^|[^A-Za-z0-9_])${a=t,a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}([^A-Za-z0-9_]|$)`).test(e);var a}function Vs(e,t,a){if(t(e))return e;for(const s of e.children??[]){const e=Vs(s,t,a);if(null!=e)return e}if(null!=a&&"prefab"===e.type){const s=a.get(e.assetId);if(null!=s){const e=s.prefab.objects.find(e=>Vs(e,t,a));if(null!=e)return e}}return null}const Ns=new C,zs=new C,$s=new C,Us=new O,Fs=new O,Rs=new y,Ws=new y,_s=new M;export function freezeSkinnedMeshes(e,t=!1){if(null==e)return e;e.updateWorldMatrix(!0,!0);const a=[];e.traverse(e=>{e.isSkinnedMesh&&a.push(e)});let s=e;for(const e of a){const a=Gs(e,t),r=e.parent;if(null==r){s=a;continue}const i=r.children.indexOf(e);e.removeFromParent(),r.add(a);const n=r.children.indexOf(a);i>=0&&n>=0&&n!==i&&(r.children.splice(n,1),r.children.splice(i,0,a))}return function(e){const t=[];e.traverse(e=>{e.isBone&&t.push(e)});for(const e of t)null!=e.parent&&!e.parent.isBone&&qs(e)&&e.removeFromParent()}(s),s}function Gs(e,t){e.updateWorldMatrix(!0,!1);const a=e.geometry.clone();t&&s(a,JSON.stringify([e.geometry.uuid,e.bindMatrix.elements,e.bindMatrixInverse.elements,e.skeleton.bones.map((t,a)=>(new y).multiplyMatrices(t.matrixWorld,e.skeleton.boneInverses[a]).elements)]));const r=a.getAttribute("position"),i=a.getAttribute("normal"),n=a.getAttribute("tangent");if(null!=r){for(let t=0;t<r.count;t++)Ns.fromBufferAttribute(r,t),e.applyBoneTransform(t,Ns),r.setXYZ(t,Ns.x,Ns.y,Ns.z);r.needsUpdate=!0}if(null!=i||null!=n){const t=a.getAttribute("skinIndex"),s=a.getAttribute("skinWeight");if(null!=t&&null!=s){for(let a=0;a<t.count;a++)Ls(e,a,Ws),null!=i&&(zs.fromBufferAttribute(i,a),_s.getNormalMatrix(Ws),zs.applyMatrix3(_s).normalize(),i.setXYZ(a,zs.x,zs.y,zs.z)),null!=n&&($s.fromBufferAttribute(n,a),$s.transformDirection(Ws),n.setXYZ(a,$s.x,$s.y,$s.z));null!=i&&(i.needsUpdate=!0),null!=n&&(n.needsUpdate=!0)}}a.deleteAttribute("skinIndex"),a.deleteAttribute("skinWeight"),a.computeBoundingBox(),a.computeBoundingSphere();const o=new w(a,e.material);return o.copy(e,!1),o.geometry=a,o.material=e.material,o.userData={...e.userData},o}function Ls(e,t,a){const s=e.geometry,r=s.getAttribute("skinIndex"),i=s.getAttribute("skinWeight"),n=e.skeleton;Us.fromBufferAttribute(r,t),Fs.fromBufferAttribute(i,t),a.identity().multiplyScalar(0);for(let e=0;e<4;e++){const t=Fs.getComponent(e);if(0===t)continue;const s=Us.getComponent(e);Rs.multiplyMatrices(n.bones[s].matrixWorld,n.boneInverses[s]);for(let e=0;e<16;e++)a.elements[e]+=Rs.elements[e]*t}return a.premultiply(e.bindMatrixInverse).multiply(e.bindMatrix),a}function qs(e){let t=!0;return e.traverse(a=>{a===e||a.isBone||(t=!1)}),t}function Js(e,t){let a=t??!1,s=!0;for(const t of e)if(!1!==t.castShadow){s=!1;break}for(const t of e)if(!0===t.castShadow)return!0;return a&&!s}function Ys(e,t){let a=t??!1,s=!0;for(const t of e)if(!1!==t.receiveShadow){s=!1;break}if(s)return!1;for(const t of e)if(!0===t.receiveShadow)return!0;return a&&!s}/*
|
|
1
|
+
import{__decorate as e,__metadata as t}from"tslib";import{LatticeGeometryCache as a,setLatticeGeometrySourceIdentity as s}from"./lattice-deformation.js";import{particleParameter as r}from"../shader-nodes/particle-parameter.js";export{createLatticeDeformation,latticePoint,isValidLattice,deformLatticeGeometry,LatticeGeometryCache}from"./lattice-deformation.js";import{ConvexPolyhedronCollisionShape as i}from"./collision/collision-shape.js";import{SpriteShader as n}from"../shader/sprite-shader.js";import{Observable as o,Subject as l}from"rxjs";import*as c from"three";import{BoxGeometry as u,BufferGeometry as d,Color as h,Euler as p,Fog as f,FogExp2 as m,Group as g,Material as y,Matrix4 as w,Mesh as S,MeshLambertMaterial as b,MeshPhongMaterial as v,MeshStandardMaterial as M,Matrix3 as A,Object3D as x,PointLight as j,Quaternion as P,Scene as I,Texture as D,Vector2 as C,Vector3 as O,Vector4 as E}from"three";import{attributes as k,batchingUniformFloat as T,batchingUniformVec2 as B,batchingUniformVec3 as V,batchingUniformVec4 as N,bool as z,BooleanExpression as $,BooleanNode as U,colorToNormal as F,float as R,deriveNodeShaderMaterial as W,FloatNode as _,ifDefApply as G,mix as L,NodeShaderMaterial as q,rgb as J,rgba as Y,RgbNode as Q,select as H,standardMaterial as Z,Texture2dLookupNode as X,textureSampler2d as K,textureSampler2dArray as ee,UniformBoolNode as te,UniformFloatNode as ae,UniformSampler2dArraySlice as se,UniformVec2Node as re,UniformVec3Node as ie,UniformVec4Node as ne,varying as oe,varyingAttributes as le,varyingTransformed as ce,vec2 as ue,Vec2Node as de,vec3 as he,Vec3Node as pe,vec4 as fe,Vec4Node as me}from"three-shader-graph";import{Service as ge}from"typedi";import{VfxActor as ye}from"../effects/vfx/vfx-actor.js";import{VisualEffect as we}from"../effects/vfx/vfx-param.js";import{Prefab as Se,PrefabOf as be}from"./objects/prefab.js";import{DataAssetRef as ve}from"./objects/data-asset.js";import{SceneRef as Me}from"./scene-ref.js";import{ModelRef as Ae}from"./model-ref.js";import{BaseActor as xe,getActorOptions as je}from"../gameplay/actors/actor.js";import Pe from"../gameplay/actors/builtin/index.js";import{ActorComponent as Ie}from"../gameplay/actors/component.js";import{PhysicsBodyType as De}from"../gameplay/services/physics/physics-system.js";import{NetMode as Ce}from"../gameplay/net/net-session.js";import{NetRole as Oe}from"../gameplay/net/service/net-actor-role.js";import{ThreeBlendingMode as Ee}from"../effects/vfx/vfx-asset.js";import{withInjectionContext as ke}from"../gameplay/inject.js";import{RenderingView as Te}from"../rendering.js";import{markMaterialUniformValuesNeedUpdate as Be,setMaterialUniformValuesAutoUpdate as Ve}from"../rendering/node-material-webgpu-resolver.js";import{curveSampler as Ne,oneMinus as ze,particleUniforms as $e,Sampler2DNode as Ue}from"../shader-nodes/index.js";import{LambertShader as Fe}from"../shader/builtin/lambert-shader.js";import{LandscapeCompositeShader as Re}from"../shader/builtin/landscape-composite-shader.js";import{LandscapeShader as We}from"../shader/builtin/landscape-shader.js";import{StandardShader as _e}from"../shader/builtin/standard-shader.js";import{UnlitShader as Ge}from"../shader/builtin/unlit-shader.js";import{extractShaderParameters as Le,getDataAssetDefinitionType as qe,getParameterDefinitionId as Je,getParameterDefinitionType as Ye,isDataAssetDefinitionAbstract as Qe,isParameterDefinitionAbstract as He,isParameterDefinitionAssignableTo as Ze,isParameterDefinitionStructAssignableTo as Xe,shaderParameterUniformName as Ke}from"../shader/parameter.js";import{ArrayMap as et,DefaultMap as tt,groupBy as at}from"../utils/collections.js";import{iterateMaterials as st}from"../utils/materials.js";import{filterChildrenShallow as rt,filterSceneShallow as it,findFirstVisibleMesh as nt,findFirstVisibleObject as ot,traverseAsync as lt}from"../utils/three/traverse.js";import{AssetMeshInstance as ct,AssetResourceLoader as ut}from"./asset-resource-loader.js";import{AssetsProvider as dt}from"./assets-provider.js";import{isCollisionMesh as ht}from"./collision/collision-shape-import.js";import{BoxCollisionShape as pt,PhysicalShapeMesh as ft}from"./collision/collision-shape.js";import{LandscapeManager as mt}from"./landscape/landscape-manager.js";import{initLandscape as gt}from"./landscape/landscape.js";import{SectionGrid as yt,smoothNormalsCrossMeshes as wt}from"./landscape/utils.js";import{createGrassFoliageMaterial as St}from"./materials/grass-foliage.js";import{createGrassMaterial as bt}from"./materials/grass.js";import{getMaterialAttribute as vt}from"./materials/utils/material-painting.js";import{PaintedScatterManager as Mt}from"./scatter/painted-scatter-manager.js";import{SurfaceScatterManager as At}from"./scatter/surface-scatter-manager.js";import{createWaterMaterial as xt}from"./materials/water.js";import{SerializedParamType as jt}from"./model.js";import{applyRuntimeParamTypeInference as Pt,convertConfiguredParamsToRuntimeTypes as It,convertConfiguredParamValueToRuntimeType as Dt,inferRuntimeSerializedParamTypeHint as Ct}from"./custom-param-runtime-types.js";import{ShapeLibrary as Ot,ShapeLibraryKeys as Et}from"./objects/shapes.js";import{ambientLightName as kt,createSky as Tt,defaultSkyMaterial as Bt}from"./sky.js";import{Curve2 as Vt}from"../utils/curve.js";import{DecalUnlitShader as Nt}from"../shader/builtin/decal-unlit-shader.js";import{DecalStandardShader as zt}from"../shader/builtin/decal-standard-shader.js";import{ClusterGenerator as $t}from"../rendering/cluster-generator.js";import{ColorLayer as Ut,defaultValueColorLayer as Ft,defaultValueMaskLayer as Rt,MaskLayer as Wt}from"../shader/color-layer.js";import{LayeredShader as _t}from"../shader/builtin/layered-shader.js";import{isColorLayerSerialized as Gt}from"../shader/color-layer.js";import{FogVolume as Lt}from"../rendering/fog/fog-volume-actor.js";import{UnscaledSprite as qt}from"../utils/three/unscaled-sprite.js";import{ToonShader as Jt}from"../shader/builtin/toon-shader.js";import{BatchedMesh2 as Yt}from"./batched-mesh-2.js";import{ParallaxStandardMaterial as Qt}from"../shader/builtin/standard-shader.js";import{parallaxOcclusionMapping as Ht}from"../shader-nodes/pom.js";import{traverseVisibleEvery as Zt}from"../utils/three/traverse.js";import{BufferGeometryUtils as Xt,RectAreaLightHelper as Kt}from"three/examples/jsm/Addons.js";import{createSequenceData as ea,isSequenceData as ta,Sequence as aa}from"../effects/sequence/sequence-data.js";import{applyUvTiling as sa}from"./../shader/uv-nodes.js";import{buildShaderGraphMaterial as ra,shaderGraphMaterialSideToThree as ia}from"../shader/graph/index.js";import{hasExecutableEventGraphDocument as na}from"../gameplay/event-graph/model.js";import{depthUniformName as oa}from"../shader-nodes/depth.js";export{Pt as applyRuntimeParamTypeInference,It as convertConfiguredParamsToRuntimeTypes,Dt as convertConfiguredParamValueToRuntimeType,Ct as inferRuntimeSerializedParamTypeHint};const la={},ca=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),ua=/^((?!chrome|android).)*safari/i.test(navigator.userAgent)||(navigator.userAgent.includes("iPhone")||navigator.userAgent.includes("iPad"))&&!!navigator.userAgent.match(/AppleWebKit/)&&!navigator.userAgent.match(/CriOS/);export const shapeDefaultColor="#aaaaaa";export class SceneMaterializerLoader{constructor(e,t,a){this.dataProvider=e,this.assetsService=t,this.assetManagerService=a}get(e,t){return new da(e,this.dataProvider,this.assetsService,this.assetManagerService,t,[],[],{create:()=>null,initActor:async()=>{}})}}let da=class{async preparePersistence(e,t,a){this.persistence=e,this.persistenceSceneId=t;const s=async(e,t,a,r)=>{for(const i of e){const e=t+i.id;if(a.length&&this.authoredPersistenceParents.set(e,a[a.length-1]),i.children&&await s(i.children,t,[...a,e],r),"prefab"!==i.type||null==i.assetId||r.includes(i.assetId))continue;const n=await this.assetsService.getAsset(i.assetId);null!=n?.prefab&&(null!=n.prefab.mainActorId&&this.prefabInstanceExposedActorMap.set(e,e+"/"+n.prefab.mainActorId),await s(n.prefab.objects,e+"/",[...a,e],[...r,i.assetId]))}};await s(a,"",[],[]);for(const e of this.prefabInstanceExposedActorMap.keys()){const t=this.persistenceActorPath(e),a=this.authoredPersistenceTargets.get(t);(null==a||e.length<a.length)&&this.authoredPersistenceTargets.set(t,e)}const r=e=>e.filter(e=>!this.isPersistenceRemoved(e.id)).map(e=>null==e.children?e:{...e,children:r(e.children)});return r(a)}persistenceActorPath(e){const t=new Set;for(;this.prefabInstanceExposedActorMap.has(e)&&!t.has(e);)t.add(e),e=this.prefabInstanceExposedActorMap.get(e);return e}isPersistenceRemoved(e){if(null==this.persistence)return!1;for(let t=e;null!=t;t=this.authoredPersistenceParents.get(t))if(this.persistence.isRemoved({sceneId:this.persistenceSceneId,path:t}))return!0;return!1}registerPersistentActors(){const e=[];if(null==this.persistence)return e;for(const[t,a]of this.materializedActors){const s={sceneId:this.persistenceSceneId,path:t},r={sceneId:this.persistenceSceneId,path:this.authoredPersistenceTargets.get(t)??t};this.persistence.register(a,s,r)&&e.push(a)}return e}get prefabEventGraphInstances(){return[...this.materializedPrefabEventGraphs.values()]}resolveSceneActor(e){const t=this.persistenceActorPath(e);if(!this.isPersistenceRemoved(t))return this.materializedActors.get(t)}constructor(e,t,s,r,i,n,o,u,d=[]){this.scene=e,this.dataProvider=t,this.assetsService=s,this.assetManagerService=r,this.renderingView=i,this.shaders=n,this.actorTypes=o,this.actorProvider=u,this.componentTypes=d,this.navigationBakes={},this.navigationRevision=0,this.objectMap=new Map,this.sceneObjectMap=new Map,this.components=[],this.landscapeManagers=[],this.materializedActors=new Map,this.authoredPersistenceTargets=new Map,this.authoredPersistenceParents=new Map,this.idToSceneObject=new Map,this.inEditor=!0,this.netMode=Ce.none,this.updated$=new l,this.removed$=new l,this.prefabEventGraphAdded$=new l,this.prefabEventGraphRemoved$=new l,this.error$=new l,this.materializedPrefabEventGraphs=new Map,this.announcedPrefabEventGraphs=new Set,this.editorActorParamSnapshot=new Map,this.editorAttachedActorComponents=new WeakMap,this.livePrefabInstances=new Map,this.sceneSettingsActive=!1,this.assets=new Map,this.vfxPreloads=new WeakMap,this.latticeGeometries=new a,this._canBeInstancedCache=new Map,this.editorStaticDrawChunks=[],this.editorStaticChunkBySource=new WeakMap,this.editorStaticSnapshotBySource=new WeakMap,this.dirtyEditorStaticDrawChunks=new Set,this.editorStaticEditingObjects=new Set,this.editorMatrixWorldEditingObjects=new Set,this.editorStaticSelectedObjects=new Set,this.editorStaticDrawSetSuspended=!1,this.editorStaticDrawSetRebuildQueued=!1,this.editorStaticFullRebuildQueued=!1,this._editorStaticDrawSetsEnabled=!0,this.editorStaticInitialized=!1,this.editorStaticDisposed=!1,this.editorStaticObjectsToRebuild=new Map,this.editorStaticDrawSetUpdated$=new l,this._originalMaterials=new Map,this.worldEnvironmentRequest=0,this.prefabInstanceChain=[],this.prefabInstanceExposedActorMap=new Map,this.geometryCache=new Map,this.collisionShapeCache=new Map,this.modelImageBitmaps=new WeakMap,this.assetManagerService.materialProvider=async e=>materialFromAsset(this.assets.get(e)??await this.assetsService.getAsset(e),this.renderingView,this.assetsService,this.assetManagerService,this.shaders),this.originalFog=e.fog,null!=this.renderingView.csm&&(this.originalGlobalLight={direction:this.renderingView.csm.lightDirection.clone(),intensity:this.renderingView.csm.lightIntensity,lights:this.renderingView.csm.lights.map(e=>({intensity:e.intensity,color:e.color.clone(),castShadow:e.castShadow,src:e.userData.src,volumetricIntensity:e.userData.volumetricIntensity}))}),t.onCreate(e=>{this.navigationRevision++,this.update(e).finally(()=>this.scheduleEditorStaticDrawSetRebuild()),this.handlePaintedScatterSceneMutation(e),this.handleSurfaceScatterSceneMutation(e)}),t.onUpdate(e=>{this.navigationRevision++,this.prepareEditorStaticObjectForMutation(e),this.update(e).finally(()=>this.scheduleEditorStaticDrawSetRebuild(e)),this.handlePaintedScatterSceneMutation(e),this.handleSurfaceScatterSceneMutation(e)}),t.onRemove(e=>{this.navigationRevision++,this.prepareEditorStaticObjectForMutation(e),this.remove(e),this.scheduleEditorStaticDrawSetRebuild(),this.handlePaintedScatterSceneMutation(e),this.handleSurfaceScatterSceneMutation(e)}),this.createAssetSubscription=s.onCreate.subscribe(e=>{this.navigationRevision++,this.assets.set(e.id,e)}),this.updateSubscription=s.onUpdate.subscribe(async t=>{this.navigationRevision++;const a=this.assets.get(t.id);if(this.assets.set(t.id,t),"material"==t.type){const a=[];e.traverse(e=>{if(e instanceof c.Mesh)if(Array.isArray(e.material))for(let s=0;s<e.material.length;s++)a.push(this.refreshMaterial(e,e.material[s],t,s));else a.push(this.refreshMaterial(e,e.material,t))}),await Promise.all(a)}else if("mesh"==t.type){this.findByAssetId(t.id).forEach(async e=>{this.remove(e.userData.src);const t=await this.materializeAndInitActor(e.userData.src);this.updated$.next({object:t,source:e.userData.src}),this.scheduleEditorStaticDrawSetRebuild()});for(const e of this.assets.values())if("prefab"==e.type){if(!e.prefab.objects.some(e=>Ns(e,e=>e.assetId==t.id,this.assets)))continue;this.findByAssetId(e.id).forEach(e=>{this.remove(e.userData.src),this.materializeAndInitActor(e.userData.src).finally(()=>this.scheduleEditorStaticDrawSetRebuild())})}this.landscapeManagers.forEach(e=>{const a=e.source?.grass?.layers?.some(e=>e.meshes.some(e=>e.assetId===t.id));a&&e.queueRefreshScatter(this.renderingView?.camera.position??new O,!0)}),null!=this.surfaceScatterManager&&(this.surfaceScatterManager.usesSourceAsset(t.id)||this.surfaceScatterManager.usesScatterAsset(t.id))&&this.surfaceScatterManager.queueRefresh(!0),this.paintedScatterManager?.usesScatterAsset(t.id)&&this.paintedScatterManager.queueRefresh(!0)}else if("prefab"===t.type){if("prefab"===a?.type&&await this.applyLivePrefabParameterUpdate(a,t))return;if(!this.inEditor)return void console.warn(`Prefab ${t.name??t.id} changed in a way that cannot be applied to its running instances. Respawn or restart to use the saved data.`);this.findByAssetId(t.id).forEach(e=>{const t=e.userData.src;this.remove(t),this.materializeAndInitActor(t).finally(()=>this.scheduleEditorStaticDrawSetRebuild())}),(this.surfaceScatterManager?.usesPrefabAsset(t.id)||this.sceneReferencesPrefabAsset(t.id)&&await this.prefabAssetContainsSurfaceScatter(t))&&await this.refreshSurfaceScatterPresence(!0),(this.paintedScatterManager?.usesPrefabAsset(t.id)||this.sceneReferencesPrefabAsset(t.id)&&await this.prefabAssetContainsPaintedScatter(t))&&await this.refreshPaintedScatterPresence(!0)}else if("vfx"===t.type)for(const e of this.dataProvider.getObjects())await ka(e,async e=>{"vfx"===e.type&&e.assetId===t.id&&(this.remove(e),await this.materializeAndInitActor(e))});else if("texture"===t.type)await this.refreshMaterialTextures(t);else if("shaderGraph"===t.type){this.scene.traverse(e=>{if(e instanceof S)if(Array.isArray(e.material))for(let a=0;a<e.material.length;a++)this.refreshMaterial(e,e.material[a],t,a);else this.refreshMaterial(e,e.material,t)});for(const e of this.dataProvider.getObjects())await ka(e,async e=>{if("vfx"===e.type&&null!=e.assetId){const a=this.assets.get(e.assetId);null!=a&&this.vfxAssetUsesShaderGraph(a,t.id)&&(this.remove(e),await this.materializeAndInitActor(e))}})}this.scheduleEditorStaticDrawSetRebuild()})}async refreshMaterialTextures(e){if("texture"!==e.type)return void console.error("Can not refresh material textures. Asset is not a texture",e);const t=new Set,a=new Set,s=[],r=s=>{t.has(s)||(t.add(s),this.materialUsesTexture(s,e.id)&&a.add(s))};if(this.scene.traverse(t=>{t instanceof c.SpotLight&&"spot"===t.userData?.src?.light?.type&&t.userData.src.light.spot.mapTextureId===e.id&&s.push(t),t instanceof S&&(Array.isArray(t.material)?t.material.forEach(r):r(t.material))}),0===a.size&&0===s.length)return;const i=await this.assetManagerService.getTexture(e);if(null!=i){for(const t of a)this.replaceMaterialTextureReferences(t,e.id,i);for(const e of s)e.map=i}else console.error("Can not refresh material textures. Texture not found",e)}materialUsesTexture(e,t){if(e instanceof c.ShaderMaterial){for(const a of Object.values(e.uniforms))if(a.value instanceof c.Texture&&a.value.userData.assetId===t)return!0}else for(const a of Object.values(e))if(a instanceof c.Texture&&a.userData.assetId===t)return!0;return!1}replaceMaterialTextureReferences(e,t,a){let s=!1;if(e instanceof c.ShaderMaterial)for(const[r,i]of Object.entries(e.uniforms))i.value instanceof c.Texture&&i.value.userData.assetId===t&&(e.uniforms[r].value=a,s=!0);else for(const[r,i]of Object.entries(e))i instanceof c.Texture&&i.userData.assetId===t&&(e[r]=a,s=!0);s&&(e.needsUpdate=!0,Be(e))}async getAsset(e){let t=this.assets.get(e);return null==t&&(t=await this.assetsService.getAsset(e),null!=t&&this.assets.set(e,t)),t}async refreshMaterial(e,t,a,s){const r=t?.userData?.assetId;if(r!==a.id){const e=this.assets.get(r);let t=!1;if(null!=e&&("shaderGraph"===a.type&&"asset"===e.material?.shaderGraph?.source&&e.material.shaderGraph.assetId===a.id&&(t=!0),!t&&null!=e.material?.shaderParams))for(const s of Object.values(e.material.shaderParams)){if(s.type===jt.Material&&s.value===a.id){t=!0;break}if(s.type===jt.Array&&"element"in s&&s.element===jt.Material&&s.value.includes(a.id)){t=!0;break}}if(!t)return}const i=await materialFromAsset(this.assets.get(r),this.renderingView,this.assetsService,this.assetManagerService,this.shaders,!1),n=i.userData,o=t.userData.receiveDecals!==n.receiveDecals;i.userData=t.userData,i.userData.hasBloom=n.hasBloom,i.userData.reflective=n.reflective,i.userData.outlineParameters=n.outlineParameters,i.userData.receiveDecals=n.receiveDecals,o&&(t.needsUpdate=!0),null!=s?es(e.material[s],i)||(e.material[s]=i):es(e.material,i)||(e.material=i,e===this.sky&&this.applySkySettings(e.material))}vfxAssetUsesShaderGraph(e,t){return null!=e.vfx&&e.vfx.emitters.some(e=>this.emitterUsesShaderGraph(e,t))}emitterUsesShaderGraph(e,t){const a=e.output;return"shaderGraph"===a.materialSource&&"asset"===a.shaderGraph?.source&&a.shaderGraph.assetId===t||!!e.children&&e.children.some(e=>this.emitterUsesShaderGraph(e,t))}getTopLevelActors(){return Array.from(this.materializedActors.entries()).filter(([e,t])=>!e.includes("/")).map(([,e])=>e)}get actorInstances(){return Array.from(this.materializedActors.values())}async initTextures(){const e="webgpu"===this.renderingView?.requestedBackend,t=e?this.renderingView.initializeBackend().catch(e=>{console.warn("Could not prepare WebGPU texture uploads before compilation",e)}):void 0,a=new Map,s=new Map,r=[];for(const e of this.collectMaterialAssignments(this.dataProvider.getObjects())){const t=this.assets.get(e.materialId);if(null!=t?.material)for(const e of Object.values(t.material.shaderParams??{}))if(e.type===jt.Texture&&"string"==typeof e.value){const t=this.assets.get(e.value);if(null==t)continue;const r=t.texture?.textureArrayFileKey;null==r?a.set(t.id,t):s.set(r,t)}}const i=[...Array.from(a.values(),e=>({asset:e,array:!1})),...Array.from(s.values(),e=>({asset:e,array:!0}))];let n=0;if(await Promise.all(Array.from({length:Math.min(16,i.length)},async()=>{for(;n<i.length;){const{asset:a,array:s}=i[n++],o=s?(await this.assetManagerService.getTextureArray(a))?.texture:await this.assetManagerService.getTexture(a);null!=o&&(e&&(await t,this.renderingView.initTexture(o)),r.push(o))}})),0!==r.length&&this.renderingView&&"webgpu"!==this.renderingView.requestedBackend){console.log(`Initializing ${r.length} textures`),console.time("Init textures");for(const e of r)this.renderingView.initTexture(e);console.timeEnd("Init textures")}}async prefetchAssets(){this.texturePrefetch=this.initTextures().catch(e=>{console.warn("Could not prefetch scene textures",e)});const e=this.collectAssetMeshIds(this.dataProvider.getObjects());await Promise.all(Array.from(e).map(async e=>{const t=this.assets.get(e);if("mesh"===t?.type)return this.assetManagerService.getMesh(t,{mergeGeomtries:!0,clone:!1})}))}collectAssetMeshIds(e,t=[],a=new Set){for(const s of e??[])this.collectObjectAssetMeshIds(s,t,a);return a}collectObjectAssetMeshIds(e,t,a){if(this.shouldBeMaterialized(e)&&("asset_mesh"===e.type&&null!=e.assetId&&a.add(e.assetId),null!=e.children&&this.collectAssetMeshIds(e.children,t,a),"prefab"===e.type&&null!=e.assetId&&!t.includes(e.assetId))){const s=this.assets.get(e.assetId);null!=s?.prefab?.objects&&this.collectAssetMeshIds(s.prefab.objects,[...t,e.assetId],a)}}collectMaterialAssignments(e,t=[],a=[]){for(const s of e??[])this.collectObjectMaterialAssignments(s,t,a);return a}collectObjectMaterialAssignments(e,t,a){if(this.shouldBeMaterialized(e)&&("shape_mesh"!==e.type&&"asset_mesh"!==e.type||null==e.materialAssignments||a.push(...e.materialAssignments),null!=e.children&&this.collectMaterialAssignments(e.children,t,a),"prefab"===e.type&&null!=e.assetId&&!t.includes(e.assetId))){const s=this.assets.get(e.assetId);null!=s?.prefab?.objects&&this.collectMaterialAssignments(s.prefab.objects,[...t,e.assetId],a)}}async init(){await this.preInit(),pa.clear(),fa.clear(),await this.prefetchAssets(),await Promise.all(this.dataProvider.getObjects().map(e=>this.materialize(e))),await this.initActorsPostInit(),this.generateOcclusionClusters(),this.announcePrefabEventGraphs(),await this.refreshPaintedScatterPresence(!0),await this.refreshSurfaceScatterPresence(!0),this.editorStaticInitialized=!0,this.rebuildEditorStaticDrawSet(),"webgpu"===this.renderingView.requestedBackend&&await this.texturePrefetch}get editorStaticDrawSetsEnabled(){return this._editorStaticDrawSetsEnabled}set editorStaticDrawSetsEnabled(e){this._editorStaticDrawSetsEnabled!==e&&(this._editorStaticDrawSetsEnabled=e,this.editorStaticInitialized&&!this.editorStaticDisposed&&(e?this.rebuildEditorStaticDrawSet():(this.editorStaticDrawSetSuspended=!1,this.editorStaticEditingObjects.clear(),this.editorStaticFullRebuildQueued=!1,this.editorStaticObjectsToRebuild.clear(),this.disposeEditorStaticDrawSet(),this.editorStaticDrawSetUpdated$.next())))}beginEditorStaticSceneEdit(e=[]){for(const e of this.editorMatrixWorldEditingObjects)xa(e,!1);this.editorMatrixWorldEditingObjects.clear();for(const t of e)this.editorMatrixWorldEditingObjects.add(t),xa(t,!0);if(!this._editorStaticDrawSetsEnabled||!this.inEditor||this.editorStaticDrawSetSuspended)return;this.editorStaticDrawSetSuspended=!0,this.editorStaticEditingObjects.clear();const t=new Set;for(const a of e){this.editorStaticEditingObjects.add(a);const e=this.editorStaticChunkBySource.get(a);null!=e&&t.add(e)}for(const e of t)this.disposeEditorStaticDrawChunk(e),this.dirtyEditorStaticDrawChunks.add(e),this.buildEditorStaticDrawChunk(e);this.editorStaticDrawSetUpdated$.next()}setEditorStaticSelectedObjects(e){if(!this.inEditor)return;const t=new Set(e),a=new Set;for(const e of this.editorStaticSelectedObjects)if(!t.has(e)){const t=this.editorStaticChunkBySource.get(e);null!=t&&a.add(t)}for(const e of t)if(!this.editorStaticSelectedObjects.has(e)){const t=this.editorStaticChunkBySource.get(e);null!=t&&a.add(t)}this.editorStaticSelectedObjects.clear();for(const e of t)this.editorStaticSelectedObjects.add(e);if(!this.editorStaticDrawSetSuspended&&"webgpu"===this.renderingView?.requestedBackend){for(const e of a)this.disposeEditorStaticDrawChunk(e),this.buildEditorStaticDrawChunk(e);a.size>0&&this.editorStaticDrawSetUpdated$.next()}}endEditorStaticSceneEdit(){for(const e of this.editorMatrixWorldEditingObjects)xa(e,!1);if(this.editorMatrixWorldEditingObjects.clear(),this.editorStaticDrawSetSuspended){this.editorStaticDrawSetSuspended=!1,this.editorStaticEditingObjects.clear();for(const e of this.dirtyEditorStaticDrawChunks)this.disposeEditorStaticDrawChunk(e),this.buildEditorStaticDrawChunk(e);this.dirtyEditorStaticDrawChunks.clear(),this.editorStaticDrawSetUpdated$.next()}}getEditorRenderObject(e){const t=e.userData?.src,a=null!=t?.id?this.sceneObjectMap.get(t.id)??e:e;if(this.editorStaticEditingObjects.has(a)||this.editorStaticSelectedObjects.has(a))return a;const s=this.editorStaticSnapshotBySource.get(a);return!0===s?.chunk.active?s.object:e}scheduleEditorStaticDrawSetRebuild(e){!this.editorStaticDisposed&&this._editorStaticDrawSetsEnabled&&this.inEditor&&!this.editorStaticDrawSetSuspended&&"webgpu"===this.renderingView?.requestedBackend&&(null==e?(this.editorStaticFullRebuildQueued=!0,this.editorStaticObjectsToRebuild.clear()):this.editorStaticFullRebuildQueued||this.editorStaticObjectsToRebuild.set(e.id,e),this.editorStaticDrawSetRebuildQueued||(this.editorStaticDrawSetRebuildQueued=!0,queueMicrotask(()=>{if(this.editorStaticDrawSetRebuildQueued=!1,this.editorStaticDisposed||this.editorStaticDrawSetSuspended)return;if(this.editorStaticFullRebuildQueued)return this.editorStaticFullRebuildQueued=!1,void this.rebuildEditorStaticDrawSet();const e=new Set;for(const t of this.editorStaticObjectsToRebuild.values()){const a=this.sceneObjectMap.get(t.id),s=null==a?null:this.editorStaticChunkBySource.get(a);if(null==s){this.editorStaticFullRebuildQueued=!0;break}e.add(s)}if(this.editorStaticObjectsToRebuild.clear(),this.editorStaticFullRebuildQueued)return this.editorStaticFullRebuildQueued=!1,void this.rebuildEditorStaticDrawSet();for(const t of e)this.disposeEditorStaticDrawChunk(t),this.buildEditorStaticDrawChunk(t);this.editorStaticDrawSetUpdated$.next()})))}prepareEditorStaticObjectForMutation(e){const t=this.sceneObjectMap.get(e.id);if(null==t)return;const a=this.editorStaticChunkBySource.get(t);!0===a?.active&&this.disposeEditorStaticDrawChunk(a)}rebuildEditorStaticDrawSet(){if(this.disposeEditorStaticDrawSet(),!this._editorStaticDrawSetsEnabled||!this.inEditor||this.editorStaticDrawSetSuspended||"webgpu"!==this.renderingView?.requestedBackend)return;const e=[];for(const t of this.idToSceneObject.values()){if("asset_mesh"!==t.type||null!=t.latticeDeformation||!0===t.hidden||t.physics?.type===De.dynamic)continue;const a=this.sceneObjectMap.get(t.id);null!=a&&this.canUseEditorStaticDrawSet(a)&&e.push(a)}const t=new g;t.name="Hology WebGPU editor static authored objects",t.visible=!1,t.userData.hologyEditorStaticAuthoredRoot=!0,this.scene.add(t),this.editorStaticAuthoredRoot=t,e.sort((e,t)=>{const a=e.userData?.src,s=t.userData?.src,r="asset_mesh"===a?.type?`${a.assetId}:${JSON.stringify(a.materialAssignments??[])}`:"",i="asset_mesh"===s?.type?`${s.assetId}:${JSON.stringify(s.materialAssignments??[])}`:"";return r.localeCompare(i)});for(let t=0;t<e.length;t+=32){const a={sources:e.slice(t,t+32),sourceVisibility:new Map,sourceUpdateMatrixWorld:new Map,sourceParents:new Map,active:!1};this.editorStaticDrawChunks.push(a);for(const e of a.sources)this.editorStaticChunkBySource.set(e,a);this.buildEditorStaticDrawChunk(a)}this.editorStaticDrawSetUpdated$.next()}buildEditorStaticDrawChunk(e){const t=new g;t.name="Hology WebGPU editor static asset mesh chunk",t.userData.hologyEditorStaticSnapshotRoot=!0,e.sourceVisibility.clear(),e.sourceUpdateMatrixWorld.clear(),e.sourceParents.clear();for(const a of e.sources){if(this.editorStaticEditingObjects.has(a)||this.editorStaticSelectedObjects.has(a)){this.editorStaticSnapshotBySource.delete(a);continue}a.updateWorldMatrix(!0,!0);const s=new g;s.name=a.name;const r=a.userData?.src;for(const e of a.children){const t=e.clone(!0),a=[];t.traverse(e=>{const t=e.userData?.src;(ht(e)||null!=t?.id&&null!=r?.id&&t.id!==r.id)&&a.push(e)});for(const e of a)e.removeFromParent();a.includes(t)||s.add(t)}s.matrix.copy(a.matrixWorld),s.matrix.decompose(s.position,s.quaternion,s.scale),s.matrixAutoUpdate=!1,t.add(s),this.editorStaticSnapshotBySource.set(a,{object:s,chunk:e}),e.sourceVisibility.set(a,a.visible),e.sourceParents.set(a,a.parent),a.visible=!1,this.editorStaticAuthoredRoot?.attach(a),e.sourceUpdateMatrixWorld.set(a,a.updateMatrixWorld),a.updateMatrixWorld=Ma}0!==t.children.length&&(va(t),this.scene.add(t),e.root=t,e.disposer=this.renderingView.registerExperimentalStaticDrawSet(t,`hology-editor-static-asset-meshes-${this.editorStaticDrawChunks.indexOf(e)}`),e.active=!0)}canUseEditorStaticDrawSet(e){let t=!1,a=!0;return e.traverseVisible(e=>{e instanceof S&&!ht(e)&&(t=!0,null!=e.geometry?.index&&null==e.customDepthMaterial&&Pa(e.material)||(a=!1))}),t&&a}disposeEditorStaticDrawSet(){for(const e of this.editorStaticDrawChunks)this.disposeEditorStaticDrawChunk(e);this.editorStaticDrawChunks.length=0,this.dirtyEditorStaticDrawChunks.clear(),this.editorStaticChunkBySource=new WeakMap,this.editorStaticSnapshotBySource=new WeakMap,this.editorStaticAuthoredRoot?.removeFromParent(),this.editorStaticAuthoredRoot=void 0}disposeEditorStaticDrawChunk(e){e.disposer?.(),e.disposer=void 0,e.root?.removeFromParent(),e.root=void 0,e.active=!1;for(const[t,a]of e.sourceParents){const e=t.userData?.src,s=null==e?.id||this.sceneObjectMap.get(e.id)===t;(null!=a&&null==t.parent&&s||null!=a&&t.parent===this.editorStaticAuthoredRoot&&s)&&a.attach(t)}e.sourceParents.clear();for(const[t,a]of e.sourceVisibility)t.visible=a;e.sourceVisibility.clear();for(const[t,a]of e.sourceUpdateMatrixWorld)t.updateMatrixWorld=a;e.sourceUpdateMatrixWorld.clear()}async preloadVisualEffects(e){const t=[],a=new Set;for(const s of e){const e=s.asset;if(a.has(e))continue;a.add(e);let r=this.inEditor?void 0:this.vfxPreloads.get(e);null==r&&(r=this.preloadVisualEffect(s).catch(t=>{throw this.vfxPreloads.get(e)===r&&this.vfxPreloads.delete(e),t}),this.inEditor||this.vfxPreloads.set(e,r)),t.push(r)}await Promise.all(t)}async preloadVisualEffect(e){const t=new Set;!function(e,t){const a=e=>{const s=e.output;switch(s.type){case"sprite":case"stretchedSprite":t.add(s.texture);break;case"trail":null!=s.texture&&t.add(s.texture);break;case"decal":t.add(s.colorMap),t.add(s.alphaMap)}e.children?.forEach(a)};e.vfx.emitters.forEach(a)}(e.asset,t),await Promise.all([this.initVfxTextures(t),(async()=>{const t=await e.create(new I);try{await t.prepareRendering()}finally{t.onEndPlay(),t.disposed.next(!0),t.object.removeFromParent()}})()])}async initVfxTextures(e){const t=await Promise.all(Array.from(e,async e=>{const t=await this.assetsService.getAsset(e);return null==t?null:this.assetManagerService.getTexture(t)}));for(const e of t)null!=e&&this.renderingView.initTexture(e)}async initVfx(){await this.preloadVisualEffects(this.actorInstances.flatMap(e=>Cs(e)))}async initActorsPostInit(e=Array.from(this.materializedActors.entries())){const t=e.map(async([e,t])=>{if(t.__isInitialised)return;const a=t.object.userData.src??t.object.userData._src;if("vfx"===a.type)return Promise.resolve();const s="prefab"===a.type?await this.assetsService.getAsset(a.assetId):null,r=e.split("/"),i=r.slice(0,-1),n=i.join("/"),o=(r[r.length-1],new Map);for(const[e,t]of this.materializedActors)if(o.set(e,t),0===n.length)e.includes("/")||o.set(e,t);else if(e.startsWith(n+"/")){const a=e.slice(n.length+1);a.includes("/")||o.set(a,t)}const l={...s?.actor?.params??{},...a.actor?.params??{}},c=[...a.actor?.innerParams??[]];for(let t=i.length-1;t>=0;t--){const a=i.slice(0,t+1).join("/"),s=this.idToSceneObject.get(a);if("prefab"===s?.type&&null!=s.prefab){const i=await this.assetsService.getAsset(s.assetId);if(null!=i){let n=!1,o=a+"/"+i.prefab?.mainActorId;for(;null!=o;){if(o===e){n=!0;break}o=this.prefabInstanceExposedActorMap.get(o)}if(n&&null!=s.prefab.params&&Object.assign(l,Fa(s.prefab.params)),null!=s.prefab.innerParams){const e=r.slice(t+1);for(const t of s.prefab.innerParams){const a=Fa(t.params);0!==Object.keys(a).length&&(n?c.push({path:Ra(t.path,e)?t.path.slice(e.length):t.path,params:a}):Ra(t.path,e)&&c.push({path:t.path.slice(e.length),params:a}))}}}}}this.rememberLivePrefabActorSettings(e,{...a.actor,params:l,innerParams:c});for(const e of c)await this.applyActorComponentParams(t,e.path.slice(),e.params,o);await this.attachEditorComponents(t,a,o);const u=await prepareClassParameters(l,t.constructor,this.assetsService,this.assetManagerService,o,this.renderingView,this.shaders,this.actorProvider,e=>{const t=n.length>0?n+"/"+e:e;return this.prefabInstanceExposedActorMap.has(t)?this.persistenceActorPath(t):null},t);Object.assign(t,u);try{return await this.actorProvider.initActor(t)}catch(e){console.error(`Failed to initiate actor (name="${a.name}", id=${a.id})`,e)}});return Promise.all(t)}async attachEditorComponents(e,t,a){const s=t.actor?.components??[],r=new Array(s.length).fill(null);this.editorAttachedActorComponents.set(e,r);for(const[i,n]of s.entries()){const s=this.componentTypes.find(e=>e.name===n.type);if(null==s){console.warn(`Component type '${n.type}' not found for actor ${t.id}`);continue}const o=e.attach(s.type);if(r[i]=o,null!=n.params){const e=await prepareClassParameters(n.params,null,this.assetsService,this.assetManagerService,a,this.renderingView,this.shaders,this.actorProvider,e=>this.prefabInstanceExposedActorMap.get(e)??null,o);Object.assign(o,e)}for(const e of n.innerParams??[])await this.applyActorComponentParams(o,e.path.slice(),e.params,a)}}addVfxChildActors(e,t=e){}async applyActorComponentParams(e,t,a,s){const r=t.length,i=t.shift();if(0==r){const t=await prepareClassParameters(a,null,this.assetsService,this.assetManagerService,s,this.renderingView,this.shaders,this.actorProvider,e=>this.prefabInstanceExposedActorMap.get(e)??null,e);for(const[a,s]of Object.entries(t))null!=s&&(e[a]=s)}else null!=e[i]&&await this.applyActorComponentParams(e[i],t,a,s)}previewLatticeDeformation(e,t){this.latticeGeometries.apply(e,t,JSON.stringify(e.userData.src?.vertexMaterials??[]))}canObjectBeInstanced(e){return null==e.latticeDeformation&&e.physics?.type!==De.dynamic&&"sky"!==e.type&&"global_fog"!==e.type&&"world_env"!==e.type}async canAssetBeInstanced(e){let t=this._canBeInstancedCache.get(e.assetId);if(null==t){const a=await this.createFromAsset(e);if(null==a)return!1;const s=[];a.traverse(e=>{!ht(e)&&e.isMesh&&s.push(e)});const r=1==s.length&&0==s[0].children.length,i=!ua,n=s.every(e=>!Array.isArray(e.material)||1===e.material.length),o=s.some(e=>e instanceof S&&null!=e.geometry.morphAttributes&&Object.keys(e.geometry.morphAttributes).length>0),l=!0;t=s.length>0&&(r||n&&i)&&l&&!o,this._canBeInstancedCache.set(e.assetId,t)}return t}async preInit(){this.renderingView?.onLoop(()=>{null!=this.sky&&this.renderingView.camera.getWorldPosition(this.sky.position)}),await this.preloadAssets()}async preloadAssets(){const e=await this.assetsService.getAssets();for(const t of e)this.assets.set(t.id,t)}shouldBeMaterialized(e){if(!1===e.enabled)return!1;if(null!=this.detailTier&&"asset_mesh"===e.type&&null!=e.assetId){const t=this.assets.get(e.assetId);if(null!=t){const e=t.mesh?.detailTier;if(null!=e)return e<=this.detailTier}}return!0}async initWithInstancing(){this.sceneSettingsActive=!0,await this.preInit(),await this.prefetchAssets(),this.experimentalStaticDrawSetDisposer?.(),this.experimentalStaticDrawSetDisposer=void 0,pa.clear(),fa.clear();const e=[],t=new et,a=new et,s=new et;let r=0,i=0,n=0;const o=new Map,l=new tt(()=>new Map),u="webgpu"===this.renderingView?.requestedBackend?new g:null,d=null!=u?new g:null;null!=u&&(u.name="Hology WebGPU static scene objects",d.name="Hology WebGPU unsorted late static scene objects");const f=(e,t)=>{if(null!=u&&function(e){return e.visible&&null!=e.geometry.index&&null==e.customDepthMaterial&&Pa(e.material,!0)}(t)){((Array.isArray(t.material)?t.material:[t.material]).some(e=>e.transparent||Ia(e))?d:u).add(e)}else this.scene.add(e)};for(const c of this.dataProvider.getObjects())await ka(c,async(c,u,d)=>{if(!this.shouldBeMaterialized(c))return;const p="asset_mesh"==c.type&&this.canObjectBeInstanced(c)&&await this.canAssetBeInstanced(c),f="shape_mesh"===c.type&&"landscape"!==c.shape&&c.physics?.type!==De.dynamic;if(p||f){if(u&&u.children?.length>0){const e=u.children.findIndex(e=>e.id===c.id);e>=0&&u.children.splice(e,1)}if(f){let e=c.shape+JSON.stringify(c.shapeParams??{})+c.castShadow+c.receiveShadow;const t=c.materialAssignments?.at(0)?.materialId,a=null!=t?this.assets.get(t):null;let r=null;if(!1&&null!=a&&"shader"!==a.material.type){if(e+=a.material.type+a.material.shader,null!=a.material.shaderParams){if(e+=Object.entries(a.material.shaderParams).filter(([e,t])=>"color"!=e).map(e=>JSON.stringify(e)).join(),null!=a.material.shaderParams.color){const e=a.material.shaderParams.color;e.type===jt.Color&&null!=e.value&&(r=new h(e.value))}}e+=a.material.outlines,null!=a.material.outlineParams&&(e+=JSON.stringify(a.material.outlineParams)),e+=a.material.reflective,e+=a.material.bloom,e+=a.material.side,e+=a.material.side,e+=a.material.transparent,e+=a.material.alphaTest}else e+=t;s.push(e,{object:{...c,parentTransform:d},color:r}),n++}else{const e=this.assets.get(c.assetId);null==e&&console.log("Can't find asset with id "+c.assetId);let s=o.get(c.assetId);if(null==s){const e=await this.createFromAsset(c,{assignMaterials:!1});if(null==e)return;if(s=o.get(c.assetId),null==s){s={useBatchedMesh:null!=nt(e)&&Zt(e,e=>!(e instanceof S)||this.testCanBatch(e.material,e.geometry)),assetMesh:e},o.set(c.assetId,s)}}const n=Ga(c.materialAssignments,e.materialAssignments);if(s.useBatchedMesh)await lt(s.assetMesh,async t=>{if(!(t instanceof S))return;const s=Array.isArray(t.material)?t.material[0]:t.material,i=await this.resolveMaterialForAssignments(s,n,e);if(null!=i){Ve(i,!1),l.get(c.id).set(t.uuid,i);let s=as(t,i);if(s+=us(i),"webgpu"===this.renderingView?.requestedBackend){const t=c.castShadow??e.castShadow??!1,a=c.receiveShadow??e.receiveShadow??!1;s+=`|detailCulling:${JSON.stringify(c.detailCulling??null)}`,s+=`|castShadow:${t?1:0}|receiveShadow:${a?1:0}`}a.push(s,{...c,parentTransform:d,meshUUID:t.uuid}),r++}else console.warn("Can not materialize mesh because missing material",c)});else{const e=c.assetId+JSON.stringify(c.materialAssignments??[]);t.push(e,{...c,parentTransform:d}),i++}}}else null==u&&e.push({...c,parentTransform:d})});console.log(`Scene init stats: \n Batched Assets: ${a.size} groups containing in total ${r} objects.\n Instanced Assets: ${t.size} groups containing in total ${i} objects.\n Shapes: ${s.size} batch groups containing in total ${n} objects. \n ${e.length} objects can not be batched. \n `),console.time("materialize batches");for(const[e,t]of a.entries()){if(0==t.length)continue;let e;o.get(t[0].assetId).assetMesh;e=this.createBatchedMesh(t,l,o);const a=this.assets.get(t[0].assetId);"webgl"===this.renderingView?.activeBackend?(e instanceof Yt&&e.perInstanceCastShadow||(e.castShadow=Ys(t,a?.castShadow??!1)),e.receiveShadow=Qs(t,a?.receiveShadow??!1)):(e.castShadow=t[0].castShadow??a?.castShadow??!1,e.receiveShadow=t[0].receiveShadow??a?.receiveShadow??!1);const s=new ct;s.add(e),s.userData.src=t[0],s.userData.detailCulling=t[0].detailCulling,s.castShadow=!1,s.receiveShadow=!1,f(s,e)}for(const e of t.values()){if(0==e.length)continue;let t;const a=o.get(e[0].assetId).assetMesh;t=await this.createInstancedMesh(e,a);const s=this.assets.get(e[0].assetId);t.castShadow=Ys(e,s?.castShadow??!1),t.receiveShadow=Qs(e,s?.receiveShadow??!1);const r=new ct;r.add(t),r.userData.src=e[0],r.userData.detailCulling=e[0].detailCulling,a instanceof ct&&(r.collisionShapes=a.collisionShapes),this.prepareCollisionShapesForInstanced(r),r.castShadow=!1,r.receiveShadow=!1,f(r,t)}console.timeEnd("materialize batches");for(const e of s.values()){if(0==e.length)continue;const t=e[0].object,a=await this.createFromShape(t),s=ot(a,e=>!ht(e)&&null!=e.geometry),r=Za(s.material);null!=e[0].color&&null!=r.color&&(r.color=new h(16777215));const i=null==s.geometry.index?Xt.mergeVertices(s.geometry):s.geometry;let n,o;!(ua||r instanceof q)?(n=new c.BatchedMesh(e.length,i.getAttribute("position").count,i.index.count,r),n.perObjectFrustumCulled=!0,o=n.addGeometry(i)):n=new c.InstancedMesh(i,r,e.length),n.castShadow=a.castShadow??!0,n.receiveShadow=s.receiveShadow??!1;for(let t=0;t<e.length;t++){const a=e[t],s=(new c.Matrix4).compose((new O).fromArray(a.object.position),(new P).setFromEuler((new p).fromArray(a.object.rotation)),(new O).fromArray(a.object.scale)),r=(new w).copy(a.object.parentTransform).multiply(s);let i;i=n instanceof c.BatchedMesh?n.addInstance(o):t,n.setMatrixAt(i,r),a.color}for(let t=0;t<e.length;t++){const s=e[t],r=new ct;r.userData.src=e[0],r.userData.detailCulling=e[0].object.detailCulling,a instanceof ft&&(r.collisionShapes=[a.collisionShape]),r.castShadow=!0,r.receiveShadow=!0,f(r,n),r.add(n),null==n.userData.hasCollision&&(n.userData.hasCollision=[]),n.userData.hasCollision[t]=!1!==s.object.collisionDetection}}if(null!=u&&u.children.length>0&&(va(u),this.scene.add(u),this.experimentalStaticDrawSetDisposer=this.renderingView.registerExperimentalStaticDrawSet(u,"hology-materialized-static-scene")),null!=d&&d.children.length>0){va(d),this.scene.add(d);const e=this.experimentalStaticDrawSetDisposer,t=this.renderingView.registerExperimentalStaticDrawSet(d,"hology-materialized-unsorted-late-static-scene",!0);this.experimentalStaticDrawSetDisposer=()=>{e?.(),t()}}await Promise.all(e.map(e=>this.materialize(e))),await this.initActorsPostInit(),this.announcePrefabEventGraphs(),await this.initVfx(),this.generateOcclusionClusters(),await this.refreshPaintedScatterPresence(!0),await this.refreshSurfaceScatterPresence(!0),"webgpu"===this.renderingView.requestedBackend&&await this.texturePrefetch}generateOcclusionClusters(){const e=new $t;e.initScene(this.scene),e.clusters.forEach(e=>{this.renderingView.addCluster(e)})}prepareCollisionShapesForInstanced(e){e instanceof ct&&e.collisionShapes.forEach(e=>{e instanceof i&&e.mesh instanceof S&&(e.mesh=e.mesh.geometry)})}setScene(e){this.scene=e}testCanBatch(e,t){return!ua&&(!Array.isArray(e)||1==e.length)&&this.testCanBatchMaterial(e)}testCanBatchMaterial(e){return null!=(Array.isArray(e)?e[0]:e)}createBatchedMesh(e,t,a){const s=new et;for(const t of e)null!=t.meshUUID?s.push(t.meshUUID??t.assetId,t):console.warn("Missing mesh uuid for batching");let r=0,i=0,n=0;const o=new Map;for(const[e,t]of s.entries()){const s=t[0].assetId,l=a.get(s);if(null==l){console.warn("Missing batching info for asset id "+s);continue}const c=ot(l.assetMesh,t=>t instanceof S&&t.uuid===e);if(null==c){console.warn("Missing mesh in batched asset");continue}o.set(e,c);const u=c.geometry.getAttribute("position");null==u&&console.warn("Missing position attribute for batched mesh"),r+=c.geometry.index.count*t.length,i+=u.count*t.length,n+=t.length}const l=["color","map","roughness","roughnessMap","metalness","metalnessMap","opacity","alphaMap","aoMap","aoMapIntensity","normalMap","normalScale","emissive","emissiveIntensity","emissiveMap"],u=new Map,d=new Map,p=[];let f=new c.MeshStandardMaterial({color:"white"});const m=t.get(e[0].id).get(e[0].meshUUID);if(null==m)throw"missing source material";if(m instanceof M&&!(m instanceof c.MeshPhysicalMaterial)){const a=new Set,s=new Map;for(const r of e){const e=t.get(r.id).get(r.meshUUID);if(null==e)throw"missing mat";for(const t of l){let r=e[t];r instanceof c.CompressedArrayTexture&&null!=r.userData.index&&(r=r.userData.index);const i=s.get(t);void 0===i||Ds(r,i)?s.set(t,r):a.add(t)}}for(const e of a){let t;const a=m[e];let s=e;if("number"==typeof a){let a=p.find(e=>e.params.length<4);if(null==a){const t="vp"+p.length;a={name:t,params:[e],node:N(t)},p.push(a)}else a.params.push(e);s=a.name,t=Ps(a.node,a.params.length-1)}else if(a instanceof E)t=N(s);else if(a instanceof O||a instanceof h)t=V(s);else if(a instanceof C)t=B(s);else if(a instanceof c.CompressedArrayTexture)s=e+"_i",t=T(s);else if(a instanceof D)continue;u.set(e,t),d.set(e,s)}let r=le.uv;m instanceof Qt&&null!=m.heightMap&&(r=Ht(r,K(m.heightMap),R(m.heightScale)));let i=Ms(u.get("opacity"),_)??R(m.opacity??1);if(null!=m.alphaMap){let e;if(m.alphaMap instanceof c.CompressedArrayTexture){const t=ee(m.alphaMap),a=Ms(u.get("alphaMap"),_)??R(m.alphaMap.userData.index??0);e=t.sample(he(r.x,r.y,a))}else e=K(m.alphaMap).sample(r);i=i.multiply(e.r)}let n=Y(Ms(u.get("color"),pe)??m.color,i);if(null!=m.map){let e;if(m.map instanceof c.CompressedArrayTexture){const t=ee(m.map),a=Ms(u.get("map"),_)??R(m.map.userData.index??0);e=t.sample(he(r.x,r.y,a))}else e=K(m.map).sample(sa(r,m.map));n=n.multiply(e),i=i.multiply(e.a)}m.vertexColors&&(n=n.multiply(fe(oe(k.color.rgb),1)));let o=Y(Ms(u.get("emissive"),pe)??m.emissive,i);if(null!=m.emissiveMap){let e;if(m.emissiveMap instanceof c.CompressedArrayTexture){const t=ee(m.emissiveMap),a=Ms(u.get("emissiveMap"),_)??R(m.emissiveMap.userData.index??0);e=t.sample(he(r.x,r.y,a))}else e=K(m.emissiveMap).sample(sa(r,m.emissiveMap));o=o.multiply(e)}const g=Ms(u.get("emissiveIntensity"),_)??R(m.emissiveIntensity??1),y=Ms(u.get("normalScale"),de)??ue(m.normalScale??new C(1,1));let w=ce.normal;if(null!=m.normalMap){let e;if(m.normalMap instanceof c.CompressedArrayTexture){const t=ee(m.normalMap),a=Ms(u.get("normalMap"),_)??R(m.normalMap.userData.index??0);e=t.sample(he(r.x,r.y,a))}else e=K(m.normalMap).sample(sa(r,m.normalMap));w=F(e.rgb,y.x)}let S=Ms(u.get("roughness"),_)??R(m.roughness??1);if(null!=m.roughnessMap){let e;if(m.roughnessMap instanceof c.CompressedArrayTexture){const t=ee(m.roughnessMap),a=Ms(u.get("roughnessMap"),_)??R(m.roughnessMap.userData.index??0);e=t.sample(he(r.x,r.y,a))}else e=K(m.roughnessMap).sample(sa(r,m.roughnessMap));S=S.multiply(e.g)}let b=Ms(u.get("metalness"),_)??R(m.metalness??0);if(null!=m.metalnessMap){let e;if(m.metalnessMap instanceof c.CompressedArrayTexture){const t=ee(m.metalnessMap),a=Ms(u.get("metalnessMap"),_)??R(m.metalnessMap.userData.index??0);e=t.sample(he(r.x,r.y,a))}else e=K(m.metalnessMap).sample(sa(r,m.metalnessMap));b=b.multiply(e.b)}let v=R(1);if(null!=m.aoMap){let e;if(m.aoMap instanceof c.CompressedArrayTexture){const t=ee(m.aoMap),a=Ms(u.get("aoMap"),_)??R(m.aoMap.userData.index??0);e=t.sample(he(r.x,r.y,a))}else e=K(m.aoMap).sample(sa(r,m.aoMap));v=v.multiply(e.r)}const M=Ms(u.get("aoMapIntensity"),_)??R(m.aoMapIntensity??0);let A=w;!0!==m.userData.disableAO&&(A=G("DOUBLE_SIDED",A,e=>H(new $("gl_FrontFacing"),e,e.multiplyScalar(-1))));const x=new q({color:Z({color:n,roughness:S,metalness:b,ambientOcclusion:v,ambientOcclusionIntensity:M,emissive:o,emissiveIntensity:g,normal:A}),normal:w,roughness:S,emissive:o.rgb,transparent:m.transparent,alphaTest:m.alphaTest,envMap:m.envMap,opacity:i});null!=m.envMap&&(x.uniforms.envMapIntensity={value:m.envMapIntensity},x.uniforms.envMapRotation={value:js(m.envMapRotation,m.envMap)}),x.envMap=m.envMap,x.side=m.side,f=x}else if(m instanceof q){const a=new Set,s=new Map,r=Object.keys(m.uniforms).filter(e=>!ps(e));for(const i of e){const e=t.get(i.id).get(i.meshUUID);if(!(e instanceof q))throw new Error("Expected NodeShaderMaterial in node material batch");for(const t of r){const r=e.uniforms[t]?.value,i=s.get(t);void 0===i||Ds(r,i)?s.set(t,r):ms(r)&&ms(i)&&gs(r)===gs(i)&&a.add(t)}}const i=new Set(Object.keys(m.uniforms)),n={};for(const e of a){let t,a;const s=m.uniforms[e]?.value;if("number"==typeof s){let s=p.find(e=>e.params.length<4);if(null==s){const t=ys("vp"+p.length,i);s={name:t,params:[e],node:N(t)},p.push(s)}else s.params.push(e);a=s.name,t=Ps(s.node,s.params.length-1)}else if(s instanceof E)a=ys(e,i),t=N(a);else if(s instanceof O||s instanceof h)a=ys(e,i),t=V(a);else{if(!(s instanceof C))continue;a=ys(e,i),t=B(a)}u.set(e,t),d.set(e,a),n[e]=t}if(0===u.size)f=m;else{const e=W(m,{color:m.outputColor,transform:m.outputTransform??null,position:null==m.outputTransform?m.outputPosition:void 0,normal:m.outputNormal??null,roughness:m.outputRoughness??null,opacity:m.outputOpacity??null,emissive:m.outputEmissive??null,uniforms:ws(m,new Set(u.keys())),uniformNodes:n});e.uniformNodes=n,g=m,(y=e).name=g.name,y.side=g.side,y.blending=g.blending,y.depthWrite=g.depthWrite,y.depthTest=g.depthTest,y.colorWrite=g.colorWrite,y.toneMapped=g.toneMapped,y.visible=g.visible,y.opacity=g.opacity,y.forceSinglePass=g.forceSinglePass,y.premultipliedAlpha=g.premultipliedAlpha,y.polygonOffset=g.polygonOffset,y.polygonOffsetFactor=g.polygonOffsetFactor,y.polygonOffsetUnits=g.polygonOffsetUnits,y.shadowSide=g.shadowSide,Object.assign(y.defines,g.defines),Object.assign(y.userData,g.userData),y.needsUpdate=!0,f=e}}else{f=m;for(const a of e){const e=t.get(a.id).get(a.meshUUID);if(e!=f){console.error(`Different materials in group for object ${a.id} and mesh uuid ${a.meshUUID}`,{objectMaterial:e,sourceMaterial:m});break}}}var g,y;const w=new Yt(n,i,r,f);for(const e of p)w.initUniform(e.name,4);for(const[e,t]of u.entries()){if(p.some(t=>t.params.includes(e)))continue;let a=1;t instanceof me||t instanceof pe?a=4:t instanceof de&&(a=2),w.initUniform(d.get(e)??e,a,0)}for(const[e,r]of s.entries()){const s=r[0].assetId,i=o.get(e);if(null==i){console.error(`Missing single asset mesh for mesh uuid ${e} and asset id ${s}`);continue}if(null==i.geometry){console.error("Missing geometry on mesh mesh");continue}const n=w.addGeometry(ss(i.geometry,m)),l=this.assets.get(s),f=a.get(s);if(null==f){console.warn("Missing batching info when configuring for asset id "+s);continue}const g=nt(f.assetMesh)?.uuid===e,y=f.assetMesh instanceof ct&&g?f.assetMesh.collisionShapes:void 0,S=this.configureBatchedInstancedMesh(r,w,i,n,y);for(let e=0;e<S.length;e++){const a=r[e],s=S[e];"webgpu"!==this.renderingView?.requestedBackend&&w.setCastShadowAt(s,a.castShadow??l?.castShadow??!1);const i=t.get(a.id).get(a.meshUUID),n=i.userData.surface;null!=n&&(w.surfaceByInstance[s]=n);for(const e of p){let t=Is.set(0,0,0,0);for(let a=0;a<e.params.length;a++){const s=fs(i,e.params[a]);"number"==typeof s&&t.setComponent(a,s)}w.setUniformAt(e.name,s,t)}for(let e of u.keys()){if(p.some(t=>t.params.includes(e)))continue;const t=d.get(e)??e;let a=fs(i,e);if(a instanceof h&&(a=new O(a.r,a.g,a.b)),a instanceof c.CompressedArrayTexture)a=a.userData.index??0;else if(a instanceof D||null==a)continue;w.setUniformAt(t,s,a)}}}return w}async createInstancedMesh(e,t){const a=ot(t,e=>!ht(e)&&null!=e.geometry),s=await this.assetsService.getAsset(e[0].assetId);await this.applyMaterials(t,Ga(e[0].materialAssignments,s.materialAssignments),s),a.updateMatrix();const r=a.geometry.clone(),i=a.material;let n;if(n=new c.InstancedMesh(r,i,e.length),this.configureBatchedInstancedMesh(e,n,a),a.material instanceof y&&n.castShadow&&n.receiveShadow&&Array.isArray(i))for(const e of i);return n}configureBatchedInstancedMesh(e,t,a,s,r){const i=[];a.updateWorldMatrix(!0,!0);for(let n=0;n<e.length;n++){let o=n;t instanceof c.BatchedMesh&&(o=t.addInstance(s)),i.push(o);const l=(new c.Matrix4).compose((new O).fromArray(e[n].position),(new P).setFromEuler((new p).fromArray(e[n].rotation)),(new O).fromArray(e[n].scale)),u=(new w).copy(e[n].parentTransform).multiply(l),d=(new w).copy(u).multiply(a.matrixWorld);t.setMatrixAt(o,d),null==t.userData.hasCollision&&(t.userData.hasCollision=[]);const h=this.assets.get(e[n].assetId);t.userData.hasCollision[o]=!1!==e[n].collisionDetection||!1!==h?.collisionDetection,null!=r&&(null==t.userData.collisionShapes&&(t.userData.collisionShapes=[]),t.userData.collisionShapes[o]=r,null==t.userData.collisionMatrices&&(t.userData.collisionMatrices=[]),t.userData.collisionMatrices[o]=u)}return i}remove(e){if(console.log("Remove scene object",e),"global_fog"==e.type)return void(this.scene.fog=this.originalFog);if("world_env"===e.type)this.resetWorldEnv(),this.worldEnvObj=null;else if("actor"==e.type||"vfx"===e.type){const t=this.materializedActors.get(e.id);null!=t?(t.disposed.next(!0),t.onEndPlay()):console.warn("Failed to remove actor",e)}else if("prefab"===e.type){this.unregisterLivePrefabInstance(e.id);const t=new Set(this.removePrefabEventGraphs(e.id).flatMap(e=>e.actors));this.materializedActors.forEach((a,s)=>{(s===e.id||s.startsWith(e.id+"/"))&&(t.has(a)||(a.disposed.next(!0),a.onEndPlay()),this.materializedActors.delete(s))})}const t=this.sceneObjectMap.get(e.id);t&&this.latticeGeometries.release(t),t?.parent.remove(t),this.sceneObjectMap.delete(e.id),this.components.filter(t=>t.object.userData.src?.id===e.id).forEach(e=>this.components.splice(this.components.indexOf(e,1))),this.landscapeManagers.filter(t=>t.source.id===e.id).forEach(e=>{e.clear(),e.stop(),this.landscapeManagers.splice(this.landscapeManagers.indexOf(e,1))}),this.removed$.next({object:t,source:e})}deleteSceneObject(e){const t=this.sceneObjectMap.get(e.id);if(this.scene.remove(t),"landscape"==e.type){const t=this.landscapeManagers.findIndex(t=>t.source.id===e.id);if(t>-1){const e=this.landscapeManagers.splice(t,1)[0];e.clear(),e.stop()}}}findByAssetId(e){return it(this.scene,t=>t.userData.src?.assetId==e,e=>null!=e.userData.src)}applyMaterials(e,t,a){return null==t?Promise.resolve([]):Promise.all(t.filter(e=>"null"!==e.materialId).map(t=>this.applyMaterial(e,t,a)))}async applyMaterial(e,t,a){await applyMaterial(e,t,async e=>{const t=await this.getAsset(e);if(null!=t)try{return materialFromAsset(t,this.renderingView,this.assetsService,this.assetManagerService,this.shaders)}catch(e){console.error("Failed to apply material",e)}else console.warn("Missing material with id "+e)},this._originalMaterials,{textureFlipY:getConvertedFbxToGlbAssignedMaterialTextureFlipY(a)})}async resolveMaterialForAssignments(e,t,a){let s=e,r=null,i=null;const n=getConvertedFbxToGlbAssignedMaterialTextureFlipY(a);for(const e of t??[]){if(!Ya(s,e,r,i))continue;const t=await this.getAsset(e.materialId);if(null==t){console.warn("Missing material with id "+e.materialId);continue}let a=await materialFromAsset(t,this.renderingView,this.assetsService,this.assetManagerService,this.shaders,!0);null!=a&&(a=Ha(a,n)),null!=a&&s.id!==a.id&&(r=r??Ja(s),i=i??s.name,s=a);break}return s}unapplyMaterials(e){e.traverse(async e=>{if(e instanceof S)if(e.material instanceof Array)for(let t=0;t<e.material.length;t++)e.material[t]=this._originalMaterials.get(e.id+"#"+t)??e.material[t];else e.material=this._originalMaterials.get(e.id)??e.material})}updateActors(e){this.navigationRevision++;const t=new Map(this.actorTypes.map(e=>[e.name,e.type])),a=new Map(e.map(e=>[e.name,e.type])),s=new Set;for(const e of new Set([...t.keys(),...a.keys()]))(t.get(e)??Pe[e])!==(a.get(e)??Pe[e])&&s.add(e);this.actorTypes=e,0!==s.size&&it(this.scene,e=>e.userData.src?.id&&"actor"===e.userData.src.type&&this.materializedActors.has(e.userData.src?.id)&&s.has(e.userData.src.actor.type)).forEach(async e=>{this.remove(e.userData.src),await this.materializeAndInitActor(e.userData.src)})}updateComponents(e){this.componentTypes=e,it(this.scene,e=>e.userData.src?.id&&"actor"===e.userData.src.type&&this.materializedActors.has(e.userData.src?.id)&&(e.userData.src.actor?.components?.length??0)>0).forEach(async e=>{this.remove(e.userData.src),await this.materializeAndInitActor(e.userData.src)})}updateShaders(e){this.shaders=e;for(const[e,t]of pa.entries())t.userData.customShaderName&&pa.delete(e);fa.clear(),this.landscapeManagers.forEach(t=>t.updateShaders(e)),it(this.scene,e=>!0).forEach(e=>{e.traverse(async e=>{if(e instanceof S)if(Array.isArray(e.material))for(let t=0;t<e.material.length;t++){const a=e.material[t].userData?.customShaderName;if(null!=a){const a=e.material[t].userData.assetId,s=await this.getAsset(a);null!=s&&this.refreshMaterial(e,e.material[t],s,t)}}else{const t=e.material.userData?.customShaderName;if(null!=t){const t=e.material.userData.assetId,a=await this.getAsset(t);null!=a&&this.refreshMaterial(e,e.material,a)}}})})}async update(e){if("sky"===e.type&&null!=this.sky&&null!=this.sky.parent)return void this.updateSky(e);if("world_env"===e.type&&null!=this.worldEnvObj)return void this.updateWorldEnv(e);const t=this.sceneObjectMap.get(e.id);if(t){let i=!1;if(t.traverseAncestors(e=>{"_hology_transform_group"===e.name&&(i=!0)}),!i){const a=this.findParent(e);null!=a&&a.uuid!=t.uuid?a.attach(t):console.error("Parent is wrong")}if(!("shape_mesh"!==e.type&&"asset_mesh"!==e.type||null==e.renderOrder&&0===t.renderOrder||e.renderOrder===t.renderOrder))return void(t.renderOrder=e.renderOrder??0);if("prefab"!==e.type&&"group"!==e.type){this.unapplyMaterials(t);this.inEditor&&e.hidden&&!1?t.traverse(e=>{e instanceof S&&(e.material.wireframe=!0)}):t.traverse(e=>{e instanceof S&&(e.material.wireframe=!1)})}if("asset_mesh"===e.type&&t.userData.assetId!==e.assetId){this.remove(e);const t=await this.materializeAndInitActor(e);return void this.updated$.next({object:t,source:e})}if("asset_mesh"===e.type&&this.latticeGeometries.apply(t,e.latticeDeformation,JSON.stringify(e.vertexMaterials??[])),"asset_mesh"===e.type){const a=this.assets.get(e.assetId);Ga(e.materialAssignments,a.materialAssignments).forEach(e=>this.applyMaterial(t,e,a))}else"shape_mesh"===e.type&&this.applyMaterials(t,e.materialAssignments);if(i||(null!=e.position&&t.position.fromArray(e.position),null!=e.scale&&t.scale.fromArray(e.scale),null!=e.rotation&&t.rotation.fromArray(e.rotation),this.inEditor&&("asset_mesh"===e.type||"shape_mesh"===e.type&&"landscape"!==e.shape)&&e.physics?.type!==De.dynamic?xa(t,!1):this.inEditor&&function(e){let t=!1;if(e.traverse(e=>{Aa.has(e)&&(t=!0)}),!t)return;e.updateWorldMatrix(!0,!0),e.traverse(e=>{Aa.has(e)&&(e.matrixWorldNeedsUpdate=!1)})}(t)),this.applyVertexMaterials(e,t),"light"==e.type){if("point"==e.light.type){const a=t;a.color=new h(e.light.point.color),a.intensity=e.light.point.intensity,a.decay=e.light.point.decay,a.castShadow=e.light.point.castShadow,a.distance=Math.max(e.light.point.distance,0),a.userData.volumetricIntensity=e.light.point.volumetricIntensity}else if("spot"==e.light.type){const a=t;a.color=new h(e.light.spot.color),a.intensity=e.light.spot.intensity,a.decay=e.light.spot.decay,a.angle=e.light.spot.angle,a.penumbra=e.light.spot.penumbra,a.castShadow=e.light.spot.castShadow,a.distance=Math.max(e.light.spot.distance,0),a.userData.volumetricIntensity=e.light.spot.volumetricIntensity,a.map=await this.loadSpotLightMap(e.light.spot.mapTextureId)}else if("directional"===e.light.type)this.applyDirectionalLight(e.light.directional,e);else if("ambient"===e.light.type)this.applyDirectionalAmbientLight(t,e.light.ambient,e);else if("rectArea"===e.light.type){const a=t;a.color=new h(e.light.rectArea.color),a.intensity=e.light.rectArea.intensity,null!=e.scale&&(a.width=e.scale[0],a.height=e.scale[1]),a.children.forEach(e=>{e instanceof Kt&&e.update()})}}else if("landscape"===e.shape){const a=this.landscapeManagers.find(t=>t.source.id===e.id),i=null==a||(s=a.source.landscape.options,r=e.landscape.options,s.density!==r.density||s.sections.x!==r.sections.x||s.sections.y!==r.sections.y);if(this.inEditor&&i){this.remove(e);const t=await this.materializeAndInitActor(e);return void this.updated$.next({object:t,source:e})}this.applyHeightMaps(t,e.landscape.heightMaps),this.inEditor&&this.landscapeManagers.filter(t=>t.source.id===e.id).forEach(t=>{t.updateSource(e),t.queueRefreshScatter(this.renderingView.camera.position,!0,e=>!0)})}else if("global_fog"===e.type){const t=(this.scene.fog instanceof m?"density":"linear")!==e.fog.type;this.scene.fog=Da(e.fog),t&&(a=this.scene).traverse(e=>{if(e instanceof S){const t=e.material;t instanceof q&&(a.fog instanceof f?(t.uniforms.fogFar.value=a.fog.far,t.uniforms.fogNear.value=a.fog.near):a.fog instanceof m&&(t.uniforms.density={value:a.fog.density}),t.needsUpdate=!0,t.uniformsNeedUpdate=!0)}}),this.fixFogColor()}else if("actor"===e.type){if(this.materializedActors.has(e.id)){const t=this.materializedActors.get(e.id);if(t instanceof Lt){const a=await prepareClassParameters(e.actor.params,null,this.assetsService,this.assetManagerService,this.materializedActors,this.renderingView,[],this.actorProvider,e=>this.prefabInstanceExposedActorMap.get(e)??null,t);return void Object.assign(t,a)}const a=this.editorActorParamSnapshot.get(e.id);if((null==a||a!==JSON.stringify(e.actor))&&!i){if(null!=t&&null!=a&&await this.tryApplyLiveActorParameterUpdate(t,e,a))return void this.updated$.next({object:t.object,source:e});this.remove(e),await this.materializeAndInitActor(e)}}}else if("shape_mesh"===e.type){const a=await this.createMeshByShape(e.shape,t.material,e.shapeParams);t instanceof ft&&(t.geometry=a.geometry,t.collisionShape=a.collisionShape)}if("shape_mesh"===e.type&&"landscape"!==e.shape)ha(t,e.castShadow,e.receiveShadow);else if("asset_mesh"===e.type){const a=this.assets.get(e.assetId);if(null==a)return void console.error("Asset not found",e.assetId);const s=e.receiveShadow??!!a.receiveShadow,r=e.castShadow??!!a.castShadow;ha(t,r,s)}e.name&&e.name.length>0&&(t.name=e.name),this.updated$.next({object:t,source:e})}else{const t=await this.materializeAndInitActor(e);this.updated$.next({object:t,source:e})}var a,s,r;this.renderingView.invalidateShadows()}async materializeAndInitActor(e,t=this.findParent(e)){const a=await this.materialize(e,t),s=Array.from(this.materializedActors.entries()).filter(([t])=>t===e.id||t.startsWith(e.id+"/"));return await this.initActorsPostInit(s),this.announcePrefabEventGraphs(e.id),a}async tryApplyLiveActorParameterUpdate(e,t,a){let s;try{s=JSON.parse(a)}catch{return!1}const r=await this.tryApplyLiveActorSettingsUpdate(e,s,t.actor);return r&&this.editorActorParamSnapshot.set(t.id,JSON.stringify(t.actor)),r}async tryApplyLiveActorSettingsUpdate(e,t,a){const s=await this.applyLiveActorSettingsUpdate(e,t,a);return s.hasChanges&&!s.rejected}async applyLiveActorSettingsUpdate(e,t,a){const s=t?.components??[],r=a?.components??[];if(t?.type!==a?.type||s.length!==r.length||s.some((e,t)=>e.type!==r[t]?.type))return{applied:t,hasChanges:!0,rejected:!0};let i=!1,n=!1;const o=await this.tryApplyLiveParameterUpdate(e,t?.params??{},a?.params??{});!1===o&&(n=!0),i||(i=!0===o);const l=await this.applyLiveInnerParameterUpdates(e,t?.innerParams??[],a?.innerParams??[]);n||(n=l.rejected),i||(i=l.hasChanges);const c=this.editorAttachedActorComponents.get(e),u=[];for(let e=0;e<r.length;e++){const t=s[e],a=r[e];if(JSON.stringify(t)===JSON.stringify(a)){u.push(a);continue}const o=c?.[e];if(null==o){n=!0,u.push(t);continue}const l=await this.tryApplyLiveParameterUpdate(o,t?.params??{},a?.params??{});!1===l&&(n=!0),i||(i=!0===l);const d=await this.applyLiveInnerParameterUpdates(o,t?.innerParams??[],a?.innerParams??[]);n||(n=d.rejected),i||(i=d.hasChanges),u.push({...a,params:!1===l?t?.params:a?.params,innerParams:d.applied})}return{applied:{...a,params:!1===o?t?.params:a?.params,innerParams:l.applied,components:u},hasChanges:i,rejected:n}}async applyLivePrefabParameterUpdate(e,t){if(!this.assetsService.supportsLivePrefabParameters)return!1;const a=this.livePrefabInstances.get(t.id);if(null==a||0===a.size)return!0;const s=Va(e.prefab?.objects??[]),r=Va(t.prefab?.objects??[]);if(s.size!==r.size||[...s.keys()].some(e=>!r.has(e)))return!1;const i=[];await this.applyLiveNestedPrefabOverrideUpdates(e,t,a,i);for(const n of a.values())for(const[a,o]of s){const s=r.get(a),l=n.actorsById.get(a);if(null==s||null==l){i.push(`${n.prefix}/${a}`);continue}const c=n.actorSettingsById.get(a)??za(o,n.source,e.prefab?.mainActorId===a),u=za(o,n.source,e.prefab?.mainActorId===a),d=$a(u,za(s,n.source,t.prefab?.mainActorId===a),n.desiredActorSettingsById.get(a)??u);if(n.desiredActorSettingsById.set(a,d),JSON.stringify(c)===JSON.stringify(d))continue;const h=await this.applyLiveActorSettingsUpdate(l,c,d);n.actorSettingsById.set(a,h.applied),h.rejected&&i.push(`${n.prefix}/${a}`)}return i.length>0&&console.warn(`Some live parameters for prefab ${t.name??t.id} were not applied. The running instances were preserved: ${i.join(", ")}`),!0}async applyLiveNestedPrefabOverrideUpdates(e,t,a,s){const r=Na(e.prefab?.objects??[]),i=Na(t.prefab?.objects??[]);for(const[e,t]of r){const r=i.get(e);if(null==r||t.assetId!==r.assetId||JSON.stringify(t.prefab)===JSON.stringify(r.prefab))continue;const n=this.assets.get(r.assetId),o=this.livePrefabInstances.get(r.assetId);if("prefab"!==n?.type||null==n.prefab||null==o)continue;const l=Va(n.prefab.objects);for(const i of a.values()){const a=`${i.prefix}/${e}`,c=o.get(a);if(null!=c){for(const[e,i]of l){const o=c.actorsById.get(e);if(null==o){s.push(`${a}/${e}`);continue}const l=za(i,t,n.prefab.mainActorId===e),u=za(i,r,n.prefab.mainActorId===e),d=c.desiredActorSettingsById.get(e)??l,h=$a(l,u,d);c.desiredActorSettingsById.set(e,h);const p=c.actorSettingsById.get(e)??d;if(JSON.stringify(p)!==JSON.stringify(h)){const t=await this.applyLiveActorSettingsUpdate(o,p,h);c.actorSettingsById.set(e,t.applied),t.rejected&&s.push(`${a}/${e}`)}}c.source=r}}}}unregisterLivePrefabInstance(e){if(0!==e.length)for(const[t,a]of this.livePrefabInstances){for(const t of[...a.keys()])(t===e||t.startsWith(e+"/"))&&a.delete(t);0===a.size&&this.livePrefabInstances.delete(t)}}rememberLivePrefabActorSettings(e,t){if(this.assetsService.supportsLivePrefabParameters)for(const a of this.livePrefabInstances.values())for(const s of a.values()){if(!e.startsWith(s.prefix+"/"))continue;const a=e.slice(s.prefix.length+1);s.actorsById.has(a)&&(s.actorSettingsById.set(a,t),s.desiredActorSettingsById.set(a,t))}}async tryApplyLiveParameterUpdate(e,t,a){const s=new Set([...new Set([...Object.keys(t),...Object.keys(a)])].filter(e=>JSON.stringify(t[e])!==JSON.stringify(a[e])));if(0===s.size)return null;const r=await prepareClassParameters(a,null,this.assetsService,this.assetManagerService,this.materializedActors,this.renderingView,this.shaders,this.actorProvider,e=>this.prefabInstanceExposedActorMap.get(e)??null,e);return await e.applySceneParameters(r,s)}async applyLiveInnerParameterUpdates(e,t,a){const s=new Map(t.map(e=>[JSON.stringify(e.path),e])),r=new Map(a.map(e=>[JSON.stringify(e.path),e]));if(s.size!==t.length||r.size!==a.length)return{applied:t,hasChanges:!0,rejected:!0};let i=!1,n=!1;const o=[];for(const t of new Set([...s.keys(),...r.keys()])){const a=s.get(t),l=r.get(t);if(JSON.stringify(a?.params??{})===JSON.stringify(l?.params??{})){null!=l&&o.push(l);continue}const c=l?.path??a?.path,u=this.resolveActorComponent(e,c);if(null==u){n=!0,null!=a&&o.push(a);continue}!0===await this.tryApplyLiveParameterUpdate(u,a?.params??{},l?.params??{})?(null!=l&&o.push(l),i=!0):(n=!0,null!=a&&o.push(a))}return{applied:o,hasChanges:i,rejected:n}}resolveActorComponent(e,t){if(null==t||0===t.length)return null;let a=e;for(const e of t){const t=a[e];if(!(t instanceof Ie))return null;a=t}return a instanceof Ie?a:null}findParent(e){const t=this.dataProvider.getObjects().flatMap(t=>t.id===e.id?null:rt(t,t=>t.children?.some(t=>t.id===e.id),()=>!0))[0];return null==t?this.scene:null!=t?it(this.scene,e=>e.userData?.src?.id===t.id,e=>null!=e.userData?.src)[0]:void 0}fixFogColor(){!0===this.renderingView.options.enableOutlines&&(this.scene.fog.color=new h(this.scene.fog.color))}findMeshWithGeometry(e){let t;return e.traverse(e=>{e instanceof S&&e.geometry&&(t=e)}),t}applyVertexMaterials(e,t){if(null==e.vertexMaterials||0===e.vertexMaterials.length)return;let a=1;for(const t of e.vertexMaterials)a=Math.max(t.w.length,a);const s=at(e.vertexMaterials,e=>e.m);t.traverse(e=>{if(e instanceof S){if(null==e.geometry)return;if(ts(vt(e,0,!1)),a>0){ts(vt(e,0,!1))}}});const r=new Set;for(const[e,i]of s.entries()){const s=null!=e?t.getObjectByName(e):this.findMeshWithGeometry(t);let n=!1;if(null==s||null==s.geometry)return void console.warn(`Failed to apply vertex materials on mesh with name "${e}"`);const o=vt(s,0,!0);ts(o);for(const e of i)o.setX(e.i,e.w[0]??0),o.setY(e.i,e.w[1]??0),o.setZ(e.i,e.w[2]??0),o.setW(e.i,e.w[3]??0),n=!0;if(a>0){const e=vt(s,4,!0);ts(e);for(const t of i)e.setX(t.i,t.w[4]??0),e.setY(t.i,t.w[5]??0),e.setZ(t.i,t.w[6]??0),e.setW(t.i,t.w[7]??0),e.needsUpdate=!0,n=!0}n&&r.add(e)}this.inEditor&&this.landscapeManagers.filter(t=>t.source.id===e.id).forEach(e=>e.queueRefreshScatter(this.renderingView.camera.position,!0,e=>r.has(e.name)))}async materialize(e,t,a=!1,s){const r=this.getNestedActorId(e.id,s);if(null!=this.persistence&&!0!==s?.runtimeSpawn){if(this.isPersistenceRemoved(r))return;if("actor"===e.type){const e=this.persistence.resolve({sceneId:this.persistenceSceneId,path:r});if(null!=e)return void this.materializedActors.set(r,e)}}if(this.idToSceneObject.set(r,e),!this.shouldBeMaterialized(e))return;let i,n;switch(e.type){case"asset_mesh":i=await this.createFromAsset(e),e.latticeDeformation||(i=freezeSkinnedMeshes(i));break;case"shape_mesh":i=await this.createFromShape(e);break;case"light":i=await this.createLight(e);break;case"particles":i=await this.createParticleSystem(e),e.collisionDetection=!1;break;case"global_fog":this.scene.fog=Da(e.fog),this.fixFogColor(),i=new g;break;case"sky":this.sky=Tt(),this.updateSky(e),i=this.sky;break;case"world_env":this.updateWorldEnv(e),i=new g,this.worldEnvObj=i;break;case"actor":({object:i,actor:n}=await this.createFromActor(e,s));break;case"group":case"scatter":i=new g;break;case"prefab":i=await this.createFromPrefab(e,s,t);break;case"vfx":i=await this.createFromVfx(e,s);break;default:console.warn(`Failed to materialize object. Unknown type '${e.type}'. This might be because the hology/core library is not compatible with the editor version or because of an error in the scene data. Scene object: id=${e.id}, name=${e.name}`)}if(null==i)return;e.name&&e.name.length>0&&(i.name=e.name),i.userData.detailCulling=e.detailCulling,this.applyTransform(e,i),a?i.userData._src=e:i.userData.src=e,null!=n&&(i.userData.actor=n,["NavMesh","NavMeshActor"].includes(e.actor?.type)&&(i.userData.navigationBake=this.navigationBakes[r]??this.navigationBakes[r.replace(/^\//,"")],this.inEditor&&(i.userData.navigationBakeSource=async()=>({objects:this.dataProvider.getObjects(),assets:await this.assetsService.getAssets(),loadCollisionShapes:async e=>(await this.assetManagerService.getMesh(e)).scene.collisionShapes??[]})),this.inEditor&&(i.userData.navigationBakeRevision=()=>this.navigationRevision))),this.inEditor,this.inEditor,this.objectMap.set(i.uuid,e),this.sceneObjectMap.set(e.id,i),e.physics?.type!==De.dynamic||null==t||this.inEditor?null==t?this.scene.add(i):null==t||"actor"!==e.type||this.inEditor?t?.add(i):(t.add(i),this.scene?.attach(i),console.log(i)):(t.add(i),i.getWorldPosition(Ca),i.getWorldQuaternion(Oa),i.getWorldScale(Ea),this.scene.add(i),i.position.copy(Ca),i.quaternion.copy(Oa),i.scale.copy(Ea)),null!=e.children&&await Promise.all(e.children?.map(e=>this.materialize(e,i,a,null==s?void 0:structuredClone(s))));const o=("asset_mesh"===e.type||"shape_mesh"===e.type&&"landscape"!==e.shape)&&e.physics?.type!==De.dynamic;if(this.inEditor&&o&&!function(e){for(let t=e;null!=t;t=t.parent)if(!0===t.userData.hologyEditorMatrixWorldAutoUpdate)return!0;return!1}(t)?xa(i,!1):this.inEditor||null!=t||"asset_mesh"!=e.type&&"shape_mesh"!==e.type&&"prefab"!==e.type&&"group"!==e.type||"landscape"===e.shape||null!=e.physics?.type&&e.physics.type==De.dynamic||va(i),null!=this.renderingView)return this.renderingView.invalidateShadows(),i;console.warn("RenderingView not found in materializer")}async handlePaintedScatterSceneMutation(e){const t=this.paintedScatterManager?.referencesSceneObject(e.id)??!1,a=await this.sceneObjectContainsPaintedScatter(e);(t||a)&&await this.refreshPaintedScatterPresence(!1)}async refreshPaintedScatterPresence(e=!1){return await this.sceneContainsPaintedScatter()?(null==this.paintedScatterManager&&(this.paintedScatterManager=new Mt(this.scene,this.dataProvider,this.renderingView,this.assetManagerService,this.assetsService)),this.paintedScatterManager.queueRefresh(e),!0):(this.disposePaintedScatterManager(),!1)}disposePaintedScatterManager(){null!=this.paintedScatterManager&&(this.paintedScatterManager.clear(),this.paintedScatterManager.stop(),this.paintedScatterManager=void 0)}async sceneContainsPaintedScatter(){return this.sceneObjectsContainPaintedScatter(this.dataProvider.getObjects())}async sceneObjectsContainPaintedScatter(e,t=[]){for(const a of e??[])if(await this.sceneObjectContainsPaintedScatter(a,t))return!0;return!1}async sceneObjectContainsPaintedScatter(e,t=[]){if("scatter"===e.type&&(e.paintedScatter?.cells?.some(e=>(e.instances?.length??0)>0)||(e.paintedScatter?.palette?.length??0)>0))return!0;if(null!=e.children&&await this.sceneObjectsContainPaintedScatter(e.children,t))return!0;if("prefab"===e.type&&null!=e.assetId){if(t.includes(e.assetId))return!1;const a=this.assets.get(e.assetId)??await this.assetsService.getAsset(e.assetId),s=a?.prefab?.objects;if(null!=s)return this.sceneObjectsContainPaintedScatter(s,[...t,e.assetId])}return!1}async handleSurfaceScatterSceneMutation(e){const t=this.surfaceScatterManager?.referencesSceneObject(e.id)??!1,a=await this.sceneObjectContainsSurfaceScatter(e);(t||a)&&await this.refreshSurfaceScatterPresence(!0)}async refreshSurfaceScatterPresence(e=!1){return await this.sceneContainsSurfaceScatter()?(null==this.surfaceScatterManager&&(this.surfaceScatterManager=new At(this.scene,this.dataProvider,this.renderingView,this.assetManagerService,this.assetsService)),this.surfaceScatterManager.queueRefresh(e),!0):(this.disposeSurfaceScatterManager(),!1)}disposeSurfaceScatterManager(){null!=this.surfaceScatterManager&&(this.surfaceScatterManager.clear(),this.surfaceScatterManager.stop(),this.surfaceScatterManager=void 0)}async sceneContainsSurfaceScatter(){return this.sceneObjectsContainSurfaceScatter(this.dataProvider.getObjects())}async sceneObjectsContainSurfaceScatter(e,t=[]){for(const a of e??[])if(await this.sceneObjectContainsSurfaceScatter(a,t))return!0;return!1}async sceneObjectContainsSurfaceScatter(e,t=[]){if("asset_mesh"===e.type&&(e.surfaceScatter?.meshes?.length??0)>0)return!0;if(null!=e.children&&await this.sceneObjectsContainSurfaceScatter(e.children,t))return!0;if("prefab"===e.type&&null!=e.assetId){if(t.includes(e.assetId))return!1;const a=this.assets.get(e.assetId)??await this.assetsService.getAsset(e.assetId),s=a?.prefab?.objects;if(null!=s)return this.sceneObjectsContainSurfaceScatter(s,[...t,e.assetId])}return!1}sceneReferencesPrefabAsset(e){const t=(a=[])=>{for(const s of a??[]){if("prefab"===s.type&&s.assetId===e)return!0;if(t(s.children))return!0}return!1};return t(this.dataProvider.getObjects())}async prefabAssetContainsSurfaceScatter(e){return"prefab"===e.type&&null!=e.prefab?.objects&&this.sceneObjectsContainSurfaceScatter(e.prefab.objects,[e.id])}async prefabAssetContainsPaintedScatter(e){return"prefab"===e.type&&null!=e.prefab?.objects&&this.sceneObjectsContainPaintedScatter(e.prefab.objects,[e.id])}applyTransform(e,t){null!=e.position&&t.position.fromArray(e.position),null!=e.scale&&t.scale.fromArray(e.scale),null!=e.rotation&&t.rotation.fromArray(e.rotation)}updateWorldEnv(e){this.renderingView.configureAmbientOcclusion(e.worldEnv.ao.enabled,e.worldEnv.ao.blendIntensity,e.worldEnv.ao);const t=e.worldEnv.toneMapping;null!=t&&this.renderingView.setBaseToneMapping(t.mapping??0,t.exposure??1);const a=e.worldEnv.environment,s=++this.worldEnvironmentRequest;null!=a&&null!=a.textureId?this.assetManagerService.getTexture(this.assets.get(a.textureId)).then(e=>{s===this.worldEnvironmentRequest&&(null!=e?this.renderingView.setWorldEnvironment({source:e,intensity:a.intensity??1}):console.error("Failed to load environment texture with id "+a.textureId))}):this.renderingView.setWorldEnvironment(null)}resetWorldEnv(){this.worldEnvironmentRequest++,this.renderingView.setWorldEnvironment(null),this.renderingView.configureAmbientOcclusion(!1),this.renderingView.setBaseToneMapping(c.NoToneMapping,1)}async updateSky(e){null!=this.sky&&(null==e?.sky?.materialId&&this.sky.material!==Bt?(this.sky.material=Bt,this.applySkySettings(this.sky.material)):this.sky.material.userData?.assetId!==e.sky.materialId&&this.updateSkyMaterial(e),null!=e.rotation&&this.sky.rotation.fromArray(e.rotation))}async updateSkyMaterial(e){const t=await this.assetsService.getAsset(e.sky.materialId);if(null==t)return void console.warn(`No material asset found for sky with id ${e.sky.materialId}`);const a=await materialFromAsset(t,this.renderingView,this.assetsService,this.assetManagerService,this.shaders,!1);this.applySkySettings(a),null!=this.sky?this.sky.material=a:console.warn("No sky has been created")}applySkySettings(e){e.side=c.BackSide,(e instanceof M||e instanceof c.MeshBasicMaterial||e instanceof c.ShaderMaterial)&&(e.fog=!1),e.depthTest=!0,e.depthWrite=!1,e.transparent=!0}async createComponent(e,t,a,s){const r=new la[a.path+"/"+a.className],i=t.id+s;r.id=i,r.object=e;for(const e of a.params)null!=e.value&&(r[e.name]=e.value);return this.components.push(r),i}async createFromActor(e,t){const a=this.actorTypes.find(t=>t.name===e.actor?.type)?.type??Pe[e.actor?.type];if(null==a)return console.warn(`Failed to materialize actor. No actor class found for type '${e.actor?.type}'.`),{object:null,actor:null};this.inEditor&&this.editorActorParamSnapshot.set(e.id,JSON.stringify(e.actor));const s=await this.actorProvider.create(a,(new O).fromArray(e.position),(new p).fromArray(e.rotation),!0),r=this.getNestedActorId(e.id,t);return s.__netSceneId=r,this.applyInitialMaterializedNetRole(s),this.materializedActors.set(r,s),{object:s?.object,actor:s}}applyInitialMaterializedNetRole(e){if(this.inEditor||this.netMode===Ce.none)return;const t=je(e.constructor);!0!==t?.replicate?this.netMode===Ce.client&&(e.netRole=Oe.none):e.netRole=this.netMode===Ce.client?Oe.simulatedProxy:Oe.authority}getNestedActorId(e,t){return null!=t?t.sceneObjectChain.join("/")+"/"+e:e}async createFromVfx(e,t){const a=await this.assetsService.getAsset(e.assetId);null==a&&console.error("Could not find asset",e);const s=await this.actorProvider.create(ye,(new O).fromArray(e.position),(new p).fromArray(e.rotation),!1);try{await s.fromAsset(a)}catch(e){return console.error("Failed to create VFX asset",e),null}return s.play(),this.materializedActors.set(this.getNestedActorId(e.id,t),s),null!=s&&(s.object.userData.actor=s),s?.object}async createFromShape(e){const t=this.inEditor&&e.hidden;let a;if("landscape"==e.shape)a=this.createLandscape(e),a.traverse(e=>{e instanceof S&&this._originalMaterials.set(e.id,e.material)});else{let s=new M({name:"Default",color:new h("#aaaaaa"),visible:this.inEditor||!e.hidden,wireframe:!!t});!0===e.collider&&(s.opacity=.3,s.color.set(2517460),s.transparent=!0);const r=await this.createMeshByShape(e.shape,s,e.shapeParams);r.castShadow=e.castShadow??!0,r.receiveShadow=e.receiveShadow??!1,!1===e.collisionDetection&&(r.collisionShape=null),r.physics=e.physics,a=r,this._originalMaterials.set(a.id,r.material),a.traverse(e=>{})}return t||(await Promise.all((e.materialAssignments??[]).filter(e=>null!=e.materialId).map(e=>this.applyMaterial(a,e))),this.applyVertexMaterials(e,a)),a}createLandscape(e){const t=e.landscape?.options;if(null==t)return console.error(`No landscape options exist on scene object ${e.id} ${e.name}`),new g;const a=gt(e.landscape.options);this.applyHeightMaps(a,e.landscape.heightMaps,!0);const s=new mt(e,this.renderingView,a,this.assetManagerService,this.assetsService,this.shaders,async t=>{await Promise.all((e.materialAssignments??[]).filter(e=>null!=e.materialId).map(e=>this.applyMaterial(t,e))),this.inEditor||this.applyVertexMaterials({...e,vertexMaterials:e.vertexMaterials?.filter(e=>e.m===t.name)},t)},!this.inEditor&&!1!==e.landscape.staticDrawSets);return this.landscapeManagers.push(s),s.refreshGeometry(),a}applyHeightMaps(e,t,a=!1){const s=new yt(e.sections);for(const e of t??[]){const t=s.find(e.x,e.y);if(!t)return;const a=t.geometry.getAttribute("position");for(const t of e.points)a.setY(t.i,t.y);a.needsUpdate=!0}const r=e.sections;r.forEach(e=>{e.geometry.computeBoundsTree(),e.geometry.computeVertexNormals()}),this.inEditor&&!a||setTimeout(()=>wt(r),50)}async createMeshByShape(e,t,a={}){if("landscape"!==e&&Et.includes(e)){const s=await prepareShapeParameters(a??{}),r=e+JSON.stringify(a);if(!this.geometryCache.has(r)){const t=Ot[e].geometry(s);(function(e){return null!=e.index&&e.hasAttribute("position")&&e.hasAttribute("normal")&&e.hasAttribute("uv")})(t)&&t.computeTangents(),this.geometryCache.set(r,t)}this.collisionShapeCache.has(r)||this.collisionShapeCache.set(r,Ot[e].collision(s));return new ft(this.geometryCache.get(r),t,this.collisionShapeCache.get(r))}if(this.inEditor)throw new Error(`Unsupported shape '${e}'`);console.warn(`Failed to create shape. Unsupported shape '${e}'. This might be because the hology/core library is not compatible with the editor version.`)}async decodeModelImage(e){const t=e.image;if("function"!=typeof createImageBitmap||"undefined"==typeof HTMLImageElement||!(t instanceof HTMLImageElement))return;const a=e.source;let s=this.modelImageBitmaps.get(a);if(null==s){const e=()=>createImageBitmap(t,{imageOrientation:"none",premultiplyAlpha:"none",colorSpaceConversion:"none"}),r=t.currentSrc||t.src,i=/^(blob:|data:)/.test(r)?this.assetManagerService.decodeImageBitmap(r):void 0;s=(i?.catch(t=>(console.warn("Worker model image decode failed; decoding locally",t),e()))??e()).then(e=>{a.data===t?a.data=e:e.close()}).catch(e=>{console.warn("Could not decode model image before upload",e)}),this.modelImageBitmaps.set(a,s)}await s,a.data!==t&&(e.needsUpdate=!0)}async createFromAsset(e,t){const a=this.assets.get(e.assetId)??await this.assetsService.getAsset(e.assetId);if(null==a)return void console.warn(`Can not find asset with id ${e.assetId} and name ${e.name}`);let{scene:s}=await this.assetManagerService.getMesh(a,{mergeGeomtries:!0});if(e.latticeDeformation&&(s=freezeSkinnedMeshes(s,!0),this.latticeGeometries.apply(s,e.latticeDeformation,JSON.stringify(e.vertexMaterials??[]))),!1!==t?.assignMaterials)try{await Promise.all(Ga(e.materialAssignments,a.materialAssignments).map(e=>this.applyMaterial(s,e,a)))}catch(t){console.error("Failed to apply material"+t,e)}const r=e.receiveShadow??!!a.receiveShadow,i=e.castShadow??!!a.castShadow;if(s.receiveShadow=r,ha(s,i,r),!1!==e.collisionDetection&&!1!==a.collisionDetection||(s.collisionShapes=[]),null!=e.physics&&!0!==this.inEditor&&(s.physics=e.physics),this.applyVertexMaterials(e,s),s.traverse(e=>{e instanceof S&&"computeBoundsTree"in e.geometry&&null==e.geometry.boundsTree&&e.geometry.computeBoundsTree()}),s.userData.assetId=e.assetId,s.traverse(e=>{if(e instanceof S)for(const t of st(e.material))Ve(t,!1)}),"webgpu"===this.renderingView.requestedBackend){await this.renderingView.initializeBackend();const e=new Set;s.traverse(t=>{if(t instanceof S)for(const a of st(t.material))if(a instanceof c.ShaderMaterial)for(const t of Object.values(a.uniforms)){const a=t.value;a instanceof D&&null!=a.image&&e.add(a)}else for(const t of Object.values(a))t instanceof D&&null!=t.image&&e.add(t)}),await Promise.all(Array.from(e,async e=>{await this.decodeModelImage(e),this.renderingView.initTexture(e)}))}return s}async createFromPrefab(e,t,a){const s=await this.assetsService.getAsset(e.assetId);if(null==s)return void console.warn(`Can not find asset with id ${e.assetId} and name ${e.name}`);null==t&&(t={sceneObjectChain:[]}),t.sceneObjectChain.push(e.id);const{object:r}=await this.createFromPrefabAsset(s,t,a,e);return t.sceneObjectChain.pop(),r}async createFromPrefabAsset(e,t,a,s,r=!0){this.assets.set(e.id,e);const i=new g;null!=s&&this.applyTransform(s,i),null!=a&&a.add(i),await Promise.all(e.prefab.objects.filter(e=>"global_fog"!==e.type&&"world_env"!==e.type).map(e=>this.materialize(e,i,!0,structuredClone(t))));const n=t.sceneObjectChain.join("/"),o=Array.from(this.materializedActors.entries()).filter(([e,t])=>e.startsWith(n+"/")&&!t.__isInitialised);o.forEach(e=>{});let l=null;if(null!=e.prefab?.mainActorId){const a=t.sceneObjectChain.join("/")+"/"+e.prefab.mainActorId;l=this.materializedActors.get(this.persistenceActorPath(a))??null}r||await this.initActorsPostInit(o);const c=Array.from(this.materializedActors.entries()).filter(([e])=>e.startsWith(n+"/")),u=c.map(([,e])=>e),d=new Map(c.map(([e,t])=>[e.slice(n.length+1),t]));if(this.assetsService.supportsLivePrefabParameters){let t=this.livePrefabInstances.get(e.id);null==t&&(t=new Map,this.livePrefabInstances.set(e.id,t));const a=new Map([...Va(e.prefab?.objects??[])].map(([t,a])=>[t,za(a,s,e.prefab?.mainActorId===t)]));t.set(n,{prefix:n,source:s,actorsById:d,actorSettingsById:a,desiredActorSettingsById:new Map(a)})}if(!this.inEditor&&!0!==t.runtimeSpawn&&na(e.prefab?.eventGraph)&&this.materializedPrefabEventGraphs.set(n,{id:n,graph:e.prefab.eventGraph,object:i,actors:u,actorsById:d,mainActor:l}),null!=e.prefab?.mainActorId&&null!=s){const a=t.sceneObjectChain.join("/"),s=a+"/"+e.prefab.mainActorId;this.prefabInstanceExposedActorMap.set(a,s)}return{object:i,actors:u,actorsById:d,mainActor:l,instanceId:n}}async createParticleSystem(e){await this.assetsService.getAsset(e.assetId);return new x}async createLight(e){if("point"===e.light.type){const t=new j(e.light.point.color,e.light.point.intensity,Math.max(e.light.point.distance,0),e.light.point.decay);if(t.castShadow=e.light.point.castShadow??!0,t.userData.volumetricIntensity=e.light.point.volumetricIntensity,this.inEditor){const e=(new c.TextureLoader).load("assets/light-bulb-icon.webp"),a=new c.SpriteMaterial({map:e,alphaTest:.5}),s=new qt(a);s.scale.multiplyScalar(.6),t.add(s)}return t}if("spot"===e.light.type){const t=new c.SpotLight(e.light.spot.color,e.light.spot.intensity,Math.max(e.light.spot.distance,0),e.light.spot.angle,e.light.spot.penumbra,e.light.spot.decay);if(t.castShadow=e.light.spot.castShadow??!0,t.userData.volumetricIntensity=e.light.spot.volumetricIntensity,t.map=await this.loadSpotLightMap(e.light.spot.mapTextureId),t.target=new x,t.target.position.set(0,-1,0),t.add(t.target),this.inEditor){const e=(new c.TextureLoader).load("assets/light-bulb-icon.webp"),a=new c.SpriteMaterial({map:e,alphaTest:.5}),s=new qt(a);s.scale.multiplyScalar(.6),t.add(s),t.add(new c.SpotLightHelper(t))}return t}if("rectArea"===e.light.type){const t=new c.RectAreaLight(e.light.rectArea.color,e.light.rectArea.intensity,e.scale?e.scale[0]:1,e.scale?e.scale[1]:1);if(this.inEditor){const e=(new c.TextureLoader).load("assets/light-bulb-icon.webp"),a=new c.SpriteMaterial({map:e,alphaTest:.5}),s=new qt(a);s.scale.multiplyScalar(.6),t.add(s);const r=new Kt(t);t.add(r)}return t}return"directional"===e.light.type?(this.applyDirectionalLight(e.light.directional,e),new g):"ambient"===e.light.type?(this.applyDirectionalAmbientLight(null,e.light.ambient,e),new g):void 0}async loadSpotLightMap(e){if(null==e)return null;const t=this.assets.get(e);return null==t||"texture"!==t.type?null:await this.assetManagerService.getTexture(t)}applyDirectionalAmbientLight(e,t,a){const s=this.scene.children.find(e=>e.name===kt);null!=s?(s.intensity=t.intensity,s.color.set(t.color),s.groundColor.set(t.color),s.userData.src=a,s.userData.volumetricIntensity=t.volumetricIntensity):console.warn("Couldn't find ambient light")}applyDirectionalLight(e,t){this.renderingView.csm.lightIntensity=e.intensity;for(const a of this.renderingView.csm.lights)a.intensity=e.intensity,a.color.set(e.color),a.castShadow=e.castShadow,a.userData.src=t,a.userData.volumetricIntensity=e.volumetricIntensity;this.renderingView.csm.lightDirection.fromArray(e.direction).normalize()}dispose(e){for(const e of this.landscapeManagers)e.stop();if(this.landscapeManagers.length=0,this.latticeGeometries.dispose(),this.editorStaticDisposed=!0,this.disposeEditorStaticDrawSet(),this.editorStaticEditingObjects.clear(),this.editorStaticSelectedObjects.clear(),this.editorStaticObjectsToRebuild.clear(),this.editorStaticDrawSetUpdated$.complete(),this.experimentalStaticDrawSetDisposer?.(),this.experimentalStaticDrawSetDisposer=void 0,this.removePrefabEventGraphs(),this.livePrefabInstances.clear(),this.updateSubscription.unsubscribe(),this.createAssetSubscription.unsubscribe(),this.disposePaintedScatterManager(),this.disposeSurfaceScatterManager(),this.sceneSettingsActive){this.worldEnvironmentRequest++,this.renderingView.setWorldEnvironment(null),this.renderingView.configureAmbientOcclusion(!1),this.renderingView.setBaseToneMapping(c.NoToneMapping,1),this.scene.fog=this.originalFog;const e=this.renderingView.csm,t=this.originalGlobalLight;if(null!=e&&null!=t){e.lightDirection.copy(t.direction),e.lightIntensity=t.intensity;for(let a=0;a<e.lights.length&&a<t.lights.length;a++){const s=e.lights[a],r=t.lights[a];s.intensity=r.intensity,s.color.copy(r.color),s.castShadow=r.castShadow,s.userData.src=r.src,s.userData.volumetricIntensity=r.volumetricIntensity}}this.sceneSettingsActive=!1}this.materializedActors.forEach(t=>{e?.has(t)||t.disposed.next(!0)}),this.materializedActors.clear()}announcePrefabEventGraphs(e){for(const[t,a]of this.materializedPrefabEventGraphs)(null==e||t===e||t.startsWith(e+"/"))&&(this.announcedPrefabEventGraphs.has(t)||(this.announcedPrefabEventGraphs.add(t),this.prefabEventGraphAdded$.next(a)))}removePrefabEventGraphs(e){const t=[];for(const[a,s]of[...this.materializedPrefabEventGraphs])(null==e||a===e||a.startsWith(e+"/"))&&(t.push(s),this.prefabEventGraphRemoved$.next(s),this.materializedPrefabEventGraphs.delete(a),this.announcedPrefabEventGraphs.delete(a));return t}};da=e([ge(),t("design:paramtypes",[I,Object,dt,ut,Te,Array,Array,Object,Array])],da);export{da as SceneMaterializer};function ha(e,t,a){e.castShadow=t,e.receiveShadow=a,e.traverse(e=>{e.castShadow=t,e.receiveShadow=a})}const pa=new Map,fa=new Map,ma=new b({color:16711935}),ga=new Map;export async function materialFromAsset(e,t,a,s,r,i=!0){if(null==e||null==e.material)return console.error("Asset or asset material is null",e),ma;const n=JSON.stringify(e.material)+t?._id,o=i&&!("shaderGraph"===e.material.type&&"asset"===e.material.shaderGraph?.source);if(o&&pa.has(n))return pa.get(n);if(o&&fa.has(n))return await fa.get(n);const l=_materialFromAsset(n,e,t,a,s,r,o);return o?fa.set(n,l).get(n):l}export async function _materialFromAsset(e,t,a,s,r,i,o=!0){const l={opacity:t.material.params?.opacity??1,map:null,emissive:t.material.params?.emissive??null,metalness:t.material.params?.metalness??0,flatShading:t.material.params?.flatShading??!1,color:new h(t.material.params?.color),transparent:null!=t.material.params?.opacity&&t.material.params?.opacity<1},u={};if(null!=t.material.params?.map){const e=t.material.params.map,a=await s.getAsset(e);null!=a&&(l.map=await r.getTexture(a))}let d,p,f;switch(t.material.type){case"phong":d=new v({...l,...u});break;case"water":d=xt(l,a);break;case"grassFoliage":d=St({color:l.color,map:l.map},a);break;case"grass":d=bt({...l,colorTwo:new h(t.material.params.colorTwo),colorThree:new h(t.material.params.colorThree)},a);break;case"shaderGraph":{const e=await async function(e,t){const a=e.material?.shaderGraph;if("local"===a?.source)return a.graph;if("asset"===a?.source){const e=await t.getAsset(a.assetId);return e?.shaderGraph??null}return e.shaderGraph??null}(t,s);if(null==e){console.warn("Missing shader graph for material "+t.name),d=ma;break}"surface"===e.target&&null!=e.materialOptions?.side&&(p=ia(e.materialOptions.side)),"decal"===e.target?f=!1:null!=e.materialOptions?.transparent&&(f=e.materialOptions.transparent);try{const n=await prepareShaderGraphParameters(t.material?.shaderParams??{},e,s,r,a,i),o=t.shaderGraphPreviewNodeId,l=t.trailBillboard;d=ra(e,{parameters:n,previewNodeId:o,trailBillboard:l,alphaTest:t.material.alphaTest}),d.userData.customShaderName="asset"===t.material.shaderGraph?.source?`shaderGraph:${t.material.shaderGraph.assetId}`:`shaderGraph:${t.id}`}catch(e){console.warn("Shader graph runtime error: "+e,e),d=ma}break}case"standard":case"unlit":case"toon":case"layered":case"lambert":case"shader":case"landscape":case"landscape-composite":case"decal-unlit":case"decal-standard":case"sprite":const e={standard:ca?Fe:_e,lambert:Fe,unlit:Ge,toon:Jt,layered:_t,landscape:We,"landscape-composite":Re,"decal-unlit":Nt,"decal-standard":zt,sprite:n}[t.material.type]??i.find(e=>e.name==t.material.shader)?.type;if(e){try{let n=new e;const o=await prepareClassParameters(t.material?.shaderParams??{},e,s,r,null,a,i,void 0,void 0,n);Object.assign(n,o),n.alphaTest=t.material.alphaTest??n.alphaTest,d=n.build()}catch(e){console.log("Shader runtime error: "+e,e),ga.has(t.material.shader)||ga.set(t.material.shader,ma.clone()),d=ga.get(t.material.shader)}d.userData.customShaderName=t.material.shader}else console.warn("Missing shader implementation with name "+t.material.shader),d=ma;break;default:throw new Error("Unsupported material type "+t.material.type)}if(a?.csm.setupMaterial(d),d.side=p??t.material.side??d.side??c.FrontSide,d.transparent=(f??t.material.transparent??l.transparent??!1)||d.transparent,d.alphaTest=t.material.alphaTest??d.alphaTest??0,d.userData.receiveDecals=t.material.receiveDecals??!0,null!=t.material.blending&&(d.blending=Ee[t.material.blending]??c.NormalBlending),!0===t.material.transparent&&(d.depthWrite=!1),t.material.bloom&&(d.userData.hasBloom=!0),t.material.reflective&&(d.userData.reflective=!0),!0===t.material.outlines&&(d.userData.outlineParameters={},null!=t.material.outlineParams&&(null!=t.material.outlineParams.color&&(d.userData.outlineParameters.color=new h(t.material.outlineParams.color).toArray()),null!=t.material.outlineParams.thickness&&(d.userData.outlineParameters.thickness=t.material.outlineParams.thickness),null!=t.material.outlineParams.opacity&&(d.userData.outlineParameters.alpha=t.material.outlineParams.opacity),null!=t.material.outlineParams.colorMode&&(d.userData.outlineParameters.colorMode=t.material.outlineParams.colorMode),null!=t.material.outlineParams.darkening&&(d.userData.outlineParameters.darkening=t.material.outlineParams.darkening))),null!=t.material.surfaceAssetId&&""!==t.material.surfaceAssetId){const e=await materializeDataAssetRef(t.material.surfaceAssetId,s,r,void 0,a,i);null!=e&&(d.userData.surface=e.value)}return d.userData.assetId=t.id,o&&null!=a&&pa.set(e,d),o&&fa.delete(e),d}export function prepareCustomParamsFromShaderGraph(e,t={}){return Object.fromEntries((e.parameters??[]).map(e=>{const a=function(e){switch(e){case"float":return jt.FloatNode;case"boolean":return jt.BooleanNode;case"texture":return jt.Sampler2DNode;case"vec2":return jt.Vec2Node;case"vec3":return jt.Vec3Node;case"vec4":return jt.Vec4Node;case"color":return jt.RgbNode}}(e.type),s=t[e.name],r=s?.override??null!=s,i=void 0!==e.defaultValue?e.defaultValue:customParameterDefaultValueByType.get(a),n=!1===r?_a(i):s?.value??_a(i);return[e.name,{type:a,value:n,override:r}]}))}export async function prepareShaderGraphParameters(e,t,a,s,i,n,o=!1){const l={},c=prepareCustomParamsFromShaderGraph(t,e),u=Object.entries(c),d=await Promise.all(u.map(([e,t])=>{if(o&&t.type===jt.FloatNode){const a=t.value,s=e=>"string"==typeof e?parseFloat(e):Number(e);if(null!=a&&"object"==typeof a&&"a"in a&&"b"in a)return null==a.a?null:r(e,s(a.a),null==a.b?void 0:s(a.b),"easing"in a?String(a.easing):void 0);if(null!=a&&""!==a)return r(e,s(a))}return wa(e,t,a,s,null,i,n)}));for(let e=0;e<u.length;e++){const[t]=u[e],a=d[e];null!=a&&(l[t]=a)}return l}export async function prepareClassParameters(e,t,a,s,r,i,n,o,l,c){const u={},{params:d,skipped:h}=It(e,{parameterType:t,parameterTarget:c,extractPropertyParameters:Le,toSerializedParamType:toSerializedParamType});for(const e of h)console.warn(`Skipping stored parameter "${e.key}" because it could not be converted from ${jt[e.sourceType]} to ${jt[e.targetType]}`);for(const[e,t]of Object.entries(d)){if(!1===t.override)continue;const c=await wa(e,t,a,s,r,i,n,o,void 0,void 0,l);null!=c&&(u[e]=c)}return u}export async function prepareShapeParameters(e,t,a){const s={};for(const[r,i]of Object.entries(e)){const e=await wa(r,i,t,a,null,void 0,void 0,void 0,void 0,void 0);null!=e&&(s[r]=e)}return s}const ya=new Map;async function wa(e,t,a,s,r,i,n,o,l=t.value,c=t.type,u,d=(t.type===jt.Struct?t.struct:void 0)){if(null==t||null==l||""===l)return null;switch(c){case jt.Array:if(Array.isArray(l)&&"element"in t)return await Promise.all(l.map(l=>wa(e,t,a,s,r,i,n,o,l,t.element,u,t.elementStruct)));break;case jt.Number:case jt.FloatNode:let f;if("string"==typeof l?f=parseFloat(l):"number"==typeof l&&(f=l),c===jt.FloatNode){if("object"==typeof l&&"a"in l&&"b"in l){const t=l;if(null==t.a)return null;const a="string"==typeof t.a?parseFloat(t.a):t.a;if(null==t.b)return a;const s="string"==typeof t.b?parseFloat(t.b):t.b,r=function(e){let t=ya.get(e);return null==t&&(t=Ne(Vt.decode(e)),ya.set(e,t)),t}(t.easing),i=r.sample(ze($e.energy)),n=new re(Ke(e)+"_curveEndpoints",new C(a,s),void 0,!1);return L(n.x,n.y,i)}return new ae(Ke(e),f,void 0,!1)}return f;case jt.Texture:let m=await s.getTexture(await a.getAsset(l));return"envmap"===e.toLowerCase()&&null!=i&&(m=i.getEnvTexture(m)),m;case jt.Sampler2DNode:const g=await a.getAsset(l);if(null!=g?.texture?.textureArrayFileKey){const{texture:t,layerIndex:a}=await s.getTextureArray(g);if(t&&null!=a)return new se(null,t,new ae(Ke(e)+"_i",a,void 0,!1))}const y=await s.getTexture(g);return y?K(y):null;case jt.Boolean:return l;case jt.BooleanNode:return new te(Ke(e),l,void 0,!1);case jt.Vector2:case jt.Vec2Node:if("object"==typeof l){const t=l instanceof Array?(new C).fromArray(l):new C(l.x,l.y);return c===jt.Vec2Node?new re(Ke(e),t,void 0,!1):t}return null;case jt.Vector3:case jt.Vec3Node:if("object"==typeof l){const t=l instanceof Array?(new O).fromArray(l):new O(l.x,l.y,l.z);return c===jt.Vec3Node?new ie(Ke(e),t,void 0,!1):t}return null;case jt.Vector4:case jt.Vec4Node:if("object"==typeof l){const t=l instanceof Array?(new E).fromArray(l):new E(l.x,l.y,l.z,l.w);return c===jt.Vec4Node?new ne(Ke(e),t,void 0,!1):t}return null;case jt.Color:case jt.RgbNode:const w=new h(l);return c===jt.RgbNode?new ie(Ke(e),new O(w.r,w.g,w.b),void 0,!1).rgb:w;case jt.String:return l;case jt.Scene:return"string"==typeof l?new Me(l):"object"==typeof l&&null!=l&&"string"==typeof l.id?new Me(l.id,"string"==typeof l.name?l.name:void 0):null;case jt.ModelRef:return"string"==typeof l?new Ae(l):null;case jt.BaseActor:const S=l;if(null==r&&console.warn("Class parameters can not be prepared as actors are not passed in"),null==S)return null;if("object"==typeof S&&null!=S.type&&null!=S.id){if("actor"===S.type)return r?.get(S.id)??null;if("prefab"===S.type){const e=u?u(S.id):null;if(null!=e)return r?.get(e)??null;const t=[];for(const[e,a]of r?.entries()??[])e.startsWith(S.id+"/")&&t.push(a);return 1===t.length?t[0]:null}}if("string"==typeof S){const e=r?.get(S);if(null!=e)return e;const t=u?u(S):null;if(null!=t)return r?.get(t)??null;const a=[];for(const[e,t]of r?.entries()??[])e.startsWith(S+"/")&&a.push(t);return 1===a.length?a[0]:null}return null;case jt.Euler:const b=l;return(new p).fromArray(b);case jt.Object3D:{const e=await a.getAsset(l),t=(await s.getMesh(e,{applyMaterials:!0,rescale:!0,mergeGeomtries:!0})).scene;return t.userData.vfxIncludeRootTransform=!0,t}case jt.Material:{if(null==l)return null;const e=await a.getAsset(l);if(null==e)return console.warn("Material asset not found for material parameter",l),null;if("shaderGraph"===e.type&&null!=e.shaderGraph){const t=`shaderGraphParameter:${e.id}:${JSON.stringify(e.shaderGraph)}:${i?._id??"none"}`,r=pa.get(t);if(null!=r)return r;const o=await prepareShaderGraphParameters({},e.shaderGraph,a,s,i,n),l=ra(e.shaderGraph,{parameters:o});return l.userData.assetId=e.id,l.userData.assetName=e.name,pa.set(t,l),l}return null==e.material?(console.warn("Using a non-material asset for material parameter"),null):await materialFromAsset(e,i,a,s,n)}case jt.AudioBuffer:return await s.getAudio(await a.getAsset(l));case jt.VisualEffect:const v=await a.getAsset(l);if(null==o){console.error("Can not create instance of visual effect because missing actor provider");break}if("vfx"in v)return new we(o,v);console.error("Using a non-vfx asset for visual effect parameter");break;case jt.Prefab:{const e=await a.getAsset(l);return null==e?(console.error("Using a non-prefab asset for prefab parameter",l),null):new Se(e)}case jt.PrefabActor:{const e=await a.getAsset(l);return null==e?(console.error("Using a non-prefab asset for prefab parameter",l),null):new be(new Se(e))}case jt.DataAsset:return materializeDataAssetRef(l,a,s,r,i,n,o,u);case jt.Sequence:{if("string"!=typeof l)return console.warn("Invalid sequence parameter value",l),null;const e=await a.getAsset(l);if("sequence"===e?.type&&"sequence"in e)return new aa(e.sequence);console.error("Using a non-sequence asset for sequence parameter");break}case jt.SequenceData:return ta(l)?l:(console.warn("Invalid inline sequence data parameter value",l),null);case jt.Struct:return async function(e,t,a,s,r,i,n,o,l){const c=Sa(e),u=c?.struct??t;if(null==u)return console.warn("Missing parameter definition id for struct parameter"),null;const d=Ye(u);if(null==d)return console.warn(`Unknown parameter definition "${u}"`),null;if(He(u))return console.warn(`Can not instantiate abstract parameter definition "${u}"`),null;if(null!=t&&u!==t&&!Xe(u,t))return console.warn(`Parameter definition "${u}" is not assignable to "${t}"`),null;let h;try{h=new d}catch(e){return console.warn(`Failed to instantiate parameter definition "${u}"`,e),null}const p=function(e){const t=Sa(e);if(null!=t)return t.value;if(ba(e))return e;if(null!=e&&"object"==typeof e&&ba(e.params))return e.params;return{}}(c?.value??e),f=await prepareClassParameters(p,null,a,s,r,i,n,o,l,h);return Object.assign(h,f),h}(l,d,a,s,r,i,n,o,u);case jt.Curve:return Vt.decode(l);case jt.ColorLayer:case jt.MaskLayer:if(Gt(l)){const e=await Ut.decode(l,async e=>await s.getTexture(await a.getAsset(e))),t=await prepareClassParameters(l.params,null,a,s,void 0,void 0,void 0,void 0,void 0,e);return Object.assign(e,t),e}return console.warn("Expecting color layer but got",l),null;case jt.AnimationClip:{const e="string"==typeof l?l:"object"==typeof l&&null!=l?l.assetId:null;if(null==e)return console.warn("Invalid animation clip asset id value",l),null;return await s.getAnimationClip(await a.getAsset(e))}}return null}export async function materializeDataAssetRef(e,t,a,s,r,i,n,l){const c="string"==typeof e?e:null!=e&&"object"==typeof e?e.assetId??e.id:null;if(null==c||""===c)return null;const u=await t.getAsset(c);if(null==u)return console.warn(`Data asset "${c}" was not found`),null;if("data"!==u.type||null==u.dataAsset)return console.warn("Using a non-data asset for data asset parameter",c),null;const d=u.dataAsset.definition;if(null==d||""===d)return console.warn(`Missing data asset definition id for asset "${u.id}"`),null;if(Qe(d))return console.warn(`Can not instantiate abstract data asset definition "${d}"`),null;const h=qe(d);if(null==h)return console.warn(`Unknown data asset definition "${d}"`),null;let p;try{p=new h}catch(e){return console.warn(`Failed to instantiate data asset definition "${d}"`,e),null}const f=u.dataAsset.params??{};if("object"!=typeof f||Array.isArray(f))return console.warn(`Invalid data asset params for asset "${u.id}"`),null;try{const e=await prepareClassParameters(f,null,t,a,s,r,i,n,l,p);Object.assign(p,e)}catch(e){return console.warn(`Failed to materialize data asset "${u.id}"`,e),null}const m=t.supportsLiveDataAssets?new o(e=>{let o=0;const c=t.onUpdate.subscribe(c=>{if(c.id!==u.id||"data"!==c.type)return;const d=++o;materializeDataAssetRef(u.id,t,a,s,r,i,n,l).then(t=>{e.closed||d!==o||null==t||e.next(t)}).catch(e=>console.warn(`Failed to reload data asset "${u.id}"`,e))});return()=>c.unsubscribe()}):void 0;return new ve(u,p,m)}function Sa(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&"string"==typeof e.struct&&ba(e.value)?e:null}function ba(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&Object.values(e).every(e=>null!=e&&"object"==typeof e&&"type"in e)}function va(e){e.updateWorldMatrix(!0,!0),e.updateMatrix(),e.traverse(e=>{e.matrixAutoUpdate=!1,e.matrixWorldNeedsUpdate=!1});const t=e.updateMatrixWorld;e.updateMatrixWorld=function(){t.apply(e),e.updateMatrixWorld=function(){}}}function Ma(){}const Aa=new WeakMap;function xa(e,t){if(t)return e.userData.hologyEditorMatrixWorldAutoUpdate=!0,void e.traverse(e=>{const t=Aa.get(e);if(null!=t){e.updateMatrixWorld=t.updateMatrixWorld;for(const[e,a]of t.matrixAutoUpdate)e.matrixAutoUpdate=a}});const a=!0===e.userData.hologyEditorMatrixWorldAutoUpdate,s=[];e.traverse(e=>{Aa.has(e)&&s.push(e)}),0!==s.length||a||s.push(e);for(const e of s)ja(e);delete e.userData.hologyEditorMatrixWorldAutoUpdate}function ja(e){const t=Aa.get(e);if(e.updateMatrix(),e.updateWorldMatrix(!0,!0),null==t){const t=new Map;e.traverse(e=>{t.set(e,e.matrixAutoUpdate)}),Aa.set(e,{updateMatrixWorld:e.updateMatrixWorld,matrixAutoUpdate:t})}e.traverse(e=>{e.matrixAutoUpdate=!1,e.matrixWorldNeedsUpdate=!1}),e.updateMatrixWorld=Ma}function Pa(e,t=!1){return Array.isArray(e)?e.every(e=>Pa(e,t)):t||!e.transparent&&!Ia(e)}function Ia(e){return e instanceof q&&(null!=e.uniforms[oa]||null!=e.uniforms.hology_scene_map)}function Da(e){return"linear"===e.type?new f(new h(e.color),e.near??100,e.far??1e3):"density"===e.type?new m(e.color,e.density):void console.warn("Invalid fog type",e)}const Ca=new O,Oa=new P,Ea=new O;new M({color:4229780});async function ka(e,t,a,s){null==s&&(s=(new w).identity());const r=s.clone().multiply(Ta(e,new c.Matrix4));if(null!=e.children&&e.children.length>0)for(let a=e.children.length-1;a>=0;a--)await ka(e.children[a],t,e,r);await t(e,a,s)}function Ta(e,t){return null==e.position||null==e.rotation||null==e.scale?t.identity():t.compose((new O).fromArray(e.position),(new P).setFromEuler((new p).fromArray(e.rotation)),(new O).fromArray(e.scale))}export function toSerializedParamType(e){if(null==e)return;const t=e.constructor.prototype;return t instanceof Number||e===Number?jt.Number:t instanceof _||"function"==typeof e.prototype.isFloat?jt.FloatNode:t instanceof D||e===D||e.isTexture?jt.Texture:t instanceof Ue||e===Ue||e===X||"function"==typeof e.prototype?.isSampler2D||!0===e.prototype?.isSampler2D?jt.Sampler2DNode:t instanceof Boolean||e===Boolean?jt.Boolean:t instanceof U?jt.BooleanNode:t instanceof h||e==h?jt.Color:t instanceof Q||"function"==typeof e.prototype.isRgb?jt.RgbNode:t instanceof C||e==C?jt.Vector2:t instanceof de||"function"==typeof e.prototype.isVec2?jt.Vec2Node:t instanceof O||e==O?jt.Vector3:t instanceof pe||"function"==typeof e.prototype.isVec3?jt.Vec3Node:t instanceof E||e==E?jt.Vector4:t instanceof me||"function"==typeof e.prototype.isVec4?jt.Vec4Node:t instanceof String||e===String?jt.String:t instanceof Me||e===Me?jt.Scene:t instanceof Ae||e===Ae?jt.ModelRef:t instanceof xe||e==xe||e.prototype instanceof xe||e.prototype==xe?jt.BaseActor:t instanceof p||e==p?jt.Euler:t instanceof x||e==x?jt.Object3D:t instanceof y||e==y?jt.Material:t instanceof AudioBuffer||e==AudioBuffer?jt.AudioBuffer:t instanceof we||e==we?jt.VisualEffect:t instanceof Se||e==Se?jt.Prefab:t instanceof be||e==be?jt.PrefabActor:t instanceof ve||e==ve?jt.DataAsset:t instanceof Vt||e==Vt?jt.Curve:t instanceof Ut||e==Ut?jt.ColorLayer:t instanceof Wt||e==Wt?jt.MaskLayer:t instanceof c.AnimationClip||e==c.AnimationClip?jt.AnimationClip:t instanceof aa||e==aa?jt.Sequence:"SequenceData"===e.name||e.prototype&&"tracks"in e.prototype?jt.SequenceData:null!=Je(e)?jt.Struct:void console.warn("Failed to map parameter type to serialized version",{type:e})}export function getCustomParamTypeInfo(e){const t=e.type===Object?void 0:toSerializedParamType(e.type),a=t===jt.Struct?Je(e.type):void 0;return!0===e.options.array?{type:jt.Array,element:t,...null!=a?{elementStruct:a}:{}}:{type:t,...null!=a?{struct:a}:{}}}export function prepareCustomParams(e,t,a={},s={}){return Object.fromEntries(e.map(e=>{const r=getCustomParamTypeInfo(e);let i=r;const n=t[e.name],o=Ba(n)?n:void 0,l=!0===s.treatAllAsOptional||!0===e.options.optional,c=s.missingOverrideDefaultsToOverride??!0;let u=o?.override;void 0===u&&null!=n&&l&&c&&(u=!0),void 0===u&&l&&(u=!1);const d=void 0!==a[e.name]||void 0!==e.options.defaultValue,h=function(e,t){if(null==e.type){const a=function(e){return ta(e)?{type:jt.SequenceData}:void 0}(t);null!=a&&(e=a)}if(e.type!==jt.Struct)return{typeInfo:e,value:t};const a=Sa(t);if(null==a)return{typeInfo:e,value:t};return{typeInfo:{...e,struct:a.struct},value:a.value}}(i,function(e,t){if(void 0!==t[e.name])return t[e.name];if(void 0!==e.options.defaultValue){const t=serializeCustomParameter(e.type,e.options.defaultValue);return void 0!==t?t:e.options.defaultValue}const a=toSerializedParamType(e.type);if(a===jt.Struct)return He(e.type)?{}:prepareCustomParamsFromType(e.type,{});return customParameterDefaultValueByType.get(a)}(e,a)),p=function(e,t){if(Ba(e))return e;if(null!=e&&"object"==typeof e&&!Array.isArray(e)&&"value"in e){const a=e;return{...t,value:a.value,..."boolean"==typeof a.override?{override:a.override}:{}}}if(t.type!==jt.SequenceData||!ta(e))return;return{type:jt.SequenceData,value:e}}(n,h.typeInfo);i=function(e,t,a){if(e.type!==jt.Struct||a?.type!==jt.Struct||null==a.struct)return e;const s=t.struct??e.struct;if(null==s||a.struct===s||Xe(a.struct,s)||null==Ye(a.struct))return{...e,struct:a.struct};return e}(h.typeInfo,r,p);const f=!1!==u||e.options.array?p?.value??function(e,t,a){if(!0===e.options.array)return a?_a(t):[];return _a(t)}(e,h.value,d):_a(h.value),m=function(e,t,a){if(t.type===jt.Struct){if(null!=t.struct&&He(t.struct))return a;const s=null!=t.struct?Ye(t.struct):e.type;return null!=s&&ba(a)?prepareCustomParamsFromType(s,a):a}if(t.type!==jt.Array||t.element!==jt.Struct||!Array.isArray(a))return a;const s=null!=t.elementStruct?Ye(t.elementStruct):e.type;return a.map(e=>{const a=Sa(e),r=a?.struct??t.elementStruct;if(null!=r&&He(r))return e;const i=null!=a?Ye(a.struct):s,n=a?.value??(ba(e)?e:null);if(null==i||null==n)return e;const o=prepareCustomParamsFromType(i,n);return null!=a?{struct:a.struct,value:o}:o})}(e,i,f);return[e.name,{...i,value:m,override:u}]}))}function Ba(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&"number"==typeof e.type&&"value"in e}function Va(e){const t=new Map,a=e=>{for(const s of e)"actor"===s.type&&null!=s.actor&&t.set(s.id,s.actor),null!=s.children&&a(s.children)};return a(e),t}function Na(e){const t=new Map,a=e=>{for(const s of e)"prefab"===s.type&&t.set(s.id,s),null!=s.children&&a(s.children)};return a(e),t}function za(e,t,a){if(!a||"prefab"!==t?.type||null==t.prefab)return e;const s=new Map((e.innerParams??[]).map(e=>[JSON.stringify(e.path),{path:e.path,params:{...e.params}}]));for(const e of t.prefab.innerParams??[]){const t=JSON.stringify(e.path),a=s.get(t);s.set(t,{path:e.path,params:{...a?.params??{},...Fa(e.params)}})}return{...e,params:{...e.params??{},...Fa(t.prefab.params)},innerParams:[...s.values()]}}function $a(e,t,a){const s=new Map((e.innerParams??[]).map(e=>[JSON.stringify(e.path),e])),r=new Map((t.innerParams??[]).map(e=>[JSON.stringify(e.path),e])),i=new Map((a.innerParams??[]).map(e=>[JSON.stringify(e.path),e])),n=[];for(const e of new Set([...s.keys(),...r.keys(),...i.keys()])){const t=s.get(e),a=r.get(e),o=i.get(e),l=Ua(t?.params??{},a?.params??{},o?.params??{});Object.keys(l).length>0&&n.push({path:a?.path??o?.path??t.path,params:l})}return{...t,params:Ua(e.params??{},t.params??{},a.params??{}),innerParams:n}}function Ua(e,t,a){const s={};for(const r of new Set([...Object.keys(e),...Object.keys(t),...Object.keys(a)]))JSON.stringify(a[r])!==JSON.stringify(e[r])?null!=a[r]&&(s[r]=a[r]):null!=t[r]&&(s[r]=t[r]);return s}function Fa(e){return null==e?{}:Object.fromEntries(Object.entries(e).filter(([,e])=>function(e){return!0===e?.override}(e)))}function Ra(e,t){return e.length>=t.length&&t.every((t,a)=>e[a]===t)}export function prepareCustomParamsFromType(e,t,a=null,s={}){const r=Le(e);if(0===r.length)return{};let i;null!=a?ke(a,()=>{i=a.get(e)}):i=new e;const n={};for(const e of r){const t=i[e.name];if(null!=t){const a=Wa(e,t);void 0!==a&&(n[e.name]=a)}}return prepareCustomParams(r,t,n,s)}function Wa(e,t){return!0===e.options.array?Array.isArray(t)?t.map(t=>serializeCustomParameter(e.type,t)??t):[]:serializeCustomParameter(e.type,t)}function _a(e){return null==e?e:Array.isArray(e)?e.map(e=>_a(e)):"object"==typeof e?"function"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e)):e}export function serializeCustomParameter(e,t){function a(){console.error("Failed to serialize value",{type:e,value:t})}switch(e){case Number:case Boolean:return t;case C:return t instanceof C?t.toArray():void a();case O:return t instanceof O?t.toArray():void a();case E:return t instanceof E?t.toArray():void a();case h:return t instanceof h?"#"+t.getHexString():"string"==typeof t?t:"number"==typeof t?"#"+new h(t).getHexString():void a();case String:return t;case p:return t instanceof p?t.toArray():void a();case Se:return t instanceof Se?t.asset?.id??null:void a();case ve:return t instanceof ve?t.id:"string"==typeof t?t:void a();case Me:return t instanceof Me?{id:t.id,...null!=t.name?{name:t.name}:{}}:void a();case Ae:return t instanceof Ae?t.id:"string"==typeof t?t:void a()}const s=Je(e);if(null!=s){const r=Sa(t);if(null!=r)return r.struct===s?r.value:r;const i=function(e,t){if(null==t||"object"!=typeof t)return e;const a=t.constructor;return null!=Je(a)&&Ze(a,e)?a:e}(e,t),n=Je(i),o=function(e,t){if(null==t)return null;if(ba(t))return t;if(null!=t&&"object"==typeof t&&ba(t.params))return t.params;if("object"!=typeof t)return;const a=Le(e),s={};for(const e of a){const a=t[e.name];if(void 0===a)continue;const r=Wa(e,a);void 0!==r&&(s[e.name]=r)}return prepareCustomParams(a,{},s)}(i,t);return void 0!==o?null!=o&&null!=n&&n!==s?{struct:n,value:o}:o:void a()}if(ta(t))return t}function Ga(e,t){return function(e,t,a){const s=[],r=new Set;for(const i of[...e??[],...t??[]]){const e=a(i);r.has(e)||(r.add(e),s.push(i))}return s}((e??[]).filter(e=>La(e.materialId)),(t??[]).filter(e=>La(e.materialId)),e=>e.name?`name:${e.name}`:`color:${e.color}`)}function La(e){return"null"!=e&&null!=e}export const customParameterDefaultValueByType=new Map([[jt.RgbNode,"#000000"],[jt.Color,"#000000"],[jt.String,""],[jt.Scene,null],[jt.ModelRef,null],[jt.Vector4,[0,0,0,0]],[jt.Vec4Node,[0,0,0,0]],[jt.Vector3,[0,0,0]],[jt.Vec3Node,[0,0,0]],[jt.Vector2,[0,0]],[jt.Vec2Node,[0,0]],[jt.Euler,[0,0,0,"XYZ"]],[jt.Array,[]],[jt.DataAsset,null],[jt.SequenceData,ea()],[jt.ColorLayer,Ft],[jt.MaskLayer,Rt]]);let qa=new h;new h;function Ja(e){return null==e?.color?null:(qa.set(e.color),"#"+qa.getHexString())}function Ya(e,t,a,s){const r="string"==typeof t.name&&""!==t.name?t.name:null;if(null!=r)return e.name===r||s===r;const i=Ja(e);return null!=i&&(i===t.color||a===t.color)}export function applyMaterial(e,t,a,s,r={}){const i=[];return e.traverse(async e=>{if(e instanceof S||e.isMesh||e instanceof c.SkinnedMesh||e.isSkinnedMesh)for(const t of st(e.material))t.hasOwnProperty("color")&&i.push(e)}),Promise.all(i.map(async e=>{if(e.material instanceof Array)for(let i=0;i<e.material.length;i++){const n=e.material[i];if(null==n.color||!(n.color instanceof h))continue;const o=Ja(n),l=n.name;if(Ya(n,t,e.userData["originalColor_"+i],e.userData["originalMaterialName_"+i])){const n=Ha(await a(t.materialId),r.textureFlipY),c=e.material[i];null!=n&&c.id!=n.id&&(e.material[i]=n,e.userData["originalColor_"+i]=e.userData["originalColor_"+i]??o,e.userData["originalMaterialName_"+i]=e.userData["originalMaterialName_"+i]??l,null!=s&&s.set(e.id+"#"+i,c))}}else if("color"in e.material){const i=e.material,n=Ja(i),o=i.name;if(Ya(i,t,e.userData.originalColor,e.userData.originalMaterialName)){const i=Ha(await a(t.materialId),r.textureFlipY),l=e.material;null!=i&&(e.material=i,e.userData.originalColor=e.userData.originalColor??n,e.userData.originalMaterialName=e.userData.originalMaterialName??o,null!=s&&(s.has(e.id)||s.set(e.id,l)))}}}))}const Qa=new WeakMap;export function getConvertedFbxToGlbAssignedMaterialTextureFlipY(e){const t=e?.mesh?.uvConversion;return"fbx2gltf"===t?.source?!0!==t.flipV&&void 0:!function(e){return"glb"===e?.fileFormat&&!0===e.originalFileKey?.toLowerCase().endsWith(".fbx")}(e)&&void 0}function Ha(e,t){if(null==e||null==t||!function(e,t){return function(e){const t=[];for(const[a,s]of Object.entries(e))Xa(a,s)&&t.push(s);if(e instanceof c.ShaderMaterial)for(const[a,s]of Object.entries(e.uniforms))Xa(a,s.value)&&t.push(s.value);return t}(e).some(e=>e.flipY!==t)}(e,t))return e;let a=Qa.get(e);null==a&&(a=new Map,Qa.set(e,a));const s=a.get(t);if(null!=s)return s;const r=Za(e);if(function(e,t){for(const a of Object.keys(e)){const s=e[a];Xa(a,s)&&(e[a]=Ka(s,t))}}(r,t),r instanceof c.ShaderMaterial){for(const[e,a]of Object.entries(r.uniforms))Xa(e,a.value)&&(a.value=Ka(a.value,t));r.uniformsNeedUpdate=!0}return r.needsUpdate=!0,a.set(t,r),r}function Za(e){const t=e.clone();return t.userData={...e.userData??{}},t}function Xa(e,t){const a=t;return(t instanceof D||!0===a?.isTexture)&&!e.toLowerCase().includes("envmap")&&!0!==a.isCompressedTexture&&!0!==a.isCompressedArrayTexture}function Ka(e,t){if(e.flipY===t)return e;const a=e.clone();return a.flipY=t,a.userData={...e.userData??{}},a.needsUpdate=!0,a}function es(e,t){if(e instanceof c.ShaderMaterial&&t instanceof c.ShaderMaterial){return e.fragmentShader+e.vertexShader==t.fragmentShader+t.vertexShader&&function(e,t){if(e instanceof c.ShaderMaterial&&t instanceof c.ShaderMaterial){for(const a in e.uniforms){if(null==t.uniforms[a])return!1;if(t.uniforms[a].value!==e.uniforms[a].value)return!1}return!0}return!1}(e,t)}return!1}function ts(e){if(null!=e){for(let t=0;t<e.array.length;t++)e.setX(t,0);e.needsUpdate=!0}}function as(e,t){const a=nt(e);return null==a?"":function(e,t){const a=Es(e,t),s=a.sort().map(t=>{const a=e.getAttribute(t);if(null!=a){const e=a.array??a.data?.array,s=e?.constructor?.name??"";return`${t}:${a.itemSize}:${a.normalized?1:0}:${s}`}const s=function(e,t){if("uv"===t&&ns(e))return{itemSize:2,normalized:!1,arrayType:"Float32Array"};throw new Error(`Unsupported synthetic batching geometry attribute: ${t}`)}(e,t);return`${t}:${s.itemSize}:${s.normalized?1:0}:${s.arrayType}`}).join(",");return`${null!=e.index?"indexed":"nonindexed"}|${s}`}(a.geometry,t)}function ss(e,t){const a=Es(e,t);if(a.length===Object.keys(e.attributes).length)return e;const s=new d;s.name=e.name;const r=e.getIndex();null!=r&&s.setIndex(r);for(const t of a)s.setAttribute(t,is(e,t));for(const t of e.groups)s.addGroup(t.start,t.count,t.materialIndex);return s.setDrawRange(e.drawRange.start,e.drawRange.count),null!=e.boundingBox&&(s.boundingBox=e.boundingBox.clone()),null!=e.boundingSphere&&(s.boundingSphere=e.boundingSphere.clone()),s.userData=e.userData,s}const rs=new WeakMap;function is(e,t){return e.getAttribute(t)??function(e,t){if("uv"===t)return function(e){let t=rs.get(e);const a=e.getAttribute("position");if(null==a)throw new Error("Can not create synthetic batching UVs without a position attribute");null!=t&&t.count===a.count||(t=new c.Float32BufferAttribute(new Float32Array(2*a.count),2),rs.set(e,t));return t}(e);throw new Error(`Unsupported synthetic batching geometry attribute: ${t}`)}(e,t)}function ns(e){return null!=e.getAttribute("position")}const os=new WeakMap,ls="hbat_",cs=new Set(["ambientLightColor","cameraNear","directionalLightShadows","directionalLights","directionalShadowMap","directionalShadowMatrix","fogColor","fogDensity","fogFar","fogNear","hemisphereLights","lightProbe","ltc_1","ltc_2","pointLightShadows","pointLights","pointShadowMap","pointShadowMatrix","receiveShadow","rectAreaLights","shadowFar","spotLightMap","spotLightMatrix","spotLightShadows","spotLights","spotShadowMap"]);function us(e){let t=os.get(e);return null==t&&(t=function(e){let t=e.type;if(e instanceof q)t+=function(e){let t="nodeShader";t+=function(e){if(null==e)return"";let t="";for(const a of Object.keys(e).sort())t+=`${a}:${String(e[a])};`;return t}(e.defines),t+=e.lights?"lights":"",t+=e.fog?"fog":"";for(const a of Object.keys(e.uniforms).sort()){if(ps(a))continue;const s=e.uniforms[a]?.value;ms(s)||(t+=`u:${a}:${vs(s)};`)}return t+=hs(e.vertexShader),t+=hs(e.fragmentShader),t}(e);else if(e instanceof c.MeshStandardMaterial&&!(e instanceof c.MeshPhysicalMaterial)||(t+=e.id+""),(e instanceof c.MeshBasicMaterial||e instanceof c.MeshLambertMaterial||e instanceof M||e instanceof v)&&(null!=e.map&&(t+="c"+e.map?.id),null!=e.aoMap&&(t+="o"+e.aoMap?.id),null!=e.lightMap&&(t+="l"+e.lightMap?.id),null!=e.envMap&&(t+="v"+e.envMap?.id),null!=e.alphaMap&&(t+="a"+e.alphaMap?.id)),e instanceof M&&(null!=e.normalMap&&(t+="n"+e.normalMap?.id),null!=e.roughnessMap&&(t+="r"+e.roughnessMap?.id),null!=e.metalnessMap&&(t+="m"+e.metalnessMap?.id),null!=e.emissiveMap&&(t+="e"+e.emissiveMap?.id)),e instanceof c.MeshPhysicalMaterial&&(null!=e.sheenColorMap&&(t+="sc"+e.sheenColorMap?.id),null!=e.sheenRoughnessMap&&(t+="sr"+e.sheenRoughnessMap?.id)),(e instanceof b||e instanceof v)&&null!=e.specularMap&&(t+="s"+e.specularMap?.id),e instanceof c.MeshToonMaterial&&(null!=e.map&&(t+="c"+e.map?.id),null!=e.aoMap&&(t+="o"+e.aoMap?.id),null!=e.lightMap&&(t+="l"+e.lightMap?.id),null!=e.alphaMap&&(t+="a"+e.alphaMap?.id)),e instanceof Qt&&null!=e.heightMap&&(t+="h"+e.heightMap?.id),e instanceof c.ShaderMaterial){t+=e.vertexShader,t+=e.fragmentShader;for(const a in e.uniforms){const s=e.uniforms[a];s&&s.value&&s.value.isTexture&&null!=s.value.id&&(t+="t:"+a+":"+s.value.id)}}null!=e.userData.outlineParameters&&(t+=e.userData.outlineParameters.color,t+=e.userData.outlineParameters.thickness,t+=e.userData.outlineParameters.alpha,t+=e.userData.outlineParameters.colorMode,t+=e.userData.outlineParameters.darkening);return t+=`side:${e.side};shadowSide:${e.shadowSide??"auto"};`,t+=e.transparent?"t":"",t+=e.vertexColors?"vc":"",t+=e.depthWrite?"dw":"",t+=e.depthTest?"dt":"",t+=`alphaTest:${e.alphaTest>0};`,t}(e),os.set(e,t)),t}const ds=new Map;function hs(e){return ds.has(e)||ds.set(e,`shader_${ds.size}`),ds.get(e)}function ps(e){return cs.has(e)||e.startsWith("hology_")}function fs(e,t){return e instanceof q?e.uniforms[t]?.value:e[t]}function ms(e){return"number"==typeof e||e instanceof C||e instanceof O||e instanceof E||e instanceof h}function gs(e){return"number"==typeof e?1:e instanceof C?2:4}function ys(e,t){const a=e.replace(/[^A-Za-z0-9_]/g,"_");let s=ls+a;for(;t.has(s);)s=ls+s;return t.add(s),s}function ws(e,t){const a={};for(const[s,r]of Object.entries(e.uniforms))t.has(s)||(a[s]={value:r.value});return a}const Ss=new WeakMap;let bs=1;function vs(e){if(null==e)return"null";if(e instanceof D||!0===e?.isTexture)return`texture:${e.id}`;if(e instanceof c.Matrix3||e instanceof c.Matrix4)return e.toArray().join(",");if("boolean"==typeof e||"number"==typeof e||"string"==typeof e)return String(e);if(Array.isArray(e)&&e.every(e=>null==e||["boolean","number","string"].includes(typeof e)))return JSON.stringify(e);if("object"==typeof e){let t=Ss.get(e);return null==t&&(t=bs++,Ss.set(e,t)),`object:${t}`}return String(e)}function Ms(e,t){if(null==e)return null;if(!(e instanceof t))throw new Error(`Value is not an instance of ${t.name}`);return e}const As=new w,xs=new p;function js(e,t){return xs.copy(e),xs.x*=-1,xs.y*=-1,xs.z*=-1,t.isCubeTexture&&!1===t.isRenderTargetTexture&&(xs.y*=-1,xs.z*=-1),(new c.Matrix3).setFromMatrix4(As.makeRotationFromEuler(xs))}function Ps(e,t){switch(t){case 0:return e.x;case 1:return e.y;case 2:return e.z;case 3:return e.w}}const Is=new E;function Ds(e,t){return e===t||null==e==(null==t)&&("number"==typeof e&&"number"==typeof t?e===t||isNaN(e)&&isNaN(t):e instanceof c.Color&&t instanceof c.Color?e.r===t.r&&e.g===t.g&&e.b===t.b:e instanceof C&&t instanceof C?e.x===t.x&&e.y===t.y:e instanceof O&&t instanceof O?e.x===t.x&&e.y===t.y&&e.z===t.z:e instanceof E&&t instanceof E&&(e.x===t.x&&e.y===t.y&&e.z===t.z&&e.w===t.w))}function Cs(e){const t=[];for(const[a,s]of Object.entries(e))s instanceof we?t.push(s):s instanceof Ie&&t.push(...Cs(s));return t}const Os=new WeakMap;function Es(e,t){const a=Object.keys(e.attributes).filter(a=>ks(e,t,a));return!e.hasAttribute("uv")&&ns(e)&&ks(e,t,"uv")&&a.push("uv"),a}function ks(e,t,a){return"position"===a||("uv"===a?function(e){if(e instanceof q)return Bs(e,"uv");if(e instanceof c.ShaderMaterial)return Vs(e.vertexShader,"uv");if(e instanceof Qt&&null!=e.heightMap)return!0;return Ts.some(t=>e[t]?.isTexture)}(t):t instanceof q?Bs(t,a):t instanceof c.ShaderMaterial?function(e,t){if("uv1"===t||"uv2"===t||"uv3"===t)return Vs(e.vertexShader,t);return!0}(t,a):"uv1"!==a&&(("color"!==a||!function(e){let t=Os.get(e);if(null!=t)return t;const a=e.getAttribute("color");if(null==a)t=!1;else{t=!0;for(let e=0;e<a.count;e++){for(let s=0;s<3;s++)if(1!==a.getComponent(e,s)){t=!1;break}if(!t)break}}return Os.set(e,t),t}(e))&&("uv2"!==a||(null!=t.lightMap||null!=t.aoMap))))}const Ts=["map","alphaMap","emissiveMap","normalMap","bumpMap","displacementMap","roughnessMap","metalnessMap","aoMap","specularMap","gradientMap","clearcoatMap","clearcoatNormalMap","clearcoatRoughnessMap","iridescenceMap","iridescenceThicknessMap","sheenColorMap","sheenRoughnessMap","transmissionMap","thicknessMap","anisotropyMap"];function Bs(e,t){return Vs(e.vertexShader,t)}function Vs(e,t){return new RegExp(`(^|[^A-Za-z0-9_])${a=t,a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}([^A-Za-z0-9_]|$)`).test(e);var a}function Ns(e,t,a){if(t(e))return e;for(const s of e.children??[]){const e=Ns(s,t,a);if(null!=e)return e}if(null!=a&&"prefab"===e.type){const s=a.get(e.assetId);if(null!=s){const e=s.prefab.objects.find(e=>Ns(e,t,a));if(null!=e)return e}}return null}const zs=new O,$s=new O,Us=new O,Fs=new E,Rs=new E,Ws=new w,_s=new w,Gs=new A;export function freezeSkinnedMeshes(e,t=!1){if(null==e)return e;e.updateWorldMatrix(!0,!0);const a=[];e.traverse(e=>{e.isSkinnedMesh&&a.push(e)});let s=e;for(const e of a){const a=Ls(e,t),r=e.parent;if(null==r){s=a;continue}const i=r.children.indexOf(e);e.removeFromParent(),r.add(a);const n=r.children.indexOf(a);i>=0&&n>=0&&n!==i&&(r.children.splice(n,1),r.children.splice(i,0,a))}return function(e){const t=[];e.traverse(e=>{e.isBone&&t.push(e)});for(const e of t)null!=e.parent&&!e.parent.isBone&&Js(e)&&e.removeFromParent()}(s),s}function Ls(e,t){e.updateWorldMatrix(!0,!1);const a=e.geometry.clone();t&&s(a,JSON.stringify([e.geometry.uuid,e.bindMatrix.elements,e.bindMatrixInverse.elements,e.skeleton.bones.map((t,a)=>(new w).multiplyMatrices(t.matrixWorld,e.skeleton.boneInverses[a]).elements)]));const r=a.getAttribute("position"),i=a.getAttribute("normal"),n=a.getAttribute("tangent");if(null!=r){for(let t=0;t<r.count;t++)zs.fromBufferAttribute(r,t),e.applyBoneTransform(t,zs),r.setXYZ(t,zs.x,zs.y,zs.z);r.needsUpdate=!0}if(null!=i||null!=n){const t=a.getAttribute("skinIndex"),s=a.getAttribute("skinWeight");if(null!=t&&null!=s){for(let a=0;a<t.count;a++)qs(e,a,_s),null!=i&&($s.fromBufferAttribute(i,a),Gs.getNormalMatrix(_s),$s.applyMatrix3(Gs).normalize(),i.setXYZ(a,$s.x,$s.y,$s.z)),null!=n&&(Us.fromBufferAttribute(n,a),Us.transformDirection(_s),n.setXYZ(a,Us.x,Us.y,Us.z));null!=i&&(i.needsUpdate=!0),null!=n&&(n.needsUpdate=!0)}}a.deleteAttribute("skinIndex"),a.deleteAttribute("skinWeight"),a.computeBoundingBox(),a.computeBoundingSphere();const o=new S(a,e.material);return o.copy(e,!1),o.geometry=a,o.material=e.material,o.userData={...e.userData},o}function qs(e,t,a){const s=e.geometry,r=s.getAttribute("skinIndex"),i=s.getAttribute("skinWeight"),n=e.skeleton;Fs.fromBufferAttribute(r,t),Rs.fromBufferAttribute(i,t),a.identity().multiplyScalar(0);for(let e=0;e<4;e++){const t=Rs.getComponent(e);if(0===t)continue;const s=Fs.getComponent(e);Ws.multiplyMatrices(n.bones[s].matrixWorld,n.boneInverses[s]);for(let e=0;e<16;e++)a.elements[e]+=Ws.elements[e]*t}return a.premultiply(e.bindMatrixInverse).multiply(e.bindMatrix),a}function Js(e){let t=!0;return e.traverse(a=>{a===e||a.isBone||(t=!1)}),t}function Ys(e,t){let a=t??!1,s=!0;for(const t of e)if(!1!==t.castShadow){s=!1;break}for(const t of e)if(!0===t.castShadow)return!0;return a&&!s}function Qs(e,t){let a=t??!1,s=!0;for(const t of e)if(!1!==t.receiveShadow){s=!1;break}if(s)return!1;for(const t of e)if(!0===t.receiveShadow)return!0;return a&&!s}/*
|
|
2
2
|
* Copyright (©) 2026 Hology Interactive AB. All rights reserved.
|
|
3
3
|
* See the LICENSE.md file for details.
|
|
4
4
|
*/
|