@hology/core 0.0.98 → 0.0.100
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/behaviours.d.ts.map +1 -1
- package/dist/effects/vfx/behaviours.js +1 -1
- package/dist/effects/vfx/trail-renderer.d.ts +11 -4
- package/dist/effects/vfx/trail-renderer.d.ts.map +1 -1
- package/dist/effects/vfx/trail-renderer.js +1 -1
- package/dist/effects/vfx/vfx-asset.d.ts +5 -2
- package/dist/effects/vfx/vfx-asset.d.ts.map +1 -1
- package/dist/effects/vfx/vfx-defs.js +1 -1
- package/dist/effects/vfx/vfx-materializer.d.ts.map +1 -1
- package/dist/effects/vfx/vfx-materializer.js +1 -1
- package/dist/effects/vfx/vfx-renderers.d.ts +4 -0
- package/dist/effects/vfx/vfx-renderers.d.ts.map +1 -1
- package/dist/effects/vfx/vfx-renderers.js +1 -1
- package/dist/gameplay/services/physics/physics-system.d.ts +7 -0
- package/dist/gameplay/services/physics/physics-system.d.ts.map +1 -1
- package/dist/gameplay/services/physics/physics-system.js +1 -1
- package/dist/rendering.d.ts +3 -0
- package/dist/rendering.d.ts.map +1 -1
- package/dist/rendering.js +1 -1
- package/dist/scene/asset-resource-loader.d.ts +1 -0
- package/dist/scene/asset-resource-loader.d.ts.map +1 -1
- package/dist/scene/asset-resource-loader.js +1 -1
- package/dist/scene/collision/collision-shape-import.d.ts.map +1 -1
- package/dist/scene/collision/collision-shape-import.js +1 -1
- package/dist/scene/collision/collision-shape.d.ts +14 -0
- package/dist/scene/collision/collision-shape.d.ts.map +1 -1
- package/dist/scene/collision/collision-shape.js +1 -1
- package/dist/scene/landscape/landscape-manager.js +1 -1
- package/dist/scene/materializer.d.ts.map +1 -1
- package/dist/scene/materializer.js +1 -1
- package/dist/scene/storage/storage.d.ts +2 -0
- package/dist/scene/storage/storage.d.ts.map +1 -1
- package/dist/scene/storage/storage.js +1 -1
- package/dist/shader/index.d.ts +1 -0
- package/dist/shader/index.d.ts.map +1 -1
- package/dist/shader/index.js +1 -1
- package/dist/shader/trail-shader.d.ts +7 -0
- package/dist/shader/trail-shader.d.ts.map +1 -0
- package/dist/shader/trail-shader.js +4 -0
- package/dist/shader-nodes/depth.d.ts +3 -1
- package/dist/shader-nodes/depth.d.ts.map +1 -1
- package/dist/shader-nodes/depth.js +1 -1
- package/dist/shader-nodes/index.d.ts +2 -1
- package/dist/shader-nodes/index.d.ts.map +1 -1
- package/dist/shader-nodes/index.js +1 -1
- package/dist/shader-nodes/scene-sample.d.ts +6 -0
- package/dist/shader-nodes/scene-sample.d.ts.map +1 -0
- package/dist/shader-nodes/scene-sample.js +4 -0
- package/dist/shader-nodes/texture-sequence.d.ts.map +1 -1
- package/dist/shader-nodes/texture-sequence.js +1 -1
- package/package.json +2 -2
- package/tsconfig.tsbuildinfo +1 -1
package/dist/rendering.d.ts
CHANGED
@@ -28,6 +28,7 @@ export declare class RenderingView {
|
|
28
28
|
paused: boolean;
|
29
29
|
aoMaskDepthRenderTarget: WebGLRenderTarget;
|
30
30
|
depthRenderTarget: WebGLRenderTarget;
|
31
|
+
sceneColorRenderTarget: WebGLRenderTarget;
|
31
32
|
csm: CSM | null;
|
32
33
|
fpsCap: number | null;
|
33
34
|
aoPass: GTAOPass;
|
@@ -49,6 +50,7 @@ export declare class RenderingView {
|
|
49
50
|
private static createDepthRenderTarget;
|
50
51
|
/** */
|
51
52
|
private static createAOMaskDepthRenderTarget;
|
53
|
+
private static createSceneColorRenderTarget;
|
52
54
|
private setupEventListeners;
|
53
55
|
stop(): void;
|
54
56
|
private onLoopCallbacks;
|
@@ -79,6 +81,7 @@ export declare class RenderingView {
|
|
79
81
|
private darkenNonBloomed;
|
80
82
|
private restoreMaterial;
|
81
83
|
private initDepthUniform;
|
84
|
+
private initResolutionUniform;
|
82
85
|
}
|
83
86
|
export declare function setRenderingPaused(value: boolean): void;
|
84
87
|
/**
|
package/dist/rendering.d.ts.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"rendering.d.ts","sourceRoot":"","sources":["../src/rendering.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAC/B,OAAO,EACL,MAAM,EAKN,QAAQ,EAIR,aAAa,EACb,iBAAiB,EAClB,MAAM,OAAO,CAAC;AAOf,OAAO,EAAE,GAAG,EAAE,MAAM,+BAA+B,CAAC;AAGpD,OAAO,EAAE,QAAQ,EAAE,MAAM,+CAA+C,CAAC;
|
1
|
+
{"version":3,"file":"rendering.d.ts","sourceRoot":"","sources":["../src/rendering.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAC/B,OAAO,EACL,MAAM,EAKN,QAAQ,EAIR,aAAa,EACb,iBAAiB,EAClB,MAAM,OAAO,CAAC;AAOf,OAAO,EAAE,GAAG,EAAE,MAAM,+BAA+B,CAAC;AAGpD,OAAO,EAAE,QAAQ,EAAE,MAAM,+CAA+C,CAAC;AA8CzE,MAAM,MAAM,oBAAoB,GAAG;IACjC,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,OAAO,CAAC,EAAE;QACR,UAAU,CAAC,EAAE,OAAO,CAAA;KACrB,CAAA;IACD,EAAE,CAAC,EAAE;QACH,OAAO,EAAE,OAAO,CAAA;KACjB,CAAA;CACF,CAAA;AAED,qBACa,aAAa;IAoHf,SAAS,EAAE,WAAW;aACb,OAAO,EAAE,oBAAoB;IApHxC,MAAM,EAAE,KAAK,CAAC,MAAM,CAAA;IACpB,aAAa,UAAO;IACpB,QAAQ,EAAE,aAAa,CAAA;IACvB,aAAa,EAAE,aAAa,CAAA;IACnC,OAAO,CAAC,QAAQ,CAAgB;IAChC,OAAO,CAAC,aAAa,CAAgB;IACrC,OAAO,CAAC,WAAW,CAAa;IACzB,KAAK,EAAE,KAAK,CAAC,KAAK,CAAA;IA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B;IAED,OAAO,CAAC,WAAW;IAsBZ,IAAI,CAAC,OAAO,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,GAAG,EAAE,SAAS,UAAQ;IAgSlE,OAAO,CAAC,WAAW,CAAM;IACzB,OAAO,CAAC,UAAU,CAA8B;IAChD,OAAO,CAAC,YAAY,CAAM;IAC1B,OAAO,CAAC,WAAW,CAAK;IACxB,OAAO,CAAC,eAAe,CAAI;IAE3B,OAAO,CAAC,cAAc,CAAyB;IAE/C,OAAO,CAAC,aAAa;IAyBd,gBAAgB,CAAC,MAAM,EAAE,MAAM;IAI/B,mBAAmB;IAInB,mBAAmB,CAAC,MAAM,EAAE,MAAM;IAIzC,OAAO,CAAC,cAAc,CAAc;IACpC,OAAO,CAAC,QAAQ,CAAQ;IACjB,MAAM,CAAC,SAAS,CAAC,EAAE,MAAM;IAmChC,OAAO,CAAC,oBAAoB,CAAK;IACjC,OAAO,CAAC,WAAW,CAAiB;IAEpC,OAAO,CAAC,QAAQ;IAIhB,OAAO,CAAC,gBAAgB;IAkBxB,OAAO,CAAC,eAAe;IAUvB,OAAO,CAAC,gBAAgB;IAkBxB,OAAO,CAAC,qBAAqB;CAe9B;AAcD,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,OAAO,QAIhD;AAuGD;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,KAAK,CAAC,QAAQ,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,GAAG,OAAO,CAIzF"}
|
package/dist/rendering.js
CHANGED
@@ -1,4 +1,4 @@
|
|
1
|
-
var e;import{__decorate as t,__metadata as i}from"tslib";import*as s from"three";import{Color as r,Material as n,Matrix4 as a,Mesh as o,PerspectiveCamera as h,ShaderChunk as l,ShaderMaterial as d}from"three";import{EffectComposer as c,FXAAShader as m,GammaCorrectionShader as p,RenderPass as u,ShaderPass as f,UnrealBloomPass as g,VRButton as v}from"three-stdlib";import{CSMShader as x,CSMUtil as w}from"./csm.js";import{NodeShaderMaterial as b}from"three-shader-graph";import{Reflector as T}from"three-stdlib";import{OutputPass as y}from"three/examples/jsm/Addons.js";import{CSM as M}from"three/examples/jsm/csm/CSM.js";import C from"three/examples/jsm/libs/stats.module.js";import{GTAOPass as R}from"three/examples/jsm/postprocessing/GTAOPass.js";import{Service as P}from"typedi";import{depthUniformName as S,farUniformName as D,nearUniformName as F,resolutionUniformName as W,supportsDepthTextureExtension as H}from"./shader-nodes/depth.js";import{elapsedTimeUniformName as A}from"./shader-nodes/time.js";import{DepthPass as L}from"./utils/three/depth-pass.js";import{GPUStatsPanel as k}from"./utils/three/gpu-stats-panel.js";import{OutlinePass as O}from"./utils/three/outline-pass.js";import{findFirstVisibleObject as j}from"./utils/three/traverse.js";(new s.Layers).set(9);const E=new s.MeshBasicMaterial({color:"black"}),B=new s.MeshDepthMaterial;B.depthPacking=s.RGBADepthPacking,B.blending=s.NoBlending,B.side=s.DoubleSide;const U=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);let z=e=class{setPaused(e){this.paused=e}resizeRender(){this.previousClientWith===this.container.clientWidth&&this.previousClientHeight===this.container.clientHeight||(this.previousClientWith=this.container.clientWidth,this.previousClientHeight=this.container.clientHeight,this.camera instanceof h&&(this.camera.aspect=this.container.clientWidth/this.container.clientHeight,this.camera.updateProjectionMatrix()),this.renderer.setPixelRatio(Math.min(this.maxPixelRatio,window.devicePixelRatio)*this.resolutionScale),this.renderer.setSize(this.container.clientWidth,this.container.clientHeight),this.composer.setSize(this.container.clientWidth*this.resolutionScale,this.container.clientHeight*this.resolutionScale),this.bloomComposer.setSize(this.container.clientWidth*this.resolutionScale,this.container.clientHeight*this.resolutionScale),this.aoMaskDepthRenderTarget.dispose(),this.aoMaskDepthRenderTarget=e.createAOMaskDepthRenderTarget(this.renderer,this.container),this.aoPass.blendMaterial.uniforms.tDepth.value=this.aoMaskDepthRenderTarget.depthTexture,this.depthRenderTarget.dispose(),this.depthRenderTarget=e.createDepthRenderTarget(this.renderer,this.container))}constructor(t,i={}){this.container=t,this.options=i,this.windowVisible=!0,this.running=!0,this.paused=!1,this.fpsCap=null,this.resolutionScale=U?.5:1,this.maxPixelRatio=U?1:window.devicePixelRatio,this.onResize=()=>{this.resizeRender(),this.paused||this.render()},this.onVisiblityChane=()=>{this.windowVisible=!document.hidden},this.isDepthTextureExtensionSupported=!1,this.onLoopCallbacks=[],this.stats=new C,this._showStats=!0,this.insetHeight=200,this.insetWidth=this.insetHeight*(16/9),this.insetOffsetY=250,this.insetMargin=10,this.maxInsetCameras=4,this.overlayCameras=new Set,this.prevClearColor=new r,this.hadBloom=!1,this.bloomStoredMaterials={},this.bloomHidden=[],null!=i.maxPixelRatio&&(this.maxPixelRatio=i.maxPixelRatio),window.renderer=this.renderer=new s.WebGLRenderer({antialias:!0,powerPreference:"high-performance"}),this.scene=new s.Scene,this.renderer.setPixelRatio(Math.min(this.maxPixelRatio,window.devicePixelRatio)*this.resolutionScale),this.renderer.setSize(t.clientWidth,t.clientHeight),this.renderer.xr.enabled=this.options.enableXR??!1,!0===this.options.enableXR&&document.body.appendChild(v.createButton(this.renderer)),this.composer=new c(this.renderer);var n=t.clientWidth/t.clientHeight;const a=new s.PerspectiveCamera(45,n,.5,800);a.layers.enable(19),this.setCamera(a),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=s.PCFSoftShadowMap,this.renderer.shadowMap.autoUpdate=i.shadows?.autoUpdate??!1,this.renderer.outputColorSpace=s.SRGBColorSpace,this.renderer.toneMapping=s.NoToneMapping,this.renderer.toneMappingExposure=1,this.renderer.gammaFactor=1.4,w.renderingView=this,w.patchThreeAdd(),this.isDepthTextureExtensionSupported=H(this.renderer),t.replaceChildren(this.renderer.domElement),this.setupEventListeners(),this.depthRenderTarget=e.createDepthRenderTarget(this.renderer,this.container),this.aoMaskDepthRenderTarget=e.createAOMaskDepthRenderTarget(this.renderer,this.container);const o=new u(this.scene,this.camera);this.composer.addPass(o);const h=new g(new s.Vector2(t.clientWidth,t.clientHeight),1.5,.4,.85);h.threshold=1,h.strength=.9,h.radius=.5,this.bloomPass=h;const l=new R(this.scene,this.camera,t.clientWidth,t.clientWidth);l.blendMaterial.uniforms.tDepth={value:this.aoMaskDepthRenderTarget.depthTexture},l.blendMaterial.uniforms.tAODepth={value:l.depthTexture},l.blendMaterial.fragmentShader="\n uniform float intensity;\n uniform sampler2D tDiffuse;\n uniform sampler2D tDepth;\n uniform sampler2D tAODepth;\n varying vec2 vUv;\n\n void main() {\n vec4 texel = texture2D( tDiffuse, vUv );\n float d = textureLod(tDepth, vUv.xy, 0.0).x;\n float d2 = textureLod(tAODepth, vUv.xy, 0.0).x;\n\n float depth = 2.0 * 1.0 * 500.0 / (500.0 + 1.0 - (2.0 * d - 1.0) * (500.0 - 1.0));\n gl_FragColor = vec4(mix(vec3(1.), texel.rgb, d2 > d ? 0.0 : intensity), texel.a);\n }\n ",l.output=R.OUTPUT.Default,l.enabled=!1,this.aoPass=l,!1!==this.options.ao?.enabled&&this.composer.addPass(l),this.renderer.info.autoReset=!1;const d=new c(this.renderer);d.renderToScreen=!1,d.addPass(o),d.addPass(h),this.bloomComposer=d,d.renderTarget2.texture.type=s.HalfFloatType,this.composer.renderTarget1.texture.type=s.HalfFloatType;const x=new f(new s.ShaderMaterial({uniforms:{baseTexture:{value:null},bloomTexture:{value:d.renderTarget2.texture}},vertexShader:"\n varying vec2 vUv;\n void main() {\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n }",fragmentShader:"\n uniform sampler2D baseTexture;\n uniform sampler2D bloomTexture;\n varying vec2 vUv;\n void main() {\n gl_FragColor = ( texture2D( baseTexture, vUv ) + vec4( 1.0 ) * texture2D( bloomTexture, vUv ) );\n }",defines:{}}),"baseTexture");if(x.needsSwap=!0,this.composer.addPass(x),this.outlinePass=new O(new s.Vector2(t.clientWidth,t.clientHeight),this.scene,this.camera),!0===i.enableOutlines){this.outlinePass.edgeThickness=0,this.outlinePass.edgeGlow=0,this.outlinePass.edgeThickness=1.5,this.outlinePass.edgeStrength=5,this.outlinePass.clear=!1,this.composer.addPass(this.outlinePass);const e=new f(m);e.uniforms.resolution.value.set(1/t.clientWidth,1/t.clientHeight),this.composer.addPass(e)}new f(p).clear=!1,this.fixStatsStyle();const b=new y;this.composer.addPass(b)}fixStatsStyle(){const e=this.stats.dom;e.style.position="absolute";const t=e.getElementsByTagName("canvas");for(let e=0;e<t.length;e++)t.item(e).style.display="inline-block"}setCamera(e){this.camera=e,this.composer.passes.forEach((t=>{t instanceof u?t.camera=e:t instanceof O?t.renderCamera=e:(t instanceof L||t instanceof R)&&(t.camera=e)})),null==this.csm?(this.csm=new M({maxFar:500,lightFar:250,lightMargin:20,cascades:4,shadowMapSize:2048,lightDirection:new s.Vector3(.5,-1,-.6).normalize(),lightIntensity:.5*Math.PI,camera:this.camera,parent:this.scene}),l.lights_fragment_begin=x.lights_fragment_begin):(this.csm.camera=this.camera,this.camera instanceof h&&(this.csm.maxFar=this.camera.far)),this.csm.updateFrustums()}setSelectedObjects(e){const t=new Map;for(const i of e)t.set(i.uuid,i);for(const i of e)i.traverse((e=>{e.uuid!==i.uuid&&t.has(e.uuid)&&t.delete(e.uuid)}));this.outlinePass.selectedObjects=Array.from(t.values())}static createDepthRenderTarget(e,t){var i=!!e.extensions.get("WEBGL_depth_texture");const r=new s.WebGLRenderTarget(t.clientWidth*e.getPixelRatio(),t.clientHeight*e.getPixelRatio());return r.texture.minFilter=s.NearestFilter,r.texture.magFilter=s.NearestFilter,r.texture.generateMipmaps=!1,r.stencilBuffer=!1,!0===i&&(r.depthTexture=new s.DepthTexture(128,128),r.depthTexture.type=s.UnsignedShortType,r.depthTexture.minFilter=s.NearestFilter,r.depthTexture.magFilter=s.NearestFilter),r}static createAOMaskDepthRenderTarget(e,t){const i=new s.WebGLRenderTarget(t.clientWidth*e.getPixelRatio(),t.clientHeight*e.getPixelRatio(),{type:s.HalfFloatType});return i.texture.minFilter=s.NearestFilter,i.texture.magFilter=s.NearestFilter,i.texture.generateMipmaps=!1,i.stencilBuffer=!1,i.depthTexture=new s.DepthTexture(128,128),i.depthTexture.type=s.UnsignedInt248Type,i.depthTexture.minFilter=s.NearestFilter,i.depthTexture.magFilter=s.NearestFilter,i}setupEventListeners(){window.addEventListener("resize",this.onResize),window.addEventListener("orientationchange",this.onResize),document.addEventListener("visibilitychange",this.onVisiblityChane)}stop(){this.running=!1,window.removeEventListener("resize",this.onResize),window.removeEventListener("orientationchange",this.onResize),document.removeEventListener("visibilitychange",this.onVisiblityChane),this.onLoopCallbacks=[],this.renderer.dispose(),this.depthRenderTarget.dispose(),this.aoMaskDepthRenderTarget.dispose(),this.csm.dispose(),this.container.replaceChildren()}onLoop(e){this.onLoopCallbacks.push(e)}removeOnLoop(e){const t=this.onLoopCallbacks.find(e);t>=0&&this.onLoopCallbacks.splice(t,1)}set showStats(e){this._showStats=e,this._showStats&&!this.container.contains(this.stats.dom)?this.container.appendChild(this.stats.dom):!this._showStats&&this.container.contains(this.stats.dom)&&this.container.removeChild(this.stats.dom)}get showStats(){return this._showStats}applyEnvMap(e){null!=this.scene.environment&&e instanceof b&&(null==e.uniforms.envMap&&(e.uniforms.envMap={value:this.scene.environment}),null==e.uniforms.envMapIntensity&&(e.uniforms.envMapIntensity={value:1}),e.uniforms.envMap.value=this.scene.environment,e.uniforms.envMapIntensity.value=this.scene.environmentIntensity,e.envMap=this.scene.environment)}loop(e,t=!1){const i=this.stats,r=i.addPanel(new C.Panel("Calls","#83f","#002")),h=i.addPanel(new C.Panel("Triangles","#c32","#002"));let l;navigator.userAgent.includes("Chrome")&&navigator.userAgent.includes("HologyEngine")&&(l=new k(this.renderer.getContext()),i.addPanel(l)),this.showStats=t;let d=10,c=1e3;const m=()=>{const e=this.renderer.info.render.calls;e>d&&(d=e,setTimeout((()=>d=10),5e3)),r.update(e,d);const t=this.renderer.info.render.triangles;t>c&&(c=t,setTimeout((()=>c=1e3),5e3)),h.update(t,c)};performance.now();s.Ray.prototype.intersectTriangle;const p=[],u=[];let f=0;const g=new a,v=new a,x=t=>{const r=this.renderer.getContext();if(this.paused&&this.running&&r.drawingBufferHeight>1)return void setTimeout((()=>x(t)),500);this.renderer.autoClear=!1,this.renderer.clear(),this.renderer.setViewport(0,0,this.container.clientWidth,this.container.clientHeight),this.camera,i.begin();let a=(t*=.001)-f;if(f=t,g.copy(this.camera.matrixWorld),a>1){let t=a;for(;t>.05;)e(V),t-=V;e(t)}else e(a);this.onLoopCallbacks.forEach((e=>e(a))),this.camera?.updateMatrixWorld(),v.copy(this.camera.matrixWorld),v.equals(g)||(this.renderer.shadowMap.needsUpdate=!0),this.resizeRender(),p.length=0,u.length=0;const h=_;if(this.camera.updateMatrixWorld(),N.multiplyMatrices(this.camera.projectionMatrix,this.camera.matrixWorldInverse),h.setFromProjectionMatrix(N),this.scene.traverseVisible((e=>{if(null!=this.scene.environment&&(e instanceof o||e instanceof s.Sprite)&&function(e,t){if(Array.isArray(e.material))for(const i of e.material)t(i);else null!=e.material&&t(e.material)}(e,(e=>this.applyEnvMap(e))),(e instanceof o||e instanceof s.Sprite)&&e.visible&&(e.material?.userData?.water||e.material?.uniforms&&null!=e.material?.uniforms[S])&&isObjectInFrustum(e,h)?(e.visible=!1,p.push(e),this.initDepthUniform(e.material),e.renderOrder=100):e instanceof T?(e.visible=!1,u.push(e)):(e instanceof o||e instanceof s.Sprite)&&function(e){if(e.material instanceof n)return e.material.transparent||e.material.alphaTest>0;if(Array.isArray(e.material))for(const t of e.material)if(t.transparent||t.alphaTest>0)return!0}(e)&&(e.visible=!1,e.layers.enable(5),u.push(e)),e instanceof o&&e.material?.uniforms&&null!=e.material?.uniforms[A])e.material.uniforms[A].value=t;else if(e instanceof o&&Array.isArray(e.material))for(const i of e.material)i.uniforms&&null!=i.uniforms[A]&&(i.uniforms[A].value=t)})),p.length>0){if(this.scene.overrideMaterial=B,this.renderer.setRenderTarget(this.depthRenderTarget),!this.paused&&null!=this.camera)try{this.renderer.clear(),this.renderer.render(this.scene,this.camera)}catch(e){console.warn(e)}this.renderer.setRenderTarget(null),this.scene.overrideMaterial=null}if(p.forEach((e=>e.visible=!0)),u.forEach((e=>e.visible=!0)),this.aoPass.enabled){if(this.scene.overrideMaterial=B,this.camera.layers.set(5),this.renderer.setRenderTarget(this.aoMaskDepthRenderTarget),!this.paused&&null!=this.camera)try{this.renderer.clear(),this.renderer.render(this.scene,this.camera)}catch(e){console.warn(e)}this.camera.layers.enableAll(),this.renderer.setRenderTarget(null),this.scene.overrideMaterial=null}try{!this.paused&&this.running&&(this.showStats&&l?.startQuery(),this.render(a),this.showStats&&l?.endQuery(),this.showStats&&m(),this.renderer.info.reset(),this.renderOverlay())}catch(e){console.warn(e)}i.end(),this.csm?.update(),this.running&&!0!==this.options.enableXR&&(this.fpsCap?setTimeout((()=>{requestAnimationFrame(x)}),1e3/this.fpsCap):requestAnimationFrame(x))};!0===this.options.enableXR?this.renderer.setAnimationLoop(x):requestAnimationFrame(x)}renderOverlay(){const e=Array.from(this.overlayCameras.values()).slice(0,this.maxInsetCameras),t=this.container.clientWidth/2,i=e.length*this.insetWidth+(e.length-1)*this.insetMargin;for(let s=0;s<e.length;s++)this.renderer.clearDepth(),this.renderer.setViewport(t-i/2+this.insetWidth*s+this.insetMargin*s,this.insetOffsetY,this.insetWidth,this.insetHeight),this.renderer.render(this.scene,e[s])}addOverlayCamera(e){this.overlayCameras.add(e)}clearOverlayCameras(){this.overlayCameras.clear()}removeOverlayCamera(e){this.overlayCameras.delete(e)}render(e){const t=this.hasBloom();if(t||this.hadBloom){const e=this.scene.fog;this.scene.fog=null;const t=this.renderer.getClearColor(this.prevClearColor);this.renderer.setClearColor(0),this.scene.traverseVisible((e=>this.darkenNonBloomed(e))),this.bloomComposer.render(),this.scene.traverse((e=>this.restoreMaterial(e))),this.bloomHidden.forEach((e=>e.visible=!0)),this.bloomHidden.length=0,this.renderer.setClearColor(t),this.scene.fog=e}this.hadBloom=t,this.composer.render(e)}hasBloom(){return null!=j(this.scene,(e=>e instanceof o&&!0===e.material?.userData?.hasBloom))}darkenNonBloomed(e){(e instanceof o||e instanceof s.Sprite||e instanceof s.Line)&&e.visible&&(null==e.material.userData||!0!==e.material.userData.hasBloom)?(this.bloomStoredMaterials[e.uuid]=e.material,!0!==e.material.transparent?e.material=E:e.visible=!1):"TransformControlsPlane"!==e.type&&"TransformControlsGizmo"!==e.type||(e.visible=!1,this.bloomHidden.push(e))}restoreMaterial(e){this.bloomStoredMaterials[e.uuid]&&(e.material=this.bloomStoredMaterials[e.uuid],delete this.bloomStoredMaterials[e.uuid],e.visible=!0)}initDepthUniform(e){e instanceof d&&(e.uniforms[S].value=this.isDepthTextureExtensionSupported?this.depthRenderTarget.depthTexture:this.depthRenderTarget.texture,null!=e.uniforms[W]&&e.uniforms[W].value.set(this.container.clientWidth*this.renderer.getPixelRatio(),this.container.clientHeight*this.renderer.getPixelRatio()),this.camera instanceof h&&(null!=e.uniforms[F]&&(e.uniforms[F].value=this.camera.near),null!=e.uniforms[D]&&(e.uniforms[D].value=this.camera.far)))}};z=e=t([P(),i("design:paramtypes",[HTMLElement,Object])],z);export{z as RenderingView};export function setRenderingPaused(e){null!=window.editor?.viewer?.renderingView&&(window.editor.viewer.renderingView.paused=e)}const V=.05;R.prototype.overrideVisibility=function(){const e=this.scene,t=this._visibilityCache;e.traverse((function(e){if(t.set(e,e.visible),(e.isPoints||e.isLine||e.isTransformControls)&&(e.visible=!1),null!=e.material){let t=!1;if(Array.isArray(e.material)){for(const i of e.material)if(null!=i.alphaTest&&i.alphaTest>0){t=!0;break}}else null!=e.material.alphaTest&&e.material.alphaTest>0&&(t=!0);t&&(e.visible=!1)}}))};const _=new s.Frustum,I=new s.Box3,N=new s.Matrix4;export function isObjectInFrustum(e,t){const i=I.setFromObject(e);return t.intersectsBox(i)}/*
|
1
|
+
var e;import{__decorate as t,__metadata as i}from"tslib";import*as r from"three";import{Color as s,Material as n,Matrix4 as a,Mesh as o,PerspectiveCamera as h,ShaderChunk as l,ShaderMaterial as d}from"three";import{EffectComposer as c,FXAAShader as m,GammaCorrectionShader as u,RenderPass as p,ShaderPass as f,UnrealBloomPass as g,VRButton as v}from"three-stdlib";import{CSMShader as x,CSMUtil as w}from"./csm.js";import{NodeShaderMaterial as b}from"three-shader-graph";import{Reflector as T}from"three-stdlib";import{OutputPass as y}from"three/examples/jsm/Addons.js";import{CSM as R}from"three/examples/jsm/csm/CSM.js";import C from"three/examples/jsm/libs/stats.module.js";import{GTAOPass as M}from"three/examples/jsm/postprocessing/GTAOPass.js";import{Service as S}from"typedi";import{depthUniformName as P,farUniformName as D,nearUniformName as F,resolutionUniformName as W,supportsDepthTextureExtension as H}from"./shader-nodes/depth.js";import{elapsedTimeUniformName as A}from"./shader-nodes/time.js";import{sceneMapUniformName as L}from"./shader-nodes/scene-sample.js";import{DepthPass as j}from"./utils/three/depth-pass.js";import{GPUStatsPanel as E}from"./utils/three/gpu-stats-panel.js";import{OutlinePass as O}from"./utils/three/outline-pass.js";import{findFirstVisibleObject as k}from"./utils/three/traverse.js";(new r.Layers).set(9);const B=new r.MeshBasicMaterial({color:"black"}),U=new r.MeshDepthMaterial;U.depthPacking=r.RGBADepthPacking,U.blending=r.NoBlending,U.side=r.DoubleSide;const z=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);let V=e=class{setPaused(e){this.paused=e}resizeRender(){this.previousClientWith===this.container.clientWidth&&this.previousClientHeight===this.container.clientHeight||0!==this.container.clientWidth&&0!==this.container.clientHeight&&(this.previousClientWith=this.container.clientWidth,this.previousClientHeight=this.container.clientHeight,this.camera instanceof h&&(this.camera.aspect=this.container.clientWidth/this.container.clientHeight,this.camera.updateProjectionMatrix()),this.renderer.setPixelRatio(Math.min(this.maxPixelRatio,window.devicePixelRatio)*this.resolutionScale),this.renderer.setSize(this.container.clientWidth,this.container.clientHeight),this.composer.setSize(this.container.clientWidth*this.resolutionScale,this.container.clientHeight*this.resolutionScale),this.bloomComposer.setSize(this.container.clientWidth*this.resolutionScale,this.container.clientHeight*this.resolutionScale),this.aoMaskDepthRenderTarget.dispose(),this.aoMaskDepthRenderTarget=e.createAOMaskDepthRenderTarget(this.renderer,this.container),this.aoPass.blendMaterial.uniforms.tDepth.value=this.aoMaskDepthRenderTarget.depthTexture,this.depthRenderTarget.dispose(),this.depthRenderTarget=e.createDepthRenderTarget(this.renderer,this.container),this.sceneColorRenderTarget.dispose(),this.sceneColorRenderTarget=e.createSceneColorRenderTarget(this.renderer,this.container))}constructor(t,i={}){this.container=t,this.options=i,this.windowVisible=!0,this.running=!0,this.paused=!1,this.fpsCap=null,this.resolutionScale=z?.5:1,this.maxPixelRatio=z?1:window.devicePixelRatio,this.onResize=()=>{this.resizeRender(),this.paused||this.render()},this.onVisiblityChane=()=>{this.windowVisible=!document.hidden},this.isDepthTextureExtensionSupported=!1,this.onLoopCallbacks=[],this.stats=new C,this._showStats=!0,this.insetHeight=200,this.insetWidth=this.insetHeight*(16/9),this.insetOffsetY=250,this.insetMargin=10,this.maxInsetCameras=4,this.overlayCameras=new Set,this.prevClearColor=new s,this.hadBloom=!1,this.bloomStoredMaterials={},this.bloomHidden=[],null!=i.maxPixelRatio&&(this.maxPixelRatio=i.maxPixelRatio),window.renderer=this.renderer=new r.WebGLRenderer({antialias:!0,powerPreference:"high-performance"}),this.scene=new r.Scene,this.renderer.setPixelRatio(Math.min(this.maxPixelRatio,window.devicePixelRatio)*this.resolutionScale),this.renderer.setSize(t.clientWidth,t.clientHeight),this.renderer.xr.enabled=this.options.enableXR??!1,!0===this.options.enableXR&&document.body.appendChild(v.createButton(this.renderer)),this.composer=new c(this.renderer);var n=(t.clientWidth||1)/(t.clientHeight||1);const a=new r.PerspectiveCamera(45,n,.5,800);a.layers.enable(19),this.setCamera(a),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=r.PCFSoftShadowMap,this.renderer.shadowMap.autoUpdate=i.shadows?.autoUpdate??!1,this.renderer.outputColorSpace=r.SRGBColorSpace,this.renderer.toneMapping=r.NoToneMapping,this.renderer.toneMappingExposure=1,this.renderer.gammaFactor=1.4,w.renderingView=this,w.patchThreeAdd(),this.isDepthTextureExtensionSupported=H(this.renderer),t.replaceChildren(this.renderer.domElement),this.setupEventListeners(),this.depthRenderTarget=e.createDepthRenderTarget(this.renderer,this.container),this.aoMaskDepthRenderTarget=e.createAOMaskDepthRenderTarget(this.renderer,this.container),this.sceneColorRenderTarget=e.createSceneColorRenderTarget(this.renderer,this.container);const o=new p(this.scene,this.camera);this.composer.addPass(o);const h=new g(new r.Vector2(t.clientWidth,t.clientHeight),1.5,.4,.85);h.threshold=1,h.strength=.9,h.radius=.5,this.bloomPass=h;const l=new M(this.scene,this.camera,t.clientWidth,t.clientWidth);l.blendMaterial.uniforms.tDepth={value:this.aoMaskDepthRenderTarget.depthTexture},l.blendMaterial.uniforms.tAODepth={value:l.depthTexture},l.blendMaterial.fragmentShader="\n uniform float intensity;\n uniform sampler2D tDiffuse;\n uniform sampler2D tDepth;\n uniform sampler2D tAODepth;\n varying vec2 vUv;\n\n void main() {\n vec4 texel = texture2D( tDiffuse, vUv );\n float d = textureLod(tDepth, vUv.xy, 0.0).x;\n float d2 = textureLod(tAODepth, vUv.xy, 0.0).x;\n\n float depth = 2.0 * 1.0 * 500.0 / (500.0 + 1.0 - (2.0 * d - 1.0) * (500.0 - 1.0));\n gl_FragColor = vec4(mix(vec3(1.), texel.rgb, d2 > d ? 0.0 : intensity), texel.a);\n }\n ",l.output=M.OUTPUT.Default,l.enabled=!1,this.aoPass=l,!1!==this.options.ao?.enabled&&this.composer.addPass(l),this.renderer.info.autoReset=!1;const d=new c(this.renderer);d.renderToScreen=!1,d.addPass(o),d.addPass(h),this.bloomComposer=d,z||(d.renderTarget2.texture.type=r.HalfFloatType,this.composer.renderTarget1.texture.type=r.HalfFloatType);const x=new f(new r.ShaderMaterial({uniforms:{baseTexture:{value:null},bloomTexture:{value:d.renderTarget2.texture}},vertexShader:"\n varying vec2 vUv;\n void main() {\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n }",fragmentShader:"\n uniform sampler2D baseTexture;\n uniform sampler2D bloomTexture;\n varying vec2 vUv;\n void main() {\n gl_FragColor = ( texture2D( baseTexture, vUv ) + vec4( 1.0 ) * texture2D( bloomTexture, vUv ) );\n }",defines:{}}),"baseTexture");if(x.needsSwap=!0,this.composer.addPass(x),this.outlinePass=new O(new r.Vector2(t.clientWidth,t.clientHeight),this.scene,this.camera),!0===i.enableOutlines){this.outlinePass.edgeThickness=0,this.outlinePass.edgeGlow=0,this.outlinePass.edgeThickness=1.5,this.outlinePass.edgeStrength=5,this.outlinePass.clear=!1,this.composer.addPass(this.outlinePass);const e=new f(m);e.uniforms.resolution.value.set(1/t.clientWidth,1/t.clientHeight),this.composer.addPass(e)}new f(u).clear=!1,this.fixStatsStyle();const b=new y;this.composer.addPass(b)}fixStatsStyle(){const e=this.stats.dom;e.style.position="absolute";const t=e.getElementsByTagName("canvas");for(let e=0;e<t.length;e++)t.item(e).style.display="inline-block"}setCamera(e){this.camera=e,this.composer.passes.forEach((t=>{t instanceof p?t.camera=e:t instanceof O?t.renderCamera=e:(t instanceof j||t instanceof M)&&(t.camera=e)})),null==this.csm?(this.csm=new R({maxFar:500,lightFar:250,lightMargin:20,cascades:4,shadowMapSize:2048,lightDirection:new r.Vector3(.5,-1,-.6).normalize(),lightIntensity:.5*Math.PI,camera:this.camera,parent:this.scene}),l.lights_fragment_begin=x.lights_fragment_begin):(this.csm.camera=this.camera,this.camera instanceof h&&(this.csm.maxFar=this.camera.far)),this.csm.updateFrustums()}setSelectedObjects(e){const t=new Map;for(const i of e)t.set(i.uuid,i);for(const i of e)i.traverse((e=>{e.uuid!==i.uuid&&t.has(e.uuid)&&t.delete(e.uuid)}));this.outlinePass.selectedObjects=Array.from(t.values())}static createDepthRenderTarget(e,t){var i=!!e.extensions.get("WEBGL_depth_texture");const s=new r.WebGLRenderTarget(t.clientWidth*e.getPixelRatio(),t.clientHeight*e.getPixelRatio());return s.texture.minFilter=r.NearestFilter,s.texture.magFilter=r.NearestFilter,s.texture.generateMipmaps=!1,s.stencilBuffer=!1,!0===i&&(s.depthTexture=new r.DepthTexture(128,128),s.depthTexture.type=r.UnsignedShortType,s.depthTexture.minFilter=r.NearestFilter,s.depthTexture.magFilter=r.NearestFilter),s}static createAOMaskDepthRenderTarget(e,t){const i=new r.WebGLRenderTarget(t.clientWidth*e.getPixelRatio(),t.clientHeight*e.getPixelRatio(),{type:r.HalfFloatType});return i.texture.minFilter=r.NearestFilter,i.texture.magFilter=r.NearestFilter,i.texture.generateMipmaps=!1,i.stencilBuffer=!1,i.depthTexture=new r.DepthTexture(128,128),i.depthTexture.type=r.UnsignedInt248Type,i.depthTexture.minFilter=r.NearestFilter,i.depthTexture.magFilter=r.NearestFilter,i}static createSceneColorRenderTarget(e,t){const i=new r.WebGLRenderTarget(t.clientWidth*e.getPixelRatio()*.5,t.clientHeight*e.getPixelRatio()*.5,{format:r.RGBAFormat,colorSpace:r.SRGBColorSpace,stencilBuffer:!1});return i.texture.minFilter=r.LinearFilter,i.texture.magFilter=r.LinearFilter,i.texture.generateMipmaps=!1,i}setupEventListeners(){window.addEventListener("resize",this.onResize),window.addEventListener("orientationchange",this.onResize),document.addEventListener("visibilitychange",this.onVisiblityChane)}stop(){this.running=!1,window.removeEventListener("resize",this.onResize),window.removeEventListener("orientationchange",this.onResize),document.removeEventListener("visibilitychange",this.onVisiblityChane),this.onLoopCallbacks=[],this.renderer.dispose(),this.depthRenderTarget.dispose(),this.aoMaskDepthRenderTarget.dispose(),this.sceneColorRenderTarget.dispose(),this.csm.dispose(),this.container.replaceChildren()}onLoop(e){this.onLoopCallbacks.push(e)}removeOnLoop(e){const t=this.onLoopCallbacks.find(e);t>=0&&this.onLoopCallbacks.splice(t,1)}set showStats(e){this._showStats=e,this._showStats&&!this.container.contains(this.stats.dom)?this.container.appendChild(this.stats.dom):!this._showStats&&this.container.contains(this.stats.dom)&&this.container.removeChild(this.stats.dom)}get showStats(){return this._showStats}applyEnvMap(e){null!=this.scene.environment&&e instanceof b&&(null==e.uniforms.envMap&&(e.uniforms.envMap={value:this.scene.environment}),null==e.uniforms.envMapIntensity&&(e.uniforms.envMapIntensity={value:1}),e.uniforms.envMap.value=this.scene.environment,e.uniforms.envMapIntensity.value=this.scene.environmentIntensity,e.envMap=this.scene.environment)}loop(e,t=!1){const i=this.stats,s=i.addPanel(new C.Panel("Calls","#83f","#002")),h=i.addPanel(new C.Panel("Triangles","#c32","#002"));let l;navigator.userAgent.includes("Chrome")&&navigator.userAgent.includes("HologyEngine")&&(l=new E(this.renderer.getContext()),i.addPanel(l)),this.showStats=t;let d=10,c=1e3;const m=()=>{const e=this.renderer.info.render.calls;e>d&&(d=e,setTimeout((()=>d=10),5e3)),s.update(e,d);const t=this.renderer.info.render.triangles;t>c&&(c=t,setTimeout((()=>c=1e3),5e3)),h.update(t,c)};performance.now();r.Ray.prototype.intersectTriangle;const u=[],p=[],f=[];let g=0;const v=new a,x=new a,w=t=>{const s=this.renderer.getContext();if(this.paused&&this.running&&s.drawingBufferHeight>1)return void setTimeout((()=>w(t)),500);this.renderer.autoClear=!1,this.renderer.clear(),this.renderer.setViewport(0,0,this.container.clientWidth,this.container.clientHeight),this.camera,i.begin();let a=(t*=.001)-g;if(g=t,v.copy(this.camera.matrixWorld),a>1){let t=a;for(;t>.05;)e(_),t-=_;e(t)}else e(a);this.onLoopCallbacks.forEach((e=>e(a))),this.camera?.updateMatrixWorld(),x.copy(this.camera.matrixWorld),x.equals(v)||(this.renderer.shadowMap.needsUpdate=!0),this.resizeRender(),u.length=0,p.length=0,f.length=0;const h=I;if(this.camera.updateMatrixWorld(),G.multiplyMatrices(this.camera.projectionMatrix,this.camera.matrixWorldInverse),h.setFromProjectionMatrix(G),this.scene.traverseVisible((e=>{if(null!=this.scene.environment&&(e instanceof o||e instanceof r.Sprite)&&function(e,t){if(Array.isArray(e.material))for(const i of e.material)t(i);else null!=e.material&&t(e.material)}(e,(e=>this.applyEnvMap(e))),(e instanceof o||e instanceof r.Sprite)&&this.initResolutionUniform(e.material),(e instanceof o||e instanceof r.Sprite)&&e.visible&&(e.material?.userData?.water||e.material?.uniforms&&null!=e.material?.uniforms[P])&&isObjectInFrustum(e,h)?(e.visible=!1,u.push(e),this.initDepthUniform(e.material),e.renderOrder=100):e instanceof T?(e.visible=!1,p.push(e)):(e instanceof o||e instanceof r.Sprite)&&e.visible&&e.material?.uniforms&&null!=e.material?.uniforms[L]&&isObjectInFrustum(e,h)?(e.visible=!1,f.push(e),e.material.uniforms[L].value=this.sceneColorRenderTarget.texture):(e instanceof o||e instanceof r.Sprite)&&function(e){if(e.material instanceof n)return e.material.transparent||e.material.alphaTest>0;if(Array.isArray(e.material))for(const t of e.material)if(t.transparent||t.alphaTest>0)return!0}(e)&&(e.visible=!1,e.layers.enable(5),p.push(e)),e instanceof o&&e.material?.uniforms&&null!=e.material?.uniforms[A])e.material.uniforms[A].value=t;else if(e instanceof o&&Array.isArray(e.material))for(const i of e.material)i.uniforms&&null!=i.uniforms[A]&&(i.uniforms[A].value=t)})),u.length>0){if(this.scene.overrideMaterial=U,this.renderer.setRenderTarget(this.depthRenderTarget),!this.paused&&null!=this.camera)try{this.renderer.clear(),this.renderer.render(this.scene,this.camera)}catch(e){console.warn(e)}this.renderer.setRenderTarget(null),this.scene.overrideMaterial=null}if(f.length>0){if(this.renderer.setRenderTarget(this.sceneColorRenderTarget),!this.paused&&null!=this.camera)try{this.renderer.clear(!0,!0,!1),this.renderer.render(this.scene,this.camera)}catch(e){console.warn("Error rendering scene color:",e)}this.renderer.setRenderTarget(null)}if(u.forEach((e=>e.visible=!0)),p.forEach((e=>e.visible=!0)),f.forEach((e=>e.visible=!0)),this.aoPass.enabled){if(this.scene.overrideMaterial=U,this.camera.layers.set(5),this.renderer.setRenderTarget(this.aoMaskDepthRenderTarget),!this.paused&&null!=this.camera)try{this.renderer.clear(),this.renderer.render(this.scene,this.camera)}catch(e){console.warn(e)}this.camera.layers.enableAll(),this.renderer.setRenderTarget(null),this.scene.overrideMaterial=null}try{!this.paused&&this.running&&(this.showStats&&l?.startQuery(),this.render(a),this.showStats&&l?.endQuery(),this.showStats&&m(),this.renderer.info.reset(),this.renderOverlay())}catch(e){console.warn(e)}i.end(),this.csm?.update(),this.running&&!0!==this.options.enableXR&&(this.fpsCap?setTimeout((()=>{requestAnimationFrame(w)}),1e3/this.fpsCap):requestAnimationFrame(w))};!0===this.options.enableXR?this.renderer.setAnimationLoop(w):requestAnimationFrame(w)}renderOverlay(){const e=Array.from(this.overlayCameras.values()).slice(0,this.maxInsetCameras),t=this.container.clientWidth/2,i=e.length*this.insetWidth+(e.length-1)*this.insetMargin;for(let r=0;r<e.length;r++)this.renderer.clearDepth(),this.renderer.setViewport(t-i/2+this.insetWidth*r+this.insetMargin*r,this.insetOffsetY,this.insetWidth,this.insetHeight),this.renderer.render(this.scene,e[r])}addOverlayCamera(e){this.overlayCameras.add(e)}clearOverlayCameras(){this.overlayCameras.clear()}removeOverlayCamera(e){this.overlayCameras.delete(e)}render(e){if(0===this.composer.renderTarget1.width||0===this.composer.renderTarget1.height)return;if(0===this.composer.renderTarget2.width||0===this.composer.renderTarget2.height)return;const t=this.hasBloom();if(t||this.hadBloom){const e=this.scene.fog;this.scene.fog=null;const t=this.renderer.getClearColor(this.prevClearColor);this.renderer.setClearColor(0),this.scene.traverseVisible((e=>this.darkenNonBloomed(e))),this.bloomComposer.render(),this.scene.traverse((e=>this.restoreMaterial(e))),this.bloomHidden.forEach((e=>e.visible=!0)),this.bloomHidden.length=0,this.renderer.setClearColor(t),this.scene.fog=e}this.hadBloom=t,this.composer.render(e)}hasBloom(){return null!=k(this.scene,(e=>e instanceof o&&!0===e.material?.userData?.hasBloom))}darkenNonBloomed(e){(e instanceof o||e instanceof r.Sprite||e instanceof r.Line)&&e.visible&&(null==e.material.userData||!0!==e.material.userData.hasBloom)?(this.bloomStoredMaterials[e.uuid]=e.material,!0!==e.material.transparent?e.material=B:e.visible=!1):"TransformControlsPlane"!==e.type&&"TransformControlsGizmo"!==e.type||(e.visible=!1,this.bloomHidden.push(e))}restoreMaterial(e){this.bloomStoredMaterials[e.uuid]&&(e.material=this.bloomStoredMaterials[e.uuid],delete this.bloomStoredMaterials[e.uuid],e.visible=!0)}initDepthUniform(e){e instanceof d&&(e.uniforms[P].value=this.isDepthTextureExtensionSupported?this.depthRenderTarget.depthTexture:this.depthRenderTarget.texture,this.camera instanceof h&&(null!=e.uniforms[F]&&(e.uniforms[F].value=this.camera.near),null!=e.uniforms[D]&&(e.uniforms[D].value=this.camera.far)))}initResolutionUniform(e){e instanceof d&&null!=e.uniforms[W]&&e.uniforms[W].value.set(this.container.clientWidth*this.renderer.getPixelRatio(),this.container.clientHeight*this.renderer.getPixelRatio())}};V=e=t([S(),i("design:paramtypes",[HTMLElement,Object])],V);export{V as RenderingView};export function setRenderingPaused(e){null!=window.editor?.viewer?.renderingView&&(window.editor.viewer.renderingView.paused=e)}const _=.05;M.prototype.overrideVisibility=function(){const e=this.scene,t=this._visibilityCache;e.traverse((function(e){if(t.set(e,e.visible),(e.isPoints||e.isLine||e.isTransformControls)&&(e.visible=!1),null!=e.material){let t=!1;if(Array.isArray(e.material)){for(const i of e.material)if(null!=i.alphaTest&&i.alphaTest>0){t=!0;break}}else null!=e.material.alphaTest&&e.material.alphaTest>0&&(t=!0);t&&(e.visible=!1)}}))};const I=new r.Frustum,N=new r.Box3,G=new r.Matrix4;export function isObjectInFrustum(e,t){const i=N.setFromObject(e);return t.intersectsBox(i)}/*
|
2
2
|
* Copyright (©) 2023. All rights reserved.
|
3
3
|
* See the LICENSE.md file for details.
|
4
4
|
*/
|
@@ -28,6 +28,7 @@ export declare class AssetResourceLoader {
|
|
28
28
|
private getUri;
|
29
29
|
getTexture(asset: Asset): Promise<Texture>;
|
30
30
|
private _getTextureLoader;
|
31
|
+
clearCache(asset: Asset): void;
|
31
32
|
private asyncMeshResults;
|
32
33
|
getMesh(asset: Asset, options?: GetMeshOptions): Promise<LoadedMesh>;
|
33
34
|
getAudio(asset: Asset): Promise<AudioBuffer>;
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"asset-resource-loader.d.ts","sourceRoot":"","sources":["../../src/scene/asset-resource-loader.ts"],"names":[],"mappings":"AAAA,OAAO,EAA6G,QAAQ,EAAE,OAAO,EAA+B,MAAM,OAAO,CAAC;AAIlL,OAAO,EAAE,KAAK,EAAY,MAAM,YAAY,CAAC;AAG7C,OAAO,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AAEhE,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAE/B,OAAO,EAAE,0BAA0B,EAAE,MAAM,mBAAmB,CAAC;AAM/D,qBAAa,mBAAmB;IAC9B,OAAO,CAAC,QAAQ,CAAQ;IACxB,OAAO,CAAC,KAAK,CAAgC;IAC7C,OAAO,CAAC,YAAY,CAA6B;IACjD,OAAO,CAAC,cAAc,CAAuB;IAC7C,OAAO,CAAC,SAAS,CAAuC;IACxD,OAAO,CAAC,SAAS,CAAsC;IACvD,OAAO,CAAC,SAAS,CAAsC;IACvD,OAAO,CAAC,aAAa,CAAyC;IAC9D,OAAO,CAAC,SAAS,CAAqC;IACtD,OAAO,CAAC,SAAS,CAAqC;IACtD,OAAO,CAAC,SAAS,CAA0C;IAC3D,OAAO,CAAC,UAAU,CAAsC;IACxD,OAAO,CAAC,cAAc,CAAmD;IACzE,OAAO,CAAC,WAAW,CAAuC;IAC1D,OAAO,CAAC,eAAe,CAAQ;IAE/B,SAAS,CAAC,OAAO,CAAC,KAAK,EAAE,OAAO;IAIhC,OAAO,CAAC,SAAS,CAAgB;IACjC,OAAO,CAAC,KAAK,CAAiC;;IAIvC,QAAQ,CAAC,QAAQ,EAAE,KAAK,CAAC,aAAa;IAMtC,UAAU,CAAC,IAAI,EAAE,MAAM;IAK9B,OAAO,CAAC,MAAM;IAKD,UAAU,CAAC,KAA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OAAO,CAAC,iBAAiB;IAYlB,UAAU,CAAC,KAAK,EAAE,KAAK;IAU9B,OAAO,CAAC,gBAAgB,CAAyC;IACpD,OAAO,CAAC,KAAK,EAAE,KAAK,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,UAAU,CAAC;IAuDpE,QAAQ,CAAC,KAAK,EAAE,KAAK,GAAG,OAAO,CAAC,WAAW,CAAC;IAMzD,OAAO,CAAC,mBAAmB,CAAsC;IACjE,OAAO,CAAC,sBAAsB;YAShB,QAAQ;IAyBtB,OAAO,CAAC,eAAe,CAAoB;IAC3C,OAAO,CAAC,kBAAkB;YAyEZ,WAAW;CAiC1B;AAgBD,MAAM,WAAW,UAAU;IACzB,KAAK,EAAE,iBAAiB,CAAC;IACzB,UAAU,EAAE,KAAK,CAAC,aAAa,EAAE,CAAA;CAClC;AAED,qBAAa,iBAAkB,SAAQ,QAAQ;IAC7C,eAAe,CAAC,EAAE,cAAc,EAAE,CAAA;IAClC,OAAO,CAAC,EAAE,0BAA0B,CAAA;CACrC;AAED,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAInD;AAiFD,MAAM,MAAM,cAAc,GAAG;IAC3B;;;;OAIG;IACH,cAAc,EAAE,OAAO,CAAA;CACxB,CAAA"}
|
@@ -1,4 +1,4 @@
|
|
1
|
-
import{AudioLoader as e,BufferGeometry as t,Group as s,LoadingManager as
|
1
|
+
import{AudioLoader as e,BufferGeometry as t,Group as s,LoadingManager as a,Mesh as i,Object3D as r,TextureLoader as n}from"three";import{GLTFLoader as o,MTLLoader as h,OBJLoader as c}from"three-stdlib";import{FBXLoader as l}from"three-stdlib";import{cloneMesh as d}from"../utils/mesh.js";import{pathJoin as m}from"../utils/files.js";import{Subject as p,firstValueFrom as u}from"rxjs";import{importCollisionShapes as f,isCollisionMesh as g}from"./collision/collision-shape-import.js";import*as w from"three";import{iterateMaterials as y}from"../utils/materials.js";import{BufferGeometryUtils as x,EXRLoader as L,KTX2Loader as M,TGALoader as b,UltraHDRLoader as A}from"three/examples/jsm/Addons.js";const S=["glb","gltf","fbx","obj"];export class AssetResourceLoader{onError(e){console.error(e)}constructor(){this.cache=new Map,this.textureCache=new Map,this.loadingManager=new a,this.glbLoader=new o(this.loadingManager),this.fbxLoader=new l(this.loadingManager),this.objLoader=new c(this.loadingManager),this.textureLoader=new n(this.loadingManager),this.tgaLoader=new b(this.loadingManager),this.exrLoader=new L(this.loadingManager),this.hdrLoader=new A(this.loadingManager),this.ktx2Loader=new M(this.loadingManager),this._textureLoader=new w.ImageBitmapLoader(this.loadingManager),this.audioLoader=new e(this.loadingManager),this.initialisedKtx2=!1,this.makeReady=new p,this.ready=u(this.makeReady),this.asyncMeshResults=new Map,this.collisionShapeCache=new Map,this.optimizedMeshes=new Set}initKtx2(e){this.initialisedKtx2=!0,this.ktx2Loader.setTranscoderPath("/assets/basis/"),this.ktx2Loader.detectSupport(e)}setDataDir(e){this.basePath=m(e,"asset-resources"),this.makeReady.next(!0)}getUri(e){return m(this.basePath,e)+`?windowId=${getElectronArg("windowId")}`}async getTexture(e){return null==e||null==e.fileKey?null:(await this.ready,this.textureCache.has(e.id)||await this._getTextureLoader(e.fileKey).loadAsync(this.getUri(e.fileKey)).then((t=>(t.wrapS=v(e.texture?.wrapS),t.wrapT=v(e.texture?.wrapT),t.flipY=e.texture?.flipY??!0,this.textureCache.set(e.id,t),t))),this.textureCache.get(e.id))}_getTextureLoader(e){return e?.toLowerCase().endsWith(".tga")?this.tgaLoader:e?.toLowerCase().endsWith(".ktx2")?this.ktx2Loader:e?.toLowerCase().endsWith(".exr")?this.exrLoader:this.textureLoader}clearCache(e){"mesh"===e.type&&Array.from(this.cache.keys()).forEach((t=>{t.startsWith(e.fileKey)&&this.cache.delete(t)}))}async getMesh(e,t){if(await this.ready,null==e)return console.error("No asset was provided"),{scene:new s,animations:[]};if(!S.includes(e.fileFormat?.toLowerCase()))return console.error("Unsupported mesh file format "+e.fileFormat,e),{scene:new s,animations:[]};const a=e.fileKey+(!0===t?.mergeGeomtries?"1":"0");if(!this.cache.has(a))try{this.asyncMeshResults.has(a)||this.asyncMeshResults.set(a,this.loadMesh(e).finally((()=>this.asyncMeshResults.delete(a)))),this.cache.set(a,await this.asyncMeshResults.get(a))}catch(e){return this.onError(e),{scene:new s,animations:[]}}const r=this.cache.get(a).scene,n=this.computeCollisionShapes(e,r);!0===t?.mergeGeomtries&&this.optimizeDrawGroups(r);const o=d(r),h=this.cache.get(a).animations;o.traverse((e=>{e instanceof i&&e.material instanceof Array&&(e.material=e.material.slice())}));const c=new AssetMeshInstance;c.add(o),c.collisionShapes=n,c.animations=h;const l=e.receiveShadow??!0,m=e.castShadow??!1;return o.traverse((e=>{e.castShadow=m,e.receiveShadow=l})),{scene:c,animations:h}}async getAudio(e){return await this.ready,this.audioLoader.loadAsync(this.getUri(e.fileKey))}computeCollisionShapes(e,t){const s=e.id+e.mesh?.collisions?.shapeType;return this.collisionShapeCache.has(s)||this.collisionShapeCache.set(s,f(t,e)),this.collisionShapeCache.get(s)}async loadMesh(e){return await this.ready,await this.loadByAsset(e).then((e=>(e.scene.traverse((e=>{g(e)&&(e.visible=!1)})),e.scene=function(e,t){let s=!1;if(t.traverseVisible((e=>{j.test(e.name)&&(s=!0)})),!s)return t;const a=new w.LOD,i=[t];for(;i.length>0;){const e=i.shift(),t=e.name.match(j);if(null!=t){const s=parseInt(t[1]);0===s?a.addLevel(e,0):console.warn(`Skipping LOD level ${s} for now as LOD is not fully supported`)}else i.push(...e.children)}return a}(0,e.scene),e)))}optimizeDrawGroups(e){if(this.optimizedMeshes.has(e.uuid))return;this.optimizedMeshes.add(e.uuid);let s=!0,a=0,r=0;if(e.traverse((e=>{if(e instanceof i&&e.geometry instanceof t&&!g(e)){a++;const t=Object.keys(e.geometry.attributes).length;t!==r&&0!==r&&(s=!1),r=t}else(e instanceof w.SkinnedMesh||e instanceof w.Bone)&&(s=!1)})),a>1&&s){const s=[],a=[],r=[];e.updateWorldMatrix(!0,!0),e.traverse((e=>{e instanceof i&&e.geometry instanceof t&&!g(e)&&!Array.isArray(e.material)&&(e.updateWorldMatrix(!0,!0),s.push(e.geometry.clone().applyMatrix4(e.matrixWorld)),a.push(e.material),r.push(e))}));for(const e of r)e.removeFromParent();const n=x.mergeGeometries(s,!0),o=[];let h=0;e:for(const e of a){for(const t of o)if(t.m.id===e.id){t.indices.push(h),h++;continue e}o.push({m:e,indices:[h]}),h++}let c=0;for(const e of o){for(const t of e.indices)n.groups[t].materialIndex=c;c++}e.add(new i(n,o.map((e=>e.m))))}e.traverse((e=>{if(e instanceof i&&e.geometry instanceof t){const t=e.geometry;Array.isArray(e.material)&&t.groups.length>1&&t.groups.length>e.material.length&&x.mergeGroups(t)}}))}async loadByAsset(e){const t=this.getUri(e.fileKey);switch(e.fileFormat){case"glb":case"gltf":return this.glbLoader.loadAsync(t).then((e=>({scene:e.scene,animations:e.animations})));case"fbx":return this.fbxLoader.loadAsync(t).then((e=>({scene:e,animations:e.animations})));case"obj":if(null!=e.materialLib){const t=new h;t.materialOptions={normalizeRGB:!1};const s=await t.loadAsync(this.getUri(e.materialLib));this.objLoader.setMaterials(s)}return this.objLoader.loadAsync(t).then((e=>(C(e),e))).then((e=>({scene:e,animations:e.animations})))}}}function C(e){if(e instanceof i)for(const t of y(e.material))t instanceof w.MeshPhongMaterial&&!t.color.isLinear&&(t.color.isLinear=!0);e.children?.forEach(C)}export class AssetMeshInstance extends r{}export function getElectronArg(e){const t=`--${e}=`,s=window.process?.argv.find((e=>e.startsWith(t)));return s?.substring(t.length)}function v(e){switch(e){case"clamp":return w.ClampToEdgeWrapping;case"repeat":return w.RepeatWrapping;case"mirror":return w.MirroredRepeatWrapping}return w.RepeatWrapping}new w.Matrix4;const j=/_LOD(\d+)$/;/*
|
2
2
|
* Copyright (©) 2023. All rights reserved.
|
3
3
|
* See the LICENSE.md file for details.
|
4
4
|
*/
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"collision-shape-import.d.ts","sourceRoot":"","sources":["../../../src/scene/collision/collision-shape-import.ts"],"names":[],"mappings":"AAAA,OAAO,EAAqB,QAAQ,EAA+B,MAAM,OAAO,CAAC;AACjF,OAAO,EAAqB,cAAc,
|
1
|
+
{"version":3,"file":"collision-shape-import.d.ts","sourceRoot":"","sources":["../../../src/scene/collision/collision-shape-import.ts"],"names":[],"mappings":"AAAA,OAAO,EAAqB,QAAQ,EAA+B,MAAM,OAAO,CAAC;AACjF,OAAO,EAAqB,cAAc,EAAqG,MAAM,sBAAsB,CAAC;AAE5K,OAAO,EAAE,KAAK,EAAE,MAAM,sBAAsB,CAAC;AAK7C,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,QAAQ,EAAE,KAAK,EAAE,KAAK,GAAG,cAAc,EAAE,CAyDrF;AAED,wBAAgB,eAAe,CAAC,MAAM,EAAE,QAAQ,WAK/C"}
|
@@ -1,4 +1,4 @@
|
|
1
|
-
import{Box3 as e,Mesh as t,Quaternion as n,Vector3 as s}from"three";import{BoxCollisionShape as i,
|
1
|
+
import{Box3 as e,Mesh as t,Quaternion as n,Vector3 as s}from"three";import{BoxCollisionShape as i,CollisionShapeSource as o,ConvexPolyhedronCollisionShape as r,SphereCollisionShape as a,TrimeshCollisionShape as m}from"./collision-shape.js";new n;export function importCollisionShapes(n,l){let c=l.mesh?.collisions?.shapeType;if(null==c){let e=!1;n.traverse((n=>{(n instanceof t||n.isMesh)&&isCollisionMesh(n)&&(e=!0)})),c=e?"imported":"convex"}const u=[];return n.traverse((n=>{if(n instanceof t||n.isMesh){let t;"imported"===c?t=function(t){if(t.name.startsWith(h.convex))return new r(t);if(t.name.startsWith(h.box)){const n=t.clone();n.quaternion.set(0,0,0,1),n.updateMatrixWorld();const o=(new e).setFromObject(n);return isFinite(o.min.lengthSq())?new i(new s(o.max.x-o.min.x,o.max.y-o.min.y,o.max.z-o.min.z)):null}if(t.name.startsWith(h.sphere)){t.geometry.computeBoundingSphere();const e=t.geometry.boundingSphere.radius*Math.max(t.scale.x,t.scale.y,t.scale.z);return new a(e)}if(t.name.startsWith(h.trimesh))return new m(t.geometry)}(n):"convex"===c?t=new r(n):"mesh"===c&&(t=new m(n.geometry)),null!=t&&(t.source="imported"!==c?o.rendered:o.custom,t.offset=n.getWorldPosition(new s),u.push(t),isCollisionMesh(n)&&(n.visible=!1))}})),u}export function isCollisionMesh(e){return e.name.startsWith(h.convex)||e.name.startsWith(h.box)||e.name.startsWith(h.sphere)||e.name.startsWith(h.trimesh)}var h;!function(e){e.convex="UCX_",e.box="UBX_",e.sphere="USP_",e.trimesh="UTM_"}(h||(h={}));new e;/*
|
2
2
|
* Copyright (©) 2023. All rights reserved.
|
3
3
|
* See the LICENSE.md file for details.
|
4
4
|
*/
|
@@ -1,5 +1,18 @@
|
|
1
1
|
import { SceneObjectPhysicsSettings } from "../../scene/materializer.js";
|
2
2
|
import { BufferGeometry, Euler, Material, Mesh, Vector3 } from "three";
|
3
|
+
export declare enum CollisionShapeSource {
|
4
|
+
/**
|
5
|
+
* The shape is distinct from the rendered mesh
|
6
|
+
* so the offset and rotation should be used even for
|
7
|
+
* instanced meshes in physics system
|
8
|
+
*/
|
9
|
+
custom = 0,
|
10
|
+
/** It is based on the geometry of the rendered mesh
|
11
|
+
* In this case, we will ignore the position and rotation
|
12
|
+
* for instanced meshes
|
13
|
+
*/
|
14
|
+
rendered = 1
|
15
|
+
}
|
3
16
|
export declare class CollisionShape {
|
4
17
|
offset: Vector3;
|
5
18
|
rotation: Euler;
|
@@ -8,6 +21,7 @@ export declare class CollisionShape {
|
|
8
21
|
friction?: number;
|
9
22
|
restitution?: number;
|
10
23
|
collisionGroup?: number;
|
24
|
+
source?: CollisionShapeSource;
|
11
25
|
withRestitution(restitution: number): this;
|
12
26
|
withOffset(vector: Vector3): this;
|
13
27
|
withRotation(rotation: Euler): this;
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"collision-shape.d.ts","sourceRoot":"","sources":["../../../src/scene/collision/collision-shape.ts"],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ED,qBAAa,8BAA+B,SAAQ,cAAc;aAE9C,IAAI,EAAE,IAAI,GAAC,cAAc;gBAAzB,IAAI,EAAE,IAAI,GAAC,cAAc;CAI5C;AAED,qBAAa,qBAAsB,SAAQ,cAAc;aAErC,QAAQ,EAAE,cAAc;gBAAxB,QAAQ,EAAE,cAAc;CAK3C;AAED,qBAAa,kBAAmB,SAAQ,cAAc;aAElC,QAAQ,EAAE,cAAc;gBAAxB,QAAQ,EAAE,cAAc;CAI3C;AAGD,qBAAa,qBAAsB,SAAQ,cAAc;IAE9C,MAAM,EAAE,MAAM;IACd,MAAM,EAAE,MAAM;gBADd,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM;CAIxB;AAGD,qBAAa,iBAAkB,SAAQ,IAAI;IAKhC,cAAc,EAAE,cAAc;IAC9B,OAAO,CAAC,EAAE,0BAA0B;IAL7C,mBAAmB,UAAO;gBAExB,QAAQ,EAAE,cAAc,EACxB,QAAQ,EAAE,QAAQ,EACX,cAAc,EAAE,cAAc,EAC9B,OAAO,CAAC,EAAE,0BAA0B;CAI9C"}
|
@@ -1,4 +1,4 @@
|
|
1
|
-
import{Euler as s,Mesh as e,Vector3 as t}from"three";export class CollisionShape{constructor(){this.offset=new t,this.rotation=new s}withRestitution(s){return this.restitution=s,this}withOffset(s){return this.offset.copy(s),this}withRotation(s){return this.rotation.copy(s),this}withDensity(s){return this.density=s,this}withMass(s){return this.mass=s,this}withFriction(s){return this.friction=s,this}static box(s){return new BoxCollisionShape(s)}static plane(s,e){return new PlaneCollisionShape(s,e)}static sphere(s){return new SphereCollisionShape(s)}static cylinder(s,e,t,i,o){return new CylinderCollisionShape(s,e,t,i,o)}static cone(s,e){return new ConeCollisionShape(s,e)}static convexPolyhedron(s){return new ConvexPolyhedronCollisionShape(s)}static trimesh(s){return new TrimeshCollisionShape(s)}static mesh(s){return new MeshCollisionShape(s)}static capsule(s,e){return new CapsuleCollisionShape(s,e)}}export class BoxCollisionShape extends CollisionShape{constructor(s){super(),this.dimensions=s}}export class PlaneCollisionShape extends CollisionShape{constructor(s,e){super(),this.width=s,this.height=e}}export class SphereCollisionShape extends CollisionShape{constructor(s){super(),this.radius=s}}export class CylinderCollisionShape extends CollisionShape{constructor(s,e,t,i,o){super(),this.radiusTop=s,this.radiusBottom=e,this.height=t,this.segments=i,this.orentation=o}}export class ConeCollisionShape extends CollisionShape{constructor(s,e){super(),this.radiusBottom=s,this.height=e}}export class ConvexPolyhedronCollisionShape extends CollisionShape{constructor(s){super(),this.mesh=s}}export class TrimeshCollisionShape extends CollisionShape{constructor(s){super(),this.geometry=s}}export class MeshCollisionShape extends CollisionShape{constructor(s){super(),this.geometry=s}}export class CapsuleCollisionShape extends CollisionShape{constructor(s,e){super(),this.length=s,this.radius=e}}export class PhysicalShapeMesh extends e{constructor(s,e,t,i){super(s,e),this.collisionShape=t,this.physics=i,this.isPhysicalShapeMesh=!0}}/*
|
1
|
+
import{Euler as s,Mesh as e,Vector3 as t}from"three";export var CollisionShapeSource;!function(s){s[s.custom=0]="custom",s[s.rendered=1]="rendered"}(CollisionShapeSource||(CollisionShapeSource={}));export class CollisionShape{constructor(){this.offset=new t,this.rotation=new s}withRestitution(s){return this.restitution=s,this}withOffset(s){return this.offset.copy(s),this}withRotation(s){return this.rotation.copy(s),this}withDensity(s){return this.density=s,this}withMass(s){return this.mass=s,this}withFriction(s){return this.friction=s,this}static box(s){return new BoxCollisionShape(s)}static plane(s,e){return new PlaneCollisionShape(s,e)}static sphere(s){return new SphereCollisionShape(s)}static cylinder(s,e,t,i,o){return new CylinderCollisionShape(s,e,t,i,o)}static cone(s,e){return new ConeCollisionShape(s,e)}static convexPolyhedron(s){return new ConvexPolyhedronCollisionShape(s)}static trimesh(s){return new TrimeshCollisionShape(s)}static mesh(s){return new MeshCollisionShape(s)}static capsule(s,e){return new CapsuleCollisionShape(s,e)}}export class BoxCollisionShape extends CollisionShape{constructor(s){super(),this.dimensions=s}}export class PlaneCollisionShape extends CollisionShape{constructor(s,e){super(),this.width=s,this.height=e}}export class SphereCollisionShape extends CollisionShape{constructor(s){super(),this.radius=s}}export class CylinderCollisionShape extends CollisionShape{constructor(s,e,t,i,o){super(),this.radiusTop=s,this.radiusBottom=e,this.height=t,this.segments=i,this.orentation=o}}export class ConeCollisionShape extends CollisionShape{constructor(s,e){super(),this.radiusBottom=s,this.height=e}}export class ConvexPolyhedronCollisionShape extends CollisionShape{constructor(s){super(),this.mesh=s}}export class TrimeshCollisionShape extends CollisionShape{constructor(s){super(),this.geometry=s}}export class MeshCollisionShape extends CollisionShape{constructor(s){super(),this.geometry=s}}export class CapsuleCollisionShape extends CollisionShape{constructor(s,e){super(),this.length=s,this.radius=e}}export class PhysicalShapeMesh extends e{constructor(s,e,t,i){super(s,e),this.collisionShape=t,this.physics=i,this.isPhysicalShapeMesh=!0}}/*
|
2
2
|
* Copyright (©) 2023. All rights reserved.
|
3
3
|
* See the LICENSE.md file for details.
|
4
4
|
*/
|
@@ -1,4 +1,4 @@
|
|
1
|
-
import{Subject as e,debounceTime as t}from"rxjs";import{Box3 as s,BufferAttribute as n,InstancedMesh as o,MathUtils as i,Matrix4 as a,Mesh as r,MeshStandardMaterial as c,PerspectiveCamera as l,PlaneGeometry as h,ShaderMaterial as u,Triangle as f,Vector2 as p,Vector3 as m}from"three";import{materialFromAsset as d}from"../../scene/materializer.js";import{getMaterialAttribute as w}from"../../scene/materials/utils/material-painting";import{whenIdle as g}from"../../utils/async.js";import{indexBy as y}from"../../utils/collections.js";import{meanVectors3withWeight as M}from"../../utils/math.js";import{LandscapeMesh as x,defaultLandscapeMaterial as b}from"./landscape.js";import{smoothNormalsCrossMeshes as S}from"./utils.js";export const grassGeometryTriangleLimit=400;new m,new m;const v=new m,A=new m,z=new m;export class LandscapeManager{constructor(s,n,o,i,r,c,l){this.view=n,this.landscape=o,this.assetManagerService=i,this.assetService=r,this.shaders=c,this.applyMaterial=l,this.scatterMeshes=new Map,this.loadedScatterSquares=new Set,this.refreshRequests=new e,this.defaultLandscapeMaterial=b.clone(),this.scatterMeshPool=[],this.onLoopHandler=()=>this.update(),this.sectionCache=new Map,this._matrix=new a,this.scatterGeometryCache=new Map,this._lastUpdatePosition=new m,this._cameraPosition=new m,this.source=JSON.parse(JSON.stringify(s)),this.view.onLoop(this.onLoopHandler),this.defaultLandscapeMaterial.name=b.name,this.defaultLandscapeMaterial.color=b.color,this.refreshRequests.pipe(t(500)).subscribe((e=>this.refreshScatter(e.origin,e.force,e.predicate)))}updateSource(e){this.source=JSON.parse(JSON.stringify(e))}updateShaders(e){this.shaders=e}async loadGrass(){const e=await this.assetService.getAsset("6ij937n72g");await this.assetManagerService.getMesh(e);this.grassGeometry=new h(2,2,3,3);const t=this.grassGeometry.getAttribute("normal");for(let e=0;e<t.count;e++)t.setXYZ(e,0,1,0);t.needsUpdate=!0,this.grassMaterial=new c({color:3765785})}refreshGeometry(){const e=this.source.landscape.options,t=(new m,new m);this.view.camera.getWorldPosition(t);const s=[];z.fromArray(this.source.position);const n=this.view.camera instanceof l?Math.min(this.view.camera.far,1e3):1e3,o=1.1*n,i=e.sections.y*e.sectionSize/-2,a=e.sections.x*e.sectionSize/-2;for(let r=0;r<e.sections.x;r++)if(v.x=a+r*e.sectionSize,!(Math.abs(t.x-v.x)>o))for(let c=0;c<e.sections.y;c++){v.z=i+c*e.sectionSize,A.copy(z).add(v);const l=A.distanceTo(t),h=`${r},${c}`,u=this.landscape.sections.find((e=>e.x===r&&e.y===c));if(l<=n){if(null==u){this.sectionCache.has(h)||this.sectionCache.set(h,this.createLandscapeMesh(this.source,e,a,i,r,c));const t=this.sectionCache.get(h);this.applyMaterial(t),this.landscape.add(t),s.push(t)}}else l>o&&this.landscape.remove(u)}S(s)}applyHeightMap(e,t,s,n=1){const o=Math.pow(s+1,2),i=e.getAttribute("position");if(1===n)for(const e of t.points)i.setY(e.i,e.y);else{const e=y(t.points??[],(e=>e.i));for(let t=0;t<i.count;t++){const s=P(t,i.count,o);let n=0;n=s%1==0?e.get(s)?.y??0:Math.floor(e.get(s)?.y),i.setY(t,n)}}i.needsUpdate=!0,e.computeVertexNormals()}deleteOldScatterMeshes(){const e=new Set;for(const[t,s]of this.source.grass?.layers.entries()??[])for(const[n,o]of s.meshes.entries()){const s=`${t}-${n}`;e.add(s)}for(const t of this.scatterMeshes.keys())if(!e.has(t)){this.scatterMeshes.get(t).forEach((e=>{e.parent?.remove(e),e.dispose()})),this.scatterMeshes.delete(t)}}queueRefreshScatter(e,t=!1,s=()=>!0){this.refreshRequests.next({origin:e,force:t,predicate:s})}async refreshScatter(e,t=!1,s=()=>!0){t&&this.scatterGeometryCache.clear(),this.deleteOldScatterMeshes();for(const[n,a]of this.source.grass?.layers.entries()??[])for(const[c,l]of a.meshes.entries()){const a=`${n}-${c}`;this.scatterMeshes.has(a)||this.scatterMeshes.set(a,new Map);const h=this.scatterMeshes.get(a),u=await this.assetService.getAsset(l.assetId);if(null==u){console.error(`Can not find asset with id ${l.assetId}`);continue}let p;try{p=await this.assetManagerService.getMesh(u)}catch(e){console.error(`Failed to load mesh in landscape manager for asset with name ${u.name}`,e);continue}const w=[];if(p.scene.traverse((e=>{e instanceof r&&w.push(e)})),1!==w.length){console.log(p),console.warn("Dynamic grass only works for meshes with a single geometry.");continue}if(!(w[0]instanceof r)){console.warn("Only meshes can be used for dynamic grass. Found:",p.scene);continue}const x=w[0];let b=x.geometry;if(this.scatterGeometryCache.has(x.geometry.uuid))b=this.scatterGeometryCache.get(x.geometry.uuid);else if(b=x.geometry.clone(),!0===l.normalsUp&&F(b),null==b.userData.updatedMatrix){p.scene.updateMatrixWorld(),b.applyMatrix4(x.matrixWorld),b.userData.updatedMatrix=!0;const e=u.mesh?.rescale??1;1!==e&&b.scale(e,e,e)}const S=b.getIndex()??b.getAttribute("position"),v=null!=S?S.count/3:0;if(v>400){console.warn(`The triangle count of ${u.name} is too big ${v}. Keep it below 400`);continue}const A=null!=u.materialAssignments&&u.materialAssignments.length>0?u.materialAssignments[0].materialId:null,z=null!=A&&"null"!==A?await d(await this.assetService.getAsset(A),null,this.assetService,this.assetManagerService,this.shaders,!1):null;let P=null!=z?z:x.material;const L=i.degToRad(l.maxSlope??90),_=Math.cos(L),T=this.landscape.sections,q=T.filter(j(e,l.viewDistance)),I=q.filter((e=>!h.has(e.uuid)||t)).filter((e=>s(e)));T.filter($(e,2*l.viewDistance)).forEach((e=>{const t=h.get(e.uuid);null!=t&&(t.visible=!1)}));for(const e of q){const t=h.get(e.uuid);null!=t&&(t.visible=!0)}performance.now();const R=this.source.landscape.options,k=R.sectionSize,D=l.density??1??1,H=R.density,X=k/H,Y=D,E=X/Math.sqrt(Y),J=Math.pow(H,2),Z=E/X,K=Math.floor(J*Y),V=[0,0,0];for(const e of I)await g((async()=>{e.updateWorldMatrix(!0,!1);const s=this._matrix,i=new m,a=e.geometry.getAttribute("position"),r=e.geometry.getAttribute("normal"),c=(this.source.vertexMaterials??[]).filter((t=>t.m===e.name)),u=y(c,(e=>e.i));let p=h.get(e.uuid);if(null==p||p.count==K&&!t||(p.parent?.remove(p),this.scatterMeshPool.push(p),h.delete(e.uuid),p=null),null==p){const e=this.scatterMeshPool.findIndex((e=>e.count>=K));e>-1?(p=this.scatterMeshPool[e],p.geometry=b,p.material=P,this.scatterMeshPool.splice(e,1)):p=new o(b,P,K),p.raycast=()=>{},p.receiveShadow=!0}p.visible=!0;const d=new f(new m,new m,new m);let[w,g,x,S]=[new m,new m,new m,new m],[v,A,z]=[[],[],[]],[L,$,j]=[new m,new m,new m,new m];const T=new m,q=new m,I=new m,R=new m,k=new f(new m,new m,new m),D=new f(new m,new m,new m),F=new f(new m,new m,new m),X=new f(new m,new m,new m);let E=0;e:for(let t=0;t<J;t++){const o=Math.floor(t/H);w.fromBufferAttribute(a,t+o),R.copy(w).applyMatrix4(e.matrixWorld),k.a.copy(w),k.b.fromBufferAttribute(a,t+1+o),k.c.fromBufferAttribute(a,t+H+1+o),D.a.copy(k.b),D.b.copy(k.c),D.c.fromBufferAttribute(a,t+H+2+o),F.a.fromBufferAttribute(r,t+o),F.b.fromBufferAttribute(r,t+1+o),F.c.fromBufferAttribute(r,t+H+1+o),X.a.copy(F.b),X.b.copy(F.c),X.c.fromBufferAttribute(r,t+H+2+o);const c=[];c[0]=u.get(t+o)?.w,c[1]=u.get(t+1+o)?.w,c[2]=u.get(t+H+1+o)?.w,c[3]=u.get(t+H+2+o)?.w;let h=0;for(let e=0;e<=1+Z;e+=Z)for(let t=0;t<=1+Z;t+=Z){if(E>K)break e;if(h++,h>Y)continue e;1-e>t?(g=k.a,x=k.b,S=k.c,L=F.a,$=F.b,j=F.c,v=c[0],A=c[1],z=c[2]):(g=D.a,x=D.b,S=D.c,L=X.a,$=X.b,j=X.c,v=c[1],A=c[2],z=c[3]),d.a.copy(g),d.b.copy(x),d.c.copy(S),B(d),T.set(w.x,0,w.z),U(d,T),d.getBarycoord(T,i).toArray(V),C[0]=v,C[1]=A,C[2]=z;if(G(C,V,.2)!==n-1)continue;if(M([g,x,S],V,q),M([L,$,j],V,I),null!=l.maxSlope&&l.maxSlope<90&&I.y<_)continue;const o=q;o.y+=O(l.offsetMin,l.offsetMax);const a=O(l.scaleMin??1,l.scaleMax??1);s.makeScale(a,a,a);const r=s.elements;r[12]=o.x,r[13]=o.y,r[14]=o.z,!1!==l.randomRotation&&N(s,a),l.alignToNormal&&W(s,o,p.matrixWorld,I);const u=p.instanceMatrix.array,f=16*E;u[f]=r[0],u[f+1]=r[1],u[f+2]=r[2],u[f+3]=r[3],u[f+4]=r[4],u[f+5]=r[5],u[f+6]=r[6],u[f+7]=r[7],u[f+8]=r[8],u[f+9]=r[9],u[f+10]=r[10],u[f+11]=r[11],u[f+12]=r[12],u[f+13]=r[13],u[f+14]=r[14],u[f+15]=r[15],E++}}p.count=E,p.instanceMatrix.needsUpdate=!0,p.position.copy(e.position),p.updateMatrix(),h.has(e.uuid)||this.landscape?.add(p),h.set(e.uuid,p),p.userData.meshConfig=l}));performance.now()}}stop(){this.view.removeOnLoop(this.onLoopHandler)}update(){this.view.camera&&(this.view.camera.getWorldPosition(this._cameraPosition),this._cameraPosition.distanceTo(this._lastUpdatePosition)>10&&(this._lastUpdatePosition.copy(this._cameraPosition),this.refreshGeometry(),this.refreshScatter(this._cameraPosition)))}clear(){this.scatterMeshes.forEach((e=>e.forEach((e=>e.parent?.remove(e)))))}createLandscapeMesh(e,t,s,n,o,i){const a=new h(t.sectionSize,t.sectionSize,t.density,t.density);a.rotateX(Math.PI/-2);const r=this.defaultLandscapeMaterial,c=new x(a,r);c.position.x=s+o*t.sectionSize,c.position.z=n+i*t.sectionSize,c.receiveShadow=!0,c.castShadow=!1,c.userData.landscape={x:o,y:i},c.x=o,c.y=i,c.name=`${o},${i}`,w(c,0,!0),w(c,4,!0);const l=e.landscape.heightMaps.find((e=>e.x===o&&e.y===i));if(null!=l&&this.applyHeightMap(a,l,t.density,1),a.computeBoundsTree(),null!=e.landscape.holes&&e.landscape.holes.length>0){const t=getHoleAttribute(c,!0);for(const s of e.landscape.holes)s.m===c.name&&t.setX(s.i,s.w[0])}return c}}export function getHoleAttribute(e,t=!1){if(!e.geometry.hasAttribute("hole")||t){const t=new Float32Array(e.geometry.getAttribute("position").array.length);e.geometry.setAttribute("hole",new n(t,1))}return e.geometry.getAttribute("hole")}function P(e,t,s){const n=Math.sqrt(t),o=Math.floor(e/n)/(n-1),i=e%n/(n-1),a=Math.sqrt(s);return(s-1)*o-(a-1)*o+(a-1)*i}new Map,new p(0,0),new p(1,0),new p(0,1),new p(1,0),new p(0,1),new p(1,1),new m;const L=new s;function $(e,t){return function(s){return L.setFromObject(s).distanceToPoint(e)>t}}function j(e,t){return function(s){return L.setFromObject(s).distanceToPoint(e)<t}}function B(e){e.a.y=0,e.b.y=0,e.c.y=0}const C=[];function G(e,t,s=.5){const n=C;let o=-1,i=-1;for(let e=0;e<n.length;e++)if(null!=n[e])for(let a=0;a<n[e].length;a++){const r=n[e][a]*t[e];r>s&&r>i&&(i=r,o=a)}return o}function O(e,t){let s=t-e,n=q();return n*=s,n+=e,n}const _=[];let T=1e3;for(;T--;)_.push(Math.random());function q(){return++T>=_.length?_[T=0]:_[T]}const I=[];let R=20;for(;R--;)I.push((new a).makeRotationY(q()*Math.PI/2));function U(e,t){let s=q(),n=q();s+n>1&&(s=1-s,n=1-n);const o=e.a,i=e.b,a=e.c;t.x=o.x+s*(i.x-o.x)+n*(a.x-o.x),t.z=o.z+s*(i.z-o.z)+n*(a.z-o.z)}new m;new m;const k=new m,D=new m(0,1,0),H=(new a).makeRotationX(Math.PI/-2);function W(e,t,s,n){e.lookAt(k,n,D).multiply(H)}new a;function N(e,t=1){const s=(++R>=I.length?I[R=0]:I[R]).elements,n=e.elements;n[0]=s[0]*t,n[4]=s[4]*t,n[8]=s[8]*t,n[1]=s[1]*t,n[5]=s[5]*t,n[9]=s[9]*t,n[2]=s[2]*t,n[6]=s[6]*t,n[10]=s[10]*t}function F(e){const t=e.getAttribute("normal");for(let e=0;e<t.count;e++)t.setXYZ(e,0,1,0);t.normalized=!0,t.needsUpdate=!0}/*
|
1
|
+
import{Subject as e,debounceTime as t}from"rxjs";import{Box3 as s,BufferAttribute as n,InstancedMesh as o,MathUtils as i,Matrix4 as a,Mesh as r,MeshStandardMaterial as c,PerspectiveCamera as l,PlaneGeometry as h,ShaderMaterial as u,Triangle as f,Vector2 as m,Vector3 as p}from"three";import{materialFromAsset as d}from"../../scene/materializer.js";import{getMaterialAttribute as w}from"../../scene/materials/utils/material-painting";import{whenIdle as g}from"../../utils/async.js";import{indexBy as y}from"../../utils/collections.js";import{meanVectors3withWeight as M}from"../../utils/math.js";import{LandscapeMesh as x,defaultLandscapeMaterial as b}from"./landscape.js";import{smoothNormalsCrossMeshes as S}from"./utils.js";export const grassGeometryTriangleLimit=400;new p,new p;const v=new p,A=new p,z=new p;export class LandscapeManager{constructor(s,n,o,i,r,c,l){this.view=n,this.landscape=o,this.assetManagerService=i,this.assetService=r,this.shaders=c,this.applyMaterial=l,this.scatterMeshes=new Map,this.loadedScatterSquares=new Set,this.refreshRequests=new e,this.defaultLandscapeMaterial=b.clone(),this.scatterMeshPool=[],this.onLoopHandler=()=>this.update(),this.sectionCache=new Map,this._matrix=new a,this.scatterGeometryCache=new Map,this._lastUpdatePosition=new p,this._cameraPosition=new p,this.source=JSON.parse(JSON.stringify(s)),this.view.onLoop(this.onLoopHandler),this.defaultLandscapeMaterial.name=b.name,this.defaultLandscapeMaterial.color=b.color,this.refreshRequests.pipe(t(500)).subscribe((e=>this.refreshScatter(e.origin,e.force,e.predicate)))}updateSource(e){this.source=JSON.parse(JSON.stringify(e))}updateShaders(e){this.shaders=e}async loadGrass(){const e=await this.assetService.getAsset("6ij937n72g");await this.assetManagerService.getMesh(e);this.grassGeometry=new h(2,2,3,3);const t=this.grassGeometry.getAttribute("normal");for(let e=0;e<t.count;e++)t.setXYZ(e,0,1,0);t.needsUpdate=!0,this.grassMaterial=new c({color:3765785})}refreshGeometry(){const e=this.source.landscape.options,t=(new p,new p);this.view.camera.getWorldPosition(t);const s=[];z.fromArray(this.source.position);const n=this.view.camera instanceof l?Math.min(this.view.camera.far,1e3):1e3,o=1.1*n,i=e.sections.y*e.sectionSize/-2,a=e.sections.x*e.sectionSize/-2;for(let r=0;r<e.sections.x;r++)if(v.x=a+r*e.sectionSize,!(Math.abs(t.x-v.x)>o))for(let c=0;c<e.sections.y;c++){v.z=i+c*e.sectionSize,A.copy(z).add(v);const l=A.distanceTo(t),h=`${r},${c}`,u=this.landscape.sections.find((e=>e.x===r&&e.y===c));if(l<=n){if(null==u){this.sectionCache.has(h)||this.sectionCache.set(h,this.createLandscapeMesh(this.source,e,a,i,r,c));const t=this.sectionCache.get(h);this.applyMaterial(t),this.landscape.add(t),s.push(t)}}else l>o&&this.landscape.remove(u)}S(s)}applyHeightMap(e,t,s,n=1){const o=Math.pow(s+1,2),i=e.getAttribute("position");if(1===n)for(const e of t.points)i.setY(e.i,e.y);else{const e=y(t.points??[],(e=>e.i));for(let t=0;t<i.count;t++){const s=P(t,i.count,o);let n=0;n=s%1==0?e.get(s)?.y??0:Math.floor(e.get(s)?.y),i.setY(t,n)}}i.needsUpdate=!0,e.computeVertexNormals()}deleteOldScatterMeshes(){const e=new Set;for(const[t,s]of this.source.grass?.layers.entries()??[])for(const[n,o]of s.meshes.entries()){const s=`${t}-${n}`;e.add(s)}for(const t of this.scatterMeshes.keys())if(!e.has(t)){this.scatterMeshes.get(t).forEach((e=>{e.parent?.remove(e),e.dispose()})),this.scatterMeshes.delete(t)}}queueRefreshScatter(e,t=!1,s=()=>!0){this.refreshRequests.next({origin:e,force:t,predicate:s})}async refreshScatter(e,t=!1,s=()=>!0){t&&this.scatterGeometryCache.clear(),this.deleteOldScatterMeshes();for(const[n,a]of this.source.grass?.layers.entries()??[])for(const[c,l]of a.meshes.entries()){const a=`${n}-${c}`;this.scatterMeshes.has(a)||this.scatterMeshes.set(a,new Map);const h=this.scatterMeshes.get(a),u=await this.assetService.getAsset(l.assetId);if(null==u){console.error(`Can not find asset with id ${l.assetId}`);continue}let m;try{m=await this.assetManagerService.getMesh(u)}catch(e){console.error(`Failed to load mesh in landscape manager for asset with name ${u.name}`,e);continue}const w=[];if(m.scene.traverse((e=>{e instanceof r&&w.push(e)})),1!==w.length){console.log(m),console.warn("Dynamic grass only works for meshes with a single geometry.");continue}if(!(w[0]instanceof r)){console.warn("Only meshes can be used for dynamic grass. Found:",m.scene);continue}const x=w[0];let b=x.geometry;if(this.scatterGeometryCache.has(x.geometry.uuid))b=this.scatterGeometryCache.get(x.geometry.uuid);else if(b=x.geometry.clone(),!0===l.normalsUp&&F(b),this.scatterGeometryCache.set(x.geometry.uuid,b),null==b.userData.updatedMatrix){m.scene.updateMatrixWorld(),b.applyMatrix4(x.matrixWorld),b.userData.updatedMatrix=!0;const e=u.mesh?.rescale??1;1!==e&&b.scale(e,e,e)}const S=b.getIndex()??b.getAttribute("position"),v=null!=S?S.count/3:0;if(v>400){console.warn(`The triangle count of ${u.name} is too big ${v}. Keep it below 400`);continue}const A=null!=u.materialAssignments&&u.materialAssignments.length>0?u.materialAssignments[0].materialId:null,z=null!=A&&"null"!==A?await d(await this.assetService.getAsset(A),null,this.assetService,this.assetManagerService,this.shaders,!1):null;let P=null!=z?z:x.material;const L=i.degToRad(l.maxSlope??90),_=Math.cos(L),T=this.landscape.sections,q=T.filter(C(e,l.viewDistance)),I=q.filter((e=>!h.has(e.uuid)||t)).filter((e=>s(e)));T.filter($(e,2*l.viewDistance)).forEach((e=>{const t=h.get(e.uuid);null!=t&&(t.visible=!1)}));for(const e of q){const t=h.get(e.uuid);null!=t&&(t.visible=!0)}performance.now();const R=this.source.landscape.options,k=R.sectionSize,D=l.density??1??1,H=R.density,X=k/H,Y=D,E=X/Math.sqrt(Y),J=Math.pow(H,2),Z=E/X,K=Math.floor(J*Y),V=[0,0,0];for(const e of I)await g((async()=>{e.updateWorldMatrix(!0,!1);const s=this._matrix,i=new p,a=e.geometry.getAttribute("position"),r=e.geometry.getAttribute("normal"),c=(this.source.vertexMaterials??[]).filter((t=>t.m===e.name)),u=y(c,(e=>e.i));let m=h.get(e.uuid);if(null==m||m.count==K&&!t||(m.parent?.remove(m),this.scatterMeshPool.push(m),h.delete(e.uuid),m=null),null==m){const e=this.scatterMeshPool.findIndex((e=>e.count>=K));e>-1?(m=this.scatterMeshPool[e],m.geometry=b,m.material=P,this.scatterMeshPool.splice(e,1)):m=new o(b,P,K),m.raycast=()=>{},m.receiveShadow=!0}m.visible=!0;const d=new f(new p,new p,new p);let[w,g,x,S]=[new p,new p,new p,new p],[v,A,z]=[[],[],[]],[L,$,C]=[new p,new p,new p,new p];const T=new p,q=new p,I=new p,R=new p,k=new f(new p,new p,new p),D=new f(new p,new p,new p),F=new f(new p,new p,new p),X=new f(new p,new p,new p);let E=0;e:for(let t=0;t<J;t++){const o=Math.floor(t/H);w.fromBufferAttribute(a,t+o),R.copy(w).applyMatrix4(e.matrixWorld),k.a.copy(w),k.b.fromBufferAttribute(a,t+1+o),k.c.fromBufferAttribute(a,t+H+1+o),D.a.copy(k.b),D.b.copy(k.c),D.c.fromBufferAttribute(a,t+H+2+o),F.a.fromBufferAttribute(r,t+o),F.b.fromBufferAttribute(r,t+1+o),F.c.fromBufferAttribute(r,t+H+1+o),X.a.copy(F.b),X.b.copy(F.c),X.c.fromBufferAttribute(r,t+H+2+o);const c=[];c[0]=u.get(t+o)?.w,c[1]=u.get(t+1+o)?.w,c[2]=u.get(t+H+1+o)?.w,c[3]=u.get(t+H+2+o)?.w;let h=0;for(let e=0;e<=1+Z;e+=Z)for(let t=0;t<=1+Z;t+=Z){if(E>K)break e;if(h++,h>Y)continue e;1-e>t?(g=k.a,x=k.b,S=k.c,L=F.a,$=F.b,C=F.c,v=c[0],A=c[1],z=c[2]):(g=D.a,x=D.b,S=D.c,L=X.a,$=X.b,C=X.c,v=c[1],A=c[2],z=c[3]),d.a.copy(g),d.b.copy(x),d.c.copy(S),G(d),T.set(w.x,0,w.z),U(d,T),d.getBarycoord(T,i).toArray(V),j[0]=v,j[1]=A,j[2]=z;if(B(j,V,.2)!==n-1)continue;if(M([g,x,S],V,q),M([L,$,C],V,I),null!=l.maxSlope&&l.maxSlope<90&&I.y<_)continue;const o=q;o.y+=O(l.offsetMin,l.offsetMax);const a=O(l.scaleMin??1,l.scaleMax??1);s.makeScale(a,a,a);const r=s.elements;r[12]=o.x,r[13]=o.y,r[14]=o.z,!1!==l.randomRotation&&N(s,a),l.alignToNormal&&W(s,o,m.matrixWorld,I);const u=m.instanceMatrix.array,f=16*E;u[f]=r[0],u[f+1]=r[1],u[f+2]=r[2],u[f+3]=r[3],u[f+4]=r[4],u[f+5]=r[5],u[f+6]=r[6],u[f+7]=r[7],u[f+8]=r[8],u[f+9]=r[9],u[f+10]=r[10],u[f+11]=r[11],u[f+12]=r[12],u[f+13]=r[13],u[f+14]=r[14],u[f+15]=r[15],E++}}m.count=E,m.instanceMatrix.needsUpdate=!0,m.position.copy(e.position),m.updateMatrix(),h.has(e.uuid)||this.landscape?.add(m),h.set(e.uuid,m),m.userData.meshConfig=l}));performance.now()}}stop(){this.view.removeOnLoop(this.onLoopHandler)}update(){this.view.camera&&(this.view.camera.getWorldPosition(this._cameraPosition),this._cameraPosition.distanceTo(this._lastUpdatePosition)>10&&(this._lastUpdatePosition.copy(this._cameraPosition),this.refreshGeometry(),this.refreshScatter(this._cameraPosition)))}clear(){this.scatterMeshes.forEach((e=>e.forEach((e=>e.parent?.remove(e)))))}createLandscapeMesh(e,t,s,n,o,i){const a=new h(t.sectionSize,t.sectionSize,t.density,t.density);a.rotateX(Math.PI/-2);const r=this.defaultLandscapeMaterial,c=new x(a,r);c.position.x=s+o*t.sectionSize,c.position.z=n+i*t.sectionSize,c.receiveShadow=!0,c.castShadow=!1,c.userData.landscape={x:o,y:i},c.x=o,c.y=i,c.name=`${o},${i}`,w(c,0,!0),w(c,4,!0);const l=e.landscape.heightMaps.find((e=>e.x===o&&e.y===i));if(null!=l&&this.applyHeightMap(a,l,t.density,1),a.computeBoundsTree(),null!=e.landscape.holes&&e.landscape.holes.length>0){const t=getHoleAttribute(c,!0);for(const s of e.landscape.holes)s.m===c.name&&t.setX(s.i,s.w[0])}return c}}export function getHoleAttribute(e,t=!1){if(!e.geometry.hasAttribute("hole")||t){const t=new Float32Array(e.geometry.getAttribute("position").array.length);e.geometry.setAttribute("hole",new n(t,1))}return e.geometry.getAttribute("hole")}function P(e,t,s){const n=Math.sqrt(t),o=Math.floor(e/n)/(n-1),i=e%n/(n-1),a=Math.sqrt(s);return(s-1)*o-(a-1)*o+(a-1)*i}new Map,new m(0,0),new m(1,0),new m(0,1),new m(1,0),new m(0,1),new m(1,1),new p;const L=new s;function $(e,t){return function(s){return L.setFromObject(s).distanceToPoint(e)>t}}function C(e,t){return function(s){return L.setFromObject(s).distanceToPoint(e)<t}}function G(e){e.a.y=0,e.b.y=0,e.c.y=0}const j=[];function B(e,t,s=.5){const n=j;let o=-1,i=-1;for(let e=0;e<n.length;e++)if(null!=n[e])for(let a=0;a<n[e].length;a++){const r=n[e][a]*t[e];r>s&&r>i&&(i=r,o=a)}return o}function O(e,t){let s=t-e,n=q();return n*=s,n+=e,n}const _=[];let T=1e3;for(;T--;)_.push(Math.random());function q(){return++T>=_.length?_[T=0]:_[T]}const I=[];let R=20;for(;R--;)I.push((new a).makeRotationY(q()*Math.PI/2));function U(e,t){let s=q(),n=q();s+n>1&&(s=1-s,n=1-n);const o=e.a,i=e.b,a=e.c;t.x=o.x+s*(i.x-o.x)+n*(a.x-o.x),t.z=o.z+s*(i.z-o.z)+n*(a.z-o.z)}new p;new p;const k=new p,D=new p(0,1,0),H=(new a).makeRotationX(Math.PI/-2);function W(e,t,s,n){e.lookAt(k,n,D).multiply(H)}new a;function N(e,t=1){const s=(++R>=I.length?I[R=0]:I[R]).elements,n=e.elements;n[0]=s[0]*t,n[4]=s[4]*t,n[8]=s[8]*t,n[1]=s[1]*t,n[5]=s[5]*t,n[9]=s[9]*t,n[2]=s[2]*t,n[6]=s[6]*t,n[10]=s[10]*t}function F(e){const t=e.getAttribute("normal");for(let e=0;e<t.count;e++)t.setXYZ(e,0,1,0);t.normalized=!0,t.needsUpdate=!0}/*
|
2
2
|
* Copyright (©) 2023. All rights reserved.
|
3
3
|
* See the LICENSE.md file for details.
|
4
4
|
*/
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"materializer.d.ts","sourceRoot":"","sources":["../../src/scene/materializer.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,OAAO,EAAgB,MAAM,MAAM,CAAA;AAC5C,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AAC9B,OAAO,EAGE,KAAK,EAEZ,QAAQ,EAMR,QAAQ,EAGR,KAAK,EAIL,OAAO,EAER,MAAM,OAAO,CAAA;AAad,OAAO,EAAE,iBAAiB,EAAE,MAAM,QAAQ,CAAA;AAG1C,OAAO,EAAE,aAAa,EAAE,MAAM,qCAAqC,CAAA;AACnE,OAAO,EAAE,SAAS,EAAE,MAAM,6BAA6B,CAAA;AAEvD,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AAE,MAAM,CAAC,MAAM,EAAE,gBAAgB,CAAC,EAAE,WAAW,GAAE,iBAAwB,GAAG,MAAM,CAAC,MAAM,EAAE,gBAAgB,CAAC,CA4BjL;AAED;;;GAGG;AACH,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,aAAa,EAAE,KAAK,EAAE,OAAO,WA+C3E;AA0BD,eAAO,MAAM,iCAAiC,+BAW5C,CAAA;AAkDF,wBAAgB,aAAa,CAAC,MAAM,EAAE,QAAQ,EAAE,UAAU,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,CAAC,EAAE,EAAE,OAAO,KAAK,OAAO,CAAC,QAAQ,CAAC,EAAE,kBAAkB,CAAC,EAAE,GAAG,CAAC,MAAM,GAAG,MAAM,EAAE,KAAK,CAAC,QAAQ,CAAC,mBA8E9L"}
|
@@ -1,4 +1,4 @@
|
|
1
|
-
import{ConvexPolyhedronCollisionShape as e}from"@hology/core";import{Subject as t}from"rxjs";import*as a from"three";import{BoxGeometry as s,Color as r,Euler as i,Fog as n,FogExp2 as o,Group as l,Material as c,Matrix4 as h,Mesh as d,MeshLambertMaterial as m,MeshPhongMaterial as p,MeshStandardMaterial as u,Object3D as f,PointLight as y,Quaternion as g,SphereGeometry as w,Texture as v,Vector2 as S,Vector3 as b,Vector4 as A}from"three";import M,{SpriteRenderer as x}from"@hology/nebula";import{bool as j,BooleanNode as P,float as I,FloatNode as E,NodeShaderMaterial as D,rgb as V,RgbNode as C,Texture2dLookupNode as N,textureSampler2d as k,vec2 as _,Vec2Node as F,vec3 as O,Vec3Node as T,vec4 as z}from"three-shader-graph";import{VfxActor as B}from"../effects/vfx/vfx-actor.js";import{VisualEffect as W}from"../effects/vfx/vfx-param.js";import{BaseActor as $}from"../gameplay/actors/actor.js";import R from"../gameplay/actors/builtin/index.js";import{PhysicsBodyType as U,withInjectionContext as G}from"../gameplay/index.js";import{Sampler2DNode as L}from"../shader-nodes/index.js";import{LambertShader as J}from"../shader/builtin/lambert-shader.js";import{LandscapeCompositeShader as H}from"../shader/builtin/landscape-composite-shader";import{LandscapeShader as q}from"../shader/builtin/landscape-shader.js";import{StandardShader as X}from"../shader/builtin/standard-shader.js";import{UnlitShader as Y}from"../shader/builtin/unlit-shader.js";import{extractShaderParameters as Z}from"../shader/parameter.js";import{ArrayMap as Q,groupBy as K}from"../utils/collections.js";import{iterateMaterials as ee}from"../utils/materials.js";import{filterChildrenShallow as te,filterSceneShallow as ae,findFirstVisibleObject as se}from"../utils/three/traverse.js";import{AssetMeshInstance as re}from"./asset-resource-loader.js";import{isCollisionMesh as ie}from"./collision/collision-shape-import.js";import{BoxCollisionShape as ne,PhysicalShapeMesh as oe}from"./collision/collision-shape.js";import{LandscapeManager as le}from"./landscape/landscape-manager.js";import{initLandscape as ce}from"./landscape/landscape.js";import{SectionGrid as he,smoothNormalsCrossMeshes as de}from"./landscape/utils.js";import{createGrassFoliageMaterial as me}from"./materials/grass-foliage.js";import{createGrassMaterial as pe}from"./materials/grass.js";import{getMaterialAttribute as ue}from"./materials/utils/material-painting.js";import{createWaterMaterial as fe}from"./materials/water.js";import{SerializedParamType as ye}from"./model.js";import{ShapeLibrary as ge,ShapeLibraryKeys as we}from"./objects/shapes.js";import{ambientLightName as ve,createSky as Se,defaultSkyMaterial as be}from"./sky.js";import{Curve2 as Ae}from"../utils/curve.js";import{DecalUnlitShader as Me}from"../shader/builtin/decal-unlit-shader.js";import{DecalStandardShader as xe}from"../shader/builtin/decal-standard-shader.js";const je={};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 SceneMaterializer(e,this.dataProvider,this.assetsService,this.assetManagerService,t,[],[],{create:()=>null,initActor:async()=>{}})}}export class SceneMaterializer{constructor(e,s,r,i,n,o,l,c){this.scene=e,this.dataProvider=s,this.assetsService=r,this.assetManagerService=i,this.renderingView=n,this.shaders=o,this.actorTypes=l,this.actorProvider=c,this.objectMap=new Map,this.sceneObjectMap=new Map,this.components=[],this.landscapeManagers=[],this.materializedActors=new Map,this.inEditor=!0,this.updated$=new t,this.removed$=new t,this.error$=new t,this.editorActorParamSnapshot=new Map,this.assets=new Map,this._canBeInstancedCache=new Map,this._originalMaterials=new Map,this.pmremGeneratorResults=new WeakMap,this.geometryCache=new Map,this.collisionShapeCache=new Map,this.originalFog=null,s.onCreate((e=>this.update(e))),s.onUpdate((e=>this.update(e))),s.onRemove((e=>this.remove(e))),this.createAssetSubscription=r.onCreate.subscribe((e=>{this.assets.set(e.id,e)})),this.updateSubscription=r.onUpdate.subscribe((async t=>{this.assets.set(t.id,t),"material"==t.type?e.traverse((e=>{if(e instanceof a.Mesh)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)})):"mesh"==t.type?(this.findByAssetId(t.id).forEach((e=>{Oe(e.userData.src.materialAssignments,t.materialAssignments).forEach((t=>{this.applyMaterial(e,t)}))})),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 b,!0)}))):"prefab"===t.type?this.findByAssetId(t.id).forEach((e=>{const t=e.userData.src;this.remove(t),this.materializeAndInitActor(t)})):"vfx"===t.type&&this.dataProvider.getObjects().forEach((e=>{Fe(e,((e,a)=>{"vfx"===e.type&&e.assetId===t.id&&(this.remove(e),this.materializeAndInitActor(e))}))}))}))}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)for(const s of Object.values(e.material.shaderParams)){if(s.type===ye.Material&&s.value===a.id){t=!0;break}if(s.type===ye.Array&&"element"in s&&s.element===ye.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;i.userData=t.userData,i.userData.hasBloom=n.hasBloom,null!=s?ze(e.material[s],i)||(e.material[s]=i):ze(e.material,i)||(e.material=i)}get actorInstances(){return Array.from(this.materializedActors.values())}async initTextures(){const e=[];if(await Promise.all(this.dataProvider.getObjects().filter((e=>"shape_mesh"===e.type||"asset_mesh"===e.type)).filter((e=>null!=e.materialAssignments)).flatMap((e=>e.materialAssignments)).map((async t=>{const a=this.assets.get(t.materialId);if(null!=a)for(const t of Object.values(a.material.shaderParams))if(t.type===ye.Texture&&"string"==typeof t.value){const a=this.assets.get(t.value),s=await this.assetManagerService.getTexture(a);null!=s&&e.push(s)}}))),await Promise.all(Array.from(this.assets.values()).map((async t=>{if("texture"===t.type){const a=await this.assetManagerService.getTexture(t);e.push(a)}}))),0!==e.length){console.log(`Initializing ${e.length} textures`),console.time("Init textures");for(const t of e)this.renderingView.renderer.initTexture(t);console.timeEnd("Init textures")}}async prefetchAssets(){const e=Array.from(new Set(this.dataProvider.getObjects().filter((e=>null!=e.assetId&&"asset_mesh"==e.type)).filter((e=>e.assetId))));await Promise.all(e.map((e=>this.assetsService.getAsset(e.assetId).then((e=>{if(null!=e)return this.assetManagerService.getMesh(e)}))))),this.initTextures()}async init(){await this.preInit(),Ie.clear(),await this.prefetchAssets(),await Promise.all(this.dataProvider.getObjects().map((e=>this.materialize(e)))),await this.initActorsPostInit()}initActorsPostInit(e=this.actorInstances){const t=e.map((async e=>{const t=e.object.userData.src??e.object.userData._src;if("vfx"===t.type)return Promise.resolve();const a=await this.assetsService.getAsset(t.assetId),s={...a?.actor?.params??{},...t.actor?.params??{}};for(const a of t.actor.innerParams??[])await this.applyActorComponentParams(e,a.path.slice(),a.params);const r=await prepareClassParameters(s,e.constructor,this.assetsService,this.assetManagerService,this.materializedActors,this.renderingView,this.shaders,this.actorProvider);Object.assign(e,r);try{return await this.actorProvider.initActor(e)}catch(e){console.error(`Failed to initiate actor (name="${t.name}", id=${t.id})`,e)}}));return Promise.all(t)}addVfxChildActors(e,t=e){}async applyActorComponentParams(e,t,a){const s=t.length,r=t.shift();if(0==s){const t=await prepareClassParameters(a,null,this.assetsService,this.assetManagerService,this.materializedActors,this.renderingView,this.shaders);for(const[a,s]of Object.entries(t))null!=s&&(e[a]=s)}else null!=e[r]&&await this.applyActorComponentParams(e[r],t,a)}canObjectBeInstanced(e){return e.physics?.type!==U.dynamic&&"sky"!==e.type&&"global_fog"!==e.type&&"world_env"!==e.type}async canAssetBeInstanced(e){if(!this._canBeInstancedCache.has(e.assetId)){const t=await this.createFromAsset(e);if(null==t)return!1;const a=[];t.traverse((e=>{!ie(e)&&e.isMesh&&a.push(e)}));const s=1==a.length&&0==a[0].children.length,r=a[0]instanceof d&&null!=a[0].geometry.morphAttributes&&Object.keys(a[0].geometry.morphAttributes).length>0,i=!0;this._canBeInstancedCache.set(e.assetId,s&&i&&!r)}return this._canBeInstancedCache.get(e.assetId)}async preInit(){this.renderingView?.onLoop((()=>{null!=this.sky&&this.renderingView.camera.getWorldPosition(this.sky.position)})),this.assetsService.getAssets().then((e=>{for(const t of e)this.assets.set(t.id,t)}))}async initWithInstancing(){await this.preInit(),await this.prefetchAssets();const t=[],s=new Q,n=new Q;for(const e of this.dataProvider.getObjects())await Fe(e,(async(e,a,i)=>{const o="asset_mesh"==e.type&&this.canObjectBeInstanced(e)&&await this.canAssetBeInstanced(e),l="shape_mesh"===e.type&&"landscape"!==e.shape&&e.physics?.type!==U.dynamic;if(o||l){if(a&&a.children?.length>0){const t=a.children.findIndex((t=>t.id===e.id));t>=0&&a.children.splice(t,1)}if(l){let t=e.shape+JSON.stringify(e.shapeParams??{})+e.castShadow+e.receiveShadow;const a=e.materialAssignments?.at(0)?.materialId,s=null!=a?this.assets.get(a):null;let o=null;if(null!=s&&"shader"!==s.material.type){if(t+=s.material.type+s.material.shader,null!=s.material.shaderParams){if(t+=Object.entries(s.material.shaderParams).filter((([e,t])=>"color"!=e)).map((e=>JSON.stringify(e))).join(),null!=s.material.shaderParams.color){const e=s.material.shaderParams.color;e.type===ye.Color&&null!=e.value&&(o=new r(e.value))}}}else t+=a;n.push(t,{object:{...e,parentTransform:i},color:o})}else{const t=e.assetId+JSON.stringify(e.materialAssignments??[]);s.push(t,{...e,parentTransform:i})}}else null==a&&t.push({...e,parentTransform:i})}));for(const t of s.values()){if(0==t.length)continue;const a=await this.createFromAsset(t[0]);if(null==a)continue;const s=await this.createInstancedMesh(t,a),r=new re;r.add(s),r.userData.src=t[0],a instanceof re&&(r.collisionShapes=a.collisionShapes),r.collisionShapes.forEach((t=>{t instanceof e&&t.mesh instanceof d&&(t.mesh=t.mesh.geometry)})),r.castShadow=!1,r.receiveShadow=!1,this.scene.add(r)}for(const e of n.values()){if(0==e.length)continue;const t=e[0].object,s=await this.createFromShape(t),n=se(s,(e=>!ie(e)&&null!=e.geometry)),o=n.material.clone();null!=e[0].color&&null!=o.color&&(o.color=new r(16777215));const l=n.geometry,c=new a.InstancedMesh(l,o,e.length);for(let t=0;t<e.length;t++){const r=e[t],o=(new a.Matrix4).compose((new b).fromArray(r.object.position),(new g).setFromEuler((new i).fromArray(r.object.rotation)),(new b).fromArray(r.object.scale)),l=(new h).copy(r.object.parentTransform).multiply(o);c.setMatrixAt(t,l),null!=r.color&&c.setColorAt(t,r.color),c.castShadow=s.castShadow??!0,c.receiveShadow=n.receiveShadow??!0;const d=new re;d.add(c),d.userData.src=e[0],s instanceof oe&&(d.collisionShapes=[s.collisionShape]),d.castShadow=!1,d.receiveShadow=!1,this.scene.add(d)}}await Promise.all(t.map((e=>this.materialize(e)))),await this.initActorsPostInit()}async createInstancedMesh(e,t){const s=se(t,(e=>!ie(e)&&null!=e.geometry)),r=await this.assetsService.getAsset(e[0].assetId);await this.applyMaterials(t,Oe(e[0].materialAssignments,r.materialAssignments)),s.updateMatrix();const n=s.geometry.clone(),o=new a.InstancedMesh(n,s.material,e.length);for(let t=0;t<e.length;t++){const r=(new a.Matrix4).compose((new b).fromArray(e[t].position),(new g).setFromEuler((new i).fromArray(e[t].rotation)),(new b).fromArray(e[t].scale)),n=(new h).copy(e[t].parentTransform).multiply(r).multiply(s.matrixWorld);o.setMatrixAt(t,n)}return o.castShadow=e[0].castShadow??r.castShadow??!0,o.receiveShadow=e[0].receiveShadow??r.receiveShadow??!0,s.material instanceof c&&o.castShadow&&o.receiveShadow&&(o.material.side=a.FrontSide),o}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)}const t=this.sceneObjectMap.get(e.id);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 ae(this.scene,(t=>t.userData.src?.assetId==e),(e=>null!=e.userData.src))}applyMaterials(e,t){return null==t?Promise.resolve([]):Promise.all(t.filter((e=>"null"!==e.materialId)).map((t=>this.applyMaterial(e,t))))}async applyMaterial(e,t){await applyMaterial(e,t,(e=>{const t=this.assets.get(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)}}),this._originalMaterials)}unapplyMaterials(e){e.traverse((async e=>{if(e instanceof d)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){console.log("update actors"),this.actorTypes=e;const t=new Set(Object.values(R));ae(this.scene,(e=>e.userData.src?.id&&"actor"===e.userData.src.type&&this.materializedActors.has(e.userData.src?.id)&&!t.has(e.userData.src.actor.type))).forEach((async e=>{this.remove(e.userData.src),await this.materializeAndInitActor(e.userData.src)}))}updateShaders(e){this.shaders=e;for(const[e,t]of Ie.entries())t.userData.customShaderName&&Ie.delete(e);this.landscapeManagers.forEach((t=>t.updateShaders(e))),ae(this.scene,(e=>!0)).forEach((e=>{e.traverse((async e=>{if(e instanceof d)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=this.assets.get(e.material[t].userData.assetId);this.refreshMaterial(e,e.material[t],a,t)}}else{const t=e.material.userData?.customShaderName;if(null!=t){const t=this.assets.get(e.material.userData.assetId);this.refreshMaterial(e,e.material,t)}}}))}))}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 s=!1;if(t.traverseAncestors((e=>{"_hology_transform_group"===e.name&&(s=!0)})),!s){const a=this.findParent(e);null!=a&&a.uuid!=t.uuid?a.attach(t):console.error("Parent is wrong")}if("prefab"!==e.type&&"group"!==e.type){this.unapplyMaterials(t);this.inEditor&&e.hidden&&!1?t.traverse((e=>{e instanceof d&&(e.material.wireframe=!0)})):t.traverse((e=>{e instanceof d&&(e.material.wireframe=!1)}))}if("asset_mesh"===e.type){const a=this.assets.get(e.assetId);Oe(e.materialAssignments,a.materialAssignments).forEach((e=>this.applyMaterial(t,e)))}else"shape_mesh"===e.type&&this.applyMaterials(t,e.materialAssignments);if(s||(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.applyVertexMaterials(e,t),"light"==e.type)if("point"==e.light.type){const a=t;a.color=new r(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)}else"directional"===e.light.type?this.applyDirectionalLight(e.light.directional):"ambient"===e.light.type&&this.applyDirectionalAmbientLight(t,e.light.ambient);else if("landscape"===e.shape){const a=this.landscapeManagers.find((t=>t.source.id===e.id)).source.landscape.options.density!==e.landscape.options.density;if(this.inEditor&&a){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 o?"density":"linear")!==e.fog.type;this.scene.fog=ke(e.fog),t&&(a=this.scene).traverse((e=>{if(e instanceof d){const t=e.material;t instanceof D&&(a.fog instanceof n?(t.uniforms.fogFar.value=a.fog.far,t.uniforms.fogNear.value=a.fog.near):a.fog instanceof o&&(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.editorActorParamSnapshot.get(e.id);null!=t&&t===JSON.stringify(e.actor)||s||(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 oe&&(t.geometry=a.geometry,t.collisionShape=a.collisionShape)}("asset_mesh"===e.type||"shape_mesh"===e.type&&"landscape"!==e.shape)&&Pe(t,e.castShadow,e.receiveShadow),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;this.renderingView.renderer.shadowMap.needsUpdate=!0}async materializeAndInitActor(e,t=this.findParent(e)){console.log("materialize actor and init");const a=await this.materialize(e,t);return Fe(e,(async e=>{if("actor"===e.type){const t=this.materializedActors.get(e.id);null!=t?await this.initActorsPostInit([t]):console.error(`Something went wrong when creating actor ${e.id}`)}})),a}findParent(e){const t=this.dataProvider.getObjects().flatMap((t=>t.id===e.id?null:te(t,(t=>t.children?.some((t=>t.id===e.id))),(()=>!0))))[0];return null==t?this.scene:null!=t?ae(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 r(this.scene.fog.color))}findMeshWithGeometry(e){let t;return e.traverse((e=>{e instanceof d&&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=K(e.vertexMaterials,(e=>e.m));t.traverse((e=>{if(e instanceof d){if(null==e.geometry)return;if(Be(ue(e,0,!1)),a>0){Be(ue(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=ue(s,0,!0);Be(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=ue(s,4,!0);Be(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){let r,i;switch(e.type){case"asset_mesh":r=await this.createFromAsset(e);break;case"shape_mesh":r=await this.createFromShape(e);break;case"light":r=await this.createLight(e);break;case"particles":r=await this.createParticleSystem(e),e.collisionDetection=!1;break;case"global_fog":this.scene.fog=ke(e.fog),this.fixFogColor(),r=new l;break;case"sky":this.sky=Se(),this.updateSky(e),r=this.sky;break;case"world_env":this.updateWorldEnv(e),r=new l,this.worldEnvObj=r;break;case"actor":({object:r,actor:i}=await this.createFromActor(e));break;case"group":r=new l;break;case"prefab":r=await this.createFromPrefabAsset(e);break;case"vfx":r=await this.createFromVfx(e);break;default:if(this.inEditor)throw new Error("unknown type "+e.type);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.`)}if(null!=r){if(e.name&&e.name.length>0&&(r.name=e.name),null!=e.position&&r.position.fromArray(e.position),null!=e.scale&&r.scale.fromArray(e.scale),null!=e.rotation&&r.rotation.fromArray(e.rotation),a?r.userData._src=e:r.userData.src=e,null!=i&&(r.userData.actor=i),this.inEditor,this.inEditor){let e=null;r instanceof oe&&(e=function(e){if(e instanceof ne)return new d(new s(...e.offset.toArray()),_e);return null}(r.collisionShape)),null!=e&&(e.layers.disable(0),e.layers.enable(18),e.scale.multiplyScalar(1.1),r.add(e))}return this.objectMap.set(r.uuid,e),this.sceneObjectMap.set(e.id,r),e.physics?.type!==U.dynamic||null==t||this.inEditor?null==t?this.scene.add(r):t?.add(r):(t.add(r),r.getWorldPosition(r.position),r.getWorldQuaternion(r.quaternion),r.getWorldScale(r.scale),this.scene?.attach(r)),null!=e.children&&await Promise.all(e.children?.map((e=>this.materialize(e,r,a)))),this.inEditor||"asset_mesh"!=e.type&&"shape_mesh"!==e.type||"landscape"===e.shape||null!=e.physics?.type&&e.physics.type==U.dynamic||Ne(r),this.renderingView.renderer.shadowMap.needsUpdate=!0,r}}updateWorldEnv(e){this.renderingView.aoPass.enabled=e.worldEnv.ao.enabled,this.renderingView.aoPass.blendIntensity=e.worldEnv.ao.blendIntensity,this.renderingView.aoPass.updateGtaoMaterial(e.worldEnv.ao),this.renderingView.aoPass.output=!0===e.worldEnv.ao.onlyAO?5:0;const t=e.worldEnv.toneMapping;null!=t&&(this.renderingView.renderer.toneMapping=t.mapping??0,this.renderingView.renderer.toneMappingExposure=t.exposure??1);const s=e.worldEnv.environment;null!=s&&null!=s.textureId?this.assetManagerService.getTexture(this.assets.get(s.textureId)).then((e=>{null==this.pmremGenerator&&(this.pmremGenerator=new a.PMREMGenerator(this.renderingView.renderer),this.pmremGenerator.compileEquirectangularShader()),this.pmremGeneratorResults.has(e)||this.pmremGeneratorResults.set(e,this.pmremGenerator.fromEquirectangular(e).texture);const t=this.pmremGeneratorResults.get(e);this.renderingView.scene.environment=t,this.renderingView.scene.environmentIntensity=s.intensity??1})):this.renderingView.scene.environment=null}resetWorldEnv(){this.renderingView.aoPass.enabled=!1,this.renderingView.aoPass.blendIntensity=1,this.renderingView.aoPass.output=0,this.renderingView.renderer.toneMapping=0,this.renderingView.renderer.toneMappingExposure=1}async updateSky(e){if(null==e?.sky?.materialId)return void(this.sky.material=be);const t=await this.assetsService.getAsset(e.sky.materialId),s=await materialFromAsset(t,this.renderingView,this.assetsService,this.assetManagerService,this.shaders,!1);s.side=a.BackSide,(s instanceof u||s instanceof a.MeshBasicMaterial||s instanceof a.ShaderMaterial)&&(s.fog=!1),null!=this.sky?this.sky.material=s:console.warn("No sky has been created")}async createComponent(e,t,a,s){const r=new je[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){const t=this.actorTypes.find((t=>t.name===e.actor?.type))?.type??R[e.actor?.type];if(null==t)return{object:null,actor:null};this.inEditor&&this.editorActorParamSnapshot.set(e.id,JSON.stringify(e.actor));const a=await this.actorProvider.create(t,(new b).fromArray(e.position),(new i).fromArray(e.rotation),!0);return this.materializedActors.set(e.id,a),{object:a?.object,actor:a}}async createFromVfx(e){const t=await this.assetsService.getAsset(e.assetId);null==t&&console.error("Could not find asset",e);const a=await this.actorProvider.create(B,(new b).fromArray(e.position),(new i).fromArray(e.rotation),!1);return await a.fromAsset(t),a.play(),this.materializedActors.set(e.id,a),null!=a&&(a.object.userData.actor=a),a?.object}cleanup(){this.materializedActors.clear()}async createFromShape(e){const t=this.inEditor&&e.hidden;let a;if("landscape"==e.shape)a=this.createLandscape(e),a.traverse((e=>{e instanceof d&&this._originalMaterials.set(e.id,e.material)}));else{let s=new u({name:"Default",color:new r("#aaaaaa"),visible:this.inEditor||!e.hidden,wireframe:!!t});const i=await this.createMeshByShape(e.shape,s,e.shapeParams);i.castShadow=e.castShadow??!0,i.receiveShadow=e.castShadow??!1,e.collisionDetection||(i.collisionShape=null),i.physics=e.physics,a=i,this._originalMaterials.set(a.id,i.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 l;const a=ce(e.landscape.options);this.applyHeightMaps(a,e.landscape.heightMaps,!0);const s=new le(e,this.renderingView,a,this.assetManagerService,this.assetsService,this.shaders,(t=>{(e.materialAssignments??[]).filter((e=>null!=e.materialId)).forEach((e=>this.applyMaterial(t,e)))}));return this.landscapeManagers.push(s),s.refreshGeometry(),a}applyHeightMaps(e,t,a=!1){const s=new he(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((()=>de(r)),50)}async createMeshByShape(e,t,a={}){if("landscape"!==e&&we.includes(e)){const s=await prepareShapeParameters(a??{}),r=e+JSON.stringify(a);return this.geometryCache.has(r)||this.geometryCache.set(r,ge[e].geometry(s)),this.collisionShapeCache.has(r)||this.collisionShapeCache.set(r,ge[e].collision(s)),new oe(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 createFromAsset(e){const t=await this.assetsService.getAsset(e.assetId);if(null==t)return void console.warn(`Can not find asset with id ${e.assetId} and name ${e.name}`);let{scene:a}=await this.assetManagerService.getMesh(t,{mergeGeomtries:!0});Oe(e.materialAssignments,t.materialAssignments).forEach((e=>this.applyMaterial(a,e)));const s=e.receiveShadow??!!t.receiveShadow??!0,r=e.castShadow??!!t.castShadow??!1;return a.receiveShadow=s,Pe(a,r,s),e.collisionDetection||(a.collisionShapes=[]),null!=e.physics&&!0!==this.inEditor&&(a.physics=e.physics),this.applyVertexMaterials(e,a),a.traverse((e=>{e instanceof d&&"computeBoundsTree"in e.geometry&&null==e.geometry.boundsTree&&e.geometry.computeBoundsTree()})),a}async createFromPrefabAsset(e){const t=await this.assetsService.getAsset(e.assetId);if(null==t)return void console.warn(`Can not find asset with id ${e.assetId} and name ${e.name}`);const a=new l;return t.prefab.objects.filter((e=>"global_fog"!==e.type&&"world_env"!==e.type)).forEach((e=>this.materialize(e,a,!0))),a}async createParticleSystem(e){const t=await this.assetsService.getAsset(e.assetId),s=new f;return await M.fromJSONAsync(t.particleSystem,a).then((e=>{const t=new x(s,a);e.addRenderer(t),this.renderingView.onLoop((t=>e.update()))})),s}async createLight(e){if("point"===e.light.type){const t=new y(e.light.point.color,e.light.point.intensity,e.light.point.distance,e.light.point.decay);if(t.castShadow=e.light.point.castShadow??!0,this.inEditor){const e=new w(.3,10,10),a=new u({color:new r(16771709)}),s=new d(e,a);t.add(s)}return t}return"directional"===e.light.type?(this.applyDirectionalLight(e.light.directional),new l):"ambient"===e.light.type?(this.applyDirectionalAmbientLight(null,e.light.ambient),new l):void 0}applyDirectionalAmbientLight(e,t){const a=this.scene.children.find((e=>e.name===ve));null!=a?(a.intensity=t.intensity,a.color.set(t.color),a.groundColor.set(t.color)):console.warn("Couldn't find ambient light")}applyDirectionalLight(e){for(const t of this.renderingView.csm.lights)t.intensity=e.intensity,t.color.set(e.color),t.castShadow=e.castShadow;this.renderingView.csm.lightDirection.fromArray(e.direction).normalize()}dispose(){this.updateSubscription.unsubscribe(),this.createAssetSubscription.unsubscribe(),this.materializedActors.forEach((e=>e.disposed.next(!0)))}}function Pe(e,t,a){e.castShadow=t,e.receiveShadow=a,e.traverse((e=>{e.castShadow=t,e.receiveShadow=a}))}const Ie=new Map,Ee=new Map,De=new m({color:16711935}),Ve=new Map;export async function materialFromAsset(e,t,a,s,r,i=!0){const n=JSON.stringify(e.material);return i&&Ie.has(n)?Ie.get(n):i&&Ee.has(n)?await Ee.get(n):Ee.set(n,_materialFromAsset(n,e,t,a,s,r,i)).get(n)}export async function _materialFromAsset(e,t,s,i,n,o,l=!0){const c={opacity:t.material.params.opacity,map:null,emissive:t.material.params.emissive??null,metalness:t.material.params.metalness??0,flatShading:t.material.params.flatShading??!1,color:new r(t.material.params.color),transparent:null!=t.material.params.opacity&&t.material.params.opacity<1},h={};if(null!=t.material.params.map){const e=t.material.params.map,a=await i.getAsset(e);null!=a&&(c.map=await n.getTexture(a))}let d;switch(t.material.type){case"phong":d=new p({...c,...h});break;case"water":d=fe(c,s);break;case"grassFoliage":d=me({color:c.color,map:c.map},s);break;case"grass":d=pe({...c,colorTwo:new r(t.material.params.colorTwo),colorThree:new r(t.material.params.colorThree)},s);break;case"standard":case"unlit":case"lambert":case"shader":case"landscape":case"landscape-composite":case"decal-unlit":case"decal-standard":const e={standard:X,lambert:J,unlit:Y,landscape:q,"landscape-composite":H,"decal-unlit":Me,"decal-standard":xe}[t.material.type]??o.find((e=>e.name==t.material.shader))?.type;if(e){try{let a=new e;const r=await prepareClassParameters(t.material?.shaderParams??{},e,i,n,null,s,o);Object.assign(a,r),d=a.build()}catch(e){console.log("Shader runtime error: "+e),Ve.has(t.material.shader)||Ve.set(t.material.shader,De.clone()),d=Ve.get(t.material.shader)}d.userData.customShaderName=t.material.shader}else console.warn("Missing shader implementation with name "+t.material.shader),d=De;break;default:throw new Error("Unsupported material type"+t.material.type)}return s?.csm.setupMaterial(d),null!=s&&Ie.set(e,d),d.side=t.material.side??d.side??a.FrontSide,d.transparent=(t.material.transparent??c.transparent??!1)||d.transparent,d.alphaTest=t.material.alphaTest??d.alphaTest??0,t.material.bloom&&(d.userData.hasBloom=!0),d.userData.assetId=t.id,Ee.delete(e),d}export async function prepareClassParameters(e,t,a,s,r,i,n,o){const l={};for(const[t,c]of Object.entries(e)){const e=await Ce(c,a,s,r,i,n,o);null!=e&&(l[t]=e)}return l}export async function prepareShapeParameters(e){const t={};for(const[a,s]of Object.entries(e)){const e=await Ce(s,null,null,null);null!=e&&(t[a]=e)}return t}async function Ce(e,t,a,s,n,o,l,c=e.value,h=e.type){if(null==e||null==c||""===c)return null;switch(h){case ye.Array:if(Array.isArray(c)&&"element"in e)return await Promise.all(c.map((r=>Ce(e,t,a,s,n,o,l,r,e.element))));break;case ye.Number:case ye.FloatNode:let h="string"==typeof c?parseFloat(c):c;return e.type===ye.FloatNode?I(h):h;case ye.Texture:return await a.getTexture(await t.getAsset(c));case ye.Sampler2DNode:return k(await a.getTexture(await t.getAsset(c)));case ye.Boolean:return c;case ye.BooleanNode:return j(c);case ye.Vector2:case ye.Vec2Node:if("object"==typeof c){const t=c instanceof Array?(new S).fromArray(c):new S(c.x,c.y);return e.type===ye.Vec2Node?_(t):t}return null;case ye.Vector3:case ye.Vec3Node:if("object"==typeof c){const t=c instanceof Array?(new b).fromArray(c):new b(c.x,c.y,c.z);return e.type===ye.Vec3Node?O(t):t}return null;case ye.Color:case ye.RgbNode:const d=new r(c);return e.type===ye.RgbNode?V(d):d;case ye.String:return c;case ye.BaseActor:const m=c;return null==s&&console.warn("Class parameters can not be prepared as actors are not passed in"),s?.get(m);case ye.Euler:const p=c;return(new i).fromArray(p);case ye.Object3D:return(await a.getMesh(await t.getAsset(c))).scene;case ye.Material:return await materialFromAsset(await t.getAsset(c),n,t,a,o);case ye.AudioBuffer:return await a.getAudio(await t.getAsset(c));case ye.VisualEffect:const u=await t.getAsset(c);if(null==l){console.error("Can not create instance of visual effect because missing actor provider");break}if("vfx"in u)return new W(l,u);console.error("Using a non-vfx asset for visual effect parameter");break;case ye.Curve:return Ae.decode(c)}return null}function Ne(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 ke(e){return"linear"===e.type?new n(new r(e.color),e.near??100,e.far??1e3):"density"===e.type?new o(e.color,e.density):void console.warn("Invalid fog type",e)}const _e=new u({color:4229780});async function Fe(e,t,s,r){null==r&&(r=(new h).identity()),await t(e,s,r);const n=r.clone().multiply(function(e,t){if(null==e.position||null==e.rotation||null==e.scale)return t.identity();return t.compose((new b).fromArray(e.position),(new g).setFromEuler((new i).fromArray(e.rotation)),(new b).fromArray(e.scale))}(e,new a.Matrix4));return Promise.all((e.children??[]).map((a=>Fe(a,t,e,n))))}export function toSerializedParamType(e){const t=e.constructor.prototype;return t instanceof Number||e===Number?ye.Number:t instanceof E||"function"==typeof e.prototype.isFloat?ye.FloatNode:t instanceof v||e===v||e.isTexture?ye.Texture:t instanceof L||e===N?ye.Sampler2DNode:t instanceof Boolean||e===Boolean?ye.Boolean:t instanceof P?ye.BooleanNode:t instanceof r||e==r?ye.Color:t instanceof C||"function"==typeof e.prototype.isRgb?ye.RgbNode:t instanceof S||e==S?ye.Vector2:t instanceof F||"function"==typeof e.prototype.isVec2?ye.Vec2Node:t instanceof b||e==b?ye.Vector3:t instanceof T||"function"==typeof e.prototype.isVec3?ye.Vec3Node:t instanceof String||e===String?ye.String:t instanceof $||e==$||e.prototype instanceof $||e.prototype==$?ye.BaseActor:t instanceof i||e==i?ye.Euler:t instanceof f||e==f?ye.Object3D:t instanceof c||e==c?ye.Material:t instanceof AudioBuffer||e==AudioBuffer?ye.AudioBuffer:t instanceof W||e==W?ye.VisualEffect:t instanceof Ae||e==Ae?ye.Curve:void console.warn("Failed to map parameter type to serialized version",{type:e})}export function prepareCustomParams(e,t,a={}){return Object.fromEntries(e.map((e=>[e.name,{type:e.options.array?ye.Array:toSerializedParamType(e.type),...e.options.array?{element:toSerializedParamType(e.type)}:{},value:t[e.name]?.value??(!0!==e.options.array?a[e.name]??customParameterDefaultValueByType.get(toSerializedParamType(e.type)):[])}])))}export function prepareCustomParamsFromType(e,t,a=null){const s=Z(e);if(0===s.length)return{};let r;null!=a?G(a,(()=>{r=a.get(e)})):r=new e;const i={};for(const e of s){const t=r[e.name];if(null!=t&&!0!==e.options.array){const a=serializeCustomParameter(e.type,t);null!=a&&(i[e.name]=a)}}return prepareCustomParams(s,t,i)}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 S:return t instanceof S?t.toArray():void a();case b:return t instanceof b?t.toArray():void a();case A:return t instanceof A?t.toArray():void a();case r:return t instanceof r?"#"+t.getHexString():"string"==typeof t?t:"number"==typeof t?"#"+new r(t).getHexString():void a();case String:return t;case i:return t instanceof i?t.toArray():void a()}}function Oe(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=>Te(e.materialId))),(t??[]).filter((e=>Te(e.materialId))),(e=>e.color+e.name))}function Te(e){return"null"!=e&&null!=e}export const customParameterDefaultValueByType=new Map([[ye.RgbNode,"#000000"],[ye.Color,"#000000"],[ye.Vector4,[0,0,0,0]],[ye.Vec4Node,[0,0,0,0]],[ye.Vector3,[0,0,0]],[ye.Vec3Node,[0,0,0]],[ye.Vector2,[0,0]],[ye.Vec2Node,[0,0]],[ye.Euler,[0,0,0,"XYZ"]],[ye.Array,[]]]);export function applyMaterial(e,t,s,i){const n=[];return e.traverse((async e=>{if(e instanceof d||e.isMesh||e instanceof a.SkinnedMesh||e.isSkinnedMesh)for(const t of ee(e.material))t.hasOwnProperty("color")&&n.push(e)})),Promise.all(n.map((async e=>{if(e.material instanceof Array)for(let a=0;a<e.material.length;a++){const n=e.material[a];if(null==n.color||!(n.color instanceof r))continue;const o="#"+n.color.getHexString(),l=n.name;if(o===t.color&&(n.name===t.name||null==t.name)||e.userData["originalColor_"+a]===t.color&&e.userData["originalMaterialName_"+a]===t.name){const r=await s(t.materialId),n=e.material[a];null!=r&&n.id!=r.id&&(e.material[a]=r,e.userData["originalColor_"+a]=e.userData["originalColor_"+a]??o,e.userData["originalMaterialName_"+a]=e.userData["originalMaterialName_"+a]??l,null!=i&&i.set(e.id+"#"+a,n))}}else if("color"in e.material){const a="#"+e.material.color.getHexString(),r=e.material.name;if(a===t.color&&(e.material.name===t.name||null==t.name)||e.userData.originalColor===t.color&&e.userData.originalName===t.name){const n=await s(t.materialId),o=e.material;null!=n&&(e.material=n,e.userData.originalColor=e.userData.originalColor??a,e.userData.originalMaterialName=e.userData.originalMaterialName??r,null!=i&&(i.has(e.id)||i.set(e.id,o)))}}})))}function ze(e,t){if(e instanceof a.ShaderMaterial&&t instanceof a.ShaderMaterial){return e.fragmentShader+e.vertexShader==t.fragmentShader+t.vertexShader&&function(e,t){if(e instanceof a.ShaderMaterial&&t instanceof a.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 Be(e){if(null!=e){for(let t=0;t<e.array.length;t++)e.setX(t,0);e.needsUpdate=!0}}/*
|
1
|
+
import{ConvexPolyhedronCollisionShape as e}from"@hology/core";import{Subject as t}from"rxjs";import*as a from"three";import{BoxGeometry as s,Color as r,Euler as i,Fog as n,FogExp2 as o,Group as l,Material as c,Matrix4 as h,Mesh as d,MeshLambertMaterial as m,MeshPhongMaterial as p,MeshStandardMaterial as u,Object3D as f,PointLight as y,Quaternion as g,SphereGeometry as w,Texture as v,Vector2 as S,Vector3 as b,Vector4 as A}from"three";import M,{SpriteRenderer as x}from"@hology/nebula";import{bool as j,BooleanNode as P,float as I,FloatNode as E,NodeShaderMaterial as D,rgb as V,RgbNode as C,Texture2dLookupNode as N,textureSampler2d as k,vec2 as _,Vec2Node as F,vec3 as O,Vec3Node as T,vec4 as z}from"three-shader-graph";import{VfxActor as B}from"../effects/vfx/vfx-actor.js";import{VisualEffect as W}from"../effects/vfx/vfx-param.js";import{BaseActor as $}from"../gameplay/actors/actor.js";import R from"../gameplay/actors/builtin/index.js";import{PhysicsBodyType as U,withInjectionContext as G}from"../gameplay/index.js";import{Sampler2DNode as L}from"../shader-nodes/index.js";import{LambertShader as J}from"../shader/builtin/lambert-shader.js";import{LandscapeCompositeShader as H}from"../shader/builtin/landscape-composite-shader";import{LandscapeShader as q}from"../shader/builtin/landscape-shader.js";import{StandardShader as X}from"../shader/builtin/standard-shader.js";import{UnlitShader as Y}from"../shader/builtin/unlit-shader.js";import{extractShaderParameters as Z}from"../shader/parameter.js";import{ArrayMap as Q,groupBy as K}from"../utils/collections.js";import{iterateMaterials as ee}from"../utils/materials.js";import{filterChildrenShallow as te,filterSceneShallow as ae,findFirstVisibleObject as se}from"../utils/three/traverse.js";import{AssetMeshInstance as re}from"./asset-resource-loader.js";import{isCollisionMesh as ie}from"./collision/collision-shape-import.js";import{BoxCollisionShape as ne,PhysicalShapeMesh as oe}from"./collision/collision-shape.js";import{LandscapeManager as le}from"./landscape/landscape-manager.js";import{initLandscape as ce}from"./landscape/landscape.js";import{SectionGrid as he,smoothNormalsCrossMeshes as de}from"./landscape/utils.js";import{createGrassFoliageMaterial as me}from"./materials/grass-foliage.js";import{createGrassMaterial as pe}from"./materials/grass.js";import{getMaterialAttribute as ue}from"./materials/utils/material-painting.js";import{createWaterMaterial as fe}from"./materials/water.js";import{SerializedParamType as ye}from"./model.js";import{ShapeLibrary as ge,ShapeLibraryKeys as we}from"./objects/shapes.js";import{ambientLightName as ve,createSky as Se,defaultSkyMaterial as be}from"./sky.js";import{Curve2 as Ae}from"../utils/curve.js";import{DecalUnlitShader as Me}from"../shader/builtin/decal-unlit-shader.js";import{DecalStandardShader as xe}from"../shader/builtin/decal-standard-shader.js";const je={};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 SceneMaterializer(e,this.dataProvider,this.assetsService,this.assetManagerService,t,[],[],{create:()=>null,initActor:async()=>{}})}}export class SceneMaterializer{constructor(e,s,r,i,n,o,l,c){this.scene=e,this.dataProvider=s,this.assetsService=r,this.assetManagerService=i,this.renderingView=n,this.shaders=o,this.actorTypes=l,this.actorProvider=c,this.objectMap=new Map,this.sceneObjectMap=new Map,this.components=[],this.landscapeManagers=[],this.materializedActors=new Map,this.inEditor=!0,this.updated$=new t,this.removed$=new t,this.error$=new t,this.editorActorParamSnapshot=new Map,this.assets=new Map,this._canBeInstancedCache=new Map,this._originalMaterials=new Map,this.pmremGeneratorResults=new WeakMap,this.geometryCache=new Map,this.collisionShapeCache=new Map,this.originalFog=null,s.onCreate((e=>this.update(e))),s.onUpdate((e=>this.update(e))),s.onRemove((e=>this.remove(e))),this.createAssetSubscription=r.onCreate.subscribe((e=>{this.assets.set(e.id,e)})),this.updateSubscription=r.onUpdate.subscribe((async t=>{this.assets.set(t.id,t),"material"==t.type?e.traverse((e=>{if(e instanceof a.Mesh)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)})):"mesh"==t.type?(this.findByAssetId(t.id).forEach((e=>{this.remove(e.userData.src),this.materializeAndInitActor(e.userData.src)})),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 b,!0)}))):"prefab"===t.type?this.findByAssetId(t.id).forEach((e=>{const t=e.userData.src;this.remove(t),this.materializeAndInitActor(t)})):"vfx"===t.type&&this.dataProvider.getObjects().forEach((e=>{Fe(e,((e,a)=>{"vfx"===e.type&&e.assetId===t.id&&(this.remove(e),this.materializeAndInitActor(e))}))}))}))}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)for(const s of Object.values(e.material.shaderParams)){if(s.type===ye.Material&&s.value===a.id){t=!0;break}if(s.type===ye.Array&&"element"in s&&s.element===ye.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;i.userData=t.userData,i.userData.hasBloom=n.hasBloom,null!=s?ze(e.material[s],i)||(e.material[s]=i):ze(e.material,i)||(e.material=i)}get actorInstances(){return Array.from(this.materializedActors.values())}async initTextures(){const e=[];if(await Promise.all(this.dataProvider.getObjects().filter((e=>"shape_mesh"===e.type||"asset_mesh"===e.type)).filter((e=>null!=e.materialAssignments)).flatMap((e=>e.materialAssignments)).map((async t=>{const a=this.assets.get(t.materialId);if(null!=a)for(const t of Object.values(a.material.shaderParams))if(t.type===ye.Texture&&"string"==typeof t.value){const a=this.assets.get(t.value),s=await this.assetManagerService.getTexture(a);null!=s&&e.push(s)}}))),await Promise.all(Array.from(this.assets.values()).map((async t=>{if("texture"===t.type){const a=await this.assetManagerService.getTexture(t);e.push(a)}}))),0!==e.length){console.log(`Initializing ${e.length} textures`),console.time("Init textures");for(const t of e)this.renderingView.renderer.initTexture(t);console.timeEnd("Init textures")}}async prefetchAssets(){const e=Array.from(new Set(this.dataProvider.getObjects().filter((e=>null!=e.assetId&&"asset_mesh"==e.type)).filter((e=>e.assetId))));await Promise.all(e.map((e=>this.assetsService.getAsset(e.assetId).then((e=>{if(null!=e)return this.assetManagerService.getMesh(e)}))))),this.initTextures()}async init(){await this.preInit(),Ie.clear(),await this.prefetchAssets(),await Promise.all(this.dataProvider.getObjects().map((e=>this.materialize(e)))),await this.initActorsPostInit()}initActorsPostInit(e=this.actorInstances){const t=e.map((async e=>{const t=e.object.userData.src??e.object.userData._src;if("vfx"===t.type)return Promise.resolve();const a=await this.assetsService.getAsset(t.assetId),s={...a?.actor?.params??{},...t.actor?.params??{}};for(const a of t.actor.innerParams??[])await this.applyActorComponentParams(e,a.path.slice(),a.params);const r=await prepareClassParameters(s,e.constructor,this.assetsService,this.assetManagerService,this.materializedActors,this.renderingView,this.shaders,this.actorProvider);Object.assign(e,r);try{return await this.actorProvider.initActor(e)}catch(e){console.error(`Failed to initiate actor (name="${t.name}", id=${t.id})`,e)}}));return Promise.all(t)}addVfxChildActors(e,t=e){}async applyActorComponentParams(e,t,a){const s=t.length,r=t.shift();if(0==s){const t=await prepareClassParameters(a,null,this.assetsService,this.assetManagerService,this.materializedActors,this.renderingView,this.shaders);for(const[a,s]of Object.entries(t))null!=s&&(e[a]=s)}else null!=e[r]&&await this.applyActorComponentParams(e[r],t,a)}canObjectBeInstanced(e){return e.physics?.type!==U.dynamic&&"sky"!==e.type&&"global_fog"!==e.type&&"world_env"!==e.type}async canAssetBeInstanced(e){if(!this._canBeInstancedCache.has(e.assetId)){const t=await this.createFromAsset(e);if(null==t)return!1;const a=[];t.traverse((e=>{!ie(e)&&e.isMesh&&a.push(e)}));const s=1==a.length&&0==a[0].children.length,r=a[0]instanceof d&&null!=a[0].geometry.morphAttributes&&Object.keys(a[0].geometry.morphAttributes).length>0,i=!0;this._canBeInstancedCache.set(e.assetId,s&&i&&!r)}return this._canBeInstancedCache.get(e.assetId)}async preInit(){this.renderingView?.onLoop((()=>{null!=this.sky&&this.renderingView.camera.getWorldPosition(this.sky.position)})),this.assetsService.getAssets().then((e=>{for(const t of e)this.assets.set(t.id,t)}))}async initWithInstancing(){await this.preInit(),await this.prefetchAssets();const t=[],s=new Q,n=new Q;for(const e of this.dataProvider.getObjects())await Fe(e,(async(e,a,i)=>{const o="asset_mesh"==e.type&&this.canObjectBeInstanced(e)&&await this.canAssetBeInstanced(e),l="shape_mesh"===e.type&&"landscape"!==e.shape&&e.physics?.type!==U.dynamic;if(o||l){if(a&&a.children?.length>0){const t=a.children.findIndex((t=>t.id===e.id));t>=0&&a.children.splice(t,1)}if(l){let t=e.shape+JSON.stringify(e.shapeParams??{})+e.castShadow+e.receiveShadow;const a=e.materialAssignments?.at(0)?.materialId,s=null!=a?this.assets.get(a):null;let o=null;if(null!=s&&"shader"!==s.material.type){if(t+=s.material.type+s.material.shader,null!=s.material.shaderParams){if(t+=Object.entries(s.material.shaderParams).filter((([e,t])=>"color"!=e)).map((e=>JSON.stringify(e))).join(),null!=s.material.shaderParams.color){const e=s.material.shaderParams.color;e.type===ye.Color&&null!=e.value&&(o=new r(e.value))}}}else t+=a;n.push(t,{object:{...e,parentTransform:i},color:o})}else{const t=e.assetId+JSON.stringify(e.materialAssignments??[]);s.push(t,{...e,parentTransform:i})}}else null==a&&t.push({...e,parentTransform:i})}));for(const t of s.values()){if(0==t.length)continue;const a=await this.createFromAsset(t[0]);if(null==a)continue;const s=await this.createInstancedMesh(t,a),r=new re;r.add(s),r.userData.src=t[0],a instanceof re&&(r.collisionShapes=a.collisionShapes),r.collisionShapes.forEach((t=>{t instanceof e&&t.mesh instanceof d&&(t.mesh=t.mesh.geometry)})),r.castShadow=!1,r.receiveShadow=!1,this.scene.add(r)}for(const e of n.values()){if(0==e.length)continue;const t=e[0].object,s=await this.createFromShape(t),n=se(s,(e=>!ie(e)&&null!=e.geometry)),o=n.material.clone();null!=e[0].color&&null!=o.color&&(o.color=new r(16777215));const l=n.geometry,c=new a.InstancedMesh(l,o,e.length);for(let t=0;t<e.length;t++){const r=e[t],o=(new a.Matrix4).compose((new b).fromArray(r.object.position),(new g).setFromEuler((new i).fromArray(r.object.rotation)),(new b).fromArray(r.object.scale)),l=(new h).copy(r.object.parentTransform).multiply(o);c.setMatrixAt(t,l),null!=r.color&&c.setColorAt(t,r.color),c.castShadow=s.castShadow??!0,c.receiveShadow=n.receiveShadow??!0;const d=new re;d.add(c),d.userData.src=e[0],s instanceof oe&&(d.collisionShapes=[s.collisionShape]),d.castShadow=!1,d.receiveShadow=!1,this.scene.add(d)}}await Promise.all(t.map((e=>this.materialize(e)))),await this.initActorsPostInit()}async createInstancedMesh(e,t){const s=se(t,(e=>!ie(e)&&null!=e.geometry)),r=await this.assetsService.getAsset(e[0].assetId);await this.applyMaterials(t,Oe(e[0].materialAssignments,r.materialAssignments)),s.updateMatrix();const n=s.geometry.clone(),o=new a.InstancedMesh(n,s.material,e.length);for(let t=0;t<e.length;t++){const r=(new a.Matrix4).compose((new b).fromArray(e[t].position),(new g).setFromEuler((new i).fromArray(e[t].rotation)),(new b).fromArray(e[t].scale)),n=(new h).copy(e[t].parentTransform).multiply(r).multiply(s.matrixWorld);o.setMatrixAt(t,n)}return o.castShadow=e[0].castShadow??r.castShadow??!0,o.receiveShadow=e[0].receiveShadow??r.receiveShadow??!0,s.material instanceof c&&o.castShadow&&o.receiveShadow&&(o.material.side=a.FrontSide),o}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)}const t=this.sceneObjectMap.get(e.id);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 ae(this.scene,(t=>t.userData.src?.assetId==e),(e=>null!=e.userData.src))}applyMaterials(e,t){return null==t?Promise.resolve([]):Promise.all(t.filter((e=>"null"!==e.materialId)).map((t=>this.applyMaterial(e,t))))}async applyMaterial(e,t){await applyMaterial(e,t,(e=>{const t=this.assets.get(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)}}),this._originalMaterials)}unapplyMaterials(e){e.traverse((async e=>{if(e instanceof d)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){console.log("update actors"),this.actorTypes=e;const t=new Set(Object.values(R));ae(this.scene,(e=>e.userData.src?.id&&"actor"===e.userData.src.type&&this.materializedActors.has(e.userData.src?.id)&&!t.has(e.userData.src.actor.type))).forEach((async e=>{this.remove(e.userData.src),await this.materializeAndInitActor(e.userData.src)}))}updateShaders(e){this.shaders=e;for(const[e,t]of Ie.entries())t.userData.customShaderName&&Ie.delete(e);this.landscapeManagers.forEach((t=>t.updateShaders(e))),ae(this.scene,(e=>!0)).forEach((e=>{e.traverse((async e=>{if(e instanceof d)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=this.assets.get(e.material[t].userData.assetId);this.refreshMaterial(e,e.material[t],a,t)}}else{const t=e.material.userData?.customShaderName;if(null!=t){const t=this.assets.get(e.material.userData.assetId);this.refreshMaterial(e,e.material,t)}}}))}))}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 s=!1;if(t.traverseAncestors((e=>{"_hology_transform_group"===e.name&&(s=!0)})),!s){const a=this.findParent(e);null!=a&&a.uuid!=t.uuid?a.attach(t):console.error("Parent is wrong")}if("prefab"!==e.type&&"group"!==e.type){this.unapplyMaterials(t);this.inEditor&&e.hidden&&!1?t.traverse((e=>{e instanceof d&&(e.material.wireframe=!0)})):t.traverse((e=>{e instanceof d&&(e.material.wireframe=!1)}))}if("asset_mesh"===e.type){const a=this.assets.get(e.assetId);Oe(e.materialAssignments,a.materialAssignments).forEach((e=>this.applyMaterial(t,e)))}else"shape_mesh"===e.type&&this.applyMaterials(t,e.materialAssignments);if(s||(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.applyVertexMaterials(e,t),"light"==e.type)if("point"==e.light.type){const a=t;a.color=new r(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)}else"directional"===e.light.type?this.applyDirectionalLight(e.light.directional):"ambient"===e.light.type&&this.applyDirectionalAmbientLight(t,e.light.ambient);else if("landscape"===e.shape){const a=this.landscapeManagers.find((t=>t.source.id===e.id)).source.landscape.options.density!==e.landscape.options.density;if(this.inEditor&&a){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 o?"density":"linear")!==e.fog.type;this.scene.fog=ke(e.fog),t&&(a=this.scene).traverse((e=>{if(e instanceof d){const t=e.material;t instanceof D&&(a.fog instanceof n?(t.uniforms.fogFar.value=a.fog.far,t.uniforms.fogNear.value=a.fog.near):a.fog instanceof o&&(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.editorActorParamSnapshot.get(e.id);null!=t&&t===JSON.stringify(e.actor)||s||(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 oe&&(t.geometry=a.geometry,t.collisionShape=a.collisionShape)}("asset_mesh"===e.type||"shape_mesh"===e.type&&"landscape"!==e.shape)&&Pe(t,e.castShadow,e.receiveShadow),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;this.renderingView.renderer.shadowMap.needsUpdate=!0}async materializeAndInitActor(e,t=this.findParent(e)){const a=await this.materialize(e,t);return Fe(e,(async e=>{if("actor"===e.type){const t=this.materializedActors.get(e.id);null!=t?await this.initActorsPostInit([t]):console.error(`Something went wrong when creating actor ${e.id}`)}})),a}findParent(e){const t=this.dataProvider.getObjects().flatMap((t=>t.id===e.id?null:te(t,(t=>t.children?.some((t=>t.id===e.id))),(()=>!0))))[0];return null==t?this.scene:null!=t?ae(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 r(this.scene.fog.color))}findMeshWithGeometry(e){let t;return e.traverse((e=>{e instanceof d&&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=K(e.vertexMaterials,(e=>e.m));t.traverse((e=>{if(e instanceof d){if(null==e.geometry)return;if(Be(ue(e,0,!1)),a>0){Be(ue(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=ue(s,0,!0);Be(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=ue(s,4,!0);Be(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){let r,i;switch(e.type){case"asset_mesh":r=await this.createFromAsset(e);break;case"shape_mesh":r=await this.createFromShape(e);break;case"light":r=await this.createLight(e);break;case"particles":r=await this.createParticleSystem(e),e.collisionDetection=!1;break;case"global_fog":this.scene.fog=ke(e.fog),this.fixFogColor(),r=new l;break;case"sky":this.sky=Se(),this.updateSky(e),r=this.sky;break;case"world_env":this.updateWorldEnv(e),r=new l,this.worldEnvObj=r;break;case"actor":({object:r,actor:i}=await this.createFromActor(e));break;case"group":r=new l;break;case"prefab":r=await this.createFromPrefabAsset(e);break;case"vfx":r=await this.createFromVfx(e);break;default:if(this.inEditor)throw new Error("unknown type "+e.type);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.`)}if(null!=r){if(e.name&&e.name.length>0&&(r.name=e.name),null!=e.position&&r.position.fromArray(e.position),null!=e.scale&&r.scale.fromArray(e.scale),null!=e.rotation&&r.rotation.fromArray(e.rotation),a?r.userData._src=e:r.userData.src=e,null!=i&&(r.userData.actor=i),this.inEditor,this.inEditor){let e=null;r instanceof oe&&(e=function(e){if(e instanceof ne)return new d(new s(...e.offset.toArray()),_e);return null}(r.collisionShape)),null!=e&&(e.layers.disable(0),e.layers.enable(18),e.scale.multiplyScalar(1.1),r.add(e))}return this.objectMap.set(r.uuid,e),this.sceneObjectMap.set(e.id,r),e.physics?.type!==U.dynamic||null==t||this.inEditor?null==t?this.scene.add(r):t?.add(r):(t.add(r),r.getWorldPosition(r.position),r.getWorldQuaternion(r.quaternion),r.getWorldScale(r.scale),this.scene?.attach(r)),null!=e.children&&await Promise.all(e.children?.map((e=>this.materialize(e,r,a)))),this.inEditor||"asset_mesh"!=e.type&&"shape_mesh"!==e.type||"landscape"===e.shape||null!=e.physics?.type&&e.physics.type==U.dynamic||Ne(r),this.renderingView.renderer.shadowMap.needsUpdate=!0,r}}updateWorldEnv(e){this.renderingView.aoPass.enabled=e.worldEnv.ao.enabled,this.renderingView.aoPass.blendIntensity=e.worldEnv.ao.blendIntensity,this.renderingView.aoPass.updateGtaoMaterial(e.worldEnv.ao),this.renderingView.aoPass.output=!0===e.worldEnv.ao.onlyAO?5:0;const t=e.worldEnv.toneMapping;null!=t&&(this.renderingView.renderer.toneMapping=t.mapping??0,this.renderingView.renderer.toneMappingExposure=t.exposure??1);const s=e.worldEnv.environment;null!=s&&null!=s.textureId?this.assetManagerService.getTexture(this.assets.get(s.textureId)).then((e=>{null==this.pmremGenerator&&(this.pmremGenerator=new a.PMREMGenerator(this.renderingView.renderer),this.pmremGenerator.compileEquirectangularShader()),this.pmremGeneratorResults.has(e)||this.pmremGeneratorResults.set(e,this.pmremGenerator.fromEquirectangular(e).texture);const t=this.pmremGeneratorResults.get(e);this.renderingView.scene.environment=t,this.renderingView.scene.environmentIntensity=s.intensity??1})):this.renderingView.scene.environment=null}resetWorldEnv(){this.renderingView.aoPass.enabled=!1,this.renderingView.aoPass.blendIntensity=1,this.renderingView.aoPass.output=0,this.renderingView.renderer.toneMapping=0,this.renderingView.renderer.toneMappingExposure=1}async updateSky(e){if(null==e?.sky?.materialId)return void(this.sky.material=be);const t=await this.assetsService.getAsset(e.sky.materialId),s=await materialFromAsset(t,this.renderingView,this.assetsService,this.assetManagerService,this.shaders,!1);s.side=a.BackSide,(s instanceof u||s instanceof a.MeshBasicMaterial||s instanceof a.ShaderMaterial)&&(s.fog=!1),null!=this.sky?this.sky.material=s:console.warn("No sky has been created")}async createComponent(e,t,a,s){const r=new je[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){const t=this.actorTypes.find((t=>t.name===e.actor?.type))?.type??R[e.actor?.type];if(null==t)return{object:null,actor:null};this.inEditor&&this.editorActorParamSnapshot.set(e.id,JSON.stringify(e.actor));const a=await this.actorProvider.create(t,(new b).fromArray(e.position),(new i).fromArray(e.rotation),!0);return this.materializedActors.set(e.id,a),{object:a?.object,actor:a}}async createFromVfx(e){const t=await this.assetsService.getAsset(e.assetId);null==t&&console.error("Could not find asset",e);const a=await this.actorProvider.create(B,(new b).fromArray(e.position),(new i).fromArray(e.rotation),!1);return await a.fromAsset(t),a.play(),this.materializedActors.set(e.id,a),null!=a&&(a.object.userData.actor=a),a?.object}cleanup(){this.materializedActors.clear()}async createFromShape(e){const t=this.inEditor&&e.hidden;let a;if("landscape"==e.shape)a=this.createLandscape(e),a.traverse((e=>{e instanceof d&&this._originalMaterials.set(e.id,e.material)}));else{let s=new u({name:"Default",color:new r("#aaaaaa"),visible:this.inEditor||!e.hidden,wireframe:!!t});const i=await this.createMeshByShape(e.shape,s,e.shapeParams);i.castShadow=e.castShadow??!0,i.receiveShadow=e.castShadow??!1,e.collisionDetection||(i.collisionShape=null),i.physics=e.physics,a=i,this._originalMaterials.set(a.id,i.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 l;const a=ce(e.landscape.options);this.applyHeightMaps(a,e.landscape.heightMaps,!0);const s=new le(e,this.renderingView,a,this.assetManagerService,this.assetsService,this.shaders,(t=>{(e.materialAssignments??[]).filter((e=>null!=e.materialId)).forEach((e=>this.applyMaterial(t,e)))}));return this.landscapeManagers.push(s),s.refreshGeometry(),a}applyHeightMaps(e,t,a=!1){const s=new he(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((()=>de(r)),50)}async createMeshByShape(e,t,a={}){if("landscape"!==e&&we.includes(e)){const s=await prepareShapeParameters(a??{}),r=e+JSON.stringify(a);return this.geometryCache.has(r)||this.geometryCache.set(r,ge[e].geometry(s)),this.collisionShapeCache.has(r)||this.collisionShapeCache.set(r,ge[e].collision(s)),new oe(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 createFromAsset(e){const t=await this.assetsService.getAsset(e.assetId);if(null==t)return void console.warn(`Can not find asset with id ${e.assetId} and name ${e.name}`);let{scene:a}=await this.assetManagerService.getMesh(t,{mergeGeomtries:!0});Oe(e.materialAssignments,t.materialAssignments).forEach((e=>this.applyMaterial(a,e)));const s=e.receiveShadow??!!t.receiveShadow??!0,r=e.castShadow??!!t.castShadow??!1;return a.receiveShadow=s,Pe(a,r,s),e.collisionDetection||(a.collisionShapes=[]),null!=e.physics&&!0!==this.inEditor&&(a.physics=e.physics),this.applyVertexMaterials(e,a),a.traverse((e=>{e instanceof d&&"computeBoundsTree"in e.geometry&&null==e.geometry.boundsTree&&e.geometry.computeBoundsTree()})),a}async createFromPrefabAsset(e){const t=await this.assetsService.getAsset(e.assetId);if(null==t)return void console.warn(`Can not find asset with id ${e.assetId} and name ${e.name}`);const a=new l;return t.prefab.objects.filter((e=>"global_fog"!==e.type&&"world_env"!==e.type)).forEach((e=>this.materialize(e,a,!0))),a}async createParticleSystem(e){const t=await this.assetsService.getAsset(e.assetId),s=new f;return await M.fromJSONAsync(t.particleSystem,a).then((e=>{const t=new x(s,a);e.addRenderer(t),this.renderingView.onLoop((t=>e.update()))})),s}async createLight(e){if("point"===e.light.type){const t=new y(e.light.point.color,e.light.point.intensity,e.light.point.distance,e.light.point.decay);if(t.castShadow=e.light.point.castShadow??!0,this.inEditor){const e=new w(.3,10,10),a=new u({color:new r(16771709)}),s=new d(e,a);t.add(s)}return t}return"directional"===e.light.type?(this.applyDirectionalLight(e.light.directional),new l):"ambient"===e.light.type?(this.applyDirectionalAmbientLight(null,e.light.ambient),new l):void 0}applyDirectionalAmbientLight(e,t){const a=this.scene.children.find((e=>e.name===ve));null!=a?(a.intensity=t.intensity,a.color.set(t.color),a.groundColor.set(t.color)):console.warn("Couldn't find ambient light")}applyDirectionalLight(e){for(const t of this.renderingView.csm.lights)t.intensity=e.intensity,t.color.set(e.color),t.castShadow=e.castShadow;this.renderingView.csm.lightDirection.fromArray(e.direction).normalize()}dispose(){this.updateSubscription.unsubscribe(),this.createAssetSubscription.unsubscribe(),this.materializedActors.forEach((e=>e.disposed.next(!0)))}}function Pe(e,t,a){e.castShadow=t,e.receiveShadow=a,e.traverse((e=>{e.castShadow=t,e.receiveShadow=a}))}const Ie=new Map,Ee=new Map,De=new m({color:16711935}),Ve=new Map;export async function materialFromAsset(e,t,a,s,r,i=!0){const n=JSON.stringify(e.material);return i&&Ie.has(n)?Ie.get(n):i&&Ee.has(n)?await Ee.get(n):Ee.set(n,_materialFromAsset(n,e,t,a,s,r,i)).get(n)}export async function _materialFromAsset(e,t,s,i,n,o,l=!0){const c={opacity:t.material.params.opacity,map:null,emissive:t.material.params.emissive??null,metalness:t.material.params.metalness??0,flatShading:t.material.params.flatShading??!1,color:new r(t.material.params.color),transparent:null!=t.material.params.opacity&&t.material.params.opacity<1},h={};if(null!=t.material.params.map){const e=t.material.params.map,a=await i.getAsset(e);null!=a&&(c.map=await n.getTexture(a))}let d;switch(t.material.type){case"phong":d=new p({...c,...h});break;case"water":d=fe(c,s);break;case"grassFoliage":d=me({color:c.color,map:c.map},s);break;case"grass":d=pe({...c,colorTwo:new r(t.material.params.colorTwo),colorThree:new r(t.material.params.colorThree)},s);break;case"standard":case"unlit":case"lambert":case"shader":case"landscape":case"landscape-composite":case"decal-unlit":case"decal-standard":const e={standard:X,lambert:J,unlit:Y,landscape:q,"landscape-composite":H,"decal-unlit":Me,"decal-standard":xe}[t.material.type]??o.find((e=>e.name==t.material.shader))?.type;if(e){try{let a=new e;const r=await prepareClassParameters(t.material?.shaderParams??{},e,i,n,null,s,o);Object.assign(a,r),d=a.build()}catch(e){console.log("Shader runtime error: "+e),Ve.has(t.material.shader)||Ve.set(t.material.shader,De.clone()),d=Ve.get(t.material.shader)}d.userData.customShaderName=t.material.shader}else console.warn("Missing shader implementation with name "+t.material.shader),d=De;break;default:throw new Error("Unsupported material type"+t.material.type)}return s?.csm.setupMaterial(d),null!=s&&Ie.set(e,d),d.side=t.material.side??d.side??a.FrontSide,d.transparent=(t.material.transparent??c.transparent??!1)||d.transparent,d.alphaTest=t.material.alphaTest??d.alphaTest??0,t.material.bloom&&(d.userData.hasBloom=!0),d.userData.assetId=t.id,Ee.delete(e),d}export async function prepareClassParameters(e,t,a,s,r,i,n,o){const l={};for(const[t,c]of Object.entries(e)){const e=await Ce(c,a,s,r,i,n,o);null!=e&&(l[t]=e)}return l}export async function prepareShapeParameters(e){const t={};for(const[a,s]of Object.entries(e)){const e=await Ce(s,null,null,null);null!=e&&(t[a]=e)}return t}async function Ce(e,t,a,s,n,o,l,c=e.value,h=e.type){if(null==e||null==c||""===c)return null;switch(h){case ye.Array:if(Array.isArray(c)&&"element"in e)return await Promise.all(c.map((r=>Ce(e,t,a,s,n,o,l,r,e.element))));break;case ye.Number:case ye.FloatNode:let h="string"==typeof c?parseFloat(c):c;return e.type===ye.FloatNode?I(h):h;case ye.Texture:return await a.getTexture(await t.getAsset(c));case ye.Sampler2DNode:return k(await a.getTexture(await t.getAsset(c)));case ye.Boolean:return c;case ye.BooleanNode:return j(c);case ye.Vector2:case ye.Vec2Node:if("object"==typeof c){const t=c instanceof Array?(new S).fromArray(c):new S(c.x,c.y);return e.type===ye.Vec2Node?_(t):t}return null;case ye.Vector3:case ye.Vec3Node:if("object"==typeof c){const t=c instanceof Array?(new b).fromArray(c):new b(c.x,c.y,c.z);return e.type===ye.Vec3Node?O(t):t}return null;case ye.Color:case ye.RgbNode:const d=new r(c);return e.type===ye.RgbNode?V(d):d;case ye.String:return c;case ye.BaseActor:const m=c;return null==s&&console.warn("Class parameters can not be prepared as actors are not passed in"),s?.get(m);case ye.Euler:const p=c;return(new i).fromArray(p);case ye.Object3D:return(await a.getMesh(await t.getAsset(c))).scene;case ye.Material:return await materialFromAsset(await t.getAsset(c),n,t,a,o);case ye.AudioBuffer:return await a.getAudio(await t.getAsset(c));case ye.VisualEffect:const u=await t.getAsset(c);if(null==l){console.error("Can not create instance of visual effect because missing actor provider");break}if("vfx"in u)return new W(l,u);console.error("Using a non-vfx asset for visual effect parameter");break;case ye.Curve:return Ae.decode(c)}return null}function Ne(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 ke(e){return"linear"===e.type?new n(new r(e.color),e.near??100,e.far??1e3):"density"===e.type?new o(e.color,e.density):void console.warn("Invalid fog type",e)}const _e=new u({color:4229780});async function Fe(e,t,s,r){null==r&&(r=(new h).identity()),await t(e,s,r);const n=r.clone().multiply(function(e,t){if(null==e.position||null==e.rotation||null==e.scale)return t.identity();return t.compose((new b).fromArray(e.position),(new g).setFromEuler((new i).fromArray(e.rotation)),(new b).fromArray(e.scale))}(e,new a.Matrix4));return Promise.all((e.children??[]).map((a=>Fe(a,t,e,n))))}export function toSerializedParamType(e){const t=e.constructor.prototype;return t instanceof Number||e===Number?ye.Number:t instanceof E||"function"==typeof e.prototype.isFloat?ye.FloatNode:t instanceof v||e===v||e.isTexture?ye.Texture:t instanceof L||e===N?ye.Sampler2DNode:t instanceof Boolean||e===Boolean?ye.Boolean:t instanceof P?ye.BooleanNode:t instanceof r||e==r?ye.Color:t instanceof C||"function"==typeof e.prototype.isRgb?ye.RgbNode:t instanceof S||e==S?ye.Vector2:t instanceof F||"function"==typeof e.prototype.isVec2?ye.Vec2Node:t instanceof b||e==b?ye.Vector3:t instanceof T||"function"==typeof e.prototype.isVec3?ye.Vec3Node:t instanceof String||e===String?ye.String:t instanceof $||e==$||e.prototype instanceof $||e.prototype==$?ye.BaseActor:t instanceof i||e==i?ye.Euler:t instanceof f||e==f?ye.Object3D:t instanceof c||e==c?ye.Material:t instanceof AudioBuffer||e==AudioBuffer?ye.AudioBuffer:t instanceof W||e==W?ye.VisualEffect:t instanceof Ae||e==Ae?ye.Curve:void console.warn("Failed to map parameter type to serialized version",{type:e})}export function prepareCustomParams(e,t,a={}){return Object.fromEntries(e.map((e=>[e.name,{type:e.options.array?ye.Array:toSerializedParamType(e.type),...e.options.array?{element:toSerializedParamType(e.type)}:{},value:t[e.name]?.value??(!0!==e.options.array?a[e.name]??customParameterDefaultValueByType.get(toSerializedParamType(e.type)):[])}])))}export function prepareCustomParamsFromType(e,t,a=null){const s=Z(e);if(0===s.length)return{};let r;null!=a?G(a,(()=>{r=a.get(e)})):r=new e;const i={};for(const e of s){const t=r[e.name];if(null!=t&&!0!==e.options.array){const a=serializeCustomParameter(e.type,t);null!=a&&(i[e.name]=a)}}return prepareCustomParams(s,t,i)}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 S:return t instanceof S?t.toArray():void a();case b:return t instanceof b?t.toArray():void a();case A:return t instanceof A?t.toArray():void a();case r:return t instanceof r?"#"+t.getHexString():"string"==typeof t?t:"number"==typeof t?"#"+new r(t).getHexString():void a();case String:return t;case i:return t instanceof i?t.toArray():void a()}}function Oe(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=>Te(e.materialId))),(t??[]).filter((e=>Te(e.materialId))),(e=>e.color+e.name))}function Te(e){return"null"!=e&&null!=e}export const customParameterDefaultValueByType=new Map([[ye.RgbNode,"#000000"],[ye.Color,"#000000"],[ye.Vector4,[0,0,0,0]],[ye.Vec4Node,[0,0,0,0]],[ye.Vector3,[0,0,0]],[ye.Vec3Node,[0,0,0]],[ye.Vector2,[0,0]],[ye.Vec2Node,[0,0]],[ye.Euler,[0,0,0,"XYZ"]],[ye.Array,[]]]);export function applyMaterial(e,t,s,i){const n=[];return e.traverse((async e=>{if(e instanceof d||e.isMesh||e instanceof a.SkinnedMesh||e.isSkinnedMesh)for(const t of ee(e.material))t.hasOwnProperty("color")&&n.push(e)})),Promise.all(n.map((async e=>{if(e.material instanceof Array)for(let a=0;a<e.material.length;a++){const n=e.material[a];if(null==n.color||!(n.color instanceof r))continue;const o="#"+n.color.getHexString(),l=n.name;if(o===t.color&&(n.name===t.name||null==t.name)||e.userData["originalColor_"+a]===t.color&&e.userData["originalMaterialName_"+a]===t.name){const r=await s(t.materialId),n=e.material[a];null!=r&&n.id!=r.id&&(e.material[a]=r,e.userData["originalColor_"+a]=e.userData["originalColor_"+a]??o,e.userData["originalMaterialName_"+a]=e.userData["originalMaterialName_"+a]??l,null!=i&&i.set(e.id+"#"+a,n))}}else if("color"in e.material){const a="#"+e.material.color.getHexString(),r=e.material.name;if(a===t.color&&(e.material.name===t.name||null==t.name)||e.userData.originalColor===t.color&&e.userData.originalName===t.name){const n=await s(t.materialId),o=e.material;null!=n&&(e.material=n,e.userData.originalColor=e.userData.originalColor??a,e.userData.originalMaterialName=e.userData.originalMaterialName??r,null!=i&&(i.has(e.id)||i.set(e.id,o)))}}})))}function ze(e,t){if(e instanceof a.ShaderMaterial&&t instanceof a.ShaderMaterial){return e.fragmentShader+e.vertexShader==t.fragmentShader+t.vertexShader&&function(e,t){if(e instanceof a.ShaderMaterial&&t instanceof a.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 Be(e){if(null!=e){for(let t=0;t<e.array.length;t++)e.setX(t,0);e.needsUpdate=!0}}/*
|
2
2
|
* Copyright (©) 2023. All rights reserved.
|
3
3
|
* See the LICENSE.md file for details.
|
4
4
|
*/
|
@@ -19,6 +19,7 @@ export declare class ObjectStorage<T extends StorageEntity> {
|
|
19
19
|
private loaded;
|
20
20
|
private cachedIndex;
|
21
21
|
private shouldCreateIndex;
|
22
|
+
private get pathResources();
|
22
23
|
constructor(name: string, filePathFn?: (o: ObjectIndexEntry) => string);
|
23
24
|
setBasePath(path: string): void;
|
24
25
|
private determineIfMetaFileShouldBeCreated;
|
@@ -66,6 +67,7 @@ export declare class ObjectStorage<T extends StorageEntity> {
|
|
66
67
|
replaceFile(asset: T, replacementFile: string): Promise<void>;
|
67
68
|
deleteFile(fileKey: string): Promise<void>;
|
68
69
|
private privateObjectPath;
|
70
|
+
private privateObjectRelativePath;
|
69
71
|
private watchers;
|
70
72
|
private watchDir;
|
71
73
|
}
|