@hology/core 0.0.249 → 0.0.251

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.
Files changed (46) hide show
  1. package/dist/effects/vfx/gpu-sprite-runtime.js +1 -1
  2. package/dist/effects/vfx/gpu-vfx-world-service.js +1 -1
  3. package/dist/gameplay/actors/actor.js +1 -1
  4. package/dist/gameplay/actors/camera/third-person-camera-component.js +1 -1
  5. package/dist/gameplay/ai/dynamic-tiled-navmesh.js +1 -1
  6. package/dist/gameplay/initiate.d.ts +4 -0
  7. package/dist/gameplay/initiate.js +1 -1
  8. package/dist/gameplay/services/render.d.ts +11 -3
  9. package/dist/gameplay/services/render.js +1 -1
  10. package/dist/rendering/native-dlss-upscaler.d.ts +104 -0
  11. package/dist/rendering/native-dlss-upscaler.js +4 -0
  12. package/dist/rendering/node-material-webgpu-resolver.d.ts +2 -1
  13. package/dist/rendering/node-material-webgpu-resolver.js +1 -1
  14. package/dist/rendering/post-process-effect.d.ts +1 -1
  15. package/dist/rendering/post-process-effect.js +1 -1
  16. package/dist/rendering/rendering-backend.d.ts +9 -0
  17. package/dist/rendering/rendering-backend.js +4 -0
  18. package/dist/rendering/upscaling-pass.d.ts +9 -1
  19. package/dist/rendering/upscaling-pass.js +1 -1
  20. package/dist/rendering/webgl-backend.d.ts +32 -0
  21. package/dist/rendering/webgl-backend.js +4 -0
  22. package/dist/rendering/webgpu-experimental-backend.d.ts +19 -2
  23. package/dist/rendering/webgpu-experimental-backend.js +1 -1
  24. package/dist/rendering/webgpu-runtime-bridge.d.ts +22 -0
  25. package/dist/rendering/webgpu-runtime-bridge.js +4 -0
  26. package/dist/rendering.d.ts +45 -16
  27. package/dist/rendering.js +1 -1
  28. package/dist/scene/asset-resource-loader.d.ts +5 -0
  29. package/dist/scene/asset-resource-loader.js +1 -1
  30. package/dist/scene/materializer.js +1 -1
  31. package/dist/scene/materials/water.js +1 -1
  32. package/dist/scene/runtime-bundled-backend-service.d.ts +7 -0
  33. package/dist/scene/runtime-bundled-backend-service.js +1 -1
  34. package/dist/scene/storage/packed-json.js +1 -1
  35. package/dist/secondary-motion/runtime.d.ts +1 -1
  36. package/dist/secondary-motion/runtime.js +1 -1
  37. package/dist/test/actor-attachment.test.d.ts +2 -0
  38. package/dist/test/actor-attachment.test.js +4 -0
  39. package/dist/test/gpu-sprite-compiler.test.js +1 -1
  40. package/dist/test/native-dlss-upscaler.test.d.ts +2 -0
  41. package/dist/test/native-dlss-upscaler.test.js +4 -0
  42. package/dist/test/node-material-webgpu-resolver.test.js +1 -1
  43. package/dist/test/webgpu-experimental-backend.test.js +1 -1
  44. package/dist/utils/uuid.js +1 -1
  45. package/package.json +1 -1
  46. package/tsconfig.tsbuildinfo +1 -1
@@ -1,4 +1,4 @@
1
- import{__decorate as e,__metadata as t}from"tslib";import*as s from"three";import{Service as r}from"typedi";import{inject as i}from"../../gameplay/inject.js";import{AssetLoader as n}from"../../gameplay/services/asset-loader.js";import{ViewController as a}from"../../gameplay/services/render.js";import{AssetResourceLoader as o}from"../../scene/asset-resource-loader.js";import{AssetsProvider as l}from"../../scene/assets-provider.js";import{ShaderProvider as h}from"../../gameplay/services/shader-provider.js";import{createGpuSpriteShaderGraphResolver as u}from"./vfx-materializer.js";import{GpuSpriteRenderClassCache as c,hasGpuUnsupportedVfxInputBindings as d}from"./gpu-sprite-compiler.js";import{addGpuSpriteRenderGraphPasses as p}from"./gpu-sprite-render-graph.js";import{GpuSpriteWorldRuntime as m}from"./gpu-sprite-world-runtime.js";import{buildGpuSpriteTemplate as g,GpuSpriteTemplateCache as f}from"./gpu-sprite-template.js";import{gpuVfxCapacityClass as y}from"./gpu-vfx-capacity.js";export class GpuVfxEffectHandle{constructor(e,t){this.epoch=e,this.instance=t,this.released=!1}setPosition(e){return!this.released&&this.epoch.runtime.setPosition(this.instance,e)}setTransform(e){return!this.released&&this.epoch.runtime.setTransform(this.instance,e)}pause(){return!this.released&&this.epoch.runtime.pause(this.instance)}play(){return!this.released&&this.epoch.runtime.play(this.instance)}restart(){return!this.released&&this.epoch.runtime.restart(this.instance)}stop(){return!this.released&&this.epoch.runtime.stop(this.instance)}expire(e){return!this.released&&this.epoch.runtime.stop(this.instance,Math.max(0,e))}kill(){return!this.released&&this.epoch.runtime.stop(this.instance,0)}setTimescale(e){return!this.released&&this.epoch.runtime.setTimescale(this.instance,e)}setInput(e,t){return!this.released&&this.epoch.runtime.setInput(this.instance,e,t)}release(){return!this.released&&(this.released=!0,this.epoch.runtime.destroy(this.instance))}get active(){return!this.released&&this.epoch.runtime.has(this.instance)}}export class PreparedGpuVfxEffect{constructor(e,t,s){this.entry=e,this.spawnEntry=t,this.releaseEntry=s,this.released=!1}spawn(e){return this.released?null:this.spawnEntry(this.entry,e)}release(){this.released||(this.released=!0,this.releaseEntry(this.entry))}}let v=class{constructor(){this.view=i(a),this.assetLoader=i(n),this.assetsProvider=i(l),this.assetResources=i(o),this.shaderProvider=i(h),this.templateCache=new f,this.renderClassCache=new c,this.entriesByAssetId=new Map,this.entries=new Set,this.epochs=new Set,this.reportedCpuFallbacks=new Set,this.cpuFallbackReasons=new Map,this.currentEpoch=null,this.nextGeneration=1,this.rebuildTail=Promise.resolve(!0),this.unregisterRenderGraph=null,this.estimatedWorldBytes=0,this.profilingEnabled=!1,this.view.onLateUpdate().subscribe(e=>this.update(e))}setProfilingEnabled(e){this.profilingEnabled=e}getStats(){const e=this.currentEpoch;return null==e?null:{particles:e.runtime.runtime.getStats(),scheduler:e.runtime.scheduler.getStats()}}beginPipelineWarmup(){const e=[],t=new s.Vector3;for(const s of this.epochs){for(const r of s.templateIndices.values()){const i=s.runtime.spawn(r,t);null!=i&&e.push({epoch:s,instance:i})}s.runtime.flushActivePages()}return()=>{for(const{epoch:t,instance:s}of e)t.runtime.destroy(s);for(const e of this.epochs)e.runtime.flushActivePages()}}async prepare(e,t,s){if(this.cpuFallbackReasons.delete(this.fallbackKey(e,t)),"webgpu-experimental"!==this.view.requestedBackend)return this.reportCpuFallback(e,t,[`GPU VFX requires the WebGPU renderer; the requested renderer is "${this.view.requestedBackend}".`]),null;if(d(e))return this.reportCpuFallback(e,t,["one or more authored VFX input bindings are not supported on GPU"]),null;let r=null==s||0===s.size?this.entriesByAssetId.get(e.id):void 0;if(null==r||r.asset!==e||r.revision!==t){const i=r;r={asset:e,revision:t,pending:(async()=>(null!=i&&await this.retireEntry(i.pending),this.createEntry(e,t,s)))()},null!=s&&0!==s.size||this.entriesByAssetId.set(e.id,r)}const i=await r.pending;if(null==i)return this.reportCpuFallback(e,t,["GPU template preparation rejected this asset without a diagnostic"]),null;i.references+=1;const n=y(i.references),a=this.currentEpoch?.reservations.get(i)??0,o=i.reservedInstances;return n>i.reservedInstances&&(i.reservedInstances=n),a<n&&!await this.queueRebuild()?(i.references-=1,i.reservedInstances=o,this.reportCpuFallback(e,t,["the shared GPU VFX world could not grow within its memory budget or WebGPU device limits"]),null):new PreparedGpuVfxEffect(i,(e,t)=>this.spawn(e,t),e=>this.releaseEntry(e))}getFallbackReasons(e,t){return this.cpuFallbackReasons.get(this.fallbackKey(e,t))??[]}async createEntry(e,t,s){const r={assets:this.assets,renderClassCache:this.renderClassCache,resolveCustomMaterial:this.resolveCustomMaterial,revision:t,meshInputs:s},i=null==s||0===s.size?await this.templateCache.resolve(e,r):await g(e,r);if(null==i.template){const s=i.compatibility.issues.filter(e=>"error"===e.severity).map(e=>`${e.emitter}: ${e.message}`);return this.reportCpuFallback(e,t,s.length>0?s:i.reasons),null}const n={asset:e,revision:t,references:0,reservedInstances:1,retired:!1,runtimeMeshInput:null!=s&&s.size>0,template:i.template};return this.entries.add(n),n}spawn(e,t){let s=this.currentEpoch,r=s?.templateIndices.get(e);if(null==r&&e.retired)for(const t of this.epochs){const i=t.templateIndices.get(e);t.disposalQueued||null==i||(s=t,r=i)}if(null==s||null==r)return null;const i=s.runtime.spawn(r,t);return null==i?null:new GpuVfxEffectHandle(s,i)}releaseEntry(e){e.references=Math.max(0,e.references-1),!e.runtimeMeshInput||e.references>0||e.retired||(e.retired=!0,this.entries.delete(e),this.queueRebuild())}async retireEntry(e){const t=await e;null!=t&&(t.retired=!0,this.entries.delete(t))}queueRebuild(){const e=this.rebuildTail.then(()=>this.rebuildWorld()).catch(e=>(console.error("[Hology GPU VFX] Failed to rebuild the shared world generation.",e),!1));return this.rebuildTail=e,e}async rebuildWorld(){const e=[...this.entries].filter(e=>!e.retired);if(0===e.length)return null!=this.currentEpoch&&(this.currentEpoch.retired=!0,this.currentEpoch=null,this.disposeRetiredEpochs()),!0;if(null!=this.currentEpoch&&this.currentEpoch.templateIndices.size===e.length&&e.every(e=>(this.currentEpoch.reservations.get(e)??0)>=e.reservedInstances))return!0;const t=[...this.epochs].reduce((e,t)=>t===this.currentEpoch&&0===t.runtime.scheduler.getStats().activeInstances?e:e+t.estimatedBytes,0),s=Math.max(0,this.view.webgpuVfxWorldMemoryBudgetBytes-t),r=await m.create({templates:e.map(e=>({asset:e.asset,revision:e.revision,maximumInstances:e.reservedInstances,preparedTemplate:e.template})),assets:this.assets,templateCache:this.templateCache,renderClassCache:this.renderClassCache,resolveCustomMaterial:this.resolveCustomMaterial,particlePageSize:256,aliveCountReadback:this.profilingEnabled,device:this.view.experimentalWebGpuDevice??void 0,maximumStorageBytes:s});if(null==r)return!1;const i=r.runtime.getStats().storageBytes;if(i>this.view.webgpuVfxWorldMemoryBudgetBytes||t+i>this.view.webgpuVfxWorldMemoryBudgetBytes)return r.dispose(),console.warn(`[Hology GPU VFX] Refusing shared world growth: retained storage would become ${w(t+i)} MiB, exceeding the ${w(this.view.webgpuVfxWorldMemoryBudgetBytes)} MiB budget.`),!1;const n={generation:this.nextGeneration++,runtime:r,templateIndices:new Map(e.map((e,t)=>[e,t])),reservations:new Map(e.map(e=>[e,e.reservedInstances])),estimatedBytes:i,retired:!1,disposalQueued:!1};return null!=this.currentEpoch&&(this.currentEpoch.retired=!0),this.currentEpoch=n,this.epochs.add(n),this.estimatedWorldBytes+=i,this.ensureRenderGraph(),console.info(`[Hology GPU VFX] Shared world generation ${n.generation}: ${e.length} template(s), ${e.reduce((e,t)=>e+t.reservedInstances,0)} reserved instance(s), ${r.runtime.emitters.length} emitter slots, ${r.runtime.getStats().capacity.toLocaleString()} particle slots, ${w(i)} MiB estimated storage.`),this.disposeRetiredEpochs(),!0}ensureRenderGraph(){if(null!=this.unregisterRenderGraph)return;const e=(e,t)=>p(e,this,t,"WorldGpuVfx");e.getSceneTextureReads=()=>this.getSceneTextureReads(),this.unregisterRenderGraph=this.view.registerExperimentalWebGpuRenderGraphExtension(e)}update(e){for(const t of this.epochs)t.runtime.update(e);this.disposeRetiredEpochs()}disposeRetiredEpochs(){for(const e of this.epochs){if(!e.retired||e.disposalQueued||0!==e.runtime.scheduler.getStats().activeInstances||[...e.templateIndices.keys()].some(e=>e.retired&&e.references>0))continue;e.disposalQueued=!0,this.epochs.delete(e),this.estimatedWorldBytes=Math.max(0,this.estimatedWorldBytes-e.estimatedBytes);const t=()=>{e.runtime.dispose(),console.info(`[Hology GPU VFX] Retired shared world generation ${e.generation}, releasing ${w(e.estimatedBytes)} MiB estimated storage.`)},s=this.view.experimentalWebGpuDevice;null==s?t():s.queue.onSubmittedWorkDone().then(t,t)}}reportCpuFallback(e,t,s){const r=this.fallbackKey(e,t);this.cpuFallbackReasons.set(r,[...s]),this.reportedCpuFallbacks.has(r)||(this.reportedCpuFallbacks.add(r),console.warn(`[Hology GPU VFX] Falling back to CPU for "${e.name}".`,s))}fallbackKey(e,t){return`${e.id}:${t??""}`}executeCompute(e){for(const t of this.epochs)t.runtime.runtime.executeCompute(e)}executeRender(e,t){for(const s of this.epochs)s.runtime.runtime.executeRender(e,t)}getSceneTextureReads(){const e=new Set;for(const t of this.epochs)if(t.runtime.runtime.hasActiveParticles)for(const s of t.runtime.runtime.getSceneTextureReads())e.add(s);return[...e]}getComputeTextureReads(){const e=new Set;for(const t of this.epochs)if(t.runtime.runtime.hasActiveParticles)for(const s of t.runtime.runtime.getComputeTextureReads())e.add(s);return[...e]}get assets(){return{getTexture:e=>this.assetLoader.getTextureByAssetId(e),getMesh:async e=>(await this.assetResources.getMesh(await this.assetsProvider.getAsset(e),{applyMaterials:!0,rescale:!0})).scene}}get resolveCustomMaterial(){return u(this.assetsProvider,this.assetResources,this.shaderProvider,{getAsset:e=>this.assetLoader.getAsset(e),getTexture:e=>this.assetLoader.getTextureByAssetId(e),getMaterial:e=>this.assetLoader.getMaterialByAssetId(e),getMesh:e=>this.assetLoader.getModelByAssetId(e).then(e=>e.scene)})}};v=e([r(),t("design:paramtypes",[])],v);export{v as GpuVfxWorldService};function w(e){return(e/1048576).toFixed(1)}/*
1
+ import{__decorate as e,__metadata as t}from"tslib";import*as s from"three";import{Service as r}from"typedi";import{inject as i}from"../../gameplay/inject.js";import{AssetLoader as n}from"../../gameplay/services/asset-loader.js";import{ViewController as a}from"../../gameplay/services/render.js";import{AssetResourceLoader as o}from"../../scene/asset-resource-loader.js";import{AssetsProvider as l}from"../../scene/assets-provider.js";import{ShaderProvider as h}from"../../gameplay/services/shader-provider.js";import{ensureWebGpuRuntimeBindings as u}from"../../rendering/webgpu-runtime-bridge.js";import{createGpuSpriteShaderGraphResolver as c}from"./vfx-materializer.js";import{GpuSpriteRenderClassCache as d,hasGpuUnsupportedVfxInputBindings as p}from"./gpu-sprite-compiler.js";import{addGpuSpriteRenderGraphPasses as m}from"./gpu-sprite-render-graph.js";import{GpuSpriteWorldRuntime as g}from"./gpu-sprite-world-runtime.js";import{buildGpuSpriteTemplate as f,GpuSpriteTemplateCache as y}from"./gpu-sprite-template.js";import{gpuVfxCapacityClass as v}from"./gpu-vfx-capacity.js";export class GpuVfxEffectHandle{constructor(e,t){this.epoch=e,this.instance=t,this.released=!1}setPosition(e){return!this.released&&this.epoch.runtime.setPosition(this.instance,e)}setTransform(e){return!this.released&&this.epoch.runtime.setTransform(this.instance,e)}pause(){return!this.released&&this.epoch.runtime.pause(this.instance)}play(){return!this.released&&this.epoch.runtime.play(this.instance)}restart(){return!this.released&&this.epoch.runtime.restart(this.instance)}stop(){return!this.released&&this.epoch.runtime.stop(this.instance)}expire(e){return!this.released&&this.epoch.runtime.stop(this.instance,Math.max(0,e))}kill(){return!this.released&&this.epoch.runtime.stop(this.instance,0)}setTimescale(e){return!this.released&&this.epoch.runtime.setTimescale(this.instance,e)}setInput(e,t){return!this.released&&this.epoch.runtime.setInput(this.instance,e,t)}release(){return!this.released&&(this.released=!0,this.epoch.runtime.destroy(this.instance))}get active(){return!this.released&&this.epoch.runtime.has(this.instance)}}export class PreparedGpuVfxEffect{constructor(e,t,s){this.entry=e,this.spawnEntry=t,this.releaseEntry=s,this.released=!1}spawn(e){return this.released?null:this.spawnEntry(this.entry,e)}release(){this.released||(this.released=!0,this.releaseEntry(this.entry))}}let w=class{constructor(){this.view=i(a),this.assetLoader=i(n),this.assetsProvider=i(l),this.assetResources=i(o),this.shaderProvider=i(h),this.templateCache=new y,this.renderClassCache=new d,this.entriesByAssetId=new Map,this.entries=new Set,this.epochs=new Set,this.reportedCpuFallbacks=new Set,this.cpuFallbackReasons=new Map,this.currentEpoch=null,this.nextGeneration=1,this.rebuildTail=Promise.resolve(!0),this.unregisterRenderGraph=null,this.estimatedWorldBytes=0,this.profilingEnabled=!1,this.view.onLateUpdate().subscribe(e=>this.update(e))}setProfilingEnabled(e){this.profilingEnabled=e}getStats(){const e=this.currentEpoch;return null==e?null:{particles:e.runtime.runtime.getStats(),scheduler:e.runtime.scheduler.getStats()}}beginPipelineWarmup(){const e=[],t=new s.Vector3;for(const s of this.epochs){for(const r of s.templateIndices.values()){const i=s.runtime.spawn(r,t);null!=i&&e.push({epoch:s,instance:i})}s.runtime.flushActivePages()}return()=>{for(const{epoch:t,instance:s}of e)t.runtime.destroy(s);for(const e of this.epochs)e.runtime.flushActivePages()}}async prepare(e,t,s){if(this.cpuFallbackReasons.delete(this.fallbackKey(e,t)),"webgpu"!==this.view.requestedBackend)return this.reportCpuFallback(e,t,[`GPU VFX requires the WebGPU renderer; the requested renderer is "${this.view.requestedBackend}".`]),null;if(await u(),p(e))return this.reportCpuFallback(e,t,["one or more authored VFX input bindings are not supported on GPU"]),null;let r=null==s||0===s.size?this.entriesByAssetId.get(e.id):void 0;if(null==r||r.asset!==e||r.revision!==t){const i=r;r={asset:e,revision:t,pending:(async()=>(null!=i&&await this.retireEntry(i.pending),this.createEntry(e,t,s)))()},null!=s&&0!==s.size||this.entriesByAssetId.set(e.id,r)}const i=await r.pending;if(null==i)return this.reportCpuFallback(e,t,["GPU template preparation rejected this asset without a diagnostic"]),null;i.references+=1;const n=v(i.references),a=this.currentEpoch?.reservations.get(i)??0,o=i.reservedInstances;return n>i.reservedInstances&&(i.reservedInstances=n),a<n&&!await this.queueRebuild()?(i.references-=1,i.reservedInstances=o,this.reportCpuFallback(e,t,["the shared GPU VFX world could not grow within its memory budget or WebGPU device limits"]),null):new PreparedGpuVfxEffect(i,(e,t)=>this.spawn(e,t),e=>this.releaseEntry(e))}getFallbackReasons(e,t){return this.cpuFallbackReasons.get(this.fallbackKey(e,t))??[]}async createEntry(e,t,s){const r={assets:this.assets,renderClassCache:this.renderClassCache,resolveCustomMaterial:this.resolveCustomMaterial,revision:t,meshInputs:s},i=null==s||0===s.size?await this.templateCache.resolve(e,r):await f(e,r);if(null==i.template){const s=i.compatibility.issues.filter(e=>"error"===e.severity).map(e=>`${e.emitter}: ${e.message}`);return this.reportCpuFallback(e,t,s.length>0?s:i.reasons),null}const n={asset:e,revision:t,references:0,reservedInstances:1,retired:!1,runtimeMeshInput:null!=s&&s.size>0,template:i.template};return this.entries.add(n),n}spawn(e,t){let s=this.currentEpoch,r=s?.templateIndices.get(e);if(null==r&&e.retired)for(const t of this.epochs){const i=t.templateIndices.get(e);t.disposalQueued||null==i||(s=t,r=i)}if(null==s||null==r)return null;const i=s.runtime.spawn(r,t);return null==i?null:new GpuVfxEffectHandle(s,i)}releaseEntry(e){e.references=Math.max(0,e.references-1),!e.runtimeMeshInput||e.references>0||e.retired||(e.retired=!0,this.entries.delete(e),this.queueRebuild())}async retireEntry(e){const t=await e;null!=t&&(t.retired=!0,this.entries.delete(t))}queueRebuild(){const e=this.rebuildTail.then(()=>this.rebuildWorld()).catch(e=>(console.error("[Hology GPU VFX] Failed to rebuild the shared world generation.",e),!1));return this.rebuildTail=e,e}async rebuildWorld(){const e=[...this.entries].filter(e=>!e.retired);if(0===e.length)return null!=this.currentEpoch&&(this.currentEpoch.retired=!0,this.currentEpoch=null,this.disposeRetiredEpochs()),!0;if(null!=this.currentEpoch&&this.currentEpoch.templateIndices.size===e.length&&e.every(e=>(this.currentEpoch.reservations.get(e)??0)>=e.reservedInstances))return!0;const t=[...this.epochs].reduce((e,t)=>t===this.currentEpoch&&0===t.runtime.scheduler.getStats().activeInstances?e:e+t.estimatedBytes,0),s=Math.max(0,this.view.webgpuVfxWorldMemoryBudgetBytes-t),r=await g.create({templates:e.map(e=>({asset:e.asset,revision:e.revision,maximumInstances:e.reservedInstances,preparedTemplate:e.template})),assets:this.assets,templateCache:this.templateCache,renderClassCache:this.renderClassCache,resolveCustomMaterial:this.resolveCustomMaterial,particlePageSize:256,aliveCountReadback:this.profilingEnabled,device:this.view.experimentalWebGpuDevice??void 0,maximumStorageBytes:s});if(null==r)return!1;const i=r.runtime.getStats().storageBytes;if(i>this.view.webgpuVfxWorldMemoryBudgetBytes||t+i>this.view.webgpuVfxWorldMemoryBudgetBytes)return r.dispose(),console.warn(`[Hology GPU VFX] Refusing shared world growth: retained storage would become ${b(t+i)} MiB, exceeding the ${b(this.view.webgpuVfxWorldMemoryBudgetBytes)} MiB budget.`),!1;const n={generation:this.nextGeneration++,runtime:r,templateIndices:new Map(e.map((e,t)=>[e,t])),reservations:new Map(e.map(e=>[e,e.reservedInstances])),estimatedBytes:i,retired:!1,disposalQueued:!1};return null!=this.currentEpoch&&(this.currentEpoch.retired=!0),this.currentEpoch=n,this.epochs.add(n),this.estimatedWorldBytes+=i,this.ensureRenderGraph(),console.info(`[Hology GPU VFX] Shared world generation ${n.generation}: ${e.length} template(s), ${e.reduce((e,t)=>e+t.reservedInstances,0)} reserved instance(s), ${r.runtime.emitters.length} emitter slots, ${r.runtime.getStats().capacity.toLocaleString()} particle slots, ${b(i)} MiB estimated storage.`),this.disposeRetiredEpochs(),!0}ensureRenderGraph(){if(null!=this.unregisterRenderGraph)return;const e=(e,t)=>m(e,this,t,"WorldGpuVfx");e.getSceneTextureReads=()=>this.getSceneTextureReads(),this.unregisterRenderGraph=this.view.registerExperimentalWebGpuRenderGraphExtension(e)}update(e){for(const t of this.epochs)t.runtime.update(e);this.disposeRetiredEpochs()}disposeRetiredEpochs(){for(const e of this.epochs){if(!e.retired||e.disposalQueued||0!==e.runtime.scheduler.getStats().activeInstances||[...e.templateIndices.keys()].some(e=>e.retired&&e.references>0))continue;e.disposalQueued=!0,this.epochs.delete(e),this.estimatedWorldBytes=Math.max(0,this.estimatedWorldBytes-e.estimatedBytes);const t=()=>{e.runtime.dispose(),console.info(`[Hology GPU VFX] Retired shared world generation ${e.generation}, releasing ${b(e.estimatedBytes)} MiB estimated storage.`)},s=this.view.experimentalWebGpuDevice;null==s?t():s.queue.onSubmittedWorkDone().then(t,t)}}reportCpuFallback(e,t,s){const r=this.fallbackKey(e,t);this.cpuFallbackReasons.set(r,[...s]),this.reportedCpuFallbacks.has(r)||(this.reportedCpuFallbacks.add(r),console.warn(`[Hology GPU VFX] Falling back to CPU for "${e.name}".`,s))}fallbackKey(e,t){return`${e.id}:${t??""}`}executeCompute(e){for(const t of this.epochs)t.runtime.runtime.executeCompute(e)}executeRender(e,t){for(const s of this.epochs)s.runtime.runtime.executeRender(e,t)}getSceneTextureReads(){const e=new Set;for(const t of this.epochs)if(t.runtime.runtime.hasActiveParticles)for(const s of t.runtime.runtime.getSceneTextureReads())e.add(s);return[...e]}getComputeTextureReads(){const e=new Set;for(const t of this.epochs)if(t.runtime.runtime.hasActiveParticles)for(const s of t.runtime.runtime.getComputeTextureReads())e.add(s);return[...e]}get assets(){return{getTexture:e=>this.assetLoader.getTextureByAssetId(e),getMesh:async e=>(await this.assetResources.getMesh(await this.assetsProvider.getAsset(e),{applyMaterials:!0,rescale:!0})).scene}}get resolveCustomMaterial(){return c(this.assetsProvider,this.assetResources,this.shaderProvider,{getAsset:e=>this.assetLoader.getAsset(e),getTexture:e=>this.assetLoader.getTextureByAssetId(e),getMaterial:e=>this.assetLoader.getMaterialByAssetId(e),getMesh:e=>this.assetLoader.getModelByAssetId(e).then(e=>e.scene)})}};w=e([r(),t("design:paramtypes",[])],w);export{w as GpuVfxWorldService};function b(e){return(e/1048576).toFixed(1)}/*
2
2
  * Copyright (©) 2026 Hology Interactive AB. All rights reserved.
3
3
  * See the LICENSE.md file for details.
4
4
  */
@@ -1,4 +1,4 @@
1
- import{__decorate as t,__metadata as e}from"tslib";import o,{ignore as i}from"@plumier/reflect";import{Subject as s,skipWhile as r}from"rxjs";import{Group as n}from"three";import a,{Service as p}from"typedi";import{ActorComponent as c}from"./component.js";import{initComponentsSync as d}from"./internal/component-init.js";import{activeContainerInstance as m,containerRefMap as l}from"./internal/container-map.js";import{randomString as h}from"../../utils/math.js";import{inject as u}from"../inject.js";import{ViewController as f}from"../services/render.js";import{actorConstructContext as y}from"./factory.js";import{NetRole as j}from"../net/service/net-actor-role.js";import{registerActorClass as g}from"./type-registry.js";export{getActorClassById,getActorClassId,getRegisteredActorClasses}from"./type-registry.js";export const $actorOptions=Symbol("actor-options");export function getActorOptions(t){return t[$actorOptions]??b}const b={replicate:!1};export function Actor(t=b){const e=p({transient:!0});return function(i){const s=arguments[1],r=t.typeId??s?.name??i.name,n=g(r,i);null!=n&&n!==i&&console.warn(`Duplicate actor class name ${r}`),i.__actorId=r,i.__isActor=!0,e(i),o.noop()(i),o.parameterProperties()(i),i[$actorOptions]=t}}let U=0;export class BaseActor{get position(){return this.object?.position}get quaternion(){return this.object?.quaternion}get rotation(){return this.object?.rotation}onInit(){}onBeginPlay(){}onEndPlay(){}applySceneParameters(t,e){return!1}onUpdate(t){}onLateUpdate(t){}constructor(){this.id=++U,this.netRole=j.authority,this.__isInitialised=!1,this.object=new n,this.disposed=new s,this.attachedComponents=[],y.actor=this,this.onUpdate!==BaseActor.prototype.onUpdate&&u(f).onUpdate(this).pipe(r(()=>!this.__isInitialised)).subscribe(t=>this.onUpdate(t)),this.onLateUpdate!==BaseActor.prototype.onLateUpdate&&u(f).onLateUpdate(this).pipe(r(()=>!this.__isInitialised)).subscribe(t=>this.onLateUpdate(t))}attach(t,e){const o=m.value,i=l.get(this)??m.value??a.of("default");m.value=i;const s=h();i.set({id:s,type:t,transient:!0});const r=i.get(s);if(m.value=o,null!=e)for(const t of Object.keys(e))r[t]=e[t];return this.__isInitialised&&(r.actor=this,r.onInit(),d(r,this)),this.attachedComponents.push(r),r}getComponent(t){for(const e of Object.values(this))if(e instanceof t)return e;for(const e of this.attachedComponents)if(e instanceof t)return e}}t([i(),e("design:type",Object),e("design:paramtypes",[])],BaseActor.prototype,"position",null),t([i(),e("design:type",Object),e("design:paramtypes",[])],BaseActor.prototype,"quaternion",null),t([i(),e("design:type",Object),e("design:paramtypes",[])],BaseActor.prototype,"rotation",null);export function _setupActorUpdateEventHandlers(){this.onUpdate!==c.prototype.onUpdate&&u(f).onUpdate(this.actor).pipe(r(()=>!this.actor?.__isInitialised)).subscribe(t=>this.onUpdate(t)),this.onLateUpdate!==c.prototype.onLateUpdate&&u(f).onLateUpdate(this.actor).pipe(r(()=>!this.actor?.__isInitialised)).subscribe(t=>this.onLateUpdate(t))}/*
1
+ import{__decorate as t,__metadata as e}from"tslib";import o,{ignore as i}from"@plumier/reflect";import{Subject as r,skipWhile as s}from"rxjs";import{Group as n}from"three";import a,{Service as p}from"typedi";import{ActorComponent as c}from"./component.js";import{initComponentsSync as d}from"./internal/component-init.js";import{activeContainerInstance as l,containerRefMap as m}from"./internal/container-map.js";import{randomString as h}from"../../utils/math.js";import{inject as u}from"../inject.js";import{ViewController as f}from"../services/render.js";import{actorConstructContext as y}from"./factory.js";import{NetRole as j}from"../net/service/net-actor-role.js";import{registerActorClass as g}from"./type-registry.js";export{getActorClassById,getActorClassId,getRegisteredActorClasses}from"./type-registry.js";export const $actorOptions=Symbol("actor-options");export function getActorOptions(t){return t[$actorOptions]??b}const b={replicate:!1};export function Actor(t=b){const e=p({transient:!0});return function(i){const r=arguments[1],s=t.typeId??r?.name??i.name,n=g(s,i);null!=n&&n!==i&&console.warn(`Duplicate actor class name ${s}`),i.__actorId=s,i.__isActor=!0,e(i),o.noop()(i),o.parameterProperties()(i),i[$actorOptions]=t}}let U=0;export class BaseActor{get position(){return this.object?.position}get quaternion(){return this.object?.quaternion}get rotation(){return this.object?.rotation}onInit(){}onBeginPlay(){}onEndPlay(){}applySceneParameters(t,e){return!1}onUpdate(t){}onLateUpdate(t){}constructor(){this.id=++U,this.netRole=j.authority,this.__isInitialised=!1,this.object=new n,this.disposed=new r,this.attachedComponents=[],y.actor=this,this.onUpdate!==BaseActor.prototype.onUpdate&&u(f).onUpdate(this).pipe(s(()=>!this.__isInitialised)).subscribe(t=>this.onUpdate(t)),this.onLateUpdate!==BaseActor.prototype.onLateUpdate&&u(f).onLateUpdate(this).pipe(s(()=>!this.__isInitialised)).subscribe(t=>this.onLateUpdate(t))}attach(t,e){const o=l.value,i=m.get(this)??l.value??a.of("default"),r=h(),s=y.actor;let n;try{l.value=i,y.actor=this,i.set({id:r,type:t,transient:!0}),n=i.get(r)}finally{y.actor=s,l.value=o}if(n.actor=this,null!=e)for(const t of Object.keys(e))n[t]=e[t];return this.__isInitialised&&(n.onInit(),d(n,this)),this.attachedComponents.push(n),n}getComponent(t){for(const e of Object.values(this))if(e instanceof t)return e;for(const e of this.attachedComponents)if(e instanceof t)return e}}t([i(),e("design:type",Object),e("design:paramtypes",[])],BaseActor.prototype,"position",null),t([i(),e("design:type",Object),e("design:paramtypes",[])],BaseActor.prototype,"quaternion",null),t([i(),e("design:type",Object),e("design:paramtypes",[])],BaseActor.prototype,"rotation",null);export function _setupActorUpdateEventHandlers(){this.onUpdate!==c.prototype.onUpdate&&u(f).onUpdate(this.actor).pipe(s(()=>!this.actor?.__isInitialised)).subscribe(t=>this.onUpdate(t)),this.onLateUpdate!==c.prototype.onLateUpdate&&u(f).onLateUpdate(this.actor).pipe(s(()=>!this.actor?.__isInitialised)).subscribe(t=>this.onLateUpdate(t))}/*
2
2
  * Copyright (©) 2026 Hology Interactive AB. All rights reserved.
3
3
  * See the LICENSE.md file for details.
4
4
  */
@@ -1,4 +1,4 @@
1
- import{__decorate as t,__metadata as o}from"tslib";import{ActorComponent as e,Component as i}from"../component.js";import{Vector3 as s,MathUtils as r,PerspectiveCamera as n,Object3D as h}from"three";import{ViewController as a}from"../../services/render.js";import{DecimalInput as l,RestrictedRotationInput as c}from"../../input/index.js";import{PhysicsSystem as p}from"../../services/physics/physics-system.js";import{Parameter as m}from"../../../shader/parameter.js";import{World as d}from"../../services/world.js";import{inject as u}from"../../inject.js";import{ease as y}from"@hology/nebula";const f=void 0!==window&&/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);let C=class extends e{constructor(){super(),this.viewController=u(a),this.physicsSystem=u(p),this.aspect=this.viewController.htmlElement.clientWidth/this.viewController.htmlElement.clientHeight,this.near=.1,this.far=500,this.viewAngle=f?30:45,this.collision=!0,this.collisionSphereRadius=.25,this.smoothCamera=!1,this.smoothSpeed=10,this.teleportSnapDistance=5,this.camera=new n(this.viewAngle,this.aspect,this.near,this.far),this.distance=9,this.minDistance=1.5,this.maxDistance=this.distance,this.height=3,this.offsetX=-1,this.offsetY=2,this.offsetZ=1.5,this.autoActivate=!0,this.bounceBackSpeed=3,this.restrictedDistance=0,this.hasCollisionRestriction=!1,this.rotationInput=new c(-Math.PI/4,Math.PI/2-.7),this.zoomInput=new l(1,0,1),this.offset=new s,this.lookAtOffset=new s(this.offsetX,0,this.offsetZ),this.fixedBehind=!0,this.world=u(d),this.activated=!1,this.isMouseLocked=!1,this.prevFixedBehind=!1,this.blendDurationLeft=0,this.pointerEventsRegistered=!1,this.temporaryControlActive=!1,this.temporaryControlWeight=0,this.temporaryControlTargetWeight=0,this.temporaryControlBlendInDuration=.5,this.temporaryControlBlendOutDuration=.5,this.temporaryControlPositionEnabled=!1,this.temporaryControlBaseFieldOfView=this.camera.fov,this.temporaryControlFieldOfView=null,this.temporaryControlPosition=new s,this.temporaryControlLookAt=new s,this.pointerLockInactivatedAt=null,this.onMouseDown=t=>{this.isMouseLocked||"mouse"!==t.pointerType||this.hideCursor()},this.onKeyDown=t=>{"Escape"===t.key&&this.showCursor()},this.onPointerLockChange=()=>{this.isMouseLocked=null!=document.pointerLockElement||null!=document.mozPointerLockElement,this.element.style.cursor=this.isMouseLocked?"none":"default",this.isMouseLocked||(this.pointerLockInactivatedAt=performance.now())},this.prevLookAt=new s,this.smoothedLookAt=new s,this.previousTargetLookAt=new s,this.hasSmoothedLookAt=!1,this.smoothedRotX=0,this.smoothedRotY=0,this.smoothZoom=0}async onInit(){this.prevFixedBehind=this.fixedBehind,this.world.scene.add(this.camera),this.rotationInput.rotation.copy(this.actor.rotation),this.smoothedRotX=this.rotationInput.rotation.x,this.smoothedRotY=this.rotationInput.rotation.y,this.hasCollisionRestriction=!1,this.lookAtOffset.set(this.offsetX,0,this.offsetZ),this.smoothZoom=this.zoomInput.value,this.autoActivate&&this.activate(),this.disposed.subscribe(()=>{this.unregisterPointerEvents()})}activate(){this.activated=!0,this.hasSmoothedLookAt=!1,this.viewController.setCamera(this.camera),this.isMouseLocked=null!=document.pointerLockElement||null!=document.mozPointerLockElement,this.registerPointerEvents()}deactivate(){this.activated=!1,this.isMouseLocked=!1,this.unregisterPointerEvents()}setTemporaryControl(t,o,e={}){this.temporaryControlPosition.copy(t),this.temporaryControlLookAt.copy(o),this.temporaryControlPositionEnabled=!0,this.activateTemporaryControl(e)}setTemporaryLookAt(t,o={}){this.temporaryControlLookAt.copy(t),this.temporaryControlPositionEnabled=!1,this.activateTemporaryControl(o)}activateTemporaryControl(t){this.temporaryControlActive||(this.temporaryControlBaseFieldOfView=this.camera.fov),this.temporaryControlFieldOfView=null==t.fieldOfView?null:r.clamp(t.fieldOfView,1,179),null!=t.blendInDuration&&(this.temporaryControlBlendInDuration=Math.max(0,t.blendInDuration)),null!=t.blendOutDuration&&(this.temporaryControlBlendOutDuration=Math.max(0,t.blendOutDuration)),this.temporaryControlActive=!0,this.temporaryControlTargetWeight=1}clearTemporaryControl(t){this.temporaryControlActive&&(null!=t&&(this.temporaryControlBlendOutDuration=Math.max(0,t)),this.temporaryControlTargetWeight=0)}registerPointerEvents(){if(this.pointerEventsRegistered||null==document.body.requestPointerLock)return;const t=this.element;t.addEventListener("pointerdown",this.onMouseDown),t.addEventListener("keydown",this.onKeyDown),document.addEventListener("pointerlockchange",this.onPointerLockChange,!1),this.pointerEventsRegistered=!0}unregisterPointerEvents(){if(!this.pointerEventsRegistered)return;const t=this.element;t.removeEventListener("pointerdown",this.onMouseDown),t.removeEventListener("keydown",this.onKeyDown),document.removeEventListener("pointerlockchange",this.onPointerLockChange,!1),this.pointerEventsRegistered=!1}onLateUpdate(t){this.activated&&this.setFromRotation(t)}get element(){return this.viewController.htmlElement}hideCursor({ignoreRecentUnlock:t=!1}={}){!t&&null!=this.pointerLockInactivatedAt&&performance.now()-this.pointerLockInactivatedAt<1600||this.requestPointerLock()}requestPointerLock(){const t=this.element.getElementsByTagName("canvas")[0];if(null!=t&&t.isConnected&&t.ownerDocument===document&&null!=t.requestPointerLock)try{const o=t.requestPointerLock({unadjustedMovement:!0});o?.catch(()=>this.onPointerLockChange())}catch{this.onPointerLockChange()}else this.onPointerLockChange()}showCursor(){this.pointerLockInactivatedAt=performance.now(),this.element.style.cursor="default",null==document.pointerLockElement&&null==document.mozPointerLockElement||window.document.exitPointerLock(),this.isMouseLocked=!1}setFromRotation(t){this.lookAtOffset.set(this.offsetX,0,this.offsetZ),this.fixedBehind!==this.prevFixedBehind?(this.blendDurationLeft=1,this.prevFixedBehind=this.fixedBehind):this.blendDurationLeft>0&&(this.blendDurationLeft-=t);let o=this.zoomInput.value,e=this.rotationInput.rotation.x,i=this.rotationInput.rotation.y;if(this.smoothCamera){const s=1-Math.exp(-this.smoothSpeed*t*2);this.smoothedRotX=r.lerp(this.smoothedRotX,e,s),this.smoothedRotY=r.lerp(this.smoothedRotY,i,s),e=this.smoothedRotX,i=this.smoothedRotY,this.smoothZoom=r.lerp(this.smoothZoom,o,.4*s),o=this.smoothZoom}else this.smoothedRotX=e,this.smoothedRotY=i;const s=r.clamp(this.distance,this.minDistance,Math.max(this.distance*o,this.minDistance)),n=Math.cos(e)*s,h=this.fixedBehind?0:i;this.offset.x=Math.sin(-h)*n,this.offset.y=Math.sin(e)*s+this.offsetY,this.offset.z=Math.cos(-h)*-n,this.fixedBehind&&this.offset.add(this.lookAtOffset),this.updateCameraPosition(t)}checkForCollision(t,o){const e=g.subVectors(this.camera.position,t),i=e.length();if(i<.001)return;e.divideScalar(i);const s=this.physicsSystem.sphereCast(t,this.collisionSphereRadius,e,i,void 0,{excludeActor:this.actor,excludeTriggers:!0,collisionFilter:-2}),n=s.hasHit?Math.max(this.minDistance,s.distance-.05):i;if(!this.hasCollisionRestriction||n<=this.restrictedDistance)this.restrictedDistance=n,this.hasCollisionRestriction=!0;else{const t=1-Math.exp(-this.bounceBackSpeed*o);this.restrictedDistance=r.lerp(this.restrictedDistance,n,t)}this.camera.position.copy(t).addScaledVector(e,Math.min(i,this.restrictedDistance))}getLookAtPosition(){const t=k;return t.set(0,0,0),t.y=this.height,this.fixedBehind&&t.add(this.lookAtOffset),t.applyMatrix4(this.actor.object.matrixWorld),t}updateCameraPosition(t){this.actor.object.updateWorldMatrix(!0,!1),this.fixedBehind?(v.position.set(this.offset.x,this.offset.y,this.offset.z),v.rotation.set(0,0,0),v.scale.set(1,1,1),v.applyMatrix4(this.actor.object.matrix)):v.position.copy(this.actor.position).add(this.offset);const o=y.easeInOutCubic(1-this.blendDurationLeft);if(this.blendDurationLeft>0){const t=this.getLookAtPosition();this.prevLookAt.lerp(t,o),this.camera.lookAt(this.prevLookAt),this.camera.position.lerp(v.position,o),this.smoothedLookAt.copy(this.prevLookAt),this.previousTargetLookAt.copy(t),this.hasSmoothedLookAt=!0}else{const o=this.getLookAtPosition();if(this.smoothCamera){const e=1-Math.exp(-this.smoothSpeed*t),i=Math.max(0,this.teleportSnapDistance);!this.hasSmoothedLookAt||this.previousTargetLookAt.distanceToSquared(o)>i*i?this.smoothedLookAt.copy(o):this.smoothedLookAt.lerp(o,e)}else this.smoothedLookAt.copy(o);this.previousTargetLookAt.copy(o),this.hasSmoothedLookAt=!0,L.subVectors(v.position,o),this.camera.position.copy(this.smoothedLookAt).add(L),this.camera.lookAt(this.smoothedLookAt),this.prevLookAt.copy(this.smoothedLookAt)}this.collision&&(this.checkForCollision(this.prevLookAt,t),this.camera.lookAt(this.prevLookAt)),this.applyTemporaryControl(t)}applyTemporaryControl(t){if(!this.temporaryControlActive)return;this.temporaryControlTargetWeight>this.temporaryControlWeight?this.temporaryControlWeight=0===this.temporaryControlBlendInDuration?1:Math.min(1,this.temporaryControlWeight+t/this.temporaryControlBlendInDuration):this.temporaryControlTargetWeight<this.temporaryControlWeight&&(this.temporaryControlWeight=0===this.temporaryControlBlendOutDuration?0:Math.max(0,this.temporaryControlWeight-t/this.temporaryControlBlendOutDuration));const o=y.easeInOutCubic(this.temporaryControlWeight);this.temporaryControlPositionEnabled&&this.camera.position.lerp(this.getTemporaryControlPosition(),o),x.position.copy(this.camera.position),x.up.copy(this.camera.up),x.lookAt(this.temporaryControlLookAt),this.camera.quaternion.slerp(x.quaternion,o);const e=this.temporaryControlFieldOfView??this.temporaryControlBaseFieldOfView,i=r.lerp(this.temporaryControlBaseFieldOfView,e,o);this.camera.fov!==i&&(this.camera.fov=i,this.camera.updateProjectionMatrix()),0===this.temporaryControlTargetWeight&&0===this.temporaryControlWeight&&(this.temporaryControlActive=!1)}getTemporaryControlPosition(){if(!this.collision)return this.temporaryControlPosition;A.subVectors(this.temporaryControlPosition,this.temporaryControlLookAt);const t=A.length();if(t<.001)return this.temporaryControlPosition;A.divideScalar(t);const o=this.physicsSystem.sphereCast(this.temporaryControlLookAt,this.collisionSphereRadius,A,t,void 0,{excludeActor:this.actor,excludeTriggers:!0,collisionFilter:-2});return!o.hasHit||o.distance>=t?this.temporaryControlPosition:w.copy(this.temporaryControlLookAt).addScaledVector(A,Math.max(0,o.distance-.05))}};t([m(),o("design:type",Number)],C.prototype,"near",void 0),t([m(),o("design:type",Number)],C.prototype,"far",void 0),t([m(),o("design:type",Number)],C.prototype,"viewAngle",void 0),t([m(),o("design:type",Boolean)],C.prototype,"collision",void 0),t([m(),o("design:type",Number)],C.prototype,"collisionSphereRadius",void 0),t([m(),o("design:type",Boolean)],C.prototype,"smoothCamera",void 0),t([m(),o("design:type",Number)],C.prototype,"smoothSpeed",void 0),t([m(),o("design:type",Number)],C.prototype,"teleportSnapDistance",void 0),C=t([i(),o("design:paramtypes",[])],C);export{C as ThirdPersonCameraComponent};const v=new h,k=new s,L=new s,g=new s,A=new s,w=new s,x=new n;export class ThirdPartyCameraComponent extends C{}/*
1
+ import{__decorate as t,__metadata as o}from"tslib";import{ActorComponent as e,Component as i}from"../component.js";import{Vector3 as s,MathUtils as r,PerspectiveCamera as n,Object3D as h}from"three";import{ViewController as a}from"../../services/render.js";import{DecimalInput as l,RestrictedRotationInput as c}from"../../input/index.js";import{PhysicsSystem as p}from"../../services/physics/physics-system.js";import{Parameter as m}from"../../../shader/parameter.js";import{World as d}from"../../services/world.js";import{inject as u}from"../../inject.js";import{ease as y}from"@hology/nebula";const f=void 0!==window&&/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);let C=class extends e{constructor(){super(),this.viewController=u(a),this.physicsSystem=u(p),this.aspect=this.viewController.htmlElement.clientWidth/this.viewController.htmlElement.clientHeight,this.near=.1,this.far=500,this.viewAngle=f?30:45,this.collision=!0,this.collisionSphereRadius=.25,this.smoothCamera=!1,this.smoothSpeed=10,this.teleportSnapDistance=5,this.camera=new n(this.viewAngle,this.aspect,this.near,this.far),this.distance=9,this.minDistance=1.5,this.maxDistance=this.distance,this.height=3,this.offsetX=-1,this.offsetY=2,this.offsetZ=1.5,this.autoActivate=!0,this.bounceBackSpeed=3,this.restrictedDistance=0,this.hasCollisionRestriction=!1,this.rotationInput=new c(-Math.PI/4,Math.PI/2-.7),this.zoomInput=new l(1,0,1),this.offset=new s,this.lookAtOffset=new s(this.offsetX,0,this.offsetZ),this.fixedBehind=!0,this.world=u(d),this.activated=!1,this.isMouseLocked=!1,this.prevFixedBehind=!1,this.blendDurationLeft=0,this.pointerEventsRegistered=!1,this.temporaryControlActive=!1,this.temporaryControlWeight=0,this.temporaryControlTargetWeight=0,this.temporaryControlBlendInDuration=.5,this.temporaryControlBlendOutDuration=.5,this.temporaryControlPositionEnabled=!1,this.temporaryControlBaseFieldOfView=this.camera.fov,this.temporaryControlFieldOfView=null,this.temporaryControlPosition=new s,this.temporaryControlLookAt=new s,this.pointerLockInactivatedAt=null,this.onMouseDown=t=>{this.isMouseLocked||"mouse"!==t.pointerType||this.hideCursor()},this.onKeyDown=t=>{"Escape"===t.key&&this.showCursor()},this.onPointerLockChange=()=>{this.isMouseLocked=null!=document.pointerLockElement||null!=document.mozPointerLockElement,this.element.style.cursor=this.isMouseLocked?"none":"default",this.isMouseLocked||(this.pointerLockInactivatedAt=performance.now())},this.prevLookAt=new s,this.smoothedLookAt=new s,this.previousTargetLookAt=new s,this.hasSmoothedLookAt=!1,this.smoothedRotX=0,this.smoothedRotY=0,this.smoothZoom=0}async onInit(){this.prevFixedBehind=this.fixedBehind,this.world.scene.add(this.camera),this.rotationInput.rotation.copy(this.actor.rotation),this.smoothedRotX=this.rotationInput.rotation.x,this.smoothedRotY=this.rotationInput.rotation.y,this.hasCollisionRestriction=!1,this.lookAtOffset.set(this.offsetX,0,this.offsetZ),this.smoothZoom=this.zoomInput.value,this.autoActivate&&this.activate(),this.disposed.subscribe(()=>{this.unregisterPointerEvents()})}activate(){this.activated=!0,this.hasSmoothedLookAt=!1,this.viewController.setCamera(this.camera),this.isMouseLocked=null!=document.pointerLockElement||null!=document.mozPointerLockElement,this.registerPointerEvents()}deactivate(){this.activated=!1,this.isMouseLocked=!1,this.unregisterPointerEvents()}setTemporaryControl(t,o,e={}){this.temporaryControlPosition.copy(t),this.temporaryControlLookAt.copy(o),this.temporaryControlPositionEnabled=!0,this.activateTemporaryControl(e)}setTemporaryLookAt(t,o={}){this.temporaryControlLookAt.copy(t),this.temporaryControlPositionEnabled=!1,this.activateTemporaryControl(o)}activateTemporaryControl(t){this.temporaryControlActive||(this.temporaryControlBaseFieldOfView=this.camera.fov),this.temporaryControlFieldOfView=null==t.fieldOfView?null:r.clamp(t.fieldOfView,1,179),null!=t.blendInDuration&&(this.temporaryControlBlendInDuration=Math.max(0,t.blendInDuration)),null!=t.blendOutDuration&&(this.temporaryControlBlendOutDuration=Math.max(0,t.blendOutDuration)),this.temporaryControlActive=!0,this.temporaryControlTargetWeight=1}clearTemporaryControl(t){this.temporaryControlActive&&(null!=t&&(this.temporaryControlBlendOutDuration=Math.max(0,t)),this.temporaryControlTargetWeight=0)}registerPointerEvents(){if(this.pointerEventsRegistered||null==document.body.requestPointerLock)return;const t=this.element;t.addEventListener("pointerdown",this.onMouseDown),t.addEventListener("keydown",this.onKeyDown),document.addEventListener("pointerlockchange",this.onPointerLockChange,!1),this.pointerEventsRegistered=!0}unregisterPointerEvents(){if(!this.pointerEventsRegistered)return;const t=this.element;t.removeEventListener("pointerdown",this.onMouseDown),t.removeEventListener("keydown",this.onKeyDown),document.removeEventListener("pointerlockchange",this.onPointerLockChange,!1),this.pointerEventsRegistered=!1}onLateUpdate(t){this.activated&&this.setFromRotation(t)}get element(){return this.viewController.htmlElement}hideCursor({ignoreRecentUnlock:t=!1}={}){const o=!1!==navigator.pointerLockRequiresCooldown;!t&&o&&null!=this.pointerLockInactivatedAt&&performance.now()-this.pointerLockInactivatedAt<1600||this.requestPointerLock()}requestPointerLock(){const t=this.element.getElementsByTagName("canvas")[0],o=null!=t?.requestPointerLock?t:null!=this.element.requestPointerLock?this.element:null;if(null!=o)try{const t=o.requestPointerLock({unadjustedMovement:!0});t?.catch(()=>this.onPointerLockChange())}catch{this.onPointerLockChange()}else this.onPointerLockChange()}showCursor(){this.pointerLockInactivatedAt=performance.now(),this.element.style.cursor="default",null==document.pointerLockElement&&null==document.mozPointerLockElement||window.document.exitPointerLock(),this.isMouseLocked=!1}setFromRotation(t){this.lookAtOffset.set(this.offsetX,0,this.offsetZ),this.fixedBehind!==this.prevFixedBehind?(this.blendDurationLeft=1,this.prevFixedBehind=this.fixedBehind):this.blendDurationLeft>0&&(this.blendDurationLeft-=t);let o=this.zoomInput.value,e=this.rotationInput.rotation.x,i=this.rotationInput.rotation.y;if(this.smoothCamera){const s=1-Math.exp(-this.smoothSpeed*t*2);this.smoothedRotX=r.lerp(this.smoothedRotX,e,s),this.smoothedRotY=r.lerp(this.smoothedRotY,i,s),e=this.smoothedRotX,i=this.smoothedRotY,this.smoothZoom=r.lerp(this.smoothZoom,o,.4*s),o=this.smoothZoom}else this.smoothedRotX=e,this.smoothedRotY=i;const s=r.clamp(this.distance,this.minDistance,Math.max(this.distance*o,this.minDistance)),n=Math.cos(e)*s,h=this.fixedBehind?0:i;this.offset.x=Math.sin(-h)*n,this.offset.y=Math.sin(e)*s+this.offsetY,this.offset.z=Math.cos(-h)*-n,this.fixedBehind&&this.offset.add(this.lookAtOffset),this.updateCameraPosition(t)}checkForCollision(t,o){const e=g.subVectors(this.camera.position,t),i=e.length();if(i<.001)return;e.divideScalar(i);const s=this.physicsSystem.sphereCast(t,this.collisionSphereRadius,e,i,void 0,{excludeActor:this.actor,excludeTriggers:!0,collisionFilter:-2}),n=s.hasHit?Math.max(this.minDistance,s.distance-.05):i;if(!this.hasCollisionRestriction||n<=this.restrictedDistance)this.restrictedDistance=n,this.hasCollisionRestriction=!0;else{const t=1-Math.exp(-this.bounceBackSpeed*o);this.restrictedDistance=r.lerp(this.restrictedDistance,n,t)}this.camera.position.copy(t).addScaledVector(e,Math.min(i,this.restrictedDistance))}getLookAtPosition(){const t=k;return t.set(0,0,0),t.y=this.height,this.fixedBehind&&t.add(this.lookAtOffset),t.applyMatrix4(this.actor.object.matrixWorld),t}updateCameraPosition(t){this.actor.object.updateWorldMatrix(!0,!1),this.fixedBehind?(v.position.set(this.offset.x,this.offset.y,this.offset.z),v.rotation.set(0,0,0),v.scale.set(1,1,1),v.applyMatrix4(this.actor.object.matrix)):v.position.copy(this.actor.position).add(this.offset);const o=y.easeInOutCubic(1-this.blendDurationLeft);if(this.blendDurationLeft>0){const t=this.getLookAtPosition();this.prevLookAt.lerp(t,o),this.camera.lookAt(this.prevLookAt),this.camera.position.lerp(v.position,o),this.smoothedLookAt.copy(this.prevLookAt),this.previousTargetLookAt.copy(t),this.hasSmoothedLookAt=!0}else{const o=this.getLookAtPosition();if(this.smoothCamera){const e=1-Math.exp(-this.smoothSpeed*t),i=Math.max(0,this.teleportSnapDistance);!this.hasSmoothedLookAt||this.previousTargetLookAt.distanceToSquared(o)>i*i?this.smoothedLookAt.copy(o):this.smoothedLookAt.lerp(o,e)}else this.smoothedLookAt.copy(o);this.previousTargetLookAt.copy(o),this.hasSmoothedLookAt=!0,L.subVectors(v.position,o),this.camera.position.copy(this.smoothedLookAt).add(L),this.camera.lookAt(this.smoothedLookAt),this.prevLookAt.copy(this.smoothedLookAt)}this.collision&&(this.checkForCollision(this.prevLookAt,t),this.camera.lookAt(this.prevLookAt)),this.applyTemporaryControl(t)}applyTemporaryControl(t){if(!this.temporaryControlActive)return;this.temporaryControlTargetWeight>this.temporaryControlWeight?this.temporaryControlWeight=0===this.temporaryControlBlendInDuration?1:Math.min(1,this.temporaryControlWeight+t/this.temporaryControlBlendInDuration):this.temporaryControlTargetWeight<this.temporaryControlWeight&&(this.temporaryControlWeight=0===this.temporaryControlBlendOutDuration?0:Math.max(0,this.temporaryControlWeight-t/this.temporaryControlBlendOutDuration));const o=y.easeInOutCubic(this.temporaryControlWeight);this.temporaryControlPositionEnabled&&this.camera.position.lerp(this.getTemporaryControlPosition(),o),P.position.copy(this.camera.position),P.up.copy(this.camera.up),P.lookAt(this.temporaryControlLookAt),this.camera.quaternion.slerp(P.quaternion,o);const e=this.temporaryControlFieldOfView??this.temporaryControlBaseFieldOfView,i=r.lerp(this.temporaryControlBaseFieldOfView,e,o);this.camera.fov!==i&&(this.camera.fov=i,this.camera.updateProjectionMatrix()),0===this.temporaryControlTargetWeight&&0===this.temporaryControlWeight&&(this.temporaryControlActive=!1)}getTemporaryControlPosition(){if(!this.collision)return this.temporaryControlPosition;A.subVectors(this.temporaryControlPosition,this.temporaryControlLookAt);const t=A.length();if(t<.001)return this.temporaryControlPosition;A.divideScalar(t);const o=this.physicsSystem.sphereCast(this.temporaryControlLookAt,this.collisionSphereRadius,A,t,void 0,{excludeActor:this.actor,excludeTriggers:!0,collisionFilter:-2});return!o.hasHit||o.distance>=t?this.temporaryControlPosition:w.copy(this.temporaryControlLookAt).addScaledVector(A,Math.max(0,o.distance-.05))}};t([m(),o("design:type",Number)],C.prototype,"near",void 0),t([m(),o("design:type",Number)],C.prototype,"far",void 0),t([m(),o("design:type",Number)],C.prototype,"viewAngle",void 0),t([m(),o("design:type",Boolean)],C.prototype,"collision",void 0),t([m(),o("design:type",Number)],C.prototype,"collisionSphereRadius",void 0),t([m(),o("design:type",Boolean)],C.prototype,"smoothCamera",void 0),t([m(),o("design:type",Number)],C.prototype,"smoothSpeed",void 0),t([m(),o("design:type",Number)],C.prototype,"teleportSnapDistance",void 0),C=t([i(),o("design:paramtypes",[])],C);export{C as ThirdPersonCameraComponent};const v=new h,k=new s,L=new s,g=new s,A=new s,w=new s,P=new n;export class ThirdPartyCameraComponent extends C{}/*
2
2
  * Copyright (©) 2026 Hology Interactive AB. All rights reserved.
3
3
  * See the LICENSE.md file for details.
4
4
  */
@@ -1,4 +1,4 @@
1
- import{NavMesh as t,NavMeshParams as e,Raw as i,UnsignedCharArray as s,recastConfigDefaults as o,statusToReadableString as r}from"recast-navigation";import*as n from"three";import{buildConfig as a,buildTile as h}from"./build-tile.js";import{Subject as l}from"rxjs";import{executeTask as d,hasWorkerBuilder as u}from"../../worker/index.js";import{hasSharedArrayBufferSupport as c}from"../../utils/buffer.js";export const MAX_NAV_MESH_WORKERS=4;export const getTileBounds=(t,e,i,s,o)=>[[t.x+i*o,t.y,t.z+s*o],[t.x+(i+1)*o,e.y,t.z+(s+1)*o]];export class DynamicTiledNavMesh{constructor(i){this.navMeshVersion=0,this.onNavMeshUpdate=new l,this.abortController=new AbortController;const s=i.navMeshBounds.min,r=i.navMeshBounds.max,n=[s.toArray(),r.toArray()],h=i.navMeshBounds.min;this.navMeshBoundsMin=s,this.navMeshBoundsMax=r,this.navMeshBounds=n,this.navMeshOrigin=h,this.cacheId=i.cacheId,this.workerLimit=Math.min(4,Math.max(0,i.workers));const d={...o,...i.recastConfig};this.recastConfig=d;const u=new t,{tileWidth:c,tileHeight:M,tcs:m,maxPolysPerTile:v}=a({recastConfig:d,navMeshBounds:n});this.tileWidth=c,this.tileHeight=M,this.tcs=m;const f=e.create({orig:h,tileWidth:d.tileSize*d.cs,tileHeight:d.tileSize*d.cs,maxTiles:i.maxTiles,maxPolys:v});u.initTiled(f),this.navMesh=u}onResult(t){if(t.data.error)return void console.error(t.data.error);const{tileX:e,tileY:o,navMeshData:n}=t.data;if(this.navMesh.removeTile(this.navMesh.getTileRefAt(e,o,0)),null==n)return this.navMeshVersion++,void this.onNavMeshUpdate.next([this.navMeshVersion,[e,o]]);const a=new s;a.copy(n);const h=this.navMesh.addTile(a,i.Module.DT_TILE_FREE_DATA,0);i.Detour.statusFailed(h.status)&&(console.error(i.Module.RC_LOG_WARNING,`Failed to add tile to nav mesh\n\ttx: ${e}, ty: ${o},status: ${r(h.status)} (${h.status})`),a.destroy()),this.navMeshVersion++,this.onNavMeshUpdate.next([this.navMeshVersion,[e,o]])}buildTile(t,e,[i,s],o=!1,r=[]){const n=c&&t.buffer instanceof window.SharedArrayBuffer,a=n?t:new Float32Array(t),l=n?e:new Uint32Array(e),[v,f]=getTileBounds(this.navMeshBoundsMin,this.navMeshBoundsMax,i,s,this.tcs),g={tileX:i,tileY:s,tileBoundsMin:v,tileBoundsMax:f,recastConfig:this.recastConfig,navMeshBounds:this.navMeshBounds,keepIntermediates:!1,positions:a,indices:l,areaModifiers:r};return this.workerLimit>0&&u()?d("navmesh.buildTile",g,{transfer:n?void 0:[a.buffer,l.buffer],signal:this.abortController.signal,priority:"background"}).then(t=>this.onResult({data:t})).catch(t=>{"AbortError"!==t?.name&&console.error("Navmesh worker failed",t)}):new Promise(t=>{requestIdleCallback(()=>{const e=this.cacheId+JSON.stringify({tileX:g.tileX,tileY:g.tileY,areaModifiers:g.areaModifiers});if(o){const i=localStorage.getItem(e);if(null!=i){const e=m(i);return this.onResult({data:{tileX:g.tileX,tileY:g.tileY,navMeshData:e}}),void t({})}}else localStorage.removeItem(e);const i=h(g);if(!i.success)return console.error("error"in i?i.error:"Unknown navmesh tile build error"),void t(i);if(!i.data)return localStorage.removeItem(e),this.onResult({data:{tileX:g.tileX,tileY:g.tileY}}),void t(i);const s=i.data.toTypedArray();localStorage.setItem(e,M(s)),this.onResult({data:{tileX:g.tileX,tileY:g.tileY,navMeshData:s}}),t(i)})})}buildAllTiles(t,e){const{tileWidth:i,tileHeight:s}=this;for(let o=0;o<s;o++)for(let s=0;s<i;s++)this.buildTile(t,e,[s,o])}getTileForWorldPosition(t){return[Math.floor((t.x-this.navMeshBoundsMin.x)/this.tcs),Math.floor((t.z-this.navMeshBoundsMin.z)/this.tcs)]}getTilesForBounds(t){if(!t.intersectsBox(new n.Box3(this.navMeshBoundsMin,this.navMeshBoundsMax)))return[];const e=this.getTileForWorldPosition(t.min),i=this.getTileForWorldPosition(t.max);e[0]=Math.max(0,Math.min(this.tileWidth-1,e[0])),e[1]=Math.max(0,Math.min(this.tileHeight-1,e[1])),i[0]=Math.max(0,Math.min(this.tileWidth-1,i[0])),i[1]=Math.max(0,Math.min(this.tileHeight-1,i[1]));const s=[];for(let t=e[1];t<=i[1];t++)for(let o=e[0];o<=i[0];o++)s.push([o,t]);return s}destroy(){this.abortController.abort(),this.navMesh.destroy(),this.onNavMeshUpdate.complete()}}const M=function(t){return btoa(String.fromCharCode(...t))},m=function(t){if(!t)return null;const e=atob(t),i=e.length,s=new Uint8Array(i);for(let t=0;t<i;t++)s[t]=e.charCodeAt(t);return s};/*
1
+ import{NavMesh as t,NavMeshParams as e,Raw as i,UnsignedCharArray as s,recastConfigDefaults as o,statusToReadableString as r}from"recast-navigation";import*as n from"three";import{buildConfig as a,buildTile as h}from"./build-tile.js";import{Subject as l}from"rxjs";import{executeTask as d,hasWorkerBuilder as u}from"../../worker/index.js";import{hasSharedArrayBufferSupport as c}from"../../utils/buffer.js";export const MAX_NAV_MESH_WORKERS=4;export const getTileBounds=(t,e,i,s,o)=>[[t.x+i*o,t.y,t.z+s*o],[t.x+(i+1)*o,e.y,t.z+(s+1)*o]];export class DynamicTiledNavMesh{constructor(i){this.navMeshVersion=0,this.onNavMeshUpdate=new l,this.abortController=new AbortController;const s=i.navMeshBounds.min,r=i.navMeshBounds.max,n=[s.toArray(),r.toArray()],h=i.navMeshBounds.min;this.navMeshBoundsMin=s,this.navMeshBoundsMax=r,this.navMeshBounds=n,this.navMeshOrigin=h,this.cacheId=i.cacheId,this.workerLimit=Math.min(4,Math.max(0,i.workers));const d={...o,...i.recastConfig};this.recastConfig=d;const u=new t,{tileWidth:c,tileHeight:M,tcs:m,maxPolysPerTile:v}=a({recastConfig:d,navMeshBounds:n});this.tileWidth=c,this.tileHeight=M,this.tcs=m;const f=e.create({orig:h,tileWidth:d.tileSize*d.cs,tileHeight:d.tileSize*d.cs,maxTiles:i.maxTiles,maxPolys:v});u.initTiled(f),this.navMesh=u}onResult(t){if(t.data.error)return void console.error(t.data.error);const{tileX:e,tileY:o,navMeshData:n}=t.data;if(this.navMesh.removeTile(this.navMesh.getTileRefAt(e,o,0)),null==n)return this.navMeshVersion++,void this.onNavMeshUpdate.next([this.navMeshVersion,[e,o]]);const a=new s;a.copy(n);const h=this.navMesh.addTile(a,i.Module.DT_TILE_FREE_DATA,0);i.Detour.statusFailed(h.status)&&(console.error(i.Module.RC_LOG_WARNING,`Failed to add tile to nav mesh\n\ttx: ${e}, ty: ${o},status: ${r(h.status)} (${h.status})`),a.destroy()),this.navMeshVersion++,this.onNavMeshUpdate.next([this.navMeshVersion,[e,o]])}buildTile(t,e,[i,s],o=!1,r=[]){const n=c&&t.buffer instanceof window.SharedArrayBuffer,a=n?t:new Float32Array(t),l=n?e:new Uint32Array(e),[v,f]=getTileBounds(this.navMeshBoundsMin,this.navMeshBoundsMax,i,s,this.tcs),g={tileX:i,tileY:s,tileBoundsMin:v,tileBoundsMax:f,recastConfig:this.recastConfig,navMeshBounds:this.navMeshBounds,keepIntermediates:!1,positions:a,indices:l,areaModifiers:r};return this.workerLimit>0&&u()?d("navmesh.buildTile",g,{transfer:n?void 0:[a.buffer,l.buffer],signal:this.abortController.signal,priority:"background"}).then(t=>this.onResult({data:t})).catch(t=>{"AbortError"!==t?.name&&console.error("Navmesh worker failed",t)}):new Promise(t=>{(globalThis.requestIdleCallback??(t=>setTimeout(t,0)))(()=>{const e=this.cacheId+JSON.stringify({tileX:g.tileX,tileY:g.tileY,areaModifiers:g.areaModifiers});if(o){const i=localStorage.getItem(e);if(null!=i){const e=m(i);return this.onResult({data:{tileX:g.tileX,tileY:g.tileY,navMeshData:e}}),void t({})}}else localStorage.removeItem(e);const i=h(g);if(!i.success)return console.error("error"in i?i.error:"Unknown navmesh tile build error"),void t(i);if(!i.data)return localStorage.removeItem(e),this.onResult({data:{tileX:g.tileX,tileY:g.tileY}}),void t(i);const s=i.data.toTypedArray();localStorage.setItem(e,M(s)),this.onResult({data:{tileX:g.tileX,tileY:g.tileY,navMeshData:s}}),t(i)})})}buildAllTiles(t,e){const{tileWidth:i,tileHeight:s}=this;for(let o=0;o<s;o++)for(let s=0;s<i;s++)this.buildTile(t,e,[s,o])}getTileForWorldPosition(t){return[Math.floor((t.x-this.navMeshBoundsMin.x)/this.tcs),Math.floor((t.z-this.navMeshBoundsMin.z)/this.tcs)]}getTilesForBounds(t){if(!t.intersectsBox(new n.Box3(this.navMeshBoundsMin,this.navMeshBoundsMax)))return[];const e=this.getTileForWorldPosition(t.min),i=this.getTileForWorldPosition(t.max);e[0]=Math.max(0,Math.min(this.tileWidth-1,e[0])),e[1]=Math.max(0,Math.min(this.tileHeight-1,e[1])),i[0]=Math.max(0,Math.min(this.tileWidth-1,i[0])),i[1]=Math.max(0,Math.min(this.tileHeight-1,i[1]));const s=[];for(let t=e[1];t<=i[1];t++)for(let o=e[0];o<=i[0];o++)s.push([o,t]);return s}destroy(){this.abortController.abort(),this.navMesh.destroy(),this.onNavMeshUpdate.complete()}}const M=function(t){return btoa(String.fromCharCode(...t))},m=function(t){if(!t)return null;const e=atob(t),i=e.length,s=new Uint8Array(i);for(let t=0;t<i;t++)s[t]=e.charCodeAt(t);return s};/*
2
2
  * Copyright (©) 2026 Hology Interactive AB. All rights reserved.
3
3
  * See the LICENSE.md file for details.
4
4
  */
@@ -12,6 +12,10 @@ export type InitiateGameConfig = {
12
12
  element: HTMLElement;
13
13
  sceneName: string;
14
14
  dataDir: string;
15
+ /** Bypasses callback-based Three file loaders for runtimes with a partial DOM implementation. */
16
+ directAssetFileLoading?: boolean;
17
+ /** Target-specific location of the generated hology_data.json bundle. */
18
+ runtimeDataUrl?: string | URL;
15
19
  shaders: {
16
20
  [name: string]: ShaderType;
17
21
  };
@@ -1,4 +1,4 @@
1
- import e from"typedi";import{loadScene as t}from"../scene/bootstrap.js";import{ActorFactory as n}from"./actors/factory.js";import{World as s}from"./services/world.js";import{SceneMaterializer as o}from"../scene/materializer.js";import{ViewController as r}from"./services/render.js";import{RenderingView as i}from"../rendering.js";import{PhysicsSystem as a}from"./services/physics/physics-system.js";import{MeshComponent as c}from"./actors/builtin/components/mesh-component.js";import{builtInComponents as d}from"./actors/builtin/components/index.js";import{activeContainerInstance as m}from"./actors/internal/container-map.js";import{InputService as l}from"./input/index.js";import{RuntimeAssetsService as p}from"../scene/runtime-asset-service.js";import{AssetResourceLoader as u}from"../scene/asset-resource-loader.js";import{AssetLoader as h}from"./services/asset-loader.js";import{polyfillClient as g}from"./polyfill.js";import{Subject as f}from"rxjs";import{PointerEvents as w}from"./services/pointer-events.js";import{RuntimeBundledBackendService as b}from"../scene/runtime-bundled-backend-service.js";import{Scene as v}from"three";import{ShaderProvider as S}from"./services/shader-provider.js";import{SceneDataService as j}from"../scene/scene-data-service.js";import{NetMode as x}from"./net/net-session.js";import{AssetsProvider as y}from"../scene/assets-provider.js";import{GpuVfxWorldService as I}from"../effects/vfx/gpu-vfx-world-service.js";export function initiateGame(f,w){if(g(),0!=w.element.childNodes.length)return console.error("Can not initialize the game with a non-empty html element"),null;e.has(r);const P=e.of("default"),D=new HologyRuntime(P),G=new n(P,{inEditor:!1});var k;G.classes=w.actors,e.set(n,G),k=w.element,Object.assign(k.style,{position:"absolute",top:"0",left:"0",width:"100%",height:"100%",overflow:"hidden"});const W=new i(w.element,{backend:w.rendering?.backend??"webgpu-experimental",enableXR:!0===w.xr?.enabled,maxPixelRatio:w.rendering?.maxPixelRatio,resolutionScale:w.rendering?.resolutionScale,dynamicResolution:w.rendering?.dynamicResolution,upscaling:w.rendering?.upscaling,webgpuPostProcessing:w.rendering?.webgpuPostProcessing,webgpuDirectionalShadows:w.rendering?.webgpuDirectionalShadows,webgpuVfx:w.rendering?.webgpuVfx??"auto",msaa:w.rendering?.msaa,fpsCap:w.rendering?.fpsCap,depthPrepass:{enabled:!0===w.rendering?.depthPrepass?.enabled},bloom:{enabled:!1!==w?.rendering?.bloom?.enabled},reflection:{enabled:!1!==w?.rendering?.reflection?.enabled},occlusionCulling:{enabled:!1!==w?.rendering?.occlusionCulling?.enabled},shadows:{cascadeUpdateIntervals:[22,40,60,120]}});W.renderer.shadowMap.enabled=w.rendering?.shadows?.enabled??!0,W.renderer.shadowMap.autoUpdate=w.rendering?.shadows?.autoUpdate??!0,W.renderer.debug.checkShaderErrors=!1,e.set(i,W);const E=new r(W);e.set(r,E);const R=new b,A=new p(R),C=new u;C.setDataDir(w.dataDir),C.initKtx2(W.renderer);const M=Object.entries(w.shaders).map(([e,t])=>({name:e,type:t})),z=Object.entries(w.actors).map(([e,t])=>({name:e,type:t})),F={...d,...w.components??{}},O=Object.entries(F).map(([e,t])=>({name:e,type:t})),U=new S(M);e.set(S,U);const q=new h(C,A,M);e.set(y,A),e.set(u,C),e.set(h,q);const H=new v,N=new o(H,new j,A,C,W,M,z,G,O);N.inEditor=!1,N.netMode=w.multi?.session?.mode??x.none,e.set(o,N);const T=e.get(s);return e.set(s,T),T.materializer=N,(async()=>{const n=e.get(a);if(await n.start(),D.isShutdown)return;if(await R.preloadData(),D.isShutdown)return;if(T.scene=H,null!=w.multi?.session){const{NetService:e}=await import("./net/service/net-service.js"),t=P.get(e);t.session=w.multi.session,t.start(),D.shutdownStarted.subscribe(()=>t.stop())}const{scene:s,actors:o,materializer:r}=await t(W,w.sceneName,w.dataDir,w.shaders,w.actors,F,G,R,A,C,{detailTier:w.detailTier,nodeMode:w.multi?.session?.mode??x.none});T.scene=s,n.scene=T.scene;for(const e of H.children)T.scene.add(e);if(D.isShutdown)return void W.stop();e.import([c]);for(const e of o)T.addActor(e);n.addFromScene(s),await T.startSceneEventGraphs(r),m.value=P,P.remove(f),P.set({id:f,type:f});const i=P.get(f);if(m.value=null,D.gameInstance=i,i instanceof GameInstance&&await i.onPreload(),D.isShutdown)return void W.stop();if(console.log("Start compile shaders"),console.time("compile shaders"),await W.compileAsync(),console.timeEnd("compile shaders"),"webgpu-experimental"===W.activeBackend?console.log("Finished compiling the experimental WebGPU scene."):console.log("Finished compile shaders. Programs: ",W.renderer.info.programs?.length??0),console.log("Start init scene textures"),console.time("init scene textures"),W.initTextures(),console.timeEnd("init scene textures"),"webgpu-experimental"===W.activeBackend){const e=P.get(I).beginPipelineWarmup();try{W.render(0),await(W.experimentalWebGpuDevice?.queue.onSubmittedWorkDone())}finally{e()}W.render(0),await(W.experimentalWebGpuDevice?.queue.onSubmittedWorkDone()),await new Promise(e=>requestAnimationFrame(()=>e()))}const d=P.get(l);W.loop(e=>{d.update(e)}),D.status=5,D.shutdownStarted.subscribe(()=>{C.disposeAll()}),i instanceof GameInstance&&await i.onStart(),D._resolver(!0)})(),D}export class GameInstance{onPreload(){}onStart(){}onShutdown(){}}export function createHologyScene(){}export class HologyRuntime{constructor(e){this.containerInstance=e,this.status=0,this.isShutdown=!1,this.shutdownStarted=new f,this.ready=new Promise(e=>{this._resolver=e})}getWorld(){return this.containerInstance.get(s)}getService(e){return this.containerInstance.get(e)}shutdown(){this.isShutdown=!0;const e=this.shutdownStarted;e.next(),e.complete(),this.gameInstance instanceof GameInstance&&this.gameInstance.onShutdown(),this.containerInstance.get(l).stop();const t=this.containerInstance.get(i);t?.stop();const n=this.getWorld();n.stopSceneEventGraphs();const s=this.containerInstance.get(r);s.setMuted(!0),s.dispose();for(const e of[...n.actors])n.removeActor(e);this.containerInstance.get(a).stop(),this.containerInstance.get(o).dispose();const c=this.containerInstance.get(y);c instanceof p&&c.dispose(),this.containerInstance.get(w).stop(),this.containerInstance.reset(),this.shutdownStarted.complete()}}/*
1
+ import e from"typedi";import{loadScene as t}from"../scene/bootstrap.js";import{ActorFactory as n}from"./actors/factory.js";import{World as s}from"./services/world.js";import{SceneMaterializer as o}from"../scene/materializer.js";import{ViewController as i}from"./services/render.js";import{RenderingView as r}from"../rendering.js";import{PhysicsSystem as a}from"./services/physics/physics-system.js";import{MeshComponent as c}from"./actors/builtin/components/mesh-component.js";import{builtInComponents as d}from"./actors/builtin/components/index.js";import{activeContainerInstance as l}from"./actors/internal/container-map.js";import{InputService as m}from"./input/index.js";import{RuntimeAssetsService as p}from"../scene/runtime-asset-service.js";import{AssetResourceLoader as u}from"../scene/asset-resource-loader.js";import{AssetLoader as g}from"./services/asset-loader.js";import{polyfillClient as h}from"./polyfill.js";import{Subject as f}from"rxjs";import{PointerEvents as w}from"./services/pointer-events.js";import{RuntimeBundledBackendService as b}from"../scene/runtime-bundled-backend-service.js";import{Scene as v}from"three";import{ShaderProvider as y}from"./services/shader-provider.js";import{SceneDataService as S}from"../scene/scene-data-service.js";import{NetMode as j}from"./net/net-session.js";import{AssetsProvider as x}from"../scene/assets-provider.js";import{GpuVfxWorldService as I}from"../effects/vfx/gpu-vfx-world-service.js";export function initiateGame(f,w){if(h(),0!=w.element.childNodes.length)return console.error("Can not initialize the game with a non-empty html element"),null;e.has(i);const P=e.of("default"),D=new HologyRuntime(P),G=new n(P,{inEditor:!1});var k;G.classes=w.actors,e.set(n,G),k=w.element,Object.assign(k.style,{position:"absolute",top:"0",left:"0",width:"100%",height:"100%",overflow:"hidden"});const W=new r(w.element,{backend:w.rendering?.backend??"webgpu",enableXR:!0===w.xr?.enabled,maxPixelRatio:w.rendering?.maxPixelRatio,resolutionScale:w.rendering?.resolutionScale,dynamicResolution:w.rendering?.dynamicResolution,upscaling:w.rendering?.upscaling,webgpuPostProcessing:w.rendering?.webgpuPostProcessing,webgpuDirectionalShadows:w.rendering?.webgpuDirectionalShadows,webgpuVfx:w.rendering?.webgpuVfx??"auto",msaa:w.rendering?.msaa,fpsCap:w.rendering?.fpsCap,depthPrepass:{enabled:!0===w.rendering?.depthPrepass?.enabled},bloom:{enabled:!1!==w?.rendering?.bloom?.enabled},reflection:{enabled:!1!==w?.rendering?.reflection?.enabled},occlusionCulling:{enabled:!1!==w?.rendering?.occlusionCulling?.enabled},shadows:{enabled:w.rendering?.shadows?.enabled??!0,autoUpdate:w.rendering?.shadows?.autoUpdate??!0,cascadeUpdateIntervals:[22,40,60,120]}});e.set(r,W);const F=new i(W);e.set(i,F);const H=new b(w.runtimeDataUrl),R=new p(H),z=new u;z.setDataDir(w.dataDir),z.setDirectFileLoading(!0===w.directAssetFileLoading),"webgpu"===W.requestedBackend?z.initKtx2ForWebGpu():z.initKtx2(W.renderer);const A=Object.entries(w.shaders).map(([e,t])=>({name:e,type:t})),E=Object.entries(w.actors).map(([e,t])=>({name:e,type:t})),C={...d,...w.components??{}},U=Object.entries(C).map(([e,t])=>({name:e,type:t})),q=new y(A);e.set(y,q);const O=new g(z,R,A);e.set(x,R),e.set(u,z),e.set(g,O);const B=new v,L=new o(B,new S,R,z,W,A,E,G,U);L.inEditor=!1,L.netMode=w.multi?.session?.mode??j.none,e.set(o,L);const M=e.get(s);return e.set(s,M),M.materializer=L,(async()=>{const n=e.get(a);if(console.info("[Hology] Initializing physics."),await n.start(),console.info("[Hology] Physics initialized."),D.isShutdown)return;if(console.info("[Hology] Loading runtime data."),await H.preloadData(),console.info("[Hology] Runtime data loaded."),D.isShutdown)return;if(M.scene=B,null!=w.multi?.session){const{NetService:e}=await import("./net/service/net-service.js"),t=P.get(e);t.session=w.multi.session,t.start(),D.shutdownStarted.subscribe(()=>t.stop())}const{scene:s,actors:o,materializer:i}=await t(W,w.sceneName,w.dataDir,w.shaders,w.actors,C,G,H,R,z,{detailTier:w.detailTier,nodeMode:w.multi?.session?.mode??j.none});M.scene=s,n.scene=M.scene;for(const e of B.children)M.scene.add(e);if(D.isShutdown)return void W.stop();e.import([c]);for(const e of o)M.addActor(e);n.addFromScene(s),await M.startSceneEventGraphs(i),l.value=P,P.remove(f),P.set({id:f,type:f});const r=P.get(f);if(l.value=null,D.gameInstance=r,r instanceof GameInstance&&await r.onPreload(),D.isShutdown)return void W.stop();if(console.log("Start compile shaders"),console.time("compile shaders"),await W.compileAsync(),console.timeEnd("compile shaders"),"webgpu"===W.activeBackend?console.log("Finished compiling the experimental WebGPU scene."):console.log("Finished compile shaders. Programs: ",W.renderer.info.programs?.length??0),console.log("Start init scene textures"),console.time("init scene textures"),await W.initTexturesAsync(),console.timeEnd("init scene textures"),"webgpu"===W.activeBackend){const e=P.get(I).beginPipelineWarmup();try{W.render(0),await(W.experimentalWebGpuDevice?.queue.onSubmittedWorkDone())}finally{e()}W.render(0),await(W.experimentalWebGpuDevice?.queue.onSubmittedWorkDone()),await new Promise(e=>requestAnimationFrame(()=>e()))}const d=P.get(m);W.loop(e=>{d.update(e)}),D.status=5,D.shutdownStarted.subscribe(()=>{z.disposeAll()}),r instanceof GameInstance&&await r.onStart(),D._resolver(!0)})().catch(e=>{D.status=10,console.error("Failed to initialize Hology runtime.",e),e instanceof Error&&console.error(e.stack)}),D}export class GameInstance{onPreload(){}onStart(){}onShutdown(){}}export function createHologyScene(){}export class HologyRuntime{constructor(e){this.containerInstance=e,this.status=0,this.isShutdown=!1,this.shutdownStarted=new f,this.ready=new Promise(e=>{this._resolver=e})}getWorld(){return this.containerInstance.get(s)}getService(e){return this.containerInstance.get(e)}shutdown(){this.isShutdown=!0;const e=this.shutdownStarted;e.next(),e.complete(),this.gameInstance instanceof GameInstance&&this.gameInstance.onShutdown(),this.containerInstance.get(m).stop();const t=this.containerInstance.get(r);t?.stop();const n=this.getWorld();n.stopSceneEventGraphs();const s=this.containerInstance.get(i);s.setMuted(!0),s.dispose();for(const e of[...n.actors])n.removeActor(e);this.containerInstance.get(a).stop(),this.containerInstance.get(o).dispose();const c=this.containerInstance.get(x);c instanceof p&&c.dispose(),this.containerInstance.get(w).stop(),this.containerInstance.reset(),this.shutdownStarted.complete()}}/*
2
2
  * Copyright (©) 2026 Hology Interactive AB. All rights reserved.
3
3
  * See the LICENSE.md file for details.
4
4
  */
@@ -7,7 +7,7 @@ import { BaseActor } from '../../gameplay/actors/actor.js';
7
7
  import { PostProcessVolume } from "@hology/core";
8
8
  import type { PostProcessEffect, PostProcessEffectOptions } from '../../rendering/post-process-effect.js';
9
9
  import type { PostProcessMaterialSource } from "../../shader/post-process-shader.js";
10
- import type { ExperimentalWebGpuRenderGraphExtension, RenderingBackend } from '../../rendering.js';
10
+ import type { ActiveRenderingBackend, ExperimentalWebGpuRenderGraphExtension } from '../../rendering.js';
11
11
  import type { VfxBackendPreference } from '../../effects/vfx/gpu-sprite-compiler.js';
12
12
  import { type CameraShakeRequest } from "./camera-shake.js";
13
13
  export type { CameraShakeRequest, CameraShakeSample, CameraShakeSettings, CameraShakeVector3, } from "./camera-shake.js";
@@ -44,15 +44,19 @@ export declare class ViewController {
44
44
  private readonly accumulatedCameraShakeSample;
45
45
  private readonly scratchCameraShakeSample;
46
46
  constructor(view: RenderingView);
47
- get activeBackend(): RenderingBackend;
48
- get requestedBackend(): RenderingBackend;
47
+ get activeBackend(): ActiveRenderingBackend | null;
48
+ get requestedBackend(): ActiveRenderingBackend;
49
49
  get vfxBackendPreference(): VfxBackendPreference;
50
50
  get webgpuVfxInstancesPerTemplate(): number;
51
51
  get webgpuVfxTemplateMemoryBudgetBytes(): number;
52
52
  get webgpuVfxWorldMemoryBudgetBytes(): number;
53
53
  /** @deprecated Retained for source compatibility; GPU VFX no longer performs timed eviction. */
54
54
  get webgpuVfxColdTemplateSeconds(): number;
55
+ get webGpuDevice(): GPUDevice | null;
56
+ /** @deprecated Use webGpuDevice. */
55
57
  get experimentalWebGpuDevice(): GPUDevice | null;
58
+ registerWebGpuRenderGraphExtension(extension: ExperimentalWebGpuRenderGraphExtension): () => void;
59
+ /** @deprecated Use registerWebGpuRenderGraphExtension. */
56
60
  registerExperimentalWebGpuRenderGraphExtension(extension: ExperimentalWebGpuRenderGraphExtension): () => void;
57
61
  private handleFrame;
58
62
  set timeScale(value: number);
@@ -68,6 +72,10 @@ export declare class ViewController {
68
72
  get fpsCap(): number | null;
69
73
  set showStats(value: boolean);
70
74
  get showStats(): boolean;
75
+ /** Enables renderer timing collection without requiring the HTML stats UI. */
76
+ setProfilingEnabled(enabled: boolean): void;
77
+ /** Returns the latest completed WebGPU frame profile when profiling is enabled. */
78
+ getLastFrameProfile(): import("@hology/webgpu-renderer").RendererFrameProfile;
71
79
  addPostProcessVolume(volume: PostProcessVolume): void;
72
80
  removePostProcessVolume(volume: PostProcessVolume): void;
73
81
  addPostProcessEffect(source: PostProcessMaterialSource, options?: PostProcessEffectOptions): PostProcessEffect;
@@ -1,4 +1,4 @@
1
- import{__decorate as e,__metadata as t}from"tslib";import{Service as a}from"typedi";import{Camera as i}from"three";import{RenderingView as r}from"../../rendering.js";import{BehaviorSubject as s,Subject as n,takeUntil as h}from"rxjs";import*as o from"three";import{GameTimeScheduler as m}from"./game-time-scheduler.js";import{createCameraShakeSample as l,resetCameraShakeSample as u,sampleCameraShake as c}from"./camera-shake.js";export{defaultPostProcessEffectStage,postProcessEffectStages}from"../../rendering/post-process-effect.js";let d=class{constructor(e){this.view=e,this.tick=new n,this.lateTick=new n,this.audioListener=new o.AudioListener,this.pausedChanged=new s(!1),this.mutedChanged=new s(!1),this._muted=!1,this._masterVolume=1,this._cameraShakeIntensity=1,this._timeScale=1,this._hitStopRemaining=0,this.scheduler=new m,this.cameraOverrideId=0,this.cameraOverrides=[],this.cameraShakeId=0,this.gameplayCameraShakes=[],this.cameraShakeContributions=new Map,this.presentationCamera=null,this.accumulatedCameraShakeSample=l(),this.scratchCameraShakeSample=l(),this.outlined=[],this.baseCamera=e.camera,this.sourceCamera=e.camera,e.onLoop(e=>{this.handleFrame(e)}),e.camera.add(this.audioListener),window.hology_view=this}get activeBackend(){return this.view.activeBackend}get requestedBackend(){return this.view.requestedBackend}get vfxBackendPreference(){return this.view.vfxBackendPreference}get webgpuVfxInstancesPerTemplate(){return this.view.webgpuVfxInstancesPerTemplate}get webgpuVfxTemplateMemoryBudgetBytes(){return this.view.webgpuVfxTemplateMemoryBudgetBytes}get webgpuVfxWorldMemoryBudgetBytes(){return this.view.webgpuVfxWorldMemoryBudgetBytes}get webgpuVfxColdTemplateSeconds(){return this.view.webgpuVfxColdTemplateSeconds}get experimentalWebGpuDevice(){return this.view.experimentalWebGpuDevice}registerExperimentalWebGpuRenderGraphExtension(e){return this.view.registerExperimentalWebGpuRenderGraphExtension(e)}handleFrame(e){let t=this._timeScale,a=0;this._hitStopRemaining>0?(this._hitStopRemaining-=1e3*e,this._hitStopRemaining<=0&&(this._hitStopRemaining=0),t=0):a=e*this._timeScale,this.advanceGameplayCameraShakes(a),this.tick.next(a),this.scheduler.update(1e3*a),this.lateTick.next(a),this.view.simulationTimeScale=t,this.refreshCameraPresentation()}set timeScale(e){this._timeScale=Math.max(0,e)}get timeScale(){return this._timeScale}applyHitStop(e){this._hitStopRemaining=Math.max(this._hitStopRemaining,e)}set fpsCap(e){this.view.fpsCap=e}get fpsCap(){return this.view.fpsCap}set showStats(e){this.view.showStats=e}get showStats(){return this.view.showStats}setLightVolume(e){this.view.lightVolume=e}getLightVolume(){return this.view.lightVolume}addPostProcessVolume(e){this.view.addPostProcessVolume(e)}removePostProcessVolume(e){this.view.removePostProcessVolume(e)}addPostProcessEffect(e,t){return this.view.addPostProcessEffect(e,t)}onUpdate(e){return null==e?this.tick:this.tick.pipe(h(e.disposed))}onLateUpdate(e){return null==e?this.lateTick:this.lateTick.pipe(h(e.disposed))}setCamera(e){const t=e instanceof i?e:e.camera.instance;this.baseCamera=t,0===this.cameraOverrides.length&&(this.sourceCamera=t,this.refreshCameraPresentation())}getCamera(){return this.view.camera}getSourceCamera(){return this.sourceCamera}getBaseCamera(){return this.baseCamera}applyCameraShake(e){const t=function(e){return{duration:Math.max(0,e.duration??0),attack:e.attack??0,decay:e.decay??0,frequency:e.frequency??24,positionAmplitude:e.positionAmplitude?[...e.positionAmplitude]:[0,0,0],rotationAmplitude:e.rotationAmplitude?[...e.rotationAmplitude]:[0,0,0],seed:e.seed}}(e);if(t.duration<=0)return{release:()=>{}};const a={id:++this.cameraShakeId,request:t,elapsedTime:0,seedOverride:t.seed};this.gameplayCameraShakes.push(a),this.refreshCameraPresentation();let i=!1;return{release:()=>{i||(i=!0,this.releaseGameplayCameraShake(a.id))}}}setCameraShakeContribution(e,t,a,i,r){if(a.duration<=0)return void this.removeCameraShakeContribution(e,t);let s=this.cameraShakeContributions.get(e);s||(s=new Map,this.cameraShakeContributions.set(e,s));const n=s.get(t);n?(n.request=a,n.elapsedTime=Math.max(0,i),n.seedOverride=r):s.set(t,{key:t,request:a,elapsedTime:Math.max(0,i),seedOverride:r}),this.refreshCameraPresentation()}removeCameraShakeContribution(e,t){const a=this.cameraShakeContributions.get(e);a?.delete(t)&&(0===a.size&&this.cameraShakeContributions.delete(e),this.refreshCameraPresentation())}clearCameraShakeContributionsForOwner(e){this.cameraShakeContributions.delete(e)&&this.refreshCameraPresentation()}pushCameraOverride(e,t,a=0){const i={id:++this.cameraOverrideId,camera:e,owner:t,priority:a};this.cameraOverrides.push(i),this.applyTopCameraOverride();let r=!1;return{release:()=>{r||(r=!0,this.releaseCameraOverrideEntry(i))}}}releaseCameraOverridesForOwner(e){const t=this.cameraOverrides.filter(t=>t.owner!==e);t.length!==this.cameraOverrides.length&&(this.cameraOverrides=t,this.applyTopCameraOverride())}releaseCameraOverrideEntry(e){const t=this.cameraOverrides.indexOf(e);-1!==t&&(this.cameraOverrides.splice(t,1),this.applyTopCameraOverride())}applyTopCameraOverride(){const e=this.getTopCameraOverride();this.sourceCamera=e?.camera??this.baseCamera,this.refreshCameraPresentation()}getTopCameraOverride(){let e;for(const t of this.cameraOverrides)(!e||t.priority>e.priority||t.priority===e.priority&&t.id>e.id)&&(e=t);return e}applyRenderedCamera(e){this.view.camera!==e&&this.view.setCamera(e),e.add(this.audioListener)}releaseGameplayCameraShake(e){const t=this.gameplayCameraShakes.findIndex(t=>t.id===e);-1!==t&&(this.gameplayCameraShakes.splice(t,1),this.refreshCameraPresentation())}advanceGameplayCameraShakes(e){if(!(e<=0||0===this.gameplayCameraShakes.length))for(let t=this.gameplayCameraShakes.length-1;t>=0;t--){const a=this.gameplayCameraShakes[t];a.elapsedTime+=e,a.elapsedTime>a.request.duration&&this.gameplayCameraShakes.splice(t,1)}}refreshCameraPresentation(){if(!this.hasActiveCameraShake())return void this.applyRenderedCamera(this.sourceCamera);const e=this.ensurePresentationCamera();this.copyCameraState(this.sourceCamera,e),this.accumulateCameraShakeSamples(),this.applyCameraShakeSample(e),this.applyRenderedCamera(e)}hasActiveCameraShake(){if(this.gameplayCameraShakes.length>0)return!0;for(const e of this.cameraShakeContributions.values())if(e.size>0)return!0;return!1}ensurePresentationCamera(){return this.presentationCamera||(this.presentationCamera=new o.PerspectiveCamera,this.presentationCamera.name="View Controller Presentation Camera"),this.presentationCamera}copyCameraState(e,t){e.updateWorldMatrix(!0,!1),t.position.copy(e.getWorldPosition(v)),t.quaternion.copy(e.getWorldQuaternion(w)),t.scale.copy(e.getWorldScale(f)),t.layers.mask=e.layers.mask,e instanceof o.PerspectiveCamera?(t.fov=e.fov,t.near=e.near,t.far=e.far,t.aspect=e.aspect,t.zoom=e.zoom,t.focus=e.focus,t.filmGauge=e.filmGauge,t.filmOffset=e.filmOffset,t.view=null==e.view?null:{enabled:e.view.enabled,fullWidth:e.view.fullWidth,fullHeight:e.view.fullHeight,offsetX:e.view.offsetX,offsetY:e.view.offsetY,width:e.view.width,height:e.view.height},t.updateProjectionMatrix()):(t.projectionMatrix.copy(e.projectionMatrix),t.projectionMatrixInverse.copy(e.projectionMatrixInverse))}accumulateCameraShakeSamples(){u(this.accumulatedCameraShakeSample);for(let e=0;e<this.gameplayCameraShakes.length;e++)this.accumulateCameraShakeEntry(this.gameplayCameraShakes[e]);for(const e of this.cameraShakeContributions.values())for(const t of e.values())this.accumulateCameraShakeEntry(t)}accumulateCameraShakeEntry(e){const t=c(e.request,e.elapsedTime,this.scratchCameraShakeSample,e.seedOverride);if(t)for(let e=0;e<3;e++)this.accumulatedCameraShakeSample.position[e]+=t.position[e],this.accumulatedCameraShakeSample.rotation[e]+=t.rotation[e]}applyCameraShakeSample(e){k.copy(e.quaternion),y.set(this.accumulatedCameraShakeSample.position[0]*this._cameraShakeIntensity,this.accumulatedCameraShakeSample.position[1]*this._cameraShakeIntensity,this.accumulatedCameraShakeSample.position[2]*this._cameraShakeIntensity),y.applyQuaternion(k),e.position.add(y),x.set(this.accumulatedCameraShakeSample.rotation[0]*this._cameraShakeIntensity,this.accumulatedCameraShakeSample.rotation[1]*this._cameraShakeIntensity,this.accumulatedCameraShakeSample.rotation[2]*this._cameraShakeIntensity),O.setFromEuler(x),e.quaternion.copy(k).multiply(O),e.updateMatrixWorld(!0)}setMuted(e){this._muted=e,this.applyAudioGain(),this.mutedChanged.next(e)}getMuted(){return this._muted}set masterVolume(e){this._masterVolume=Math.min(Math.max(e,0),1),this.applyAudioGain()}get masterVolume(){return this._masterVolume}set cameraShakeIntensity(e){this._cameraShakeIntensity=Math.min(Math.max(e,0),1),this.refreshCameraPresentation()}get cameraShakeIntensity(){return this._cameraShakeIntensity}applyAudioGain(){this.audioListener.gain.gain.setValueAtTime(this._muted?0:this._masterVolume,this.audioListener.context.currentTime)}setOutlined(e){this.outlined.length=0;const t=this.outlined;for(let a=0;a<e.length;a++)t[a]=e[a];this.view.setSelectedObjects(t),this.view.setEnableOutlines(e.length>0)}getOutlined(){return this.outlined}addOutlined(e){this.outlined.includes(e)||(this.outlined.push(e),this.view.setSelectedObjects(this.outlined),this.view.setEnableOutlines(!0))}removeOutlined(e){const t=this.outlined.indexOf(e);-1!==t&&(this.outlined.splice(t,1),this.view.setSelectedObjects(this.outlined))}setOutlineColor(e){this.view.outlinePass?.visibleEdgeColor.copy(e)}getOutlineColor(){return this.view.outlinePass?.visibleEdgeColor}setOutlineThickness(e){this.view.outlinePass.edgeThickness=e}getOutlineThickness(){return this.view.outlinePass.edgeThickness}get htmlElement(){return this.view.container}getViewportSize(e=S){return this.view.getClientSize(e)}get paused(){return this.view.paused}set paused(e){e!=this.paused&&(e?this.pauseRendering():this.unpauseRendering())}pauseRendering(){this.view.paused=!0,this.pausedChanged.next(this.view.paused),this.scheduler.pause()}unpauseRendering(){this.view.paused=!1,this.pausedChanged.next(this.view.paused),this.scheduler.resume()}setInterval(e,t,a){return this.scheduler.setInterval(e,t,a)}clearInterval(e){this.scheduler.clearInterval(e)}dispose(){this.view.running&&this.view.stop(),this.scheduler.dispose(),this.cameraOverrides.length=0,this.gameplayCameraShakes.length=0,this.cameraShakeContributions.clear(),this.audioListener.removeFromParent(),this.tick.complete(),this.lateTick.complete(),this.paused=!0}createTimer(e){return this.scheduler.createTimer(e)}getScreenPosition(e,t=C,a=this.getViewportSize()){const i=this.getCamera();return p.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),i instanceof o.PerspectiveCamera&&(g.setFromProjectionMatrix(p),!g.containsPoint(e))?null:(t.copy(e),t.project(i),t.x=(t.x+1)/2*a.x,t.y=(1-t.y)/2*a.y,t)}};d=e([a(),t("design:paramtypes",[r])],d);export{d as ViewController};const p=new o.Matrix4,C=new o.Vector3,S=new o.Vector2,g=new o.Frustum,v=new o.Vector3,f=new o.Vector3,w=new o.Quaternion,k=new o.Quaternion,y=new o.Vector3,x=new o.Euler(0,0,0,"XYZ"),O=new o.Quaternion;/*
1
+ import{__decorate as e,__metadata as t}from"tslib";import{Service as a}from"typedi";import{Camera as i}from"three";import{RenderingView as r}from"../../rendering.js";import{BehaviorSubject as s,Subject as n,takeUntil as h}from"rxjs";import*as o from"three";import{GameTimeScheduler as m}from"./game-time-scheduler.js";import{createCameraShakeSample as l,resetCameraShakeSample as u,sampleCameraShake as c}from"./camera-shake.js";export{defaultPostProcessEffectStage,postProcessEffectStages}from"../../rendering/post-process-effect.js";let d=class{constructor(e){this.view=e,this.tick=new n,this.lateTick=new n,this.audioListener=new o.AudioListener,this.pausedChanged=new s(!1),this.mutedChanged=new s(!1),this._muted=!1,this._masterVolume=1,this._cameraShakeIntensity=1,this._timeScale=1,this._hitStopRemaining=0,this.scheduler=new m,this.cameraOverrideId=0,this.cameraOverrides=[],this.cameraShakeId=0,this.gameplayCameraShakes=[],this.cameraShakeContributions=new Map,this.presentationCamera=null,this.accumulatedCameraShakeSample=l(),this.scratchCameraShakeSample=l(),this.outlined=[],this.baseCamera=e.camera,this.sourceCamera=e.camera,e.onLoop(e=>{this.handleFrame(e)}),e.camera.add(this.audioListener),window.hology_view=this}get activeBackend(){return this.view.activeBackend}get requestedBackend(){return this.view.requestedBackend}get vfxBackendPreference(){return this.view.vfxBackendPreference}get webgpuVfxInstancesPerTemplate(){return this.view.webgpuVfxInstancesPerTemplate}get webgpuVfxTemplateMemoryBudgetBytes(){return this.view.webgpuVfxTemplateMemoryBudgetBytes}get webgpuVfxWorldMemoryBudgetBytes(){return this.view.webgpuVfxWorldMemoryBudgetBytes}get webgpuVfxColdTemplateSeconds(){return this.view.webgpuVfxColdTemplateSeconds}get webGpuDevice(){return this.view.webGpuDevice}get experimentalWebGpuDevice(){return this.webGpuDevice}registerWebGpuRenderGraphExtension(e){return this.view.registerWebGpuRenderGraphExtension(e)}registerExperimentalWebGpuRenderGraphExtension(e){return this.registerWebGpuRenderGraphExtension(e)}handleFrame(e){let t=this._timeScale,a=0;this._hitStopRemaining>0?(this._hitStopRemaining-=1e3*e,this._hitStopRemaining<=0&&(this._hitStopRemaining=0),t=0):a=e*this._timeScale,this.advanceGameplayCameraShakes(a),this.tick.next(a),this.scheduler.update(1e3*a),this.lateTick.next(a),this.view.simulationTimeScale=t,this.refreshCameraPresentation()}set timeScale(e){this._timeScale=Math.max(0,e)}get timeScale(){return this._timeScale}applyHitStop(e){this._hitStopRemaining=Math.max(this._hitStopRemaining,e)}set fpsCap(e){this.view.fpsCap=e}get fpsCap(){return this.view.fpsCap}set showStats(e){this.view.showStats=e}get showStats(){return this.view.showStats}setProfilingEnabled(e){this.view.setProfilingEnabled(e)}getLastFrameProfile(){return this.view.getLastFrameProfile()}setLightVolume(e){this.view.lightVolume=e}getLightVolume(){return this.view.lightVolume}addPostProcessVolume(e){this.view.addPostProcessVolume(e)}removePostProcessVolume(e){this.view.removePostProcessVolume(e)}addPostProcessEffect(e,t){return this.view.addPostProcessEffect(e,t)}onUpdate(e){return null==e?this.tick:this.tick.pipe(h(e.disposed))}onLateUpdate(e){return null==e?this.lateTick:this.lateTick.pipe(h(e.disposed))}setCamera(e){const t=e instanceof i?e:e.camera.instance;this.baseCamera=t,0===this.cameraOverrides.length&&(this.sourceCamera=t,this.refreshCameraPresentation())}getCamera(){return this.view.camera}getSourceCamera(){return this.sourceCamera}getBaseCamera(){return this.baseCamera}applyCameraShake(e){const t=function(e){return{duration:Math.max(0,e.duration??0),attack:e.attack??0,decay:e.decay??0,frequency:e.frequency??24,positionAmplitude:e.positionAmplitude?[...e.positionAmplitude]:[0,0,0],rotationAmplitude:e.rotationAmplitude?[...e.rotationAmplitude]:[0,0,0],seed:e.seed}}(e);if(t.duration<=0)return{release:()=>{}};const a={id:++this.cameraShakeId,request:t,elapsedTime:0,seedOverride:t.seed};this.gameplayCameraShakes.push(a),this.refreshCameraPresentation();let i=!1;return{release:()=>{i||(i=!0,this.releaseGameplayCameraShake(a.id))}}}setCameraShakeContribution(e,t,a,i,r){if(a.duration<=0)return void this.removeCameraShakeContribution(e,t);let s=this.cameraShakeContributions.get(e);s||(s=new Map,this.cameraShakeContributions.set(e,s));const n=s.get(t);n?(n.request=a,n.elapsedTime=Math.max(0,i),n.seedOverride=r):s.set(t,{key:t,request:a,elapsedTime:Math.max(0,i),seedOverride:r}),this.refreshCameraPresentation()}removeCameraShakeContribution(e,t){const a=this.cameraShakeContributions.get(e);a?.delete(t)&&(0===a.size&&this.cameraShakeContributions.delete(e),this.refreshCameraPresentation())}clearCameraShakeContributionsForOwner(e){this.cameraShakeContributions.delete(e)&&this.refreshCameraPresentation()}pushCameraOverride(e,t,a=0){const i={id:++this.cameraOverrideId,camera:e,owner:t,priority:a};this.cameraOverrides.push(i),this.applyTopCameraOverride();let r=!1;return{release:()=>{r||(r=!0,this.releaseCameraOverrideEntry(i))}}}releaseCameraOverridesForOwner(e){const t=this.cameraOverrides.filter(t=>t.owner!==e);t.length!==this.cameraOverrides.length&&(this.cameraOverrides=t,this.applyTopCameraOverride())}releaseCameraOverrideEntry(e){const t=this.cameraOverrides.indexOf(e);-1!==t&&(this.cameraOverrides.splice(t,1),this.applyTopCameraOverride())}applyTopCameraOverride(){const e=this.getTopCameraOverride();this.sourceCamera=e?.camera??this.baseCamera,this.refreshCameraPresentation()}getTopCameraOverride(){let e;for(const t of this.cameraOverrides)(!e||t.priority>e.priority||t.priority===e.priority&&t.id>e.id)&&(e=t);return e}applyRenderedCamera(e){this.view.camera!==e&&this.view.setCamera(e),e.add(this.audioListener)}releaseGameplayCameraShake(e){const t=this.gameplayCameraShakes.findIndex(t=>t.id===e);-1!==t&&(this.gameplayCameraShakes.splice(t,1),this.refreshCameraPresentation())}advanceGameplayCameraShakes(e){if(!(e<=0||0===this.gameplayCameraShakes.length))for(let t=this.gameplayCameraShakes.length-1;t>=0;t--){const a=this.gameplayCameraShakes[t];a.elapsedTime+=e,a.elapsedTime>a.request.duration&&this.gameplayCameraShakes.splice(t,1)}}refreshCameraPresentation(){if(!this.hasActiveCameraShake())return void this.applyRenderedCamera(this.sourceCamera);const e=this.ensurePresentationCamera();this.copyCameraState(this.sourceCamera,e),this.accumulateCameraShakeSamples(),this.applyCameraShakeSample(e),this.applyRenderedCamera(e)}hasActiveCameraShake(){if(this.gameplayCameraShakes.length>0)return!0;for(const e of this.cameraShakeContributions.values())if(e.size>0)return!0;return!1}ensurePresentationCamera(){return this.presentationCamera||(this.presentationCamera=new o.PerspectiveCamera,this.presentationCamera.name="View Controller Presentation Camera"),this.presentationCamera}copyCameraState(e,t){e.updateWorldMatrix(!0,!1),t.position.copy(e.getWorldPosition(S)),t.quaternion.copy(e.getWorldQuaternion(w)),t.scale.copy(e.getWorldScale(f)),t.layers.mask=e.layers.mask,e instanceof o.PerspectiveCamera?(t.fov=e.fov,t.near=e.near,t.far=e.far,t.aspect=e.aspect,t.zoom=e.zoom,t.focus=e.focus,t.filmGauge=e.filmGauge,t.filmOffset=e.filmOffset,t.view=null==e.view?null:{enabled:e.view.enabled,fullWidth:e.view.fullWidth,fullHeight:e.view.fullHeight,offsetX:e.view.offsetX,offsetY:e.view.offsetY,width:e.view.width,height:e.view.height},t.updateProjectionMatrix()):(t.projectionMatrix.copy(e.projectionMatrix),t.projectionMatrixInverse.copy(e.projectionMatrixInverse))}accumulateCameraShakeSamples(){u(this.accumulatedCameraShakeSample);for(let e=0;e<this.gameplayCameraShakes.length;e++)this.accumulateCameraShakeEntry(this.gameplayCameraShakes[e]);for(const e of this.cameraShakeContributions.values())for(const t of e.values())this.accumulateCameraShakeEntry(t)}accumulateCameraShakeEntry(e){const t=c(e.request,e.elapsedTime,this.scratchCameraShakeSample,e.seedOverride);if(t)for(let e=0;e<3;e++)this.accumulatedCameraShakeSample.position[e]+=t.position[e],this.accumulatedCameraShakeSample.rotation[e]+=t.rotation[e]}applyCameraShakeSample(e){k.copy(e.quaternion),y.set(this.accumulatedCameraShakeSample.position[0]*this._cameraShakeIntensity,this.accumulatedCameraShakeSample.position[1]*this._cameraShakeIntensity,this.accumulatedCameraShakeSample.position[2]*this._cameraShakeIntensity),y.applyQuaternion(k),e.position.add(y),x.set(this.accumulatedCameraShakeSample.rotation[0]*this._cameraShakeIntensity,this.accumulatedCameraShakeSample.rotation[1]*this._cameraShakeIntensity,this.accumulatedCameraShakeSample.rotation[2]*this._cameraShakeIntensity),P.setFromEuler(x),e.quaternion.copy(k).multiply(P),e.updateMatrixWorld(!0)}setMuted(e){this._muted=e,this.applyAudioGain(),this.mutedChanged.next(e)}getMuted(){return this._muted}set masterVolume(e){this._masterVolume=Math.min(Math.max(e,0),1),this.applyAudioGain()}get masterVolume(){return this._masterVolume}set cameraShakeIntensity(e){this._cameraShakeIntensity=Math.min(Math.max(e,0),1),this.refreshCameraPresentation()}get cameraShakeIntensity(){return this._cameraShakeIntensity}applyAudioGain(){this.audioListener.gain.gain.setValueAtTime(this._muted?0:this._masterVolume,this.audioListener.context.currentTime)}setOutlined(e){this.outlined.length=0;const t=this.outlined;for(let a=0;a<e.length;a++)t[a]=e[a];this.view.setSelectedObjects(t),this.view.setEnableOutlines(e.length>0)}getOutlined(){return this.outlined}addOutlined(e){this.outlined.includes(e)||(this.outlined.push(e),this.view.setSelectedObjects(this.outlined),this.view.setEnableOutlines(!0))}removeOutlined(e){const t=this.outlined.indexOf(e);-1!==t&&(this.outlined.splice(t,1),this.view.setSelectedObjects(this.outlined))}setOutlineColor(e){this.view.outlinePass?.visibleEdgeColor.copy(e)}getOutlineColor(){return this.view.outlinePass?.visibleEdgeColor}setOutlineThickness(e){this.view.outlinePass.edgeThickness=e}getOutlineThickness(){return this.view.outlinePass.edgeThickness}get htmlElement(){return this.view.container}getViewportSize(e=g){return this.view.getClientSize(e)}get paused(){return this.view.paused}set paused(e){e!=this.paused&&(e?this.pauseRendering():this.unpauseRendering())}pauseRendering(){this.view.paused=!0,this.pausedChanged.next(this.view.paused),this.scheduler.pause()}unpauseRendering(){this.view.paused=!1,this.pausedChanged.next(this.view.paused),this.scheduler.resume()}setInterval(e,t,a){return this.scheduler.setInterval(e,t,a)}clearInterval(e){this.scheduler.clearInterval(e)}dispose(){this.view.running&&this.view.stop(),this.scheduler.dispose(),this.cameraOverrides.length=0,this.gameplayCameraShakes.length=0,this.cameraShakeContributions.clear(),this.audioListener.removeFromParent(),this.tick.complete(),this.lateTick.complete(),this.paused=!0}createTimer(e){return this.scheduler.createTimer(e)}getScreenPosition(e,t=C,a=this.getViewportSize()){const i=this.getCamera();return p.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),i instanceof o.PerspectiveCamera&&(v.setFromProjectionMatrix(p),!v.containsPoint(e))?null:(t.copy(e),t.project(i),t.x=(t.x+1)/2*a.x,t.y=(1-t.y)/2*a.y,t)}};d=e([a(),t("design:paramtypes",[r])],d);export{d as ViewController};const p=new o.Matrix4,C=new o.Vector3,g=new o.Vector2,v=new o.Frustum,S=new o.Vector3,f=new o.Vector3,w=new o.Quaternion,k=new o.Quaternion,y=new o.Vector3,x=new o.Euler(0,0,0,"XYZ"),P=new o.Quaternion;/*
2
2
  * Copyright (©) 2026 Hology Interactive AB. All rights reserved.
3
3
  * See the LICENSE.md file for details.
4
4
  */
@@ -0,0 +1,104 @@
1
+ import * as THREE from 'three';
2
+ import type { FrameGraphBuilder } from '@hology/webgpu-renderer';
3
+ import type { DlssQualityMode } from './upscaling-pass.js';
4
+ export interface NativeUpscalingCapability {
5
+ readonly apiVersion: number;
6
+ readonly backend: string;
7
+ readonly compiled: boolean;
8
+ readonly available: boolean;
9
+ readonly reason: string;
10
+ }
11
+ interface NativeUpscalingHost {
12
+ getCapabilities(): NativeUpscalingCapability;
13
+ getOptimalSettings(options: {
14
+ outputWidth: number;
15
+ outputHeight: number;
16
+ mode: DlssQualityMode;
17
+ }): {
18
+ renderWidth: number;
19
+ renderHeight: number;
20
+ };
21
+ createSession(options: {
22
+ renderWidth: number;
23
+ renderHeight: number;
24
+ outputWidth: number;
25
+ outputHeight: number;
26
+ mode: DlssQualityMode;
27
+ }): NativeUpscalingSession;
28
+ }
29
+ interface NativeUpscalingSession {
30
+ readonly color: GPUTexture;
31
+ readonly depth: GPUTexture;
32
+ readonly motionVectors: GPUTexture;
33
+ readonly output: GPUTexture;
34
+ evaluate(options: NativeDlssFrame): void;
35
+ }
36
+ interface NativeDlssFrame {
37
+ cameraViewToClip: Float32Array;
38
+ clipToCameraView: Float32Array;
39
+ clipToPreviousClip: Float32Array;
40
+ previousClipToClip: Float32Array;
41
+ cameraPosition: Float32Array;
42
+ cameraUp: Float32Array;
43
+ cameraRight: Float32Array;
44
+ cameraForward: Float32Array;
45
+ jitterX: number;
46
+ jitterY: number;
47
+ nearPlane: number;
48
+ farPlane: number;
49
+ verticalFov: number;
50
+ aspectRatio: number;
51
+ reset: boolean;
52
+ orthographic: boolean;
53
+ }
54
+ export interface NativePostSubmitContext {
55
+ readonly device: GPUDevice;
56
+ present(sourceView: GPUTextureView): void;
57
+ }
58
+ export declare class NativeDlssUpscaler {
59
+ private readonly host;
60
+ private readonly mode;
61
+ private session;
62
+ private sessionSize;
63
+ private pipeline;
64
+ private bindGroup;
65
+ private colorView;
66
+ private depthView;
67
+ private motionView;
68
+ private outputView;
69
+ private inputColorView;
70
+ private inputDepthView;
71
+ private inputMotionView;
72
+ private fallbackView;
73
+ private presentFallbackOnce;
74
+ private failed;
75
+ private resetPending;
76
+ private historyValid;
77
+ private frameIndex;
78
+ private readonly previousViewProjection;
79
+ private readonly currentViewProjection;
80
+ private readonly currentViewProjectionInverse;
81
+ private readonly projection;
82
+ private readonly projectionInverse;
83
+ private readonly clipToPreviousClip;
84
+ private readonly previousClipToClip;
85
+ readonly jitter: THREE.Vector2;
86
+ private readonly cameraPosition;
87
+ private readonly cameraUp;
88
+ private readonly cameraRight;
89
+ private readonly cameraForward;
90
+ private readonly frame;
91
+ constructor(host: NativeUpscalingHost, mode: DlssQualityMode);
92
+ get enabled(): boolean;
93
+ getRenderScale(outputWidth: number, outputHeight: number): number;
94
+ addInputPass(graph: FrameGraphBuilder, color: string, motionVectors: string): void;
95
+ postSubmit: ({ present }: NativePostSubmitContext) => void;
96
+ prepareFrame(camera: THREE.PerspectiveCamera | THREE.OrthographicCamera): void;
97
+ finishFrame(camera: THREE.PerspectiveCamera | THREE.OrthographicCamera): void;
98
+ reset(): void;
99
+ dispose(): void;
100
+ private disable;
101
+ }
102
+ export declare function createNativeDlssUpscaler(mode: DlssQualityMode): NativeDlssUpscaler | null;
103
+ export {};
104
+ //# sourceMappingURL=native-dlss-upscaler.d.ts.map
@@ -0,0 +1,4 @@
1
+ import*as i from"three";const t=(new i.Matrix4).set(1,0,0,0,0,1,0,0,0,0,.5,.5,0,0,0,1);function e(i,t){const e=i.elements;t[0]=e[0],t[1]=e[4],t[2]=e[8],t[3]=e[12],t[4]=e[1],t[5]=e[5],t[6]=e[9],t[7]=e[13],t[8]=e[2],t[9]=e[6],t[10]=e[10],t[11]=e[14],t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15]}function r(i,t){t[0]=i.x,t[1]=i.y,t[2]=i.z}function s(i,t){let e=0,r=1/t;for(;i>0;)e+=r*(i%t),i=Math.floor(i/t),r/=t;return e}export class NativeDlssUpscaler{constructor(t,e){this.host=t,this.mode=e,this.session=null,this.sessionSize="",this.pipeline=null,this.bindGroup=null,this.colorView=null,this.depthView=null,this.motionView=null,this.outputView=null,this.inputColorView=null,this.inputDepthView=null,this.inputMotionView=null,this.fallbackView=null,this.presentFallbackOnce=!1,this.failed=!1,this.resetPending=!0,this.historyValid=!1,this.frameIndex=0,this.previousViewProjection=new i.Matrix4,this.currentViewProjection=new i.Matrix4,this.currentViewProjectionInverse=new i.Matrix4,this.projection=new i.Matrix4,this.projectionInverse=new i.Matrix4,this.clipToPreviousClip=new i.Matrix4,this.previousClipToClip=new i.Matrix4,this.jitter=new i.Vector2,this.cameraPosition=new i.Vector3,this.cameraUp=new i.Vector3,this.cameraRight=new i.Vector3,this.cameraForward=new i.Vector3,this.frame={cameraViewToClip:new Float32Array(16),clipToCameraView:new Float32Array(16),clipToPreviousClip:new Float32Array(16),previousClipToClip:new Float32Array(16),cameraPosition:new Float32Array(3),cameraUp:new Float32Array([0,1,0]),cameraRight:new Float32Array([1,0,0]),cameraForward:new Float32Array([0,0,-1]),jitterX:0,jitterY:0,nearPlane:.1,farPlane:1e3,verticalFov:1,aspectRatio:1,reset:!0,orthographic:!1},this.postSubmit=({present:i})=>{if(this.presentFallbackOnce)return this.presentFallbackOnce=!1,void(null!=this.fallbackView&&i(this.fallbackView));if(!this.failed&&null!=this.session&&null!=this.outputView)try{this.frame.reset=this.resetPending,this.session.evaluate(this.frame),this.resetPending=!1,i(this.outputView)}catch(t){this.disable(t),null!=this.fallbackView&&(this.presentFallbackOnce=!1,i(this.fallbackView))}}}get enabled(){return!this.failed}getRenderScale(i,t){if(this.failed)return 1;try{const e=this.host.getOptimalSettings({outputWidth:i,outputHeight:t,mode:this.mode});return Math.min(e.renderWidth/i,e.renderHeight/t)}catch(i){return this.disable(i),1}}addInputPass(i,t,e){i.addPass({name:"NativeDlssInputs",inputs:{color:t,depth:i.mainDepth,motion:e},execute:i=>{const r=i.getColorView(t),s=i.depthView,n=i.getColorView(e);if(this.fallbackView=r,!this.failed)try{const t=`${i.width}x${i.height}:${i.presentationWidth}x${i.presentationHeight}`;null!=this.session&&this.sessionSize===t||(this.session=this.host.createSession({renderWidth:i.width,renderHeight:i.height,outputWidth:i.presentationWidth,outputHeight:i.presentationHeight,mode:this.mode}),this.sessionSize=t,this.colorView=this.session.color.createView(),this.depthView=this.session.depth.createView(),this.motionView=this.session.motionVectors.createView(),this.outputView=this.session.output.createView(),this.pipeline??(this.pipeline=function(i){const t=i.createShaderModule({label:"native-dlss-inputs-shader",code:"\n struct VertexOutput { @builtin(position) position: vec4<f32> };\n @vertex fn vertexMain(@builtin(vertex_index) index: u32) -> VertexOutput {\n var positions = array<vec2<f32>, 3>(vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0));\n var output: VertexOutput;\n output.position = vec4(positions[index], 0.0, 1.0);\n return output;\n }\n @group(0) @binding(0) var inputColor: texture_2d<f32>;\n @group(0) @binding(1) var inputDepth: texture_depth_2d;\n @group(0) @binding(2) var inputMotion: texture_2d<f32>;\n struct FragmentOutput {\n @location(0) color: vec4<f32>,\n @location(1) depth: f32,\n @location(2) motion: vec2<f32>,\n };\n @fragment fn fragmentMain(@builtin(position) position: vec4<f32>) -> FragmentOutput {\n let pixel = vec2<i32>(position.xy);\n var output: FragmentOutput;\n output.color = textureLoad(inputColor, pixel, 0);\n output.depth = textureLoad(inputDepth, pixel, 0);\n output.motion = textureLoad(inputMotion, pixel, 0).xy;\n return output;\n }\n "});return i.createRenderPipeline({label:"native-dlss-inputs-pipeline",layout:"auto",vertex:{module:t,entryPoint:"vertexMain"},fragment:{module:t,entryPoint:"fragmentMain",targets:[{format:"rgba16float"},{format:"r32float"},{format:"rg16float"}]},primitive:{topology:"triangle-list"}})}(i.device)),this.bindGroup=null,this.reset()),null!=this.bindGroup&&this.inputColorView===r&&this.inputDepthView===s&&this.inputMotionView===n||(this.bindGroup=i.device.createBindGroup({label:"native-dlss-inputs-bind-group",layout:this.pipeline.getBindGroupLayout(0),entries:[{binding:0,resource:r},{binding:1,resource:s},{binding:2,resource:n}]}),this.inputColorView=r,this.inputDepthView=s,this.inputMotionView=n);const e=i.encoder.beginRenderPass({colorAttachments:[{view:this.colorView,clearValue:{r:0,g:0,b:0,a:0},loadOp:"clear",storeOp:"store"},{view:this.depthView,clearValue:{r:1,g:0,b:0,a:0},loadOp:"clear",storeOp:"store"},{view:this.motionView,clearValue:{r:0,g:0,b:0,a:0},loadOp:"clear",storeOp:"store"}]});e.setPipeline(this.pipeline),e.setBindGroup(0,this.bindGroup),e.draw(3),e.end()}catch(i){this.disable(i)}}})}prepareFrame(n){if(this.failed)return;this.projection.multiplyMatrices(t,n.projectionMatrix),this.projectionInverse.copy(this.projection).invert();const o=this.currentViewProjection.multiplyMatrices(this.projection,n.matrixWorldInverse);this.currentViewProjectionInverse.copy(o).invert(),this.historyValid?(this.clipToPreviousClip.multiplyMatrices(this.previousViewProjection,this.currentViewProjectionInverse),this.previousClipToClip.copy(this.previousViewProjection).invert().premultiply(o)):(this.clipToPreviousClip.identity(),this.previousClipToClip.identity());const a=this.frameIndex%32+1;this.jitter.set(s(a,2)-.5,s(a,3)-.5),this.frameIndex++,e(this.projection,this.frame.cameraViewToClip),e(this.projectionInverse,this.frame.clipToCameraView),e(this.clipToPreviousClip,this.frame.clipToPreviousClip),e(this.previousClipToClip,this.frame.previousClipToClip),this.frame.jitterX=this.jitter.x,this.frame.jitterY=-this.jitter.y,this.cameraPosition.setFromMatrixPosition(n.matrixWorld),this.cameraRight.setFromMatrixColumn(n.matrixWorld,0).normalize(),this.cameraUp.setFromMatrixColumn(n.matrixWorld,1).normalize(),n.getWorldDirection(this.cameraForward),r(this.cameraPosition,this.frame.cameraPosition),r(this.cameraRight,this.frame.cameraRight),r(this.cameraUp,this.frame.cameraUp),r(this.cameraForward,this.frame.cameraForward);const l=n instanceof i.PerspectiveCamera?n:null;this.frame.nearPlane=n.near,this.frame.farPlane=n.far,this.frame.verticalFov=null==l?0:i.MathUtils.degToRad(l.fov),this.frame.aspectRatio=l?.aspect??1,this.frame.reset=this.resetPending||!this.historyValid,this.frame.orthographic=null==l}finishFrame(i){this.failed||(this.previousViewProjection.multiplyMatrices(this.projection,i.matrixWorldInverse),this.historyValid=!0)}reset(){this.resetPending=!0,this.historyValid=!1,this.frameIndex=0}dispose(){this.session=null,this.bindGroup=null,this.inputColorView=this.inputDepthView=this.inputMotionView=null,this.colorView=this.depthView=this.motionView=this.outputView=this.fallbackView=null}disable(i){this.failed||(this.failed=!0,this.presentFallbackOnce=!0,this.jitter.set(0,0),console.warn("[Hology WebGPU] Native DLSS failed; continuing with normal WebGPU presentation.",i))}}export function createNativeDlssUpscaler(i){const t=navigator.gpu.nativeUpscaling,e=t?.getCapabilities();return null==t||1!==e?.apiVersion||!0!==e.available?(console.warn("[Hology WebGPU] Native DLSS-SR is unavailable; using TAA fallback."+(null!=e&&1!==e.apiVersion?` Unsupported native upscaling API version ${e.apiVersion}.`:e?.reason?` ${e.reason}`:"")),null):(console.info("[Hology WebGPU] Native DLSS-SR is active."),new NativeDlssUpscaler(t,i))}/*
2
+ * Copyright (©) 2026 Hology Interactive AB. All rights reserved.
3
+ * See the LICENSE.md file for details.
4
+ */
@@ -56,6 +56,7 @@ type MRTOutputsResolverFn = (mat: NodeShaderMaterial, drawStage?: NodeMaterialWe
56
56
  export declare class NodeMaterialWebGpuResolver {
57
57
  private readonly webGpu;
58
58
  private readonly mrtResolver?;
59
+ private readonly environmentTextureResolver?;
59
60
  private readonly cache;
60
61
  private readonly failedSignatures;
61
62
  private readonly mappedMaterialsCache;
@@ -67,7 +68,7 @@ export declare class NodeMaterialWebGpuResolver {
67
68
  private worldEnvironmentTexture;
68
69
  private worldEnvironmentIntensity;
69
70
  private worldEnvironmentRevision;
70
- constructor(webGpu: NodeMaterialWebGpuModule, mrtResolver?: MRTOutputsResolverFn);
71
+ constructor(webGpu: NodeMaterialWebGpuModule, mrtResolver?: MRTOutputsResolverFn, environmentTextureResolver?: (texture: THREE.Texture) => THREE.Texture);
71
72
  setWorldEnvironment(environment: ResolvedWorldEnvironment | null): void;
72
73
  resolve(material: THREE.Material, drawStage?: NodeMaterialWebGpuDrawStage): ResolvedWebGpuMaterial | undefined;
73
74
  private getOrCreateOutlineMaterial;
@@ -1,4 +1,4 @@
1
- import*as e from"three";import{compileNodeWebGpuFullscreen as t,compileNodeShaderMaterialForWebGpu as a,NodeShaderMaterial as i,webGpuRendererBindings as n,textureSampler2d as s,float as o,length as r,max as l,rgba as u,isWgslCompiler as p,isWgslFragmentCompiler as m,sqrt as c,normalize as d,transformed as h,uniformFloat as f,uniforms as M,vec4 as v,Vec3Node as y,toonMaterial as g}from"three-shader-graph";import{StandardShader as V}from"../shader/builtin/standard-shader.js";import{LambertShader as w}from"../shader/builtin/lambert-shader.js";import{ToonShader as S}from"../shader/builtin/toon-shader.js";import{UnlitShader as I}from"../shader/builtin/unlit-shader.js";import{SpriteShader as x}from"../shader/sprite-shader.js";import{elapsedTimeUniformName as T}from"../shader-nodes/time.js";import{depthUniformName as E,farUniformName as b,nearUniformName as C,resolutionUniformName as W,sceneNormalUniformName as U}from"../shader-nodes/depth.js";import{sceneMapUniformName as A}from"../shader-nodes/scene-sample.js";const N={...n,uniformExpressions:{...n.uniformExpressions,ambientLightColor:{type:"vec3",expression:"rendererAmbientLight()"},[T]:{type:"float",expression:"rendererElapsedTime()"},[C]:{type:"float",expression:"rendererCameraNear()"},[b]:{type:"float",expression:"rendererCameraFar()"},[W]:{type:"vec2",expression:"rendererViewportSize()"}},sceneTextures:{[A]:{semantic:"sceneColor",sampleType:"float"},[E]:{semantic:"sceneDepth",sampleType:"depth"}},attributes:{material:{shaderLocation:6,format:"float32x4",defaultValue:[0,0,0,0]},material2:{shaderLocation:7,format:"float32x4",defaultValue:[0,0,0,0]},hole:{shaderLocation:8,format:"float32",defaultValue:[0]},offset:{shaderLocation:9,format:"float32x3",stepMode:"instance",defaultValue:[0,0,0]},velocity:{shaderLocation:10,format:"float32x4",stepMode:"instance",defaultValue:[0,0,0,0]},size:{shaderLocation:11,format:"float32x3",stepMode:"instance",defaultValue:[0,0,0]},rotation:{shaderLocation:12,format:"float32",stepMode:"instance",defaultValue:[0]},particleData:{shaderLocation:13,format:"float32x3",stepMode:"instance",defaultValue:[1,1,0]},particleColor:{shaderLocation:14,format:"float32x4",stepMode:"instance",defaultValue:[1,1,1,1]}}};class k extends y{constructor(e){super(),this.fallback=e}compile(e){if(!p(e))return{out:e.get(this.fallback)};if(m(e))throw new Error("OutlineLocalPositionNode can only be used in the vertex stage");const t=`outline_local_position_${e.variable()}`;return{chunk:`\n#ifdef USE_SKINNING\n let ${t} = rendererSkinPosition(input.position, input.skinIndex, input.skinWeight).xyz;\n#else\n let ${t} = input.position;\n#endif`,out:t}}}class L extends y{constructor(e){super(),this.fallback=e}compile(e){if(!p(e))return{out:e.get(this.fallback)};if(m(e))throw new Error("OutlineLocalNormalNode can only be used in the vertex stage");const t=`outline_local_normal_${e.variable()}`;return{chunk:`\n#ifdef USE_SKINNING\n let ${t} = rendererSkinNormal(input.normal, input.skinIndex, input.skinWeight);\n#else\n let ${t} = input.normal;\n#endif`,out:t}}}export function setMaterialUniformValuesAutoUpdate(e,t){e.uniformValuesAutoUpdate=t}export function markMaterialUniformValuesNeedUpdate(e){const t=e;"uniformValuesNeedsUpdate"in t?t.uniformValuesNeedsUpdate=!0:t.uniformValuesAutoVersion=(t.uniformValuesAutoVersion??0)+1}function R(e){return!1!==e.uniformValuesAutoUpdate}function F(e){return e.uniformValuesAutoVersion??0}export function withThreeDefaultVertexAttributeValues(e){return e.map(e=>"uv1"===e.name&&null==e.defaultValue?{...e,defaultValue:[0,0]}:e)}const D=new WeakMap,O=new WeakMap;export function createNodeMaterialSignature(e){const t=O.get(e);if(null!=t)return t;const a=JSON.stringify({version:e.version,vertexShader:e.vertexShader,fragmentShader:e.fragmentShader,alphaTest:e.alphaTest,alphaToCoverage:e.alphaToCoverage,blending:e.blending,colorWrite:e.colorWrite,depthFunc:e.depthFunc,depthTest:e.depthTest,depthWrite:e.depthWrite,polygonOffset:e.polygonOffset,polygonOffsetFactor:e.polygonOffsetFactor,polygonOffsetUnits:e.polygonOffsetUnits,premultipliedAlpha:e.premultipliedAlpha,side:e.side,stencilWrite:e.stencilWrite,transparent:e.transparent,wireframe:e.wireframe});return O.set(e,a),a}export class NodeMaterialWebGpuResolver{constructor(e,t){this.webGpu=e,this.mrtResolver=t,this.cache=new WeakMap,this.failedSignatures=new WeakMap,this.mappedMaterialsCache=new WeakMap,this.mappedMaterialsSignatures=new WeakMap,this.observedNodeMaterials=new Map,this.outlineMaterials=new WeakMap,this.worldEnvironmentMaterials=new WeakSet,this.worldEnvironment=null,this.worldEnvironmentTexture=null,this.worldEnvironmentIntensity=0,this.worldEnvironmentRevision=0,this.cacheValues=new Set}setWorldEnvironment(e){const t=e?.texture??null,a=e?.intensity??0;if(this.worldEnvironmentTexture!==t||this.worldEnvironmentIntensity!==a){if(this.worldEnvironmentTexture!==t)this.worldEnvironmentRevision++;else if(null!=e)for(const e of this.cacheValues)e.inheritsWorldEnvironment&&null!=e.material.uniforms.envMapIntensity&&(e.material.uniforms.envMapIntensity.value=a,e.material.uniformValuesNeedsUpdate=!0);this.worldEnvironment=e,this.worldEnvironmentTexture=t,this.worldEnvironmentIntensity=a}}resolve(e,t=void 0){let n,s=!1;if(e instanceof i)n=e,this.observeNodeMaterial(n);else{const t=this.getOrCreateMappedNodeMaterial(e);if(null==t)return;n=t,s=!0}if("outline"===t){if(null==n.outputAlbedo)return;s&&_(e,n),n.userData.outlineParameters=e.userData?.outlineParameters,n=this.getOrCreateOutlineMaterial(n),s=!1}n.visible=e.visible,s&&(n.userData.receiveDecals=e.userData.receiveDecals);const o=t??"default",r=this.cache.get(n),l=r?.get(o);if(s&&null!=l&&l.sourceVersion===e.version&&l.worldEnvironmentRevision===this.worldEnvironmentRevision){const t=R(e),a=F(e);return l.material.uniformValuesAutoUpdate=t,this.syncInheritedWorldEnvironmentSource(n,l),t||l.sourceUniformValuesAutoVersion!==a?(_(e,n),l.compiled.syncLiveUniforms(l.material.uniforms),P(n,l.material.uniforms),$(n,l.material),l.sourceUniformValuesAutoVersion=a,t||(l.material.uniformValuesNeedsUpdate=!0),l.material):l.material}if(!s&&null!=l&&l.sourceVersion===e.version&&l.worldEnvironmentRevision===this.worldEnvironmentRevision&&z(n,l.compiled))return this.syncInheritedWorldEnvironmentSource(n,l),j(n,l),l.material;s&&_(e,n);const u=this.prepareWorldEnvironment(n),p=this.getNodeMaterialSignature(n,u);if(l?.signature===p&&z(n,l.compiled))return s?(l.material.uniformValuesAutoUpdate=R(e),l.compiled.syncLiveUniforms(l.material.uniforms),P(n,l.material.uniforms),$(n,l.material),l.sourceUniformValuesAutoVersion=F(e),l.material.uniformValuesAutoUpdate||(l.material.uniformValuesNeedsUpdate=!0)):j(n,l,!0),l.sourceVersion=e.version,l.worldEnvironmentRevision=this.worldEnvironmentRevision,l.material;try{const i=this.mrtResolver?.(n,t),m=a(n,N,i),c=new this.webGpu.WGSLShaderMaterial({vertexShader:m.vertexShader,fragmentShader:m.fragmentShader,depthVertexShader:m.depthVertexShader,depthFragmentShader:m.depthFragmentShader,pointShadowVertexShader:m.pointShadowVertexShader,pointShadowFragmentShader:m.pointShadowFragmentShader,uniforms:m.uniforms,textures:m.textures,sceneTextures:m.sceneTextures,graphTextures:m.graphTextures,vertexAttributes:withThreeDefaultVertexAttributeValues(m.vertexAttributes),uniformValuesAutoUpdate:s?R(e):n.uniformValuesAutoUpdate,transparent:m.renderState?.transparent,alphaTest:m.renderState?.alphaTest,depthTest:m.renderState?.depthTest,depthWrite:m.renderState?.depthWrite,side:m.renderState?.side,wireframe:n.wireframe});c.uniformValuesAutoUpdate=s?R(e):n.uniformValuesAutoUpdate,function(e,t){if(null==e)return;Object.assign(t,e)}(m.renderState,c),null!=l&&(l.material.dispose(),this.cacheValues.delete(l));const d={signature:p,compiled:m,material:c,inheritsWorldEnvironment:u,sourceVersion:e.version,sourceUniformValuesAutoVersion:s?F(e):n.uniformValuesAutoVersion,worldEnvironmentRevision:this.worldEnvironmentRevision},h=r??new Map;return h.set(o,d),this.cache.set(n,h),this.cacheValues.add(d),P(n,c.uniforms),$(n,c),c}catch(e){let t=this.failedSignatures.get(n);if(null==t&&(t=new Map,this.failedSignatures.set(n,t)),t.get(o)!==p){t.set(o,p);const a=e instanceof Error?e.message:String(e),i=n.name||n.uuid;console.warn(`[Hology WebGPU experiment] Falling back for NodeShaderMaterial "${i}": ${a}`,{material:n,error:e})}return}}getOrCreateOutlineMaterial(t){let a=this.outlineMaterials.get(t);if(null==a){const n=t.nodeMaterialDefinition,s=t.outputAlbedo;if(null==s)throw new Error("Cannot derive an outline material without an albedo output");const p=f("outlineThickness",.003),m=f("outlineDarkening",.65),y=f("outlineAlpha",1),V=new k(h.position.xyz),w=new L(h.normal),S=n.transform?.multiplyVec(v(V,1))??v(V,1),I=M.modelViewMatrix.multiplyVec(S),x=d(M.normalMatrix.multiplyVec(w)),T=c(l(r(I.xyz),o(1e-4))).multiply(.5),E=I.xyz.add(x.multiplyScalar(p.multiply(T))),b=M.projectionMatrix.multiplyVec(I),C=M.projectionMatrix.multiplyVec(v(E,1)),W=(n.position??b).add(C.subtract(b)),U=u(g({color:s.rgb.multiplyScalar(o(1).subtract(m))}),t.outputOpacity.multiply(y));a=new i({color:U,position:W,opacity:t.outputOpacity,discard:n.discard,alphaTest:t.alphaTest,transparent:!0,fog:!1,outputEncoding:n.outputEncoding,uniforms:n.uniforms,uniformNodes:n.uniformNodes}),a.side=e.BackSide,a.depthTest=!0,a.depthWrite=!0,this.outlineMaterials.set(t,a)}const n=t.userData?.outlineParameters;a.uniforms.outlineThickness.value=n?.thickness??.003,a.uniforms.outlineDarkening.value=e.MathUtils.clamp(n?.darkening??.65,0,1),a.uniforms.outlineAlpha.value=e.MathUtils.clamp(n?.alpha??t.opacity,0,1),a.userData.outlineSource=t;for(const e in t.uniforms)null!=a.uniforms[e]&&(a.uniforms[e].value=t.uniforms[e].value);return a}compileFullscreen(e){const a=t({color:e.outputColor,wgslBindings:{...N,uniformExpressions:{},graphTextures:{...N.graphTextures,[U]:{resource:"hologyNormalRoughness",dimension:"2d",sampleType:"float",sampler:"filtering"}}}}),i=a.syncLiveUniforms;return{...a,syncLiveUniforms(t){i(t),P(e,t)}}}getOrCreateMappedNodeMaterial(t){const a=function(t){const a=[t.vertexColors,t.transparent,t.alphaTest,t.side,t.depthTest,t.depthWrite,t.wireframe??!1];t instanceof e.MeshStandardMaterial||t instanceof e.MeshPhysicalMaterial?a.push(t.map?t.map.uuid:null,t.normalMap?t.normalMap.uuid:null,t.roughnessMap?t.roughnessMap.uuid:null,t.metalnessMap?t.metalnessMap.uuid:null,t.aoMap?t.aoMap.uuid:null,t.emissiveMap?t.emissiveMap.uuid:null,t.lightMap?t.lightMap.uuid:null,t.alphaMap?t.alphaMap.uuid:null,t.envMap?t.envMap.uuid:null):t instanceof e.MeshLambertMaterial?a.push(t.map?t.map.uuid:null,t.normalMap?t.normalMap.uuid:null,t.aoMap?t.aoMap.uuid:null,t.emissiveMap?t.emissiveMap.uuid:null,t.lightMap?t.lightMap.uuid:null,t.alphaMap?t.alphaMap.uuid:null,t.envMap?t.envMap.uuid:null):t instanceof e.MeshToonMaterial?a.push(t.map?t.map.uuid:null,t.normalMap?t.normalMap.uuid:null,t.aoMap?t.aoMap.uuid:null,t.emissiveMap?t.emissiveMap.uuid:null,t.lightMap?t.lightMap.uuid:null,t.alphaMap?t.alphaMap.uuid:null,t.gradientMap?t.gradientMap.uuid:null):t instanceof e.MeshBasicMaterial?a.push(t.map?t.map.uuid:null,t.aoMap?t.aoMap.uuid:null,t.lightMap?t.lightMap.uuid:null,t.alphaMap?t.alphaMap.uuid:null,t.envMap?t.envMap.uuid:null):t instanceof e.MeshPhongMaterial?a.push(t.map?t.map.uuid:null,t.normalMap?t.normalMap.uuid:null,t.aoMap?t.aoMap.uuid:null,t.emissiveMap?t.emissiveMap.uuid:null,t.lightMap?t.lightMap.uuid:null,t.alphaMap?t.alphaMap.uuid:null,t.envMap?t.envMap.uuid:null):t instanceof e.SpriteMaterial&&a.push(t.map?t.map.uuid:null,t.alphaMap?t.alphaMap.uuid:null,t.sizeAttenuation);return a.join(",")}(t),i=this.mappedMaterialsCache.get(t),n=this.mappedMaterialsSignatures.get(t);if(null!=i&&n===a)return i;if(null!=i){i.dispose();const e=this.cache.get(i);if(null!=e){for(const t of e.values())t.material.dispose(),this.cacheValues.delete(t);this.cache.delete(i)}}const o=function(t){if(t instanceof e.SpriteMaterial){const e=new x;e.color=t.color,e.opacity=t.opacity,e.rotation=t.rotation,e.screenSpaceSize=t.sizeAttenuation?0:1,e.alphaTest=t.alphaTest,t.map&&(e.map=t.map),t.alphaMap&&(e.alphaMap=t.alphaMap);const a=e.build();return a.transparent=t.transparent,a.side=t.side,a.depthTest=t.depthTest,a.depthWrite=t.depthWrite,a}if(t instanceof e.MeshStandardMaterial||t instanceof e.MeshPhysicalMaterial){const e=new V;e.color=t.color,e.opacity=t.opacity,e.roughness=t.roughness,e.metalness=t.metalness,e.vertexColor=t.vertexColors,t.map&&(e.map=s(t.map)),t.normalMap&&(e.normalMap=s(t.normalMap),e.normalScale=t.normalScale),t.roughnessMap&&(e.roughnessMap=s(t.roughnessMap)),t.metalnessMap&&(e.metalnessMap=s(t.metalnessMap)),t.aoMap&&(e.aoMap=s(t.aoMap),e.aoMapIntensity=t.aoMapIntensity),t.emissiveMap&&(e.emissiveMap=s(t.emissiveMap)),t.lightMap&&(e.lightMap=s(t.lightMap),e.lightMapIntensity=t.lightMapIntensity),t.alphaMap&&(e.alphaMap=s(t.alphaMap)),e.emissive=t.emissive,e.emissiveIntensity=t.emissiveIntensity,e.envMap=t.envMap,e.envMapIntensity=t.envMapIntensity,e.alphaTest=t.alphaTest;const a=e.build();return a.transparent=t.transparent,a.side=t.side,a.depthTest=t.depthTest,a.depthWrite=t.depthWrite,a.wireframe=t.wireframe,a}if(t instanceof e.MeshLambertMaterial){const e=new w;e.color=t.color,e.opacity=t.opacity,e.vertexColor=t.vertexColors,t.map&&(e.map=s(t.map)),t.normalMap&&(e.normalMap=s(t.normalMap),e.normalScale=t.normalScale),t.aoMap&&(e.aoMap=s(t.aoMap),e.aoMapIntensity=t.aoMapIntensity),t.emissiveMap&&(e.emissiveMap=s(t.emissiveMap)),t.lightMap&&(e.lightMap=s(t.lightMap),e.lightMapIntensity=t.lightMapIntensity),t.alphaMap&&(e.alphaMap=s(t.alphaMap)),e.emissive=t.emissive,e.emissiveIntensity=t.emissiveIntensity,e.envMap=t.envMap,e.alphaTest=t.alphaTest;const a=e.build();return a.transparent=t.transparent,a.side=t.side,a.depthTest=t.depthTest,a.depthWrite=t.depthWrite,a.wireframe=t.wireframe,a}if(t instanceof e.MeshToonMaterial){const e=new S;e.color=t.color,e.opacity=t.opacity,e.vertexColor=t.vertexColors,t.map&&(e.map=s(t.map)),t.normalMap&&(e.normalMap=s(t.normalMap),e.normalScale=t.normalScale),t.aoMap&&(e.aoMap=s(t.aoMap),e.aoMapIntensity=t.aoMapIntensity),t.emissiveMap&&(e.emissiveMap=s(t.emissiveMap)),t.lightMap&&(e.lightMap=s(t.lightMap),e.lightMapIntensity=t.lightMapIntensity),t.alphaMap&&(e.alphaMap=s(t.alphaMap)),e.emissive=t.emissive,e.emissiveIntensity=t.emissiveIntensity,e.alphaTest=t.alphaTest;const a=e.build();return a.transparent=t.transparent,a.side=t.side,a.depthTest=t.depthTest,a.depthWrite=t.depthWrite,a.wireframe=t.wireframe,a}if(t instanceof e.MeshBasicMaterial||t instanceof e.LineBasicMaterial){const a=new I;a.color=t.color,a.opacity=t.opacity,a.vertexColor=t.vertexColors,t instanceof e.MeshBasicMaterial&&(t.map&&(a.map=s(t.map)),t.aoMap&&(a.aoMap=s(t.aoMap),a.aoMapIntensity=t.aoMapIntensity),t.lightMap&&(a.lightMap=s(t.lightMap),a.lightMapIntensity=t.lightMapIntensity),t.alphaMap&&(a.alphaMap=s(t.alphaMap)),a.envMap=t.envMap),a.alphaTest=t.alphaTest;const i=a.build();return i.transparent=t.transparent,i.side=t.side,i.depthTest=t.depthTest,i.depthWrite=t.depthWrite,i.wireframe=t instanceof e.MeshBasicMaterial&&t.wireframe,i}if(t instanceof e.MeshPhongMaterial){const e=new V;e.color=t.color,e.opacity=t.opacity,e.roughness=Math.max(0,1-t.shininess/100),e.metalness=0,e.vertexColor=t.vertexColors,t.map&&(e.map=s(t.map)),t.normalMap&&(e.normalMap=s(t.normalMap),e.normalScale=t.normalScale),t.aoMap&&(e.aoMap=s(t.aoMap),e.aoMapIntensity=t.aoMapIntensity),t.emissiveMap&&(e.emissiveMap=s(t.emissiveMap)),t.lightMap&&(e.lightMap=s(t.lightMap),e.lightMapIntensity=t.lightMapIntensity),t.alphaMap&&(e.alphaMap=s(t.alphaMap)),e.emissive=t.emissive,e.emissiveIntensity=t.emissiveIntensity,e.envMap=t.envMap,e.alphaTest=t.alphaTest;const a=e.build();return a.transparent=t.transparent,a.side=t.side,a.depthTest=t.depthTest,a.depthWrite=t.depthWrite,a.wireframe=t.wireframe,a}return null}(t);return null==o?null:(o.wireframe=t.wireframe??!1,this.mappedMaterialsCache.set(t,o),this.mappedMaterialsSignatures.set(t,a),t.addEventListener("dispose",()=>{const e=this.mappedMaterialsCache.get(t);if(null!=e){e.dispose(),this.mappedMaterialsCache.delete(t),this.mappedMaterialsSignatures.delete(t);const a=this.cache.get(e);if(null!=a){for(const e of a.values())e.material.dispose(),this.cacheValues.delete(e);this.cache.delete(e)}}}),o)}canResolve(e){return null!=this.resolve(e)}dispose(){for(const[e,t]of this.observedNodeMaterials)e.removeEventListener("dispose",t);this.observedNodeMaterials.clear();for(const e of this.cacheValues)e.material.dispose();this.cacheValues.clear()}syncInheritedWorldEnvironmentSource(e,t){t.inheritsWorldEnvironment&&null!=this.worldEnvironment&&(e.uniforms.envMap.value=this.worldEnvironment.texture,e.uniforms.envMapIntensity.value=this.worldEnvironment.intensity)}getNodeMaterialSignature(e,t){const a=`${createNodeMaterialSignature(e)}|receiveDecals:${!1!==e.userData.receiveDecals}`;return t?`${a}|worldEnvironment:${this.worldEnvironmentRevision}`:a}prepareWorldEnvironment(t){var a,i,n;return null!=t.envMap?(this.worldEnvironmentMaterials.has(t)&&(t.uniforms.envMap={value:t.envMap},t.uniforms.envMapIntensity={value:1},t.uniforms.envMapRotation={value:new e.Matrix3},this.worldEnvironmentMaterials.delete(t)),!1):null==this.worldEnvironment?(this.worldEnvironmentMaterials.has(t)&&(delete t.uniforms.envMap,delete t.uniforms.envMapIntensity,delete t.uniforms.envMapRotation,this.worldEnvironmentMaterials.delete(t)),!1):((a=t.uniforms).envMap??(a.envMap={value:this.worldEnvironment.texture}),t.uniforms.envMap.value=this.worldEnvironment.texture,(i=t.uniforms).envMapIntensity??(i.envMapIntensity={value:this.worldEnvironment.intensity}),t.uniforms.envMapIntensity.value=this.worldEnvironment.intensity,(n=t.uniforms).envMapRotation??(n.envMapRotation={value:new e.Matrix3}),this.worldEnvironmentMaterials.add(t),!0)}observeNodeMaterial(e){if(this.observedNodeMaterials.has(e))return;const t=()=>{e.removeEventListener("dispose",t),this.observedNodeMaterials.delete(e);const a=this.cache.get(e);if(null!=a){for(const e of a.values())e.material.dispose(),this.cacheValues.delete(e);this.cache.delete(e)}const i=this.outlineMaterials.get(e);if(null!=i){const t=this.cache.get(i);if(null!=t){for(const e of t.values())e.material.dispose(),this.cacheValues.delete(e);this.cache.delete(i)}this.failedSignatures.delete(i),O.delete(i),i.dispose(),this.outlineMaterials.delete(e)}this.failedSignatures.delete(e),O.delete(e)};this.observedNodeMaterials.set(e,t),e.addEventListener("dispose",t)}}function j(e,t,a=!1){const i=t.material;i.uniformValuesAutoUpdate=e.uniformValuesAutoUpdate,(a||e.uniformValuesAutoUpdate||t.sourceUniformValuesAutoVersion!==e.uniformValuesAutoVersion)&&(t.compiled.syncLiveUniforms(i.uniforms),P(e,i.uniforms),$(e,i),t.sourceUniformValuesAutoVersion=e.uniformValuesAutoVersion,i.uniformValuesAutoUpdate||(i.uniformValuesNeedsUpdate=!0))}function P(e,t){let a=D.get(t);if(null==a){a=[];for(const e in t){const i=t[e],n=i.value,s=!0===n?.isVector2?2:!0===n?.isVector3?3:!0===n?.isVector4?4:!0===n?.isColor?5:0;a.push({name:e,target:i,copyKind:s})}D.set(t,a)}const i=e.uniforms;for(let e=0;e<a.length;e++){const t=a[e],n=i[t.name];if(null==n)continue;const s=n.value,o=t.target.value;if(s!==o){if(0!==t.copyKind){const e=s,a=o;if((2===t.copyKind?!0===e?.isVector2:3===t.copyKind?!0===e?.isVector3:4===t.copyKind?!0===e?.isVector4:!0===e?.isColor)&&"function"==typeof a?.copy){a.copy(s);continue}}t.target.value=s}}}function $(t,a){const i=t.uniforms.envMapIntensity,n=a.uniforms.envMapIntensity;null!=i&&null!=n&&(n.value=i.value);const s=t.uniforms.envMapRotation?.value,o=a.uniforms.envMapRotation?.value;s instanceof e.Matrix3&&o instanceof e.Matrix3&&o.copy(s)}function z(e,t){for(const a in t.textures){const i=t.textures[a],n=e.uniforms[a]?.value;if(B(n)&&n!==i)return!1}return!0}function B(e){return!0===e?.isTexture}function _(t,a){if(t instanceof e.SpriteMaterial){const i=a;a.uniforms.color&&(a.uniforms.color.value instanceof e.Vector3?a.uniforms.color.value.setFromColor(t.color):a.uniforms.color.value instanceof e.Color&&a.uniforms.color.value.copy(t.color)),a.uniforms.opacity&&(a.uniforms.opacity.value=t.opacity),i.rotation=t.rotation,i.screenSpaceSize=t.sizeAttenuation?0:1}else t instanceof e.MeshStandardMaterial||t instanceof e.MeshPhysicalMaterial?(a.uniforms.color&&(a.uniforms.color.value instanceof e.Vector3?a.uniforms.color.value.setFromColor(t.color):a.uniforms.color.value instanceof e.Color&&a.uniforms.color.value.copy(t.color)),a.uniforms.opacity&&(a.uniforms.opacity.value=t.opacity),a.uniforms.roughness&&(a.uniforms.roughness.value=t.roughness),a.uniforms.metalness&&(a.uniforms.metalness.value=t.metalness),a.uniforms.emissive&&(a.uniforms.emissive.value instanceof e.Vector3?a.uniforms.emissive.value.setFromColor(t.emissive):a.uniforms.emissive.value instanceof e.Color&&a.uniforms.emissive.value.copy(t.emissive)),a.uniforms.emissiveIntensity&&(a.uniforms.emissiveIntensity.value=t.emissiveIntensity),a.uniforms.normalScale&&t.normalScale&&(a.uniforms.normalScale.value=t.normalScale.x),a.uniforms.aoMapIntensity&&(a.uniforms.aoMapIntensity.value=t.aoMapIntensity),a.uniforms.lightMapIntensity&&(a.uniforms.lightMapIntensity.value=t.lightMapIntensity),a.uniforms.envMapIntensity&&(a.uniforms.envMapIntensity.value=t.envMapIntensity)):t instanceof e.MeshLambertMaterial||t instanceof e.MeshToonMaterial?(a.uniforms.color&&(a.uniforms.color.value instanceof e.Vector3?a.uniforms.color.value.setFromColor(t.color):a.uniforms.color.value instanceof e.Color&&a.uniforms.color.value.copy(t.color)),a.uniforms.opacity&&(a.uniforms.opacity.value=t.opacity),a.uniforms.emissive&&(a.uniforms.emissive.value instanceof e.Vector3?a.uniforms.emissive.value.setFromColor(t.emissive):a.uniforms.emissive.value instanceof e.Color&&a.uniforms.emissive.value.copy(t.emissive)),a.uniforms.emissiveIntensity&&(a.uniforms.emissiveIntensity.value=t.emissiveIntensity),a.uniforms.normalScale&&t.normalScale&&(a.uniforms.normalScale.value=t.normalScale.x),a.uniforms.aoMapIntensity&&(a.uniforms.aoMapIntensity.value=t.aoMapIntensity),a.uniforms.lightMapIntensity&&(a.uniforms.lightMapIntensity.value=t.lightMapIntensity)):t instanceof e.MeshBasicMaterial||t instanceof e.LineBasicMaterial?(a.uniforms.color&&(a.uniforms.color.value instanceof e.Vector3?a.uniforms.color.value.setFromColor(t.color):a.uniforms.color.value instanceof e.Color&&a.uniforms.color.value.copy(t.color)),a.uniforms.opacity&&(a.uniforms.opacity.value=t.opacity),t instanceof e.MeshBasicMaterial&&(a.uniforms.aoMapIntensity&&(a.uniforms.aoMapIntensity.value=t.aoMapIntensity),a.uniforms.lightMapIntensity&&(a.uniforms.lightMapIntensity.value=t.lightMapIntensity))):t instanceof e.MeshPhongMaterial&&(a.uniforms.color&&(a.uniforms.color.value instanceof e.Vector3?a.uniforms.color.value.setFromColor(t.color):a.uniforms.color.value instanceof e.Color&&a.uniforms.color.value.copy(t.color)),a.uniforms.opacity&&(a.uniforms.opacity.value=t.opacity),a.uniforms.roughness&&(a.uniforms.roughness.value=Math.max(0,1-t.shininess/100)),a.uniforms.emissive&&(a.uniforms.emissive.value instanceof e.Vector3?a.uniforms.emissive.value.setFromColor(t.emissive):a.uniforms.emissive.value instanceof e.Color&&a.uniforms.emissive.value.copy(t.emissive)),a.uniforms.emissiveIntensity&&(a.uniforms.emissiveIntensity.value=t.emissiveIntensity),a.uniforms.normalScale&&t.normalScale&&(a.uniforms.normalScale.value=t.normalScale.x),a.uniforms.aoMapIntensity&&(a.uniforms.aoMapIntensity.value=t.aoMapIntensity),a.uniforms.lightMapIntensity&&(a.uniforms.lightMapIntensity.value=t.lightMapIntensity))}/*
1
+ import*as e from"three";import{compileNodeWebGpuFullscreen as t,compileNodeShaderMaterialForWebGpu as a,NodeShaderMaterial as n,webGpuRendererBindings as i,textureSampler2d as s,float as o,length as r,max as l,rgba as u,isWgslCompiler as p,isWgslFragmentCompiler as m,sqrt as c,normalize as h,transformed as d,uniformFloat as f,uniforms as M,vec4 as v,Vec3Node as y,toonMaterial as g}from"three-shader-graph";import{StandardShader as V}from"../shader/builtin/standard-shader.js";import{LambertShader as w}from"../shader/builtin/lambert-shader.js";import{ToonShader as S}from"../shader/builtin/toon-shader.js";import{UnlitShader as x}from"../shader/builtin/unlit-shader.js";import{SpriteShader as I}from"../shader/sprite-shader.js";import{elapsedTimeUniformName as T}from"../shader-nodes/time.js";import{depthUniformName as E,farUniformName as b,nearUniformName as C,resolutionUniformName as W,sceneNormalUniformName as U}from"../shader-nodes/depth.js";import{sceneMapUniformName as A}from"../shader-nodes/scene-sample.js";const N={...i,uniformExpressions:{...i.uniformExpressions,ambientLightColor:{type:"vec3",expression:"rendererAmbientLight()"},[T]:{type:"float",expression:"rendererElapsedTime()"},[C]:{type:"float",expression:"rendererCameraNear()"},[b]:{type:"float",expression:"rendererCameraFar()"},[W]:{type:"vec2",expression:"rendererViewportSize()"}},sceneTextures:{[A]:{semantic:"sceneColor",sampleType:"float"},[E]:{semantic:"sceneDepth",sampleType:"depth"}},attributes:{material:{shaderLocation:6,format:"float32x4",defaultValue:[0,0,0,0]},material2:{shaderLocation:7,format:"float32x4",defaultValue:[0,0,0,0]},hole:{shaderLocation:8,format:"float32",defaultValue:[0]},offset:{shaderLocation:9,format:"float32x3",stepMode:"instance",defaultValue:[0,0,0]},velocity:{shaderLocation:10,format:"float32x4",stepMode:"instance",defaultValue:[0,0,0,0]},size:{shaderLocation:11,format:"float32x3",stepMode:"instance",defaultValue:[0,0,0]},rotation:{shaderLocation:12,format:"float32",stepMode:"instance",defaultValue:[0]},particleData:{shaderLocation:13,format:"float32x3",stepMode:"instance",defaultValue:[1,1,0]},particleColor:{shaderLocation:14,format:"float32x4",stepMode:"instance",defaultValue:[1,1,1,1]}}};class k extends y{constructor(e){super(),this.fallback=e}compile(e){if(!p(e))return{out:e.get(this.fallback)};if(m(e))throw new Error("OutlineLocalPositionNode can only be used in the vertex stage");const t=`outline_local_position_${e.variable()}`;return{chunk:`\n#ifdef USE_SKINNING\n let ${t} = rendererSkinPosition(input.position, input.skinIndex, input.skinWeight).xyz;\n#else\n let ${t} = input.position;\n#endif`,out:t}}}class L extends y{constructor(e){super(),this.fallback=e}compile(e){if(!p(e))return{out:e.get(this.fallback)};if(m(e))throw new Error("OutlineLocalNormalNode can only be used in the vertex stage");const t=`outline_local_normal_${e.variable()}`;return{chunk:`\n#ifdef USE_SKINNING\n let ${t} = rendererSkinNormal(input.normal, input.skinIndex, input.skinWeight);\n#else\n let ${t} = input.normal;\n#endif`,out:t}}}export function setMaterialUniformValuesAutoUpdate(e,t){e.uniformValuesAutoUpdate=t}export function markMaterialUniformValuesNeedUpdate(e){const t=e;"uniformValuesNeedsUpdate"in t?t.uniformValuesNeedsUpdate=!0:t.uniformValuesAutoVersion=(t.uniformValuesAutoVersion??0)+1}function R(e){return!1!==e.uniformValuesAutoUpdate}function F(e){return e.uniformValuesAutoVersion??0}export function withThreeDefaultVertexAttributeValues(e){return e.map(e=>"uv1"===e.name&&null==e.defaultValue?{...e,defaultValue:[0,0]}:e)}const D=new WeakMap,O=new WeakMap;export function createNodeMaterialSignature(e){const t=O.get(e);if(null!=t)return t;const a=JSON.stringify({version:e.version,vertexShader:e.vertexShader,fragmentShader:e.fragmentShader,alphaTest:e.alphaTest,alphaToCoverage:e.alphaToCoverage,blending:e.blending,colorWrite:e.colorWrite,depthFunc:e.depthFunc,depthTest:e.depthTest,depthWrite:e.depthWrite,polygonOffset:e.polygonOffset,polygonOffsetFactor:e.polygonOffsetFactor,polygonOffsetUnits:e.polygonOffsetUnits,premultipliedAlpha:e.premultipliedAlpha,side:e.side,stencilWrite:e.stencilWrite,transparent:e.transparent,wireframe:e.wireframe});return O.set(e,a),a}export class NodeMaterialWebGpuResolver{constructor(e,t,a){this.webGpu=e,this.mrtResolver=t,this.environmentTextureResolver=a,this.cache=new WeakMap,this.failedSignatures=new WeakMap,this.mappedMaterialsCache=new WeakMap,this.mappedMaterialsSignatures=new WeakMap,this.observedNodeMaterials=new Map,this.outlineMaterials=new WeakMap,this.worldEnvironmentMaterials=new WeakSet,this.worldEnvironment=null,this.worldEnvironmentTexture=null,this.worldEnvironmentIntensity=0,this.worldEnvironmentRevision=0,this.cacheValues=new Set}setWorldEnvironment(e){const t=e?.texture??null,a=e?.intensity??0;if(this.worldEnvironmentTexture!==t||this.worldEnvironmentIntensity!==a){if(this.worldEnvironmentTexture!==t)this.worldEnvironmentRevision++;else if(null!=e)for(const e of this.cacheValues)e.inheritsWorldEnvironment&&null!=e.material.uniforms.envMapIntensity&&(e.material.uniforms.envMapIntensity.value=a,e.material.uniformValuesNeedsUpdate=!0);this.worldEnvironment=e,this.worldEnvironmentTexture=t,this.worldEnvironmentIntensity=a}}resolve(e,t=void 0){let i,s=!1;if(e instanceof n)i=e,this.observeNodeMaterial(i);else{const t=this.getOrCreateMappedNodeMaterial(e);if(null==t)return;i=t,s=!0}if("outline"===t){if(null==i.outputAlbedo)return;s&&_(e,i),i.userData.outlineParameters=e.userData?.outlineParameters,i=this.getOrCreateOutlineMaterial(i),s=!1}i.visible=e.visible,s&&(i.userData.receiveDecals=e.userData.receiveDecals);const o=t??"default",r=this.cache.get(i),l=r?.get(o);if(s&&null!=l&&l.sourceVersion===e.version&&l.worldEnvironmentRevision===this.worldEnvironmentRevision){const t=R(e),a=F(e);return l.material.uniformValuesAutoUpdate=t,this.syncInheritedWorldEnvironmentSource(i,l),t||l.sourceUniformValuesAutoVersion!==a?(_(e,i),l.compiled.syncLiveUniforms(l.material.uniforms),P(i,l.material.uniforms),$(i,l.material),l.sourceUniformValuesAutoVersion=a,t||(l.material.uniformValuesNeedsUpdate=!0),l.material):l.material}if(!s&&null!=l&&l.sourceVersion===e.version&&l.worldEnvironmentRevision===this.worldEnvironmentRevision&&z(i,l.compiled))return this.syncInheritedWorldEnvironmentSource(i,l),j(i,l),l.material;s&&_(e,i);const u=this.prepareWorldEnvironment(i),p=this.getNodeMaterialSignature(i,u);if(l?.signature===p&&z(i,l.compiled))return s?(l.material.uniformValuesAutoUpdate=R(e),l.compiled.syncLiveUniforms(l.material.uniforms),P(i,l.material.uniforms),$(i,l.material),l.sourceUniformValuesAutoVersion=F(e),l.material.uniformValuesAutoUpdate||(l.material.uniformValuesNeedsUpdate=!0)):j(i,l,!0),l.sourceVersion=e.version,l.worldEnvironmentRevision=this.worldEnvironmentRevision,l.material;try{const n=this.mrtResolver?.(i,t),m=a(i,N,n),c=new this.webGpu.WGSLShaderMaterial({vertexShader:m.vertexShader,fragmentShader:m.fragmentShader,depthVertexShader:m.depthVertexShader,depthFragmentShader:m.depthFragmentShader,pointShadowVertexShader:m.pointShadowVertexShader,pointShadowFragmentShader:m.pointShadowFragmentShader,uniforms:m.uniforms,textures:m.textures,sceneTextures:m.sceneTextures,graphTextures:m.graphTextures,vertexAttributes:withThreeDefaultVertexAttributeValues(m.vertexAttributes),uniformValuesAutoUpdate:s?R(e):i.uniformValuesAutoUpdate,transparent:m.renderState?.transparent,alphaTest:m.renderState?.alphaTest,depthTest:m.renderState?.depthTest,depthWrite:m.renderState?.depthWrite,side:m.renderState?.side,wireframe:i.wireframe});c.uniformValuesAutoUpdate=s?R(e):i.uniformValuesAutoUpdate,function(e,t){if(null==e)return;Object.assign(t,e)}(m.renderState,c),null!=l&&(l.material.dispose(),this.cacheValues.delete(l));const h={signature:p,compiled:m,material:c,inheritsWorldEnvironment:u,sourceVersion:e.version,sourceUniformValuesAutoVersion:s?F(e):i.uniformValuesAutoVersion,worldEnvironmentRevision:this.worldEnvironmentRevision},d=r??new Map;return d.set(o,h),this.cache.set(i,d),this.cacheValues.add(h),P(i,c.uniforms),$(i,c),c}catch(e){let t=this.failedSignatures.get(i);if(null==t&&(t=new Map,this.failedSignatures.set(i,t)),t.get(o)!==p){t.set(o,p);const a=e instanceof Error?e.message:String(e),n=i.name||i.uuid;console.warn(`[Hology WebGPU experiment] Falling back for NodeShaderMaterial "${n}": ${a}`,{material:i,error:e})}return}}getOrCreateOutlineMaterial(t){let a=this.outlineMaterials.get(t);if(null==a){const i=t.nodeMaterialDefinition,s=t.outputAlbedo;if(null==s)throw new Error("Cannot derive an outline material without an albedo output");const p=f("outlineThickness",.003),m=f("outlineDarkening",.65),y=f("outlineAlpha",1),V=new k(d.position.xyz),w=new L(d.normal),S=i.transform?.multiplyVec(v(V,1))??v(V,1),x=M.modelViewMatrix.multiplyVec(S),I=h(M.normalMatrix.multiplyVec(w)),T=c(l(r(x.xyz),o(1e-4))).multiply(.5),E=x.xyz.add(I.multiplyScalar(p.multiply(T))),b=M.projectionMatrix.multiplyVec(x),C=M.projectionMatrix.multiplyVec(v(E,1)),W=(i.position??b).add(C.subtract(b)),U=u(g({color:s.rgb.multiplyScalar(o(1).subtract(m))}),t.outputOpacity.multiply(y));a=new n({color:U,position:W,opacity:t.outputOpacity,discard:i.discard,alphaTest:t.alphaTest,transparent:!0,fog:!1,outputEncoding:i.outputEncoding,uniforms:i.uniforms,uniformNodes:i.uniformNodes}),a.side=e.BackSide,a.depthTest=!0,a.depthWrite=!0,this.outlineMaterials.set(t,a)}const i=t.userData?.outlineParameters;a.uniforms.outlineThickness.value=i?.thickness??.003,a.uniforms.outlineDarkening.value=e.MathUtils.clamp(i?.darkening??.65,0,1),a.uniforms.outlineAlpha.value=e.MathUtils.clamp(i?.alpha??t.opacity,0,1),a.userData.outlineSource=t;for(const e in t.uniforms)null!=a.uniforms[e]&&(a.uniforms[e].value=t.uniforms[e].value);return a}compileFullscreen(e){const a=t({color:e.outputColor,wgslBindings:{...N,uniformExpressions:{},graphTextures:{...N.graphTextures,[U]:{resource:"hologyNormalRoughness",dimension:"2d",sampleType:"float",sampler:"filtering"}}}}),n=a.syncLiveUniforms;return{...a,syncLiveUniforms(t){n(t),P(e,t)}}}getOrCreateMappedNodeMaterial(t){const a=function(t){const a=[t.vertexColors,t.transparent,t.alphaTest,t.side,t.depthTest,t.depthWrite,t.wireframe??!1];t instanceof e.MeshStandardMaterial||t instanceof e.MeshPhysicalMaterial?a.push(t.map?t.map.uuid:null,t.normalMap?t.normalMap.uuid:null,t.roughnessMap?t.roughnessMap.uuid:null,t.metalnessMap?t.metalnessMap.uuid:null,t.aoMap?t.aoMap.uuid:null,t.emissiveMap?t.emissiveMap.uuid:null,t.lightMap?t.lightMap.uuid:null,t.alphaMap?t.alphaMap.uuid:null,t.envMap?t.envMap.uuid:null):t instanceof e.MeshLambertMaterial?a.push(t.map?t.map.uuid:null,t.normalMap?t.normalMap.uuid:null,t.aoMap?t.aoMap.uuid:null,t.emissiveMap?t.emissiveMap.uuid:null,t.lightMap?t.lightMap.uuid:null,t.alphaMap?t.alphaMap.uuid:null,t.envMap?t.envMap.uuid:null):t instanceof e.MeshToonMaterial?a.push(t.map?t.map.uuid:null,t.normalMap?t.normalMap.uuid:null,t.aoMap?t.aoMap.uuid:null,t.emissiveMap?t.emissiveMap.uuid:null,t.lightMap?t.lightMap.uuid:null,t.alphaMap?t.alphaMap.uuid:null,t.gradientMap?t.gradientMap.uuid:null):t instanceof e.MeshBasicMaterial?a.push(t.map?t.map.uuid:null,t.aoMap?t.aoMap.uuid:null,t.lightMap?t.lightMap.uuid:null,t.alphaMap?t.alphaMap.uuid:null,t.envMap?t.envMap.uuid:null):t instanceof e.MeshPhongMaterial?a.push(t.map?t.map.uuid:null,t.normalMap?t.normalMap.uuid:null,t.aoMap?t.aoMap.uuid:null,t.emissiveMap?t.emissiveMap.uuid:null,t.lightMap?t.lightMap.uuid:null,t.alphaMap?t.alphaMap.uuid:null,t.envMap?t.envMap.uuid:null):t instanceof e.SpriteMaterial&&a.push(t.map?t.map.uuid:null,t.alphaMap?t.alphaMap.uuid:null,t.sizeAttenuation);return a.join(",")}(t),n=this.mappedMaterialsCache.get(t),i=this.mappedMaterialsSignatures.get(t);if(null!=n&&i===a)return n;if(null!=n){n.dispose();const e=this.cache.get(n);if(null!=e){for(const t of e.values())t.material.dispose(),this.cacheValues.delete(t);this.cache.delete(n)}}const o=function(t){if(t instanceof e.SpriteMaterial){const e=new I;e.color=t.color,e.opacity=t.opacity,e.rotation=t.rotation,e.screenSpaceSize=t.sizeAttenuation?0:1,e.alphaTest=t.alphaTest,t.map&&(e.map=t.map),t.alphaMap&&(e.alphaMap=t.alphaMap);const a=e.build();return a.transparent=t.transparent,a.side=t.side,a.depthTest=t.depthTest,a.depthWrite=t.depthWrite,a}if(t instanceof e.MeshStandardMaterial||t instanceof e.MeshPhysicalMaterial){const e=new V;e.color=t.color,e.opacity=t.opacity,e.roughness=t.roughness,e.metalness=t.metalness,e.vertexColor=t.vertexColors,t.map&&(e.map=s(t.map)),t.normalMap&&(e.normalMap=s(t.normalMap),e.normalScale=t.normalScale),t.roughnessMap&&(e.roughnessMap=s(t.roughnessMap)),t.metalnessMap&&(e.metalnessMap=s(t.metalnessMap)),t.aoMap&&(e.aoMap=s(t.aoMap),e.aoMapIntensity=t.aoMapIntensity),t.emissiveMap&&(e.emissiveMap=s(t.emissiveMap)),t.lightMap&&(e.lightMap=s(t.lightMap),e.lightMapIntensity=t.lightMapIntensity),t.alphaMap&&(e.alphaMap=s(t.alphaMap)),e.emissive=t.emissive,e.emissiveIntensity=t.emissiveIntensity,e.envMap=t.envMap,e.envMapIntensity=t.envMapIntensity,e.alphaTest=t.alphaTest;const a=e.build();return a.transparent=t.transparent,a.side=t.side,a.depthTest=t.depthTest,a.depthWrite=t.depthWrite,a.wireframe=t.wireframe,a}if(t instanceof e.MeshLambertMaterial){const e=new w;e.color=t.color,e.opacity=t.opacity,e.vertexColor=t.vertexColors,t.map&&(e.map=s(t.map)),t.normalMap&&(e.normalMap=s(t.normalMap),e.normalScale=t.normalScale),t.aoMap&&(e.aoMap=s(t.aoMap),e.aoMapIntensity=t.aoMapIntensity),t.emissiveMap&&(e.emissiveMap=s(t.emissiveMap)),t.lightMap&&(e.lightMap=s(t.lightMap),e.lightMapIntensity=t.lightMapIntensity),t.alphaMap&&(e.alphaMap=s(t.alphaMap)),e.emissive=t.emissive,e.emissiveIntensity=t.emissiveIntensity,e.envMap=t.envMap,e.alphaTest=t.alphaTest;const a=e.build();return a.transparent=t.transparent,a.side=t.side,a.depthTest=t.depthTest,a.depthWrite=t.depthWrite,a.wireframe=t.wireframe,a}if(t instanceof e.MeshToonMaterial){const e=new S;e.color=t.color,e.opacity=t.opacity,e.vertexColor=t.vertexColors,t.map&&(e.map=s(t.map)),t.normalMap&&(e.normalMap=s(t.normalMap),e.normalScale=t.normalScale),t.aoMap&&(e.aoMap=s(t.aoMap),e.aoMapIntensity=t.aoMapIntensity),t.emissiveMap&&(e.emissiveMap=s(t.emissiveMap)),t.lightMap&&(e.lightMap=s(t.lightMap),e.lightMapIntensity=t.lightMapIntensity),t.alphaMap&&(e.alphaMap=s(t.alphaMap)),e.emissive=t.emissive,e.emissiveIntensity=t.emissiveIntensity,e.alphaTest=t.alphaTest;const a=e.build();return a.transparent=t.transparent,a.side=t.side,a.depthTest=t.depthTest,a.depthWrite=t.depthWrite,a.wireframe=t.wireframe,a}if(t instanceof e.MeshBasicMaterial||t instanceof e.LineBasicMaterial){const a=new x;a.color=t.color,a.opacity=t.opacity,a.vertexColor=t.vertexColors,t instanceof e.MeshBasicMaterial&&(t.map&&(a.map=s(t.map)),t.aoMap&&(a.aoMap=s(t.aoMap),a.aoMapIntensity=t.aoMapIntensity),t.lightMap&&(a.lightMap=s(t.lightMap),a.lightMapIntensity=t.lightMapIntensity),t.alphaMap&&(a.alphaMap=s(t.alphaMap)),a.envMap=t.envMap),a.alphaTest=t.alphaTest;const n=a.build();return n.transparent=t.transparent,n.side=t.side,n.depthTest=t.depthTest,n.depthWrite=t.depthWrite,n.wireframe=t instanceof e.MeshBasicMaterial&&t.wireframe,n}if(t instanceof e.MeshPhongMaterial){const e=new V;e.color=t.color,e.opacity=t.opacity,e.roughness=Math.max(0,1-t.shininess/100),e.metalness=0,e.vertexColor=t.vertexColors,t.map&&(e.map=s(t.map)),t.normalMap&&(e.normalMap=s(t.normalMap),e.normalScale=t.normalScale),t.aoMap&&(e.aoMap=s(t.aoMap),e.aoMapIntensity=t.aoMapIntensity),t.emissiveMap&&(e.emissiveMap=s(t.emissiveMap)),t.lightMap&&(e.lightMap=s(t.lightMap),e.lightMapIntensity=t.lightMapIntensity),t.alphaMap&&(e.alphaMap=s(t.alphaMap)),e.emissive=t.emissive,e.emissiveIntensity=t.emissiveIntensity,e.envMap=t.envMap,e.alphaTest=t.alphaTest;const a=e.build();return a.transparent=t.transparent,a.side=t.side,a.depthTest=t.depthTest,a.depthWrite=t.depthWrite,a.wireframe=t.wireframe,a}return null}(t);return null==o?null:(o.wireframe=t.wireframe??!1,this.mappedMaterialsCache.set(t,o),this.mappedMaterialsSignatures.set(t,a),t.addEventListener("dispose",()=>{const e=this.mappedMaterialsCache.get(t);if(null!=e){e.dispose(),this.mappedMaterialsCache.delete(t),this.mappedMaterialsSignatures.delete(t);const a=this.cache.get(e);if(null!=a){for(const e of a.values())e.material.dispose(),this.cacheValues.delete(e);this.cache.delete(e)}}}),o)}canResolve(e){return null!=this.resolve(e)}dispose(){for(const[e,t]of this.observedNodeMaterials)e.removeEventListener("dispose",t);this.observedNodeMaterials.clear();for(const e of this.cacheValues)e.material.dispose();this.cacheValues.clear()}syncInheritedWorldEnvironmentSource(e,t){t.inheritsWorldEnvironment&&null!=this.worldEnvironment&&(e.uniforms.envMap.value=this.worldEnvironment.texture,e.uniforms.envMapIntensity.value=this.worldEnvironment.intensity)}getNodeMaterialSignature(e,t){const a=`${createNodeMaterialSignature(e)}|receiveDecals:${!1!==e.userData.receiveDecals}`;return t?`${a}|worldEnvironment:${this.worldEnvironmentRevision}`:a}prepareWorldEnvironment(t){var a,n,i,s,o,r;if(null!=t.envMap){const s=this.environmentTextureResolver?.(t.envMap)??t.envMap;return(a=t.uniforms).envMap??(a.envMap={value:s}),t.uniforms.envMap.value=s,(n=t.uniforms).envMapIntensity??(n.envMapIntensity={value:1}),(i=t.uniforms).envMapRotation??(i.envMapRotation={value:new e.Matrix3}),this.worldEnvironmentMaterials.delete(t),!1}return null==this.worldEnvironment?(this.worldEnvironmentMaterials.has(t)&&(delete t.uniforms.envMap,delete t.uniforms.envMapIntensity,delete t.uniforms.envMapRotation,this.worldEnvironmentMaterials.delete(t)),!1):((s=t.uniforms).envMap??(s.envMap={value:this.worldEnvironment.texture}),t.uniforms.envMap.value=this.worldEnvironment.texture,(o=t.uniforms).envMapIntensity??(o.envMapIntensity={value:this.worldEnvironment.intensity}),t.uniforms.envMapIntensity.value=this.worldEnvironment.intensity,(r=t.uniforms).envMapRotation??(r.envMapRotation={value:new e.Matrix3}),this.worldEnvironmentMaterials.add(t),!0)}observeNodeMaterial(e){if(this.observedNodeMaterials.has(e))return;const t=()=>{e.removeEventListener("dispose",t),this.observedNodeMaterials.delete(e);const a=this.cache.get(e);if(null!=a){for(const e of a.values())e.material.dispose(),this.cacheValues.delete(e);this.cache.delete(e)}const n=this.outlineMaterials.get(e);if(null!=n){const t=this.cache.get(n);if(null!=t){for(const e of t.values())e.material.dispose(),this.cacheValues.delete(e);this.cache.delete(n)}this.failedSignatures.delete(n),O.delete(n),n.dispose(),this.outlineMaterials.delete(e)}this.failedSignatures.delete(e),O.delete(e)};this.observedNodeMaterials.set(e,t),e.addEventListener("dispose",t)}}function j(e,t,a=!1){const n=t.material;n.uniformValuesAutoUpdate=e.uniformValuesAutoUpdate,(a||e.uniformValuesAutoUpdate||t.sourceUniformValuesAutoVersion!==e.uniformValuesAutoVersion)&&(t.compiled.syncLiveUniforms(n.uniforms),P(e,n.uniforms),$(e,n),t.sourceUniformValuesAutoVersion=e.uniformValuesAutoVersion,n.uniformValuesAutoUpdate||(n.uniformValuesNeedsUpdate=!0))}function P(e,t){let a=D.get(t);if(null==a){a=[];for(const e in t){const n=t[e],i=n.value,s=!0===i?.isVector2?2:!0===i?.isVector3?3:!0===i?.isVector4?4:!0===i?.isColor?5:0;a.push({name:e,target:n,copyKind:s})}D.set(t,a)}const n=e.uniforms;for(let e=0;e<a.length;e++){const t=a[e],i=n[t.name];if(null==i)continue;const s=i.value,o=t.target.value;if(s!==o){if(0!==t.copyKind){const e=s,a=o;if((2===t.copyKind?!0===e?.isVector2:3===t.copyKind?!0===e?.isVector3:4===t.copyKind?!0===e?.isVector4:!0===e?.isColor)&&"function"==typeof a?.copy){a.copy(s);continue}}t.target.value=s}}}function $(t,a){const n=t.uniforms.envMapIntensity,i=a.uniforms.envMapIntensity;null!=n&&null!=i&&(i.value=n.value);const s=t.uniforms.envMapRotation?.value,o=a.uniforms.envMapRotation?.value;s instanceof e.Matrix3&&o instanceof e.Matrix3&&o.copy(s)}function z(e,t){for(const a in t.textures){const n=t.textures[a],i=e.uniforms[a]?.value;if(B(i)&&i!==n)return!1}return!0}function B(e){return!0===e?.isTexture}function _(t,a){if(t instanceof e.SpriteMaterial){const n=a;a.uniforms.color&&(a.uniforms.color.value instanceof e.Vector3?a.uniforms.color.value.setFromColor(t.color):a.uniforms.color.value instanceof e.Color&&a.uniforms.color.value.copy(t.color)),a.uniforms.opacity&&(a.uniforms.opacity.value=t.opacity),n.rotation=t.rotation,n.screenSpaceSize=t.sizeAttenuation?0:1}else t instanceof e.MeshStandardMaterial||t instanceof e.MeshPhysicalMaterial?(a.uniforms.color&&(a.uniforms.color.value instanceof e.Vector3?a.uniforms.color.value.setFromColor(t.color):a.uniforms.color.value instanceof e.Color&&a.uniforms.color.value.copy(t.color)),a.uniforms.opacity&&(a.uniforms.opacity.value=t.opacity),a.uniforms.roughness&&(a.uniforms.roughness.value=t.roughness),a.uniforms.metalness&&(a.uniforms.metalness.value=t.metalness),a.uniforms.emissive&&(a.uniforms.emissive.value instanceof e.Vector3?a.uniforms.emissive.value.setFromColor(t.emissive):a.uniforms.emissive.value instanceof e.Color&&a.uniforms.emissive.value.copy(t.emissive)),a.uniforms.emissiveIntensity&&(a.uniforms.emissiveIntensity.value=t.emissiveIntensity),a.uniforms.normalScale&&t.normalScale&&(a.uniforms.normalScale.value=t.normalScale.x),a.uniforms.aoMapIntensity&&(a.uniforms.aoMapIntensity.value=t.aoMapIntensity),a.uniforms.lightMapIntensity&&(a.uniforms.lightMapIntensity.value=t.lightMapIntensity),a.uniforms.envMapIntensity&&(a.uniforms.envMapIntensity.value=t.envMapIntensity)):t instanceof e.MeshLambertMaterial||t instanceof e.MeshToonMaterial?(a.uniforms.color&&(a.uniforms.color.value instanceof e.Vector3?a.uniforms.color.value.setFromColor(t.color):a.uniforms.color.value instanceof e.Color&&a.uniforms.color.value.copy(t.color)),a.uniforms.opacity&&(a.uniforms.opacity.value=t.opacity),a.uniforms.emissive&&(a.uniforms.emissive.value instanceof e.Vector3?a.uniforms.emissive.value.setFromColor(t.emissive):a.uniforms.emissive.value instanceof e.Color&&a.uniforms.emissive.value.copy(t.emissive)),a.uniforms.emissiveIntensity&&(a.uniforms.emissiveIntensity.value=t.emissiveIntensity),a.uniforms.normalScale&&t.normalScale&&(a.uniforms.normalScale.value=t.normalScale.x),a.uniforms.aoMapIntensity&&(a.uniforms.aoMapIntensity.value=t.aoMapIntensity),a.uniforms.lightMapIntensity&&(a.uniforms.lightMapIntensity.value=t.lightMapIntensity)):t instanceof e.MeshBasicMaterial||t instanceof e.LineBasicMaterial?(a.uniforms.color&&(a.uniforms.color.value instanceof e.Vector3?a.uniforms.color.value.setFromColor(t.color):a.uniforms.color.value instanceof e.Color&&a.uniforms.color.value.copy(t.color)),a.uniforms.opacity&&(a.uniforms.opacity.value=t.opacity),t instanceof e.MeshBasicMaterial&&(a.uniforms.aoMapIntensity&&(a.uniforms.aoMapIntensity.value=t.aoMapIntensity),a.uniforms.lightMapIntensity&&(a.uniforms.lightMapIntensity.value=t.lightMapIntensity))):t instanceof e.MeshPhongMaterial&&(a.uniforms.color&&(a.uniforms.color.value instanceof e.Vector3?a.uniforms.color.value.setFromColor(t.color):a.uniforms.color.value instanceof e.Color&&a.uniforms.color.value.copy(t.color)),a.uniforms.opacity&&(a.uniforms.opacity.value=t.opacity),a.uniforms.roughness&&(a.uniforms.roughness.value=Math.max(0,1-t.shininess/100)),a.uniforms.emissive&&(a.uniforms.emissive.value instanceof e.Vector3?a.uniforms.emissive.value.setFromColor(t.emissive):a.uniforms.emissive.value instanceof e.Color&&a.uniforms.emissive.value.copy(t.emissive)),a.uniforms.emissiveIntensity&&(a.uniforms.emissiveIntensity.value=t.emissiveIntensity),a.uniforms.normalScale&&t.normalScale&&(a.uniforms.normalScale.value=t.normalScale.x),a.uniforms.aoMapIntensity&&(a.uniforms.aoMapIntensity.value=t.aoMapIntensity),a.uniforms.lightMapIntensity&&(a.uniforms.lightMapIntensity.value=t.lightMapIntensity))}/*
2
2
  * Copyright (©) 2026 Hology Interactive AB. All rights reserved.
3
3
  * See the LICENSE.md file for details.
4
4
  */
@@ -31,7 +31,7 @@ export declare function sanitizePostProcessEffectPriority(priority: number | und
31
31
  export interface PostProcessEffectEntry {
32
32
  readonly id: number;
33
33
  readonly material: ShaderMaterial;
34
- pass: PostProcessEffectPass;
34
+ pass: PostProcessEffectPass | null;
35
35
  enabled: boolean;
36
36
  priority: number;
37
37
  stage: PostProcessEffectStage;