@hology/core 0.0.263 → 0.0.265
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/effects/sequence/sequence-player.d.ts +1 -0
- package/dist/effects/sequence/sequence-player.js +1 -1
- package/dist/effects/vfx/gpu-sprite-runtime.js +1 -1
- package/dist/effects/vfx/vfx-actor.js +1 -1
- package/dist/gameplay/ai/behavior-tree/behavior-tree.d.ts +26 -0
- package/dist/gameplay/ai/behavior-tree/behavior-tree.js +4 -0
- package/dist/gameplay/ai/behavior-tree/behavior-tree.test.d.ts +2 -0
- package/dist/gameplay/ai/behavior-tree/behavior-tree.test.js +4 -0
- package/dist/gameplay/ai/behavior-tree/bt.d.ts +83 -70
- package/dist/gameplay/ai/behavior-tree/bt.js +1 -1
- package/dist/gameplay/ai/behavior-tree/bt.test.d.ts +2 -0
- package/dist/gameplay/ai/behavior-tree/bt.test.js +4 -0
- package/dist/gameplay/ai/behavior-tree/move.d.ts +1 -0
- package/dist/gameplay/ai/behavior-tree/move.js +1 -1
- package/dist/gameplay/ai/index.d.ts +1 -0
- package/dist/gameplay/ai/index.js +1 -1
- package/dist/gameplay/services/render.d.ts +3 -0
- package/dist/gameplay/services/render.js +1 -1
- package/dist/rendering/node-material-webgpu-resolver.d.ts +1 -0
- package/dist/rendering/node-material-webgpu-resolver.js +1 -1
- package/dist/rendering/webgpu-experimental-backend.d.ts +1 -0
- package/dist/rendering/webgpu-experimental-backend.js +1 -1
- package/dist/secondary-motion/budget.d.ts +26 -0
- package/dist/secondary-motion/budget.js +4 -0
- package/dist/secondary-motion/cache.d.ts +16 -0
- package/dist/secondary-motion/cache.js +4 -0
- package/dist/secondary-motion/runtime.d.ts +15 -0
- package/dist/secondary-motion/runtime.js +1 -1
- package/dist/secondary-motion/skinned-targets.d.ts +35 -0
- package/dist/secondary-motion/skinned-targets.js +4 -0
- package/dist/test/gpu-sprite-compiler.test.js +1 -1
- package/dist/test/node-material-webgpu-resolver.test.js +1 -1
- package/dist/test/secondary-motion-budget.test.d.ts +2 -0
- package/dist/test/secondary-motion-budget.test.js +4 -0
- package/dist/test/secondary-motion-cache.test.d.ts +2 -0
- package/dist/test/secondary-motion-cache.test.js +4 -0
- package/dist/test/secondary-motion-gpu-check.d.ts +2 -0
- package/dist/test/secondary-motion-gpu-check.js +4 -0
- package/dist/test/sequence-scene-binding.test.js +1 -1
- package/dist/test/vfx-playback-transform.test.d.ts +2 -0
- package/dist/test/vfx-playback-transform.test.js +4 -0
- package/package.json +4 -1
- package/tsconfig.tsbuildinfo +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import*as e from"three";import{compileNodeWebGpuFullscreen as t,compileNodeShaderMaterialForWebGpu as a,NodeShaderMaterial as n,webGpuRendererBindings as i,webGpuTiledRendererBindings as s,textureSampler2d as o,float as r,length as l,max as u,rgba as p,isWgslCompiler as m,isWgslFragmentCompiler as c,sqrt as d,normalize as h,transformed as f,uniformFloat as M,uniforms as v,vec4 as y,Vec3Node as g,toonMaterial as V}from"three-shader-graph";import{StandardShader as w}from"../shader/builtin/standard-shader.js";import{LambertShader as S}from"../shader/builtin/lambert-shader.js";import{ToonShader as x}from"../shader/builtin/toon-shader.js";import{UnlitShader as I}from"../shader/builtin/unlit-shader.js";import{SpriteShader as T}from"../shader/sprite-shader.js";import{elapsedTimeUniformName as E}from"../shader-nodes/time.js";import{depthUniformName as b,farUniformName as C,nearUniformName as W,resolutionUniformName as U,sceneNormalUniformName as A}from"../shader-nodes/depth.js";import{sceneMapUniformName as N}from"../shader-nodes/scene-sample.js";const k={...i,uniformExpressions:{...i.uniformExpressions,ambientLightColor:{type:"vec3",expression:"rendererAmbientLight()"},[E]:{type:"float",expression:"rendererElapsedTime()"},[W]:{type:"float",expression:"rendererCameraNear()"},[C]:{type:"float",expression:"rendererCameraFar()"},[U]:{type:"vec2",expression:"rendererViewportSize()"}},sceneTextures:{[N]:{semantic:"sceneColor",sampleType:"float"},[b]:{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 L extends g{constructor(e){super(),this.fallback=e}compile(e){if(!m(e))return{out:e.get(this.fallback)};if(c(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 R extends g{constructor(e){super(),this.fallback=e}compile(e){if(!m(e))return{out:e.get(this.fallback)};if(c(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 F(e){return!1!==e.uniformValuesAutoUpdate}function D(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 O=new WeakMap,j=new WeakMap;export function createNodeMaterialSignature(e){const t=j.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 j.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,o=!1;if(e instanceof n)i=e,this.observeNodeMaterial(i);else{const t=this.getOrCreateMappedNodeMaterial(e);if(null==t)return;i=t,o=!0}if("outline"===t){if(null==i.outputAlbedo)return;o&&G(e,i),i.userData.outlineParameters=e.userData?.outlineParameters,i=this.getOrCreateOutlineMaterial(i),o=!1}i.visible=e.visible,o&&(i.userData.receiveDecals=e.userData.receiveDecals);const r=t??"default",l=this.cache.get(i),u=l?.get(r);if(o&&null!=u&&u.sourceVersion===e.version&&u.worldEnvironmentRevision===this.worldEnvironmentRevision){const t=F(e),a=D(e);return u.material.uniformValuesAutoUpdate=t,this.syncInheritedWorldEnvironmentSource(i,u),t||u.sourceUniformValuesAutoVersion!==a?(G(e,i),u.compiled.syncLiveUniforms(u.material.uniforms),$(i,u.material.uniforms),z(i,u.material),u.sourceUniformValuesAutoVersion=a,t||(u.material.uniformValuesNeedsUpdate=!0),u.material):u.material}if(!o&&null!=u&&u.sourceVersion===e.version&&u.worldEnvironmentRevision===this.worldEnvironmentRevision&&B(i,u.compiled))return this.syncInheritedWorldEnvironmentSource(i,u),P(i,u),u.material;o&&G(e,i);const p=this.prepareWorldEnvironment(i),m=this.getNodeMaterialSignature(i,p);if(u?.signature===m&&B(i,u.compiled))return o?(u.material.uniformValuesAutoUpdate=F(e),u.compiled.syncLiveUniforms(u.material.uniforms),$(i,u.material.uniforms),z(i,u.material),u.sourceUniformValuesAutoVersion=D(e),u.material.uniformValuesAutoUpdate||(u.material.uniformValuesNeedsUpdate=!0)):P(i,u,!0),u.sourceVersion=e.version,u.worldEnvironmentRevision=this.worldEnvironmentRevision,u.material;try{const n=this.mrtResolver?.(i,t),c=a(i,"opaque"===t?{...k,arrays:s.arrays}:k,n),d=new this.webGpu.WGSLShaderMaterial({vertexShader:c.vertexShader,fragmentShader:c.fragmentShader,depthVertexShader:c.depthVertexShader,depthFragmentShader:c.depthFragmentShader,pointShadowVertexShader:c.pointShadowVertexShader,pointShadowFragmentShader:c.pointShadowFragmentShader,uniforms:c.uniforms,textures:c.textures,sceneTextures:c.sceneTextures,graphTextures:c.graphTextures,vertexAttributes:withThreeDefaultVertexAttributeValues(c.vertexAttributes),uniformValuesAutoUpdate:o?F(e):i.uniformValuesAutoUpdate,transparent:c.renderState?.transparent,alphaTest:c.renderState?.alphaTest,depthTest:c.renderState?.depthTest,depthWrite:c.renderState?.depthWrite,side:c.renderState?.side,wireframe:i.wireframe});d.name=e.name||i.name||e.uuid,d.uniformValuesAutoUpdate=o?F(e):i.uniformValuesAutoUpdate,function(e,t){if(null==e)return;Object.assign(t,e)}(c.renderState,d),null!=u&&(u.material.dispose(),this.cacheValues.delete(u));const h={signature:m,compiled:c,material:d,inheritsWorldEnvironment:p,sourceVersion:e.version,sourceUniformValuesAutoVersion:o?D(e):i.uniformValuesAutoVersion,worldEnvironmentRevision:this.worldEnvironmentRevision},f=l??new Map;return f.set(r,h),this.cache.set(i,f),this.cacheValues.add(h),$(i,d.uniforms),z(i,d),d}catch(e){let t=this.failedSignatures.get(i);if(null==t&&(t=new Map,this.failedSignatures.set(i,t)),t.get(r)!==m){t.set(r,m);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 o=M("outlineThickness",.003),m=M("outlineDarkening",.65),c=M("outlineAlpha",1),g=new L(f.position.xyz),w=new R(f.normal),S=i.transform?.multiplyVec(y(g,1))??y(g,1),x=v.modelViewMatrix.multiplyVec(S),I=h(v.normalMatrix.multiplyVec(w)),T=d(u(l(x.xyz),r(1e-4))).multiply(.5),E=x.xyz.add(I.multiplyScalar(o.multiply(T))),b=v.projectionMatrix.multiplyVec(x),C=v.projectionMatrix.multiplyVec(y(E,1)),W=(i.position??b).add(C.subtract(b)),U=p(V({color:s.rgb.multiplyScalar(r(1).subtract(m))}),t.outputOpacity.multiply(c));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:{...k,uniformExpressions:{},graphTextures:{...k.graphTextures,[A]:{resource:"hologyNormalRoughness",dimension:"2d",sampleType:"float",sampler:"filtering"}}}}),n=a.syncLiveUniforms;return{...a,syncLiveUniforms(t){n(t),$(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 s=function(t){if(t instanceof e.SpriteMaterial){const e=new T;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 w;e.color=t.color,e.opacity=t.opacity,e.roughness=t.roughness,e.metalness=t.metalness,e.vertexColor=t.vertexColors,t.map&&(e.map=o(t.map)),t.normalMap&&(e.normalMap=o(t.normalMap),e.normalScale=t.normalScale),t.roughnessMap&&(e.roughnessMap=o(t.roughnessMap)),t.metalnessMap&&(e.metalnessMap=o(t.metalnessMap)),t.aoMap&&(e.aoMap=o(t.aoMap),e.aoMapIntensity=t.aoMapIntensity),t.emissiveMap&&(e.emissiveMap=o(t.emissiveMap)),t.lightMap&&(e.lightMap=o(t.lightMap),e.lightMapIntensity=t.lightMapIntensity),t.alphaMap&&(e.alphaMap=o(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 S;e.color=t.color,e.opacity=t.opacity,e.vertexColor=t.vertexColors,t.map&&(e.map=o(t.map)),t.normalMap&&(e.normalMap=o(t.normalMap),e.normalScale=t.normalScale),t.aoMap&&(e.aoMap=o(t.aoMap),e.aoMapIntensity=t.aoMapIntensity),t.emissiveMap&&(e.emissiveMap=o(t.emissiveMap)),t.lightMap&&(e.lightMap=o(t.lightMap),e.lightMapIntensity=t.lightMapIntensity),t.alphaMap&&(e.alphaMap=o(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 x;e.color=t.color,e.opacity=t.opacity,e.vertexColor=t.vertexColors,t.map&&(e.map=o(t.map)),t.normalMap&&(e.normalMap=o(t.normalMap),e.normalScale=t.normalScale),t.aoMap&&(e.aoMap=o(t.aoMap),e.aoMapIntensity=t.aoMapIntensity),t.emissiveMap&&(e.emissiveMap=o(t.emissiveMap)),t.lightMap&&(e.lightMap=o(t.lightMap),e.lightMapIntensity=t.lightMapIntensity),t.alphaMap&&(e.alphaMap=o(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=o(t.map)),t.aoMap&&(a.aoMap=o(t.aoMap),a.aoMapIntensity=t.aoMapIntensity),t.lightMap&&(a.lightMap=o(t.lightMap),a.lightMapIntensity=t.lightMapIntensity),t.alphaMap&&(a.alphaMap=o(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 w;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=o(t.map)),t.normalMap&&(e.normalMap=o(t.normalMap),e.normalScale=t.normalScale),t.aoMap&&(e.aoMap=o(t.aoMap),e.aoMapIntensity=t.aoMapIntensity),t.emissiveMap&&(e.emissiveMap=o(t.emissiveMap)),t.lightMap&&(e.lightMap=o(t.lightMap),e.lightMapIntensity=t.lightMapIntensity),t.alphaMap&&(e.alphaMap=o(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==s?null:(s.wireframe=t.wireframe??!1,this.mappedMaterialsCache.set(t,s),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)}}}),s)}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),j.delete(n),n.dispose(),this.outlineMaterials.delete(e)}this.failedSignatures.delete(e),j.delete(e)};this.observedNodeMaterials.set(e,t),e.addEventListener("dispose",t)}}function P(e,t,a=!1){const n=t.material;n.uniformValuesAutoUpdate=e.uniformValuesAutoUpdate,(a||e.uniformValuesAutoUpdate||t.sourceUniformValuesAutoVersion!==e.uniformValuesAutoVersion)&&(t.compiled.syncLiveUniforms(n.uniforms),$(e,n.uniforms),z(e,n),t.sourceUniformValuesAutoVersion=e.uniformValuesAutoVersion,n.uniformValuesAutoUpdate||(n.uniformValuesNeedsUpdate=!0))}function $(e,t){let a=O.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})}O.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 z(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 B(e,t){for(const a in t.textures){const n=t.textures[a],i=e.uniforms[a]?.value;if(_(i)&&i!==n)return!1}return!0}function _(e){return!0===e?.isTexture}function G(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))}/*
|
|
1
|
+
import*as e from"three";import{compileNodeWebGpuFullscreen as t,compileNodeShaderMaterialForWebGpu as a,NodeShaderMaterial as n,webGpuRendererBindings as i,webGpuTiledRendererBindings as s,textureSampler2d as o,float as r,length as l,max as u,rgba as p,isWgslCompiler as m,isWgslFragmentCompiler as c,sqrt as f,normalize as d,transformed as h,uniformFloat as M,uniforms as v,vec4 as y,Vec3Node as g,toonMaterial as V}from"three-shader-graph";import{StandardShader as w}from"../shader/builtin/standard-shader.js";import{LambertShader as S}from"../shader/builtin/lambert-shader.js";import{ToonShader as x}from"../shader/builtin/toon-shader.js";import{UnlitShader as I}from"../shader/builtin/unlit-shader.js";import{SpriteShader as T}from"../shader/sprite-shader.js";import{elapsedTimeUniformName as E}from"../shader-nodes/time.js";import{depthUniformName as b,farUniformName as U,nearUniformName as A,resolutionUniformName as C,sceneNormalUniformName as W}from"../shader-nodes/depth.js";import{sceneMapUniformName as N}from"../shader-nodes/scene-sample.js";const k={...i,uniformExpressions:{...i.uniformExpressions,ambientLightColor:{type:"vec3",expression:"rendererAmbientLight()"},[E]:{type:"float",expression:"rendererElapsedTime()"},[A]:{type:"float",expression:"rendererCameraNear()"},[U]:{type:"float",expression:"rendererCameraFar()"},[C]:{type:"vec2",expression:"rendererViewportSize()"}},sceneTextures:{[N]:{semantic:"sceneColor",sampleType:"float"},[b]:{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 L extends g{constructor(e){super(),this.fallback=e}compile(e){if(!m(e))return{out:e.get(this.fallback)};if(c(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 R extends g{constructor(e){super(),this.fallback=e}compile(e){if(!m(e))return{out:e.get(this.fallback)};if(c(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 D(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 O=new WeakMap,j=new WeakMap;export function createNodeMaterialSignature(e){const t=j.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 j.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.outlineUniformVersions=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,o=!1;if(e instanceof n)i=e,this.observeNodeMaterial(i);else{const t=this.getOrCreateMappedNodeMaterial(e);if(null==t)return;i=t,o=!0}if("outline"===t){if(null==i.outputAlbedo)return;o&&G(e,i),i.userData.outlineParameters=e.userData?.outlineParameters,i=this.getOrCreateOutlineMaterial(i),o=!1}i.visible=e.visible,o&&(i.userData.receiveDecals=e.userData.receiveDecals);const r=t??"default",l=this.cache.get(i),u=l?.get(r);if(o&&null!=u&&u.sourceVersion===e.version&&u.worldEnvironmentRevision===this.worldEnvironmentRevision){const t=D(e),a=F(e);return u.material.uniformValuesAutoUpdate=t,this.syncInheritedWorldEnvironmentSource(i,u),t||u.sourceUniformValuesAutoVersion!==a?(G(e,i),u.compiled.syncLiveUniforms(u.material.uniforms),$(i,u.material.uniforms),z(i,u.material),u.sourceUniformValuesAutoVersion=a,t||(u.material.uniformValuesNeedsUpdate=!0),u.material):u.material}if(!o&&null!=u&&u.sourceVersion===e.version&&u.worldEnvironmentRevision===this.worldEnvironmentRevision&&B(i,u.compiled))return this.syncInheritedWorldEnvironmentSource(i,u),P(i,u),u.material;o&&G(e,i);const p=this.prepareWorldEnvironment(i),m=this.getNodeMaterialSignature(i,p);if(u?.signature===m&&B(i,u.compiled))return o?(u.material.uniformValuesAutoUpdate=D(e),u.compiled.syncLiveUniforms(u.material.uniforms),$(i,u.material.uniforms),z(i,u.material),u.sourceUniformValuesAutoVersion=F(e),u.material.uniformValuesAutoUpdate||(u.material.uniformValuesNeedsUpdate=!0)):P(i,u,!0),u.sourceVersion=e.version,u.worldEnvironmentRevision=this.worldEnvironmentRevision,u.material;try{const n=this.mrtResolver?.(i,t),c=a(i,"opaque"===t?{...k,arrays:s.arrays}:k,n),f=new this.webGpu.WGSLShaderMaterial({vertexShader:c.vertexShader,fragmentShader:c.fragmentShader,depthVertexShader:c.depthVertexShader,depthFragmentShader:c.depthFragmentShader,pointShadowVertexShader:c.pointShadowVertexShader,pointShadowFragmentShader:c.pointShadowFragmentShader,uniforms:c.uniforms,textures:c.textures,sceneTextures:c.sceneTextures,graphTextures:c.graphTextures,vertexAttributes:withThreeDefaultVertexAttributeValues(c.vertexAttributes),uniformValuesAutoUpdate:o?D(e):i.uniformValuesAutoUpdate,transparent:c.renderState?.transparent,alphaTest:c.renderState?.alphaTest,depthTest:c.renderState?.depthTest,depthWrite:c.renderState?.depthWrite,side:c.renderState?.side,wireframe:i.wireframe});f.name=e.name||i.name||e.uuid,f.uniformValuesAutoUpdate=o?D(e):i.uniformValuesAutoUpdate,function(e,t){if(null==e)return;Object.assign(t,e)}(c.renderState,f),null!=u&&(u.material.dispose(),this.cacheValues.delete(u));const d={signature:m,compiled:c,material:f,inheritsWorldEnvironment:p,sourceVersion:e.version,sourceUniformValuesAutoVersion:o?F(e):i.uniformValuesAutoVersion,worldEnvironmentRevision:this.worldEnvironmentRevision},h=l??new Map;return h.set(r,d),this.cache.set(i,h),this.cacheValues.add(d),$(i,f.uniforms),z(i,f),f}catch(e){let t=this.failedSignatures.get(i);if(null==t&&(t=new Map,this.failedSignatures.set(i,t)),t.get(r)!==m){t.set(r,m);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 o=M("outlineThickness",.003),m=M("outlineDarkening",.65),c=M("outlineAlpha",1),g=new L(h.position.xyz),w=new R(h.normal),S=i.transform?.multiplyVec(y(g,1))??y(g,1),x=v.modelViewMatrix.multiplyVec(S),I=d(v.normalMatrix.multiplyVec(w)),T=f(u(l(x.xyz),r(1e-4))).multiply(.5),E=x.xyz.add(I.multiplyScalar(o.multiply(T))),b=v.projectionMatrix.multiplyVec(x),U=v.projectionMatrix.multiplyVec(y(E,1)),A=(i.position??b).add(U.subtract(b)),C=p(V({color:s.rgb.multiplyScalar(r(1).subtract(m))}),t.outputOpacity.multiply(c));a=new n({color:C,position:A,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),this.outlineUniformVersions.delete(t)}const i=t.userData?.outlineParameters,s=i?.thickness??.003,o=e.MathUtils.clamp(i?.darkening??.65,0,1),m=e.MathUtils.clamp(i?.alpha??t.opacity,0,1),c=a.uniforms.outlineThickness.value!==s||a.uniforms.outlineDarkening.value!==o||a.uniforms.outlineAlpha.value!==m;a.uniforms.outlineThickness.value=s,a.uniforms.outlineDarkening.value=o,a.uniforms.outlineAlpha.value=m,a.userData.outlineSource=t,a.uniformValuesAutoUpdate=t.uniformValuesAutoUpdate;let g=this.outlineUniformVersions.get(t);const w=t.uniformValuesAutoUpdate||null==g||g.version!==t.uniformValuesAutoVersion||g.uniforms!==t.uniforms;if(w){for(const e in t.uniforms)null!=a.uniforms[e]&&(a.uniforms[e].value=t.uniforms[e].value);g?(g.version=t.uniformValuesAutoVersion,g.uniforms=t.uniforms):(g={version:t.uniformValuesAutoVersion,uniforms:t.uniforms},this.outlineUniformVersions.set(t,g))}return t.uniformValuesAutoUpdate||!c&&!w||(a.uniformValuesNeedsUpdate=!0),a}compileFullscreen(e){const a=t({color:e.outputColor,wgslBindings:{...k,uniformExpressions:{},graphTextures:{...k.graphTextures,[W]:{resource:"hologyNormalRoughness",dimension:"2d",sampleType:"float",sampler:"filtering"}}}}),n=a.syncLiveUniforms;return{...a,syncLiveUniforms(t){n(t),$(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 s=function(t){if(t instanceof e.SpriteMaterial){const e=new T;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 w;e.color=t.color,e.opacity=t.opacity,e.roughness=t.roughness,e.metalness=t.metalness,e.vertexColor=t.vertexColors,t.map&&(e.map=o(t.map)),t.normalMap&&(e.normalMap=o(t.normalMap),e.normalScale=t.normalScale),t.roughnessMap&&(e.roughnessMap=o(t.roughnessMap)),t.metalnessMap&&(e.metalnessMap=o(t.metalnessMap)),t.aoMap&&(e.aoMap=o(t.aoMap),e.aoMapIntensity=t.aoMapIntensity),t.emissiveMap&&(e.emissiveMap=o(t.emissiveMap)),t.lightMap&&(e.lightMap=o(t.lightMap),e.lightMapIntensity=t.lightMapIntensity),t.alphaMap&&(e.alphaMap=o(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 S;e.color=t.color,e.opacity=t.opacity,e.vertexColor=t.vertexColors,t.map&&(e.map=o(t.map)),t.normalMap&&(e.normalMap=o(t.normalMap),e.normalScale=t.normalScale),t.aoMap&&(e.aoMap=o(t.aoMap),e.aoMapIntensity=t.aoMapIntensity),t.emissiveMap&&(e.emissiveMap=o(t.emissiveMap)),t.lightMap&&(e.lightMap=o(t.lightMap),e.lightMapIntensity=t.lightMapIntensity),t.alphaMap&&(e.alphaMap=o(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 x;e.color=t.color,e.opacity=t.opacity,e.vertexColor=t.vertexColors,t.map&&(e.map=o(t.map)),t.normalMap&&(e.normalMap=o(t.normalMap),e.normalScale=t.normalScale),t.aoMap&&(e.aoMap=o(t.aoMap),e.aoMapIntensity=t.aoMapIntensity),t.emissiveMap&&(e.emissiveMap=o(t.emissiveMap)),t.lightMap&&(e.lightMap=o(t.lightMap),e.lightMapIntensity=t.lightMapIntensity),t.alphaMap&&(e.alphaMap=o(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=o(t.map)),t.aoMap&&(a.aoMap=o(t.aoMap),a.aoMapIntensity=t.aoMapIntensity),t.lightMap&&(a.lightMap=o(t.lightMap),a.lightMapIntensity=t.lightMapIntensity),t.alphaMap&&(a.alphaMap=o(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 w;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=o(t.map)),t.normalMap&&(e.normalMap=o(t.normalMap),e.normalScale=t.normalScale),t.aoMap&&(e.aoMap=o(t.aoMap),e.aoMapIntensity=t.aoMapIntensity),t.emissiveMap&&(e.emissiveMap=o(t.emissiveMap)),t.lightMap&&(e.lightMap=o(t.lightMap),e.lightMapIntensity=t.lightMapIntensity),t.alphaMap&&(e.alphaMap=o(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==s?null:(s.wireframe=t.wireframe??!1,this.mappedMaterialsCache.set(t,s),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)}}}),s)}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),j.delete(n),n.dispose(),this.outlineMaterials.delete(e),this.outlineUniformVersions.delete(e)}this.failedSignatures.delete(e),j.delete(e)};this.observedNodeMaterials.set(e,t),e.addEventListener("dispose",t)}}function P(e,t,a=!1){const n=t.material;n.uniformValuesAutoUpdate=e.uniformValuesAutoUpdate,(a||e.uniformValuesAutoUpdate||t.sourceUniformValuesAutoVersion!==e.uniformValuesAutoVersion)&&(t.compiled.syncLiveUniforms(n.uniforms),$(e,n.uniforms),z(e,n),t.sourceUniformValuesAutoVersion=e.uniformValuesAutoVersion,n.uniformValuesAutoUpdate||(n.uniformValuesNeedsUpdate=!0))}function $(e,t){let a=O.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})}O.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 z(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 B(e,t){for(const a in t.textures){const n=t.textures[a],i=e.uniforms[a]?.value;if(_(i)&&i!==n)return!1}return!0}function _(e){return!0===e?.isTexture}function G(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
|
*/
|
|
@@ -118,6 +118,7 @@ export declare class ExperimentalWebGpuBackend implements RenderingBackendDriver
|
|
|
118
118
|
private readonly pmremResults;
|
|
119
119
|
private readonly ownedPmremResults;
|
|
120
120
|
private readonly warnedUnsupportedPostProcessStages;
|
|
121
|
+
private secondaryMotionPrepared;
|
|
121
122
|
private constructor();
|
|
122
123
|
static probeAvailability(): Promise<{
|
|
123
124
|
available: true;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import*as e from"three";import{NodeMaterialWebGpuResolver as t}from"./node-material-webgpu-resolver.js";import{configureWebGpuRuntimeBindings as i}from"./webgpu-runtime-bridge.js";import{float as n,varyingTransformed as r,vec4 as o}from"three-shader-graph";import{NodeShaderMaterial as s}from"../shader-nodes/index.js";import{sceneMapUniformName as a}from"../shader-nodes/scene-sample.js";import{depthUniformName as l}from"../shader-nodes/depth.js";import{MATERIAL_FLAG_ALPHA_TEST as d,MATERIAL_FLAG_RECEIVE_DECALS as c}from"../shader-nodes/material-flags.js";import{createMotionVectorOutput as h}from"./motion-vector-node.js";export class ExperimentalWebGpuBackend{constructor(e,t,i,n,r,o,s,a,l,d,c,h,u,p,m,g,f,v,S,b,x,P){this.renderer=e,this.fallbackMaterial=t,this.nodeMaterialResolver=i,this.gBufferFallbackSource=n,this.bloom=r,this.fxaa=o,this.smaa=s,this.gtao=a,this.ssr=l,this.taa=d,this.motionBlur=c,this.volumetricFog=h,this.colorGrading=u,this.depthOfField=p,this.outline=m,this.postProcessEffects=g,this.renderGraphExtensions=f,this.presentationExtensions=v,this.antiAliasingState=S,this.directionalShadowState=b,this.nativeDlss=x,this.kind="webgpu",this.renderScale=1,this.pmremGenerator=null,this.pmremResults=new WeakMap,this.ownedPmremResults=new Set,this.warnedUnsupportedPostProcessStages=new Set,this.canvas=P}static async probeAvailability(){if("undefined"==typeof navigator||!("gpu"in navigator))return{available:!1,reason:"The runtime does not expose navigator.gpu."};try{const e=await navigator.gpu.requestAdapter({powerPreference:"high-performance"});return null==e?{available:!1,reason:"No WebGPU adapter is available."}:{available:!0,adapter:e}}catch(e){return{available:!1,reason:`Requesting a WebGPU adapter failed: ${e instanceof Error?e.message:String(e)}`}}}static async create(m={},g){const f=await import("@hology/webgpu-renderer");i({createComputeKernel:(e,t)=>new f.ComputeKernel(e,t),buildParticleLightingShaderHeader:f.buildParticleLightingShaderHeader});const v=document.createElement("canvas");v.dataset.hologyRenderer="webgpu-experimental";const S=new f.WGSLShaderMaterial({vertexShader:u,fragmentShader:p}),b=!1!==m.nativeUpscaling&&"dlss"===m.nativeUpscaling?.method,x=b?(await import("./native-dlss-upscaler.js")).createNativeDlssUpscaler(m.nativeUpscaling?.mode??"quality"):null,P=null!=x;S.side=f.DoubleSide;const w=f,y=null!=m.motionBlur&&!1!==m.motionBlur,E=!1!==m.gtao&&(null==m.gtao||!1!==m.gtao.temporal),F=!1!==m.volumetricFog&&(null==m.volumetricFog||!1!==m.volumetricFog.temporal),M=P?"off":b?"taa":null!=(L=m).antiAliasing?L.antiAliasing:null!=L.taa&&!1!==L.taa?"taa":null!=L.smaa&&!1!==L.smaa?"smaa":null!=L.fxaa&&!1!==L.fxaa?"fxaa":!1===L.taa?"off":"taa";var L;const C=null!=m.antiAliasing,D=y||E||F||(C||"taa"===M)||P;let O=null;const G=new t(w,(e,t)=>"opaque"===t?[e.outputColor.xyz.rgba(n(e.alphaTest>0?d:0).add(!1===e.userData.receiveDecals?0:c)),o((e.outputNormal??r.normal).multiplyScalar(.5).addScalar(.5),e.outputRoughness??n(1)),...D?[h(e)]:[]]:void 0,e=>O?.getEnvironmentTexture(e)??e),R=new e.MeshStandardMaterial({color:8688803,roughness:1});if(null==G.resolve(R,"opaque"))throw S.dispose(),R.dispose(),new Error("Failed to compile the WebGPU G-buffer fallback material.");const T=!1===m.gtao?null:new f.GTAOEffect({normalSpace:"view",...f.GTAO_PRESETS.high,...m.gtao??{}}),A=!1===m.ssr||null==m.ssr?null:new f.SSREffect({normalSpace:"view",resolutionScale:.5,...m.ssr??{}}),B=!1===m.bloom?null:new f.BloomEffect({threshold:1,strength:.9,radius:.2,...m.bloom??{}}),W=C||!1!==m.fxaa&&"fxaa"===M?new f.FXAAEffect(!1===m.fxaa?{}:m.fxaa):null,V=C||!1!==m.smaa&&"smaa"===M?new f.SMAAEffect(!1===m.smaa?{}:m.smaa):null,k=P||C||!1!==m.taa&&"taa"===M?new f.TemporalAAEffect({renderScale:1,...!1===m.taa?{}:m.taa}):null,U={mode:M},I=!1===m.motionBlur||null==m.motionBlur?null:new f.MotionBlurEffect(m.motionBlur),j=m.volumetricFog||void 0,N=!1===m.volumetricFog?null:new f.VolumetricFogEffect(void 0,{...f.VOLUMETRIC_FOG_PRESETS.high,maxDistance:64,spatialJitter:!0,scatteringIntensity:Math.PI,...j,temporal:!1!==j?.temporal&&{...f.VOLUMETRIC_FOG_PRESETS.high.temporal,...j?.temporal},blur:!1!==j?.blur&&{...!1===f.VOLUMETRIC_FOG_PRESETS.high.blur?{}:f.VOLUMETRIC_FOG_PRESETS.high.blur,depthAwareUpsample:!0,...j?.blur}}),H=!1===m.colorGrading?null:new f.ColorGradingEffect({enabled:!1,...m.colorGrading??{}}),$=!1===m.depthOfField?null:new f.DepthOfFieldEffect({enabled:!1,...m.depthOfField??{}}),_=!1===m.outline?null:new f.OutlineEffect({enabled:!1,...m.outline??{}}),q=[],z=new WeakMap,J=new Set,K=[],Z=[],Q=(e,t,i)=>{let n=i;const r=q.filter(e=>e.enabled&&e.stage===t).sort((e,t)=>e.priority-t.priority||e.id-t.id);for(const t of r){if(!(t.material instanceof s)){const e=`${t.id}:material`;J.has(e)||(J.add(e),console.warn(`[Hology WebGPU experiment] Skipping custom post-process effect ${t.id}: only NodeShaderMaterial effects are supported.`));continue}try{let i=z.get(t.material);null!=i&&i.version===t.material.version||(i={version:t.material.version,shader:G.compileFullscreen(t.material)},z.set(t.material,i));const r=e.createColorTarget(`hologyCustomPostProcess${t.id}`);e.addNodeFullscreenPass({name:`HologyCustomPostProcess${t.id}`,shader:i.shader,inputOverrides:{[a]:n},outputs:r}),n=r}catch(e){const i=`${t.id}:compile:${t.material.version}`;J.has(i)||(J.add(i),console.warn(`[Hology WebGPU experiment] Skipping custom post-process effect ${t.id}: ${e instanceof Error?e.message:String(e)}`,e))}}return n},X={enabled:!0},Y=new f.WebGpuRenderer({canvas:v,fallbackMaterial:S,materialResolver:(e,t)=>G.resolve(e,t),invokeObjectRenderCallbacks:!1,hiZOcclusionCulling:!0,renderGraphProfiling:!1,sampleCount:1,multiDrawIndirect:!1,nativePostSubmit:x?.postSubmit,presentationOverlay:e=>{for(const t of Z)t(e)}});Y.setRenderScale("taa"===M?k?.renderScale??1:1),Y.setRenderGraphBuilder((e,t)=>{const i=new f.FrameGraphBuilder(t),n=i.createColorTarget("hologyNormalRoughness",{format:"rgba8unorm"}),r=D?i.createColorTarget("hologyMotionVectors",{format:"rgba16float"}):null;for(const e of K)"beforeScene"===e.stage&&e(i,i.sceneColor);X.enabled&&i.addDirectionalShadowPass(),i.addPointShadowPass(),i.addSpotShadowPass(),i.addDepthPrepass(),i.addHiZPasses(),i.addVisibilityPass(),i.addMaterialPass({name:"OpaqueGBufferPass",outputs:null==r?[i.sceneColor,n]:[i.sceneColor,n,r],drawStage:"opaque",loadDepth:!0}),i.addHiZHistoryPass("OpaqueGBufferPass");let o=i.sceneColor;if(T?.enabled){const e=T.addPasses(i,{depth:i.mainDepth,normal:n,velocity:r??void 0});o=T.addCompositePass(i,o,e)}null!=A&&(o=A.addPasses(i,{sceneColor:o,depth:i.mainDepth,normalRoughness:n}));const s=new Set(K.flatMap(e=>e.getSceneTextureReads?.()??[]));i.addSceneTextureCopyPass(o,{sceneColor:s.has("sceneColorSnapshot"),sceneDepth:s.has("sceneDepthSnapshot")||q.some(e=>e.enabled&&null!=e.material.uniforms[l])}),o=Q(i,"beforeFog",o),i.addLatePass(o);for(const e of K)null!=e.stage&&"afterScene"!==e.stage||e(i,o);null!=N&&(o=N.addPasses(i,{sceneColor:o,depth:i.mainDepth,velocity:r??void 0,volumeObjects:t.fogVolumeObjects,lights:t.extractedLights})),null!=I&&null!=r&&(o=I.addPass(i,o,r,i.mainDepth)),null!=B&&(o=B.addPass(i,o)),o=Q(i,"beforeOutline",o),null!=_&&(o=_.addPass(i,o)),o=Q(i,"beforeDepthOfField",o),null!=$&&(o=$.addPass(i,o,i.mainDepth)),o=Q(i,"beforeColorAdjustment",o),null!=H&&(o=H.addPass(i,o)),o=Q(i,"beforeAntiAliasing",o);let a="taa"===U.mode&&null!=k?k.addPass(i,o,i.mainDepth,r??void 0):o;"smaa"===U.mode&&null!=V?a=V.addPass(i,a):"fxaa"===U.mode&&null!=W&&(a=W.addPass(i,a)),a=Q(i,"beforeOutput",a);for(const e of K)"beforePresent"===e.stage&&e(i,a);!0===x?.enabled&&null!=r?x.addInputPass(i,a,r):i.present(a)});try{return await Y.initialize(g),O=new ExperimentalWebGpuBackend(Y,S,G,R,B,W,V,T,A,k,I,N,H,$,_,q,K,Z,U,X,x,v),O}catch(e){throw Y.destroy(),S.dispose(),G.dispose(),R.dispose(),T?.dispose(),V?.dispose(),I?.dispose(),N?.dispose(),_?.dispose(),e}}static supportsCamera(t){return t instanceof e.PerspectiveCamera||t instanceof e.OrthographicCamera}setSize(e,t,i,n=1){const r=this.canvas.width,o=this.canvas.height;let s=Math.min(1,Math.max(.25,n));if(!0===this.nativeDlss?.enabled){const n=Math.max(1,Math.floor(e*i)),r=Math.max(1,Math.floor(t*i));s=this.nativeDlss.getRenderScale(n,r)}const a=s!==this.renderScale;this.renderScale=s,this.renderer.setRenderScale(s),this.taa?.setRenderScale(s),this.renderer.setSize(e,t,i),(a||this.canvas.width!==r||this.canvas.height!==o)&&this.resetViewHistory()}initTexture(e){this.renderer.initTexture(e)}setPostProcessEffects(e){this.postProcessEffects.splice(0,this.postProcessEffects.length,...e);for(const t of e){if("beforeLut"!==t.stage)continue;const e=`${t.id}:${t.stage}`;this.warnedUnsupportedPostProcessStages.has(e)||(this.warnedUnsupportedPostProcessStages.add(e),console.warn(`[Hology WebGPU experiment] Skipping custom post-process effect ${t.id}: stage "${t.stage}" has no native WebGPU anchor.`))}}getDevice(){return this.renderer.getDevice()}setRenderGraphExtensions(e){this.renderGraphExtensions.length=0;for(const t of e)this.renderGraphExtensions.push(t)}setPresentationExtensions(e){this.presentationExtensions.length=0;for(const t of e)this.presentationExtensions.push(t)}setEnableOutlines(e){null!=this.outline&&(this.outline.enabled=e)}setTiledLightingEnabled(e){this.renderer.setTiledLightingEnabled(e)}setDynamicBatchingEnabled(e){this.renderer.setDynamicBatchingEnabled(e)}setSelectedObjects(e){this.outline?.setSelectedObjects(e)}setSelectedObjectInstances(e){this.outline?.setSelectedInstances(e)}setCascadedShadowRanges(e,t=[]){this.renderer.setCascadedShadowRanges(e,t),this.volumetricFog?.setCascadedDirectionalLights(t)}setDirectionalShadowOptions(e,t){this.directionalShadowState.enabled=e,this.renderer.setDirectionalShadowsEnabled(e),this.renderer.setDirectionalShadowMapSize(t)}setWorldEnvironment(e){if(null==e)return void this.nodeMaterialResolver.setWorldEnvironment(null);const t=this.getEnvironmentTexture(e.source);this.nodeMaterialResolver.setWorldEnvironment({texture:t,intensity:e.intensity})}getEnvironmentTexture(t){if(t.mapping===e.CubeUVReflectionMapping)return t;let i=this.pmremResults.get(t);return null==i&&(this.pmremGenerator??(this.pmremGenerator=this.renderer.createPMREMGenerator()),i=this.pmremGenerator.fromEquirectangular(t),this.pmremResults.set(t,i),this.ownedPmremResults.add(i)),i.texture}resetViewHistory(){this.renderer.resetViewHistory(),this.taa?.reset(),this.motionBlur?.reset(),this.gtao?.reset(),this.volumetricFog?.reset(),this.nativeDlss?.reset()}async compile(e,t){await this.renderer.compileAsync(e,t)}createStaticDrawSet(e,t,i=!1){this.renderer.setHiZOcclusionCullingEnabled(!0);const n=this.renderer.createStaticDrawSet(e,{label:t,onUnsupported:"skip",allowUnsortedLateDraws:i});return 0===n.drawCount?(n.dispose(),null):n}render(e,t,i){const n="taa"===this.antiAliasingState.mode?this.taa:null;this.volumetricFog?.setScene(e),this.renderer.setMotionVectorProjection(t.projectionMatrix),this.motionBlur?.prepareCamera(t,this.canvas.width,this.canvas.height,i),this.motionBlur?.requiresRendererHistoryReset()&&(this.renderer.resetViewHistory(),this.gtao?.reset(),this.volumetricFog?.reset()),n?.prepareCamera(t,this.canvas.width,this.canvas.height),this.nativeDlss?.prepareFrame(t);const r=!0===this.nativeDlss?.enabled?this.nativeDlss.jitter:null;this.motionBlur?.setJitterUv(n?.currentJitterUv.x??(null==r?0:r.x/Math.max(1,this.canvas.width*this.renderScale)),n?.currentJitterUv.y??(null==r?0:-r.y/Math.max(1,this.canvas.height*this.renderScale))),null!=r&&this.renderer.setProjectionJitter(r.x,r.y);let o=!1;try{this.renderer.render(e,t,i),o=!0}finally{null!=r&&this.renderer.clearProjectionJitter(),n?.finishCamera(t),o&&this.motionBlur?.commitCamera(),o&&this.nativeDlss?.finishFrame(t)}}setMotionBlurOptions(e){null!=this.motionBlur&&Object.assign(this.motionBlur.options,e)}setGTAOOptions(e){this.gtao?.setOptions(e)}setAntiAliasingMode(e){e!==this.antiAliasingState.mode&&("taa"===e&&null==this.taa||"smaa"===e&&null==this.smaa||"fxaa"===e&&null==this.fxaa?console.warn(`[Hology WebGPU experiment] Anti-aliasing mode "${e}" was not initialized. Set webgpuPostProcessing.antiAliasing in the initial rendering configuration to enable runtime switching.`):(this.antiAliasingState.mode=e,this.resetTemporalHistory()))}setGTAOQuality(e){this.gtao?.applyPreset(e)}setVolumetricFogOptions(e){this.volumetricFog?.setOptions(e)}setVolumetricFogQuality(e){this.volumetricFog?.applyPreset(e)}pushMotionBlurOverride(e){return this.motionBlur?.pushOverride(e)??null}invalidateObjectMotion(e){this.renderer.invalidateObjectMotion(e)}getLastFrameProfile(){return this.renderer.getLastFrameProfile()}setPostProcessState(e){null!=this.colorGrading&&(Object.assign(this.colorGrading.options,e??{enabled:!1}),this.colorGrading.options.enabled=!0===e?.enabled),null!=this.depthOfField&&(this.depthOfField.options.enabled=null!=e?.depthFocus||null!=e?.depthAperture||null!=e?.depthMaxBlur,this.depthOfField.options.focus=e?.depthFocus,this.depthOfField.options.aperture=e?.depthAperture,this.depthOfField.options.maxBlur=e?.depthMaxBlur)}setProfilingEnabled(e){this.renderer.setRenderGraphProfilingEnabled(e)}resetTemporalHistory(){this.taa?.reset(),this.motionBlur?.reset(),this.gtao?.reset(),this.volumetricFog?.reset(),this.renderer.resetViewHistory(),this.nativeDlss?.reset()}inspect(e,t){return inspectWebGpuScene(e,t,this.nodeMaterialResolver)}destroy(){this.nativeDlss?.dispose(),this.nodeMaterialResolver.dispose(),this.gBufferFallbackSource.dispose(),this.gtao?.dispose(),this.smaa?.dispose(),this.motionBlur?.dispose(),this.volumetricFog?.dispose();for(const e of this.ownedPmremResults)e.dispose();this.ownedPmremResults.clear(),this.renderer.destroy(),this.fallbackMaterial.dispose()}}export function inspectWebGpuScene(e,t,i){const n={meshes:0,skinnedMeshes:0,instancedMeshes:0,batchedMeshes:0,sprites:0,points:0,lines:0,missingPositionGeometry:0,transparentMaterials:0,shaderMaterialsReplaced:0,materialsReplaced:0,unsupportedCamera:ExperimentalWebGpuBackend.supportsCamera(t)?0:1};return e.traverse(e=>{if(e.isSprite)return void n.sprites++;if(e.isPoints)return void n.points++;if(e.isLine)return void n.lines++;if(!e.isMesh)return;const t=e;t.isBatchedMesh?n.batchedMeshes++:t.isInstancedMesh?n.instancedMeshes++:t.isSkinnedMesh?n.skinnedMeshes++:n.meshes++,null==t.geometry?.getAttribute("position")&&n.missingPositionGeometry++;const r=Array.isArray(t.material)?t.material:[t.material];for(const e of r){if(null==e)continue;e.transparent&&n.transparentMaterials++;const t=!0===e.isWGSLShaderMaterial||!0===e.isLineMaterial,r=!t&&!0===i?.canResolve(e);t||r||(n.materialsReplaced++,e.isShaderMaterial&&n.shaderMaterialsReplaced++)}}),n}export function formatWebGpuSceneCapabilitySummary(e){return`[Hology WebGPU experiment] ${JSON.stringify(e)}`}const u="\nstruct VertexInput {\n @location(0) position: vec3<f32>,\n @location(1) normal: vec3<f32>,\n @location(2) uv: vec2<f32>,\n @location(3) color: vec4<f32>,\n#ifdef USE_SKINNING\n @location(4) skinIndex: vec4<u32>,\n @location(5) skinWeight: vec4<f32>,\n#endif\n @builtin(instance_index) instanceIndex: u32,\n};\n\nstruct VertexOutput {\n @builtin(position) position: vec4<f32>,\n @location(0) worldPosition: vec3<f32>,\n @location(1) worldNormal: vec3<f32>,\n @location(2) color: vec4<f32>,\n};\n\n@vertex\nfn vsMain(input: VertexInput) -> VertexOutput {\n var output: VertexOutput;\n#ifdef USE_SKINNING\n let localPosition = rendererSkinPosition(input.position, input.skinIndex, input.skinWeight);\n let localNormal = rendererSkinNormal(input.normal, input.skinIndex, input.skinWeight);\n#else\n let localPosition = input.position;\n let localNormal = input.normal;\n#endif\n let world = rendererWorldPosition(localPosition, input.instanceIndex);\n output.position = rendererClipPosition(localPosition, input.instanceIndex);\n output.worldPosition = world.xyz;\n output.worldNormal = rendererWorldNormal(localNormal, input.instanceIndex);\n output.color = input.color * rendererObjectColor(input.instanceIndex);\n return output;\n}\n",p="\nstruct VertexOutput {\n @builtin(position) position: vec4<f32>,\n @location(0) worldPosition: vec3<f32>,\n @location(1) worldNormal: vec3<f32>,\n @location(2) color: vec4<f32>,\n};\n\nfn distanceAttenuation(distanceToLight: f32, cutoffDistance: f32, decayExponent: f32) -> f32 {\n var distanceFalloff = 1.0 / max(pow(distanceToLight, decayExponent), 0.01);\n if (cutoffDistance > 0.0) {\n let ratio = distanceToLight / cutoffDistance;\n let cutoff = clamp(1.0 - ratio * ratio * ratio * ratio, 0.0, 1.0);\n distanceFalloff *= cutoff * cutoff;\n }\n return distanceFalloff;\n}\n\n@fragment\nfn fsMain(input: VertexOutput) -> @location(0) vec4<f32> {\n let normal = normalize(input.worldNormal);\n let normalTint = normal * 0.5 + vec3<f32>(0.5);\n let base = mix(vec3<f32>(0.52, 0.58, 0.64), normalTint, 0.22) * input.color.rgb;\n var lighting = rendererIndirectDiffuse(normal) + vec3<f32>(0.08);\n var directionalLighting = vec3<f32>(0.0);\n let directionalCount = rendererDirectionalLightCount();\n\n for (var index: u32 = 0u; index < directionalCount; index = index + 1u) {\n let lightDirection = rendererDirectionalLightDirectionForLight(index);\n let shadow = rendererSampleDirectionalShadowForLightWithNormal(index, input.worldPosition, normal);\n directionalLighting += rendererDirectionalLightColorForLight(index) * max(dot(normal, lightDirection), 0.0) * shadow;\n }\n if (directionalCount > 0u) {\n lighting += directionalLighting / f32(directionalCount);\n }\n\n for (var index: u32 = 0u; index < rendererPointLightCount(); index = index + 1u) {\n let lightVector = rendererPointLightPositionForLight(index) - input.worldPosition;\n let distanceToLight = length(lightVector);\n let lightDirection = normalize(lightVector);\n let shadow = rendererSamplePointShadowForLightWithNormal(index, input.worldPosition, normal);\n lighting += rendererPointLightColorForLight(index) * max(dot(normal, lightDirection), 0.0) * distanceAttenuation(distanceToLight, rendererPointLightRangeForLight(index), rendererPointLightDecayForLight(index)) * shadow;\n }\n\n for (var index: u32 = 0u; index < rendererSpotLightCount(); index = index + 1u) {\n let lightVector = rendererSpotLightPositionForLight(index) - input.worldPosition;\n let distanceToLight = length(lightVector);\n let lightDirection = normalize(lightVector);\n let angleCos = dot(-lightDirection, rendererSpotLightDirectionForLight(index));\n let cone = smoothstep(rendererSpotLightConeCosForLight(index), rendererSpotLightPenumbraCosForLight(index), angleCos);\n let shadow = rendererSampleSpotShadowForLightWithNormal(index, input.worldPosition, normal);\n lighting += rendererSpotLightColorForLight(index) * max(dot(normal, lightDirection), 0.0) * cone * distanceAttenuation(distanceToLight, rendererSpotLightRangeForLight(index), rendererSpotLightDecayForLight(index)) * shadow;\n }\n\n return vec4<f32>(base * max(lighting, vec3<f32>(0.08)), input.color.a);\n}\n";/*
|
|
1
|
+
import*as e from"three";import{NodeMaterialWebGpuResolver as t}from"./node-material-webgpu-resolver.js";import{configureWebGpuRuntimeBindings as i}from"./webgpu-runtime-bridge.js";import{float as n,varyingTransformed as r,vec4 as o}from"three-shader-graph";import{NodeShaderMaterial as s}from"../shader-nodes/index.js";import{sceneMapUniformName as a}from"../shader-nodes/scene-sample.js";import{depthUniformName as l}from"../shader-nodes/depth.js";import{MATERIAL_FLAG_ALPHA_TEST as d,MATERIAL_FLAG_RECEIVE_DECALS as c}from"../shader-nodes/material-flags.js";import{createMotionVectorOutput as h}from"./motion-vector-node.js";export class ExperimentalWebGpuBackend{constructor(e,t,i,n,r,o,s,a,l,d,c,h,u,p,m,g,f,v,S,b,P,x){this.renderer=e,this.fallbackMaterial=t,this.nodeMaterialResolver=i,this.gBufferFallbackSource=n,this.bloom=r,this.fxaa=o,this.smaa=s,this.gtao=a,this.ssr=l,this.taa=d,this.motionBlur=c,this.volumetricFog=h,this.colorGrading=u,this.depthOfField=p,this.outline=m,this.postProcessEffects=g,this.renderGraphExtensions=f,this.presentationExtensions=v,this.antiAliasingState=S,this.directionalShadowState=b,this.nativeDlss=P,this.kind="webgpu",this.renderScale=1,this.pmremGenerator=null,this.pmremResults=new WeakMap,this.ownedPmremResults=new Set,this.warnedUnsupportedPostProcessStages=new Set,this.secondaryMotionPrepared=!1,this.canvas=x}static async probeAvailability(){if("undefined"==typeof navigator||!("gpu"in navigator))return{available:!1,reason:"The runtime does not expose navigator.gpu."};try{const e=await navigator.gpu.requestAdapter({powerPreference:"high-performance"});return null==e?{available:!1,reason:"No WebGPU adapter is available."}:{available:!0,adapter:e}}catch(e){return{available:!1,reason:`Requesting a WebGPU adapter failed: ${e instanceof Error?e.message:String(e)}`}}}static async create(m={},g){const f=await import("@hology/webgpu-renderer");i({createComputeKernel:(e,t)=>new f.ComputeKernel(e,t),buildParticleLightingShaderHeader:f.buildParticleLightingShaderHeader});const v=document.createElement("canvas");v.dataset.hologyRenderer="webgpu-experimental";const S=new f.WGSLShaderMaterial({vertexShader:u,fragmentShader:p}),b=!1!==m.nativeUpscaling&&"dlss"===m.nativeUpscaling?.method,P=b?(await import("./native-dlss-upscaler.js")).createNativeDlssUpscaler(m.nativeUpscaling?.mode??"quality"):null,x=null!=P;S.side=f.DoubleSide;const w=f,y=null!=m.motionBlur&&!1!==m.motionBlur,M=!1!==m.gtao&&(null==m.gtao||!1!==m.gtao.temporal),E=!1!==m.volumetricFog&&(null==m.volumetricFog||!1!==m.volumetricFog.temporal),F=x?"off":b?"taa":null!=(D=m).antiAliasing?D.antiAliasing:null!=D.taa&&!1!==D.taa?"taa":null!=D.smaa&&!1!==D.smaa?"smaa":null!=D.fxaa&&!1!==D.fxaa?"fxaa":!1===D.taa?"off":"taa";var D;const L=null!=m.antiAliasing,C=y||M||E||(L||"taa"===F)||x;let O=null;const G=new t(w,(e,t)=>"opaque"===t?[e.outputColor.xyz.rgba(n(e.alphaTest>0?d:0).add(!1===e.userData.receiveDecals?0:c)),o((e.outputNormal??r.normal).multiplyScalar(.5).addScalar(.5),e.outputRoughness??n(1)),...C?[h(e)]:[]]:void 0,e=>O?.getEnvironmentTexture(e)??e),R=new e.MeshStandardMaterial({color:8688803,roughness:1});if(null==G.resolve(R,"opaque"))throw S.dispose(),R.dispose(),new Error("Failed to compile the WebGPU G-buffer fallback material.");const T=!1===m.gtao?null:new f.GTAOEffect({normalSpace:"view",...f.GTAO_PRESETS.high,...m.gtao??{}}),A=!1===m.ssr||null==m.ssr?null:new f.SSREffect({normalSpace:"view",resolutionScale:.5,...m.ssr??{}}),B=!1===m.bloom?null:new f.BloomEffect({threshold:1,strength:.9,radius:.2,...m.bloom??{}}),W=L||!1!==m.fxaa&&"fxaa"===F?new f.FXAAEffect(!1===m.fxaa?{}:m.fxaa):null,V=L||!1!==m.smaa&&"smaa"===F?new f.SMAAEffect(!1===m.smaa?{}:m.smaa):null,k=x||L||!1!==m.taa&&"taa"===F?new f.TemporalAAEffect({renderScale:1,...!1===m.taa?{}:m.taa}):null,U={mode:F},j=!1===m.motionBlur||null==m.motionBlur?null:new f.MotionBlurEffect(m.motionBlur),I=m.volumetricFog||void 0,N=!1===m.volumetricFog?null:new f.VolumetricFogEffect(void 0,{...f.VOLUMETRIC_FOG_PRESETS.high,maxDistance:64,spatialJitter:!0,scatteringIntensity:Math.PI,...I,temporal:!1!==I?.temporal&&{...f.VOLUMETRIC_FOG_PRESETS.high.temporal,...I?.temporal},blur:!1!==I?.blur&&{...!1===f.VOLUMETRIC_FOG_PRESETS.high.blur?{}:f.VOLUMETRIC_FOG_PRESETS.high.blur,depthAwareUpsample:!0,...I?.blur}}),H=!1===m.colorGrading?null:new f.ColorGradingEffect({enabled:!1,...m.colorGrading??{}}),$=!1===m.depthOfField?null:new f.DepthOfFieldEffect({enabled:!1,...m.depthOfField??{}}),_=!1===m.outline?null:new f.OutlineEffect({enabled:!1,...m.outline??{}}),q=[],z=new WeakMap,J=new Set,K=[],Z=[],Q=(e,t,i)=>{let n=i;const r=q.filter(e=>e.enabled&&e.stage===t).sort((e,t)=>e.priority-t.priority||e.id-t.id);for(const t of r){if(!(t.material instanceof s)){const e=`${t.id}:material`;J.has(e)||(J.add(e),console.warn(`[Hology WebGPU experiment] Skipping custom post-process effect ${t.id}: only NodeShaderMaterial effects are supported.`));continue}try{let i=z.get(t.material);null!=i&&i.version===t.material.version||(i={version:t.material.version,shader:G.compileFullscreen(t.material)},z.set(t.material,i));const r=e.createColorTarget(`hologyCustomPostProcess${t.id}`);e.addNodeFullscreenPass({name:`HologyCustomPostProcess${t.id}`,shader:i.shader,inputOverrides:{[a]:n},outputs:r}),n=r}catch(e){const i=`${t.id}:compile:${t.material.version}`;J.has(i)||(J.add(i),console.warn(`[Hology WebGPU experiment] Skipping custom post-process effect ${t.id}: ${e instanceof Error?e.message:String(e)}`,e))}}return n},X={enabled:!0},Y=new f.WebGpuRenderer({canvas:v,fallbackMaterial:S,materialResolver:(e,t)=>G.resolve(e,t),invokeObjectRenderCallbacks:!1,hiZOcclusionCulling:!0,renderGraphProfiling:!1,sampleCount:1,multiDrawIndirect:!1,nativePostSubmit:P?.postSubmit,presentationOverlay:e=>{for(const t of Z)t(e)}});Y.setRenderScale("taa"===F?k?.renderScale??1:1),Y.setRenderGraphBuilder((e,t)=>{const i=new f.FrameGraphBuilder(t),n=i.createColorTarget("hologyNormalRoughness",{format:"rgba8unorm"}),r=C?i.createColorTarget("hologyMotionVectors",{format:"rgba16float"}):null;for(const e of K)"beforeScene"===e.stage&&e(i,i.sceneColor);X.enabled&&i.addDirectionalShadowPass(),i.addPointShadowPass(),i.addSpotShadowPass(),i.addDepthPrepass(),i.addHiZPasses(),i.addVisibilityPass(),i.addMaterialPass({name:"OpaqueGBufferPass",outputs:null==r?[i.sceneColor,n]:[i.sceneColor,n,r],drawStage:"opaque",loadDepth:!0}),i.addHiZHistoryPass("OpaqueGBufferPass");let o=i.sceneColor;if(T?.enabled){const e=T.addPasses(i,{depth:i.mainDepth,normal:n,velocity:r??void 0});o=T.addCompositePass(i,o,e)}null!=A&&(o=A.addPasses(i,{sceneColor:o,depth:i.mainDepth,normalRoughness:n}));const s=new Set(K.flatMap(e=>e.getSceneTextureReads?.()??[]));i.addSceneTextureCopyPass(o,{sceneColor:s.has("sceneColorSnapshot"),sceneDepth:s.has("sceneDepthSnapshot")||q.some(e=>e.enabled&&null!=e.material.uniforms[l])}),o=Q(i,"beforeFog",o),i.addLatePass(o);for(const e of K)null!=e.stage&&"afterScene"!==e.stage||e(i,o);null!=N&&(o=N.addPasses(i,{sceneColor:o,depth:i.mainDepth,velocity:r??void 0,volumeObjects:t.fogVolumeObjects,lights:t.extractedLights})),null!=j&&null!=r&&(o=j.addPass(i,o,r,i.mainDepth)),null!=B&&(o=B.addPass(i,o)),o=Q(i,"beforeOutline",o),null!=_&&(o=_.addPass(i,o)),o=Q(i,"beforeDepthOfField",o),null!=$&&(o=$.addPass(i,o,i.mainDepth)),o=Q(i,"beforeColorAdjustment",o),null!=H&&(o=H.addPass(i,o)),o=Q(i,"beforeAntiAliasing",o);let a="taa"===U.mode&&null!=k?k.addPass(i,o,i.mainDepth,r??void 0):o;"smaa"===U.mode&&null!=V?a=V.addPass(i,a):"fxaa"===U.mode&&null!=W&&(a=W.addPass(i,a)),a=Q(i,"beforeOutput",a);for(const e of K)"beforePresent"===e.stage&&e(i,a);!0===P?.enabled&&null!=r?P.addInputPass(i,a,r):i.present(a)});try{return await Y.initialize(g),O=new ExperimentalWebGpuBackend(Y,S,G,R,B,W,V,T,A,k,j,N,H,$,_,q,K,Z,U,X,P,v),O}catch(e){throw Y.destroy(),S.dispose(),G.dispose(),R.dispose(),T?.dispose(),V?.dispose(),j?.dispose(),N?.dispose(),_?.dispose(),e}}static supportsCamera(t){return t instanceof e.PerspectiveCamera||t instanceof e.OrthographicCamera}setSize(e,t,i,n=1){const r=this.canvas.width,o=this.canvas.height;let s=Math.min(1,Math.max(.25,n));if(!0===this.nativeDlss?.enabled){const n=Math.max(1,Math.floor(e*i)),r=Math.max(1,Math.floor(t*i));s=this.nativeDlss.getRenderScale(n,r)}const a=s!==this.renderScale;this.renderScale=s,this.renderer.setRenderScale(s),this.taa?.setRenderScale(s),this.renderer.setSize(e,t,i),(a||this.canvas.width!==r||this.canvas.height!==o)&&this.resetViewHistory()}initTexture(e){this.renderer.initTexture(e)}setPostProcessEffects(e){this.postProcessEffects.splice(0,this.postProcessEffects.length,...e);for(const t of e){if("beforeLut"!==t.stage)continue;const e=`${t.id}:${t.stage}`;this.warnedUnsupportedPostProcessStages.has(e)||(this.warnedUnsupportedPostProcessStages.add(e),console.warn(`[Hology WebGPU experiment] Skipping custom post-process effect ${t.id}: stage "${t.stage}" has no native WebGPU anchor.`))}}getDevice(){return this.renderer.getDevice()}setRenderGraphExtensions(e){this.renderGraphExtensions.length=0;for(const t of e)this.renderGraphExtensions.push(t)}setPresentationExtensions(e){this.presentationExtensions.length=0;for(const t of e)this.presentationExtensions.push(t)}setEnableOutlines(e){null!=this.outline&&(this.outline.enabled=e)}setTiledLightingEnabled(e){this.renderer.setTiledLightingEnabled(e)}setDynamicBatchingEnabled(e){this.renderer.setDynamicBatchingEnabled(e)}setSelectedObjects(e){this.outline?.setSelectedObjects(e)}setSelectedObjectInstances(e){this.outline?.setSelectedInstances(e)}setCascadedShadowRanges(e,t=[]){this.renderer.setCascadedShadowRanges(e,t),this.volumetricFog?.setCascadedDirectionalLights(t)}setDirectionalShadowOptions(e,t){this.directionalShadowState.enabled=e,this.renderer.setDirectionalShadowsEnabled(e),this.renderer.setDirectionalShadowMapSize(t)}setWorldEnvironment(e){if(null==e)return void this.nodeMaterialResolver.setWorldEnvironment(null);const t=this.getEnvironmentTexture(e.source);this.nodeMaterialResolver.setWorldEnvironment({texture:t,intensity:e.intensity})}getEnvironmentTexture(t){if(t.mapping===e.CubeUVReflectionMapping)return t;let i=this.pmremResults.get(t);return null==i&&(this.pmremGenerator??(this.pmremGenerator=this.renderer.createPMREMGenerator()),i=this.pmremGenerator.fromEquirectangular(t),this.pmremResults.set(t,i),this.ownedPmremResults.add(i)),i.texture}resetViewHistory(){this.renderer.resetViewHistory(),this.taa?.reset(),this.motionBlur?.reset(),this.gtao?.reset(),this.volumetricFog?.reset(),this.nativeDlss?.reset()}async compile(e,t){if(!this.secondaryMotionPrepared){let t=!1;e.traverse(e=>{const i=e.userData.secondaryMotion?.regions;Array.isArray(i)&&i.some(e=>e.enabled)&&(t=!0)});const i=this.renderer.getDevice();if(t&&i){const{prepareSecondaryMotionRuntime:e}=await import("../secondary-motion/runtime.js");e(i),this.secondaryMotionPrepared=!0}}await this.renderer.compileAsync(e,t)}createStaticDrawSet(e,t,i=!1){this.renderer.setHiZOcclusionCullingEnabled(!0);const n=this.renderer.createStaticDrawSet(e,{label:t,onUnsupported:"skip",allowUnsortedLateDraws:i});return 0===n.drawCount?(n.dispose(),null):n}render(e,t,i){const n="taa"===this.antiAliasingState.mode?this.taa:null;this.volumetricFog?.setScene(e),this.renderer.setMotionVectorProjection(t.projectionMatrix),this.motionBlur?.prepareCamera(t,this.canvas.width,this.canvas.height,i),this.motionBlur?.requiresRendererHistoryReset()&&(this.renderer.resetViewHistory(),this.gtao?.reset(),this.volumetricFog?.reset()),n?.prepareCamera(t,this.canvas.width,this.canvas.height),this.nativeDlss?.prepareFrame(t);const r=!0===this.nativeDlss?.enabled?this.nativeDlss.jitter:null;this.motionBlur?.setJitterUv(n?.currentJitterUv.x??(null==r?0:r.x/Math.max(1,this.canvas.width*this.renderScale)),n?.currentJitterUv.y??(null==r?0:-r.y/Math.max(1,this.canvas.height*this.renderScale))),null!=r&&this.renderer.setProjectionJitter(r.x,r.y);let o=!1;try{this.renderer.render(e,t,i),o=!0}finally{null!=r&&this.renderer.clearProjectionJitter(),n?.finishCamera(t),o&&this.motionBlur?.commitCamera(),o&&this.nativeDlss?.finishFrame(t)}}setMotionBlurOptions(e){null!=this.motionBlur&&Object.assign(this.motionBlur.options,e)}setGTAOOptions(e){this.gtao?.setOptions(e)}setAntiAliasingMode(e){e!==this.antiAliasingState.mode&&("taa"===e&&null==this.taa||"smaa"===e&&null==this.smaa||"fxaa"===e&&null==this.fxaa?console.warn(`[Hology WebGPU experiment] Anti-aliasing mode "${e}" was not initialized. Set webgpuPostProcessing.antiAliasing in the initial rendering configuration to enable runtime switching.`):(this.antiAliasingState.mode=e,this.resetTemporalHistory()))}setGTAOQuality(e){this.gtao?.applyPreset(e)}setVolumetricFogOptions(e){this.volumetricFog?.setOptions(e)}setVolumetricFogQuality(e){this.volumetricFog?.applyPreset(e)}pushMotionBlurOverride(e){return this.motionBlur?.pushOverride(e)??null}invalidateObjectMotion(e){this.renderer.invalidateObjectMotion(e)}getLastFrameProfile(){return this.renderer.getLastFrameProfile()}setPostProcessState(e){null!=this.colorGrading&&(Object.assign(this.colorGrading.options,e??{enabled:!1}),this.colorGrading.options.enabled=!0===e?.enabled),null!=this.depthOfField&&(this.depthOfField.options.enabled=null!=e?.depthFocus||null!=e?.depthAperture||null!=e?.depthMaxBlur,this.depthOfField.options.focus=e?.depthFocus,this.depthOfField.options.aperture=e?.depthAperture,this.depthOfField.options.maxBlur=e?.depthMaxBlur)}setProfilingEnabled(e){this.renderer.setRenderGraphProfilingEnabled(e)}resetTemporalHistory(){this.taa?.reset(),this.motionBlur?.reset(),this.gtao?.reset(),this.volumetricFog?.reset(),this.renderer.resetViewHistory(),this.nativeDlss?.reset()}inspect(e,t){return inspectWebGpuScene(e,t,this.nodeMaterialResolver)}destroy(){this.nativeDlss?.dispose(),this.nodeMaterialResolver.dispose(),this.gBufferFallbackSource.dispose(),this.gtao?.dispose(),this.smaa?.dispose(),this.motionBlur?.dispose(),this.volumetricFog?.dispose();for(const e of this.ownedPmremResults)e.dispose();this.ownedPmremResults.clear(),this.renderer.destroy(),this.fallbackMaterial.dispose()}}export function inspectWebGpuScene(e,t,i){const n={meshes:0,skinnedMeshes:0,instancedMeshes:0,batchedMeshes:0,sprites:0,points:0,lines:0,missingPositionGeometry:0,transparentMaterials:0,shaderMaterialsReplaced:0,materialsReplaced:0,unsupportedCamera:ExperimentalWebGpuBackend.supportsCamera(t)?0:1};return e.traverse(e=>{if(e.isSprite)return void n.sprites++;if(e.isPoints)return void n.points++;if(e.isLine)return void n.lines++;if(!e.isMesh)return;const t=e;t.isBatchedMesh?n.batchedMeshes++:t.isInstancedMesh?n.instancedMeshes++:t.isSkinnedMesh?n.skinnedMeshes++:n.meshes++,null==t.geometry?.getAttribute("position")&&n.missingPositionGeometry++;const r=Array.isArray(t.material)?t.material:[t.material];for(const e of r){if(null==e)continue;e.transparent&&n.transparentMaterials++;const t=!0===e.isWGSLShaderMaterial||!0===e.isLineMaterial,r=!t&&!0===i?.canResolve(e);t||r||(n.materialsReplaced++,e.isShaderMaterial&&n.shaderMaterialsReplaced++)}}),n}export function formatWebGpuSceneCapabilitySummary(e){return`[Hology WebGPU experiment] ${JSON.stringify(e)}`}const u="\nstruct VertexInput {\n @location(0) position: vec3<f32>,\n @location(1) normal: vec3<f32>,\n @location(2) uv: vec2<f32>,\n @location(3) color: vec4<f32>,\n#ifdef USE_SKINNING\n @location(4) skinIndex: vec4<u32>,\n @location(5) skinWeight: vec4<f32>,\n#endif\n @builtin(instance_index) instanceIndex: u32,\n};\n\nstruct VertexOutput {\n @builtin(position) position: vec4<f32>,\n @location(0) worldPosition: vec3<f32>,\n @location(1) worldNormal: vec3<f32>,\n @location(2) color: vec4<f32>,\n};\n\n@vertex\nfn vsMain(input: VertexInput) -> VertexOutput {\n var output: VertexOutput;\n#ifdef USE_SKINNING\n let localPosition = rendererSkinPosition(input.position, input.skinIndex, input.skinWeight);\n let localNormal = rendererSkinNormal(input.normal, input.skinIndex, input.skinWeight);\n#else\n let localPosition = input.position;\n let localNormal = input.normal;\n#endif\n let world = rendererWorldPosition(localPosition, input.instanceIndex);\n output.position = rendererClipPosition(localPosition, input.instanceIndex);\n output.worldPosition = world.xyz;\n output.worldNormal = rendererWorldNormal(localNormal, input.instanceIndex);\n output.color = input.color * rendererObjectColor(input.instanceIndex);\n return output;\n}\n",p="\nstruct VertexOutput {\n @builtin(position) position: vec4<f32>,\n @location(0) worldPosition: vec3<f32>,\n @location(1) worldNormal: vec3<f32>,\n @location(2) color: vec4<f32>,\n};\n\nfn distanceAttenuation(distanceToLight: f32, cutoffDistance: f32, decayExponent: f32) -> f32 {\n var distanceFalloff = 1.0 / max(pow(distanceToLight, decayExponent), 0.01);\n if (cutoffDistance > 0.0) {\n let ratio = distanceToLight / cutoffDistance;\n let cutoff = clamp(1.0 - ratio * ratio * ratio * ratio, 0.0, 1.0);\n distanceFalloff *= cutoff * cutoff;\n }\n return distanceFalloff;\n}\n\n@fragment\nfn fsMain(input: VertexOutput) -> @location(0) vec4<f32> {\n let normal = normalize(input.worldNormal);\n let normalTint = normal * 0.5 + vec3<f32>(0.5);\n let base = mix(vec3<f32>(0.52, 0.58, 0.64), normalTint, 0.22) * input.color.rgb;\n var lighting = rendererIndirectDiffuse(normal) + vec3<f32>(0.08);\n var directionalLighting = vec3<f32>(0.0);\n let directionalCount = rendererDirectionalLightCount();\n\n for (var index: u32 = 0u; index < directionalCount; index = index + 1u) {\n let lightDirection = rendererDirectionalLightDirectionForLight(index);\n let shadow = rendererSampleDirectionalShadowForLightWithNormal(index, input.worldPosition, normal);\n directionalLighting += rendererDirectionalLightColorForLight(index) * max(dot(normal, lightDirection), 0.0) * shadow;\n }\n if (directionalCount > 0u) {\n lighting += directionalLighting / f32(directionalCount);\n }\n\n for (var index: u32 = 0u; index < rendererPointLightCount(); index = index + 1u) {\n let lightVector = rendererPointLightPositionForLight(index) - input.worldPosition;\n let distanceToLight = length(lightVector);\n let lightDirection = normalize(lightVector);\n let shadow = rendererSamplePointShadowForLightWithNormal(index, input.worldPosition, normal);\n lighting += rendererPointLightColorForLight(index) * max(dot(normal, lightDirection), 0.0) * distanceAttenuation(distanceToLight, rendererPointLightRangeForLight(index), rendererPointLightDecayForLight(index)) * shadow;\n }\n\n for (var index: u32 = 0u; index < rendererSpotLightCount(); index = index + 1u) {\n let lightVector = rendererSpotLightPositionForLight(index) - input.worldPosition;\n let distanceToLight = length(lightVector);\n let lightDirection = normalize(lightVector);\n let angleCos = dot(-lightDirection, rendererSpotLightDirectionForLight(index));\n let cone = smoothstep(rendererSpotLightConeCosForLight(index), rendererSpotLightPenumbraCosForLight(index), angleCos);\n let shadow = rendererSampleSpotShadowForLightWithNormal(index, input.worldPosition, normal);\n lighting += rendererSpotLightColorForLight(index) * max(dot(normal, lightDirection), 0.0) * cone * distanceAttenuation(distanceToLight, rendererSpotLightRangeForLight(index), rendererSpotLightDecayForLight(index)) * shadow;\n }\n\n return vec4<f32>(base * max(lighting, vec3<f32>(0.08)), input.color.a);\n}\n";/*
|
|
2
2
|
* Copyright (©) 2026 Hology Interactive AB. All rights reserved.
|
|
3
3
|
* See the LICENSE.md file for details.
|
|
4
4
|
*/
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { Camera, Object3D } from 'three';
|
|
2
|
+
export interface SecondaryMotionBudgetHandle {
|
|
3
|
+
target: Object3D;
|
|
4
|
+
enabled: boolean;
|
|
5
|
+
/** Positive priority reserves a slot before distance-based candidates. */
|
|
6
|
+
priority: number;
|
|
7
|
+
readonly active: boolean;
|
|
8
|
+
dispose(): void;
|
|
9
|
+
}
|
|
10
|
+
/** Selects once per simulation frame. Entries and selection scratch are persistent. */
|
|
11
|
+
export declare class SecondaryMotionBudget {
|
|
12
|
+
readonly maxCharacters: number;
|
|
13
|
+
readonly maxDistance: number;
|
|
14
|
+
private readonly entries;
|
|
15
|
+
private readonly frustum;
|
|
16
|
+
private readonly viewProjection;
|
|
17
|
+
private readonly sphere;
|
|
18
|
+
private readonly cameraPosition;
|
|
19
|
+
private selectionFrame;
|
|
20
|
+
private nextId;
|
|
21
|
+
private readonly selected;
|
|
22
|
+
constructor(maxCharacters?: number, maxDistance?: number);
|
|
23
|
+
register(target: Object3D): SecondaryMotionBudgetHandle;
|
|
24
|
+
select(frame: number, camera: Camera): void;
|
|
25
|
+
}
|
|
26
|
+
//# sourceMappingURL=budget.d.ts.map
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{Frustum as e,Matrix4 as t,Sphere as i,Vector3 as s}from"three";export class SecondaryMotionBudget{constructor(r=8,o=24){if(this.maxCharacters=r,this.maxDistance=o,this.entries=[],this.frustum=new e,this.viewProjection=new t,this.sphere=new i(new s,2),this.cameraPosition=new s,this.selectionFrame=-1,this.nextId=0,!Number.isInteger(r)||r<0||!Number.isFinite(o)||o<0)throw new Error("Invalid secondary-motion budget");this.selected=new Array(r)}register(e){const t={target:e,enabled:!0,priority:0,active:!1,score:1/0,id:this.nextId++,dispose:()=>{const e=this.entries.indexOf(t);e>=0&&this.entries.splice(e,1);for(let e=0;e<this.selected.length;e++)this.selected[e]===t&&(this.selected[e]=void 0);t.active=!1,t.enabled=!1,this.selectionFrame=-1}};return this.entries.push(t),this.selectionFrame=-1,t}select(e,t){if(this.selectionFrame===e)return;this.selectionFrame=e,this.cameraPosition.setFromMatrixPosition(t.matrixWorld),this.viewProjection.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),this.frustum.setFromProjectionMatrix(this.viewProjection);for(const e of this.entries){this.sphere.center.setFromMatrixPosition(e.target.matrixWorld);const t=this.sphere.center.distanceToSquared(this.cameraPosition),i=this.maxDistance*(e.active?1.15:1),s=e.enabled&&e.target.visible&&(e.priority>0||t<=i*i&&this.frustum.intersectsSphere(this.sphere));e.score=s?t*(e.active?.8:1):1/0}let i=0;for(const e of this.entries){if(!Number.isFinite(e.score))continue;let t=0;for(;t<i&&r(this.selected[t],e)<=0;)t++;if(t>=this.maxCharacters)continue;for(let e=Math.min(i,this.maxCharacters-1);e>t;e--)this.selected[e]=this.selected[e-1];this.selected[t]=e,i=Math.min(i+1,this.maxCharacters)}for(const e of this.entries)e.active=!1;for(let e=0;e<this.selected.length;e++)e<i?this.selected[e].active=!0:this.selected[e]=void 0}}function r(e,t){const i=Number.isFinite(e.score);return i!==Number.isFinite(t.score)?i?-1:1:t.priority-e.priority||e.score-t.score||e.id-t.id}/*
|
|
2
|
+
* Copyright (©) 2026 Hology Interactive AB. All rights reserved.
|
|
3
|
+
* See the LICENSE.md file for details.
|
|
4
|
+
*/
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { BufferGeometry } from 'three';
|
|
2
|
+
import type { SecondaryMotionGeneratedRegion } from './data.js';
|
|
3
|
+
/** Borrowed immutable CPU data. GPU buffers and simulation state remain instance-owned. */
|
|
4
|
+
export interface SharedClothRegion {
|
|
5
|
+
readonly data: Readonly<SecondaryMotionGeneratedRegion>;
|
|
6
|
+
readonly activeParticleMask: Uint8Array;
|
|
7
|
+
readonly activeParticles: Uint32Array;
|
|
8
|
+
readonly hasSkinning: boolean;
|
|
9
|
+
}
|
|
10
|
+
/** Identity/version checks only on configuration/activation, never per simulation step. */
|
|
11
|
+
export declare class SharedClothRegionCache {
|
|
12
|
+
private readonly geometries;
|
|
13
|
+
get(geometry: BufferGeometry, id: string, paint?: readonly (readonly [number, number])[]): SharedClothRegion;
|
|
14
|
+
}
|
|
15
|
+
export declare const sharedClothRegionCache: SharedClothRegionCache;
|
|
16
|
+
//# sourceMappingURL=cache.d.ts.map
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{generateClothSecondaryMotionRegion as t}from"./generation.js";const e=[],n=new WeakSet;export function isSharedClothRegionData(t){return n.has(t)}export class SharedClothRegionCache{constructor(){this.geometries=new WeakMap}get(i,s,a=e){const c=i.getAttribute("position");if(!c)throw new Error("Secondary-motion geometry needs positions");const l=i.getIndex(),u=i.getAttribute("skinIndex"),g=i.getAttribute("skinWeight");let h=this.geometries.get(i);h&&o(h.sources[0],c)&&o(h.sources[1],l)&&o(h.sources[2],u)&&o(h.sources[3],g)||(h={sources:[r(c),r(l),r(u),r(g)],variants:new Map},this.geometries.set(i,h));const f=h.variants.get(s);if(f&&function(t,e){if(t.length!==2*e.length)return!1;for(let n=0;n<e.length;n++)if(t[2*n]!==e[n][0]||t[2*n+1]!==e[n][1])return!1;return!0}(f.paint,a))return f.region;const d=new Float32Array(3*c.count);for(let t=0;t<c.count;t++)d[3*t]=c.getX(t),d[3*t+1]=c.getY(t),d[3*t+2]=c.getZ(t);const m=new Float32Array(c.count),y=new Float64Array(2*a.length);for(let t=0;t<a.length;t++){const[e,n]=a[t];y[2*t]=e,y[2*t+1]=n,e>=0&&e<m.length&&(m[e]=n)}const p=l?Uint32Array.from(l.array):Uint32Array.from({length:c.count},(t,e)=>e),v=null!=u&&null!=g,w=v?new Uint16Array(4*c.count):void 0,A=v?new Float32Array(4*c.count):void 0;if(w&&A)for(let t=0;t<c.count;t++)for(let e=0;e<4;e++)w[4*t+e]=u.getComponent(t,e),A[4*t+e]=g.getComponent(t,e);const z=t(s,{positions:d,indices:p},m,w,A);Object.freeze(z),n.add(z);const C=new Uint8Array(z.particleInverseMass.length);for(let t=0;t<C.length;t++)z.particleInverseMass[t]>0&&(C[t]=1);for(const t of z.constraints)C[t]=1;let S=0;for(const t of C)S+=t;const b=new Uint32Array(S);for(let t=0,e=0;t<C.length;t++)C[t]&&(b[e++]=t);const k={data:z,activeParticleMask:C,activeParticles:b,hasSkinning:v};return h.variants.set(s,{paint:y,region:k}),k}}function r(t){const e=i(t);return{attribute:t,array:e?.array??null,version:e?.version??0,count:t?.count??0,size:t?.itemSize??0,normalized:t?.normalized??!1}}function o(t,e){const n=i(e);return t.attribute===e&&t.array===(n?.array??null)&&t.version===(n?.version??0)&&t.count===(e?.count??0)&&t.size===(e?.itemSize??0)&&t.normalized===(e?.normalized??!1)}function i(t){return t?.isInterleavedBufferAttribute?t.data:t}export const sharedClothRegionCache=new SharedClothRegionCache;/*
|
|
2
|
+
* Copyright (©) 2026 Hology Interactive AB. All rights reserved.
|
|
3
|
+
* See the LICENSE.md file for details.
|
|
4
|
+
*/
|
|
@@ -2,7 +2,10 @@ import type { RendererCustomPassContext } from '@hology/webgpu-renderer';
|
|
|
2
2
|
import type { BufferGeometry } from 'three';
|
|
3
3
|
import type { ExperimentalWebGpuRenderGraphExtension } from '../rendering/webgpu-experimental-backend.js';
|
|
4
4
|
import type { SecondaryMotionGeneratedRegion } from './data.js';
|
|
5
|
+
import { type SecondaryMotionSkinningTargets } from './skinned-targets.js';
|
|
6
|
+
export type { SecondaryMotionSkinningTargets } from './skinned-targets.js';
|
|
5
7
|
export interface SecondaryMotionComputeRuntime {
|
|
8
|
+
readonly enabled?: boolean;
|
|
6
9
|
execute(context: RendererCustomPassContext): void;
|
|
7
10
|
dispose(): void;
|
|
8
11
|
}
|
|
@@ -35,9 +38,15 @@ export interface WebGpuSecondaryMotionRegionHandle {
|
|
|
35
38
|
readonly positionBuffer: GPUBuffer;
|
|
36
39
|
setRenderGeometry(geometry: BufferGeometry | null): void;
|
|
37
40
|
updateTargets(positions: Float32Array): void;
|
|
41
|
+
/** Installs persistent particle inputs and consumes the renderer's shared GPU bone palette. */
|
|
42
|
+
setSkinningTargets(source: SecondaryMotionSkinningTargets): void;
|
|
43
|
+
/** Resets particles to their current GPU-skinned pose, including animation seeks. */
|
|
44
|
+
resetToSkinningTargets(): void;
|
|
38
45
|
reset(positions?: Float32Array): void;
|
|
39
46
|
dispose(): void;
|
|
40
47
|
}
|
|
48
|
+
/** Prepares immutable pipelines at loading time; simulation buffers stay instance-owned. */
|
|
49
|
+
export declare function prepareSecondaryMotionRuntime(device: GPUDevice): void;
|
|
41
50
|
/**
|
|
42
51
|
* First-stage GPU secondary-motion solver. Positions use vec4 storage so the
|
|
43
52
|
* same buffers can later be consumed directly by render/skinning pipelines.
|
|
@@ -57,6 +66,8 @@ export declare class WebGpuSecondaryMotionRuntime implements SecondaryMotionComp
|
|
|
57
66
|
private readonly previousCollisionSpheres;
|
|
58
67
|
private readonly collisionParams;
|
|
59
68
|
private readonly collisionColliderData;
|
|
69
|
+
private readonly collisionNextData;
|
|
70
|
+
private readonly collisionCountData;
|
|
60
71
|
private collisionCollidersInitialized;
|
|
61
72
|
private readonly collisionBindGroups;
|
|
62
73
|
private readonly integrationParamsData;
|
|
@@ -64,12 +75,16 @@ export declare class WebGpuSecondaryMotionRuntime implements SecondaryMotionComp
|
|
|
64
75
|
private readonly regions;
|
|
65
76
|
private pendingSteps;
|
|
66
77
|
private disposed;
|
|
78
|
+
private _enabled;
|
|
67
79
|
private readonly constraintIterations;
|
|
68
80
|
private readonly constraintStiffness;
|
|
69
81
|
private readonly autoAdvance;
|
|
70
82
|
private lastExecuteSeconds;
|
|
83
|
+
private skinningTargetKernels;
|
|
71
84
|
constructor(device: GPUDevice, options?: WebGpuSecondaryMotionOptions);
|
|
72
85
|
/** Updates non-inertial reference-frame motion before the next render. */
|
|
86
|
+
get enabled(): boolean;
|
|
87
|
+
setEnabled(enabled: boolean): void;
|
|
73
88
|
setFrameMotion(motion: SecondaryMotionFrameMotion): void;
|
|
74
89
|
/** Sets up to eight mesh-local spheres used to keep simulated particles outside the body. */
|
|
75
90
|
setSphereColliders(colliders: readonly SecondaryMotionSphereCollider[]): void;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{createWebGpuComputeKernel as e}from"../rendering/webgpu-runtime-bridge.js";const t=64;export class WebGpuSecondaryMotionRuntime{constructor(t,n={}){this.device=t,this.collisionColliderData=new Float32Array(96),this.collisionCollidersInitialized=!1,this.collisionBindGroups=new Map,this.integrationParamsData=new ArrayBuffer(80),this.integrationParamsView=new DataView(this.integrationParamsData),this.regions=new Map,this.pendingSteps=0,this.disposed=!1,this.lastExecuteSeconds=null,this.fixedStep=new SecondaryMotionFixedStep(n),this.constraintIterations=Math.max(0,Math.trunc(n.constraintIterations??4)),this.constraintStiffness=Math.max(0,Math.min(1,n.constraintStiffness??.9)),this.autoAdvance=n.autoAdvance??!0,this.integrationKernel=e(t,{label:"secondary-motion-integrate",code:o,bindGroupLayoutEntries:[i(0,!0),i(1,!1),i(2,!1),i(3,!0),i(4,!0),{binding:5,visibility:GPUShaderStage.COMPUTE,buffer:{type:"uniform"}}]}),this.constraintKernel=e(t,{label:"secondary-motion-distance-constraints",code:s,bindGroupLayoutEntries:[i(0,!1),i(1,!0),i(2,!0),i(3,!0),{binding:4,visibility:GPUShaderStage.COMPUTE,buffer:{type:"uniform"}}]}),this.packKernel=e(t,{label:"secondary-motion-pack-render-positions",code:a,bindGroupLayoutEntries:[i(0,!0),i(1,!0),i(2,!1)]}),this.finalizeKernel=e(t,{label:"secondary-motion-finalize-velocity",code:l,bindGroupLayoutEntries:[i(0,!0),i(1,!0),i(2,!1),{binding:3,visibility:GPUShaderStage.COMPUTE,buffer:{type:"uniform"}}]}),this.collisionKernel=e(t,{label:"secondary-motion-sphere-collision",code:c,bindGroupLayoutEntries:[i(0,!1),i(1,!0),i(2,!0),i(3,!0),i(4,!0),i(5,!1),{binding:6,visibility:GPUShaderStage.COMPUTE,buffer:{type:"uniform"}}]}),this.integrationParams=t.createBuffer({label:"secondary-motion-integration-params",size:80,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.collisionSpheres=t.createBuffer({label:"secondary-motion-collision-spheres",size:384,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),this.previousCollisionSpheres=t.createBuffer({label:"secondary-motion-previous-collision-spheres",size:384,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),this.collisionParams=t.createBuffer({label:"secondary-motion-collision-params",size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),t.queue.writeBuffer(this.collisionParams,0,new Uint32Array(4));const r=this.integrationParamsView,d=n.gravity??[0,-9.81,0];r.setFloat32(0,this.fixedStep.step,!0),r.setFloat32(4,Math.max(0,Math.min(1,n.damping??.985)),!0),r.setFloat32(8,Math.max(0,n.attachment??12),!0),r.setFloat32(16,d[0],!0),r.setFloat32(20,d[1],!0),r.setFloat32(24,d[2],!0),r.setFloat32(76,Math.max(1,4*Math.hypot(d[0],d[1],d[2])),!0),t.queue.writeBuffer(this.integrationParams,0,this.integrationParamsData)}setFrameMotion(e){this.writeFrameVector(32,e.linearAcceleration),this.writeFrameVector(48,e.angularVelocity),this.writeFrameVector(64,e.angularAcceleration),this.device.queue.writeBuffer(this.integrationParams,32,this.integrationParamsData,32,48)}setSphereColliders(e){this.setEllipsoidColliders(e.map(e=>({center:e.center,radii:[e.radius,e.radius,e.radius]})))}setEllipsoidColliders(e){const t=Math.min(e.length,8),i=new Float32Array(96);for(let n=0;n<t;n++){const t=e[n],r=12*n;i[r]=t.center[0],i[r+1]=t.center[1],i[r+2]=t.center[2],i[r+4]=Math.max(0,t.radii[0]),i[r+5]=Math.max(0,t.radii[1]),i[r+6]=Math.max(0,t.radii[2]),i[r+8]=t.rotation?.[0]??0,i[r+9]=t.rotation?.[1]??0,i[r+10]=t.rotation?.[2]??0,i[r+11]=t.rotation?.[3]??1}this.collisionCollidersInitialized?this.device.queue.writeBuffer(this.previousCollisionSpheres,0,this.collisionColliderData):(this.device.queue.writeBuffer(this.previousCollisionSpheres,0,i),this.collisionCollidersInitialized=!0),this.collisionColliderData.set(i),this.device.queue.writeBuffer(this.collisionSpheres,0,this.collisionColliderData),this.device.queue.writeBuffer(this.collisionParams,0,new Uint32Array([t,0,0,0]))}advance(e){const t=this.fixedStep.consume(e);return this.pendingSteps=Math.min(this.pendingSteps+t,this.fixedStep.maxSubsteps),t}addRegion(e){if(this.assertActive(),this.regions.has(e.id))throw new Error(`Secondary-motion region "${e.id}" is already registered`);const t=e.particleInverseMass.length,i=e.renderVertexIndices.length;if(e.particlePositions.length!==3*t)throw new Error("Secondary-motion particle positions must contain three values per particle");const o=r(e.particlePositions),s=[this.createStorageBuffer(`${e.id}-positions-a`,o),this.createStorageBuffer(`${e.id}-positions-b`,o)],a=this.createStorageBuffer(`${e.id}-velocities`,new Float32Array(4*t)),c=this.createStorageBuffer(`${e.id}-targets`,e.particlePositions),l=this.createStorageBuffer(`${e.id}-inverse-mass`,e.particleInverseMass),d=this.createStorageBuffer(`${e.id}-render-positions`,new Float32Array(3*i)),u=this.createStorageBuffer(`${e.id}-render-vertex-indices`,e.renderVertexIndices),p=[0,1].map(t=>this.integrationKernel.createBindGroup(this.device,[n(0,s[t]),n(1,a),n(2,s[1-t]),n(3,c),n(4,l),n(5,this.integrationParams)],`${e.id}-integration-${t}`)),f=s.map(e=>this.packKernel.createBindGroup(this.device,[n(0,e),n(1,u),n(2,d)])),h=[0,1].map(e=>this.finalizeKernel.createBindGroup(this.device,[n(0,s[1-e]),n(1,s[e]),n(2,a),n(3,this.integrationParams)])),g=function(e,t){if(0===e.constraints.length)return null;if(e.constraints.length%2!=0)throw new Error("Secondary-motion distance constraints must contain particle pairs");const i=e.constraints.length/2;if(e.constraintRest.length!==i||e.constraintColors.length!==i)throw new Error("Secondary-motion constraint arrays have inconsistent lengths");const n=Array.from({length:i},(e,t)=>t).sort((t,i)=>e.constraintColors[t]-e.constraintColors[i]),r=new Uint32Array(e.constraints.length),o=new Float32Array(i),s=[];let a=-1;for(let c=0;c<i;c++){const i=n[c],l=e.constraintColors[i],d=e.constraints[2*i],u=e.constraints[2*i+1];if(d>=t||u>=t)throw new Error("Secondary-motion constraint references an invalid particle");r[2*c]=d,r[2*c+1]=u,o[c]=e.constraintRest[i],l!==a?(s.push({offset:c,count:1}),a=l):s[s.length-1].count++}return{pairs:r,rest:o,batches:s}}(e,t),m=g?this.createStorageBuffer(`${e.id}-constraints`,g.pairs):null,v=g?this.createStorageBuffer(`${e.id}-constraint-rest`,g.rest):null,y=[];if(g&&m&&v)for(const t of g.batches){const i=this.device.createBuffer({label:`${e.id}-constraint-params`,size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),r=new ArrayBuffer(16),o=new DataView(r);o.setUint32(0,t.offset,!0),o.setUint32(4,t.count,!0),o.setFloat32(8,this.constraintStiffness,!0),this.device.queue.writeBuffer(i,0,r),y.push({count:t.count,params:i,bindGroups:s.map(e=>this.constraintKernel.createBindGroup(this.device,[n(0,e),n(1,l),n(2,m),n(3,v),n(4,i)]))})}const x={id:e.id,particleCount:t,renderVertexCount:i,positions:s,velocities:a,targets:c,inverseMass:l,renderPositions:d,renderVertexIndices:u,integrationBindGroups:p,packBindGroups:f,finalizeBindGroups:h,constraints:m,constraintRest:v,constraintBatches:y,state:0,disposed:!1,renderGeometry:null};this.regions.set(e.id,x);const P=this;return{id:e.id,particleCount:t,renderVertexCount:i,get positionBuffer(){return x.positions[x.state]},setRenderGeometry(e){x.renderGeometry=e},updateTargets(e){P.writeTargets(x.targets,e,t)},reset(t=e.particlePositions){P.resetRegion(x,t)},dispose(){P.removeRegion(x)}}}execute(e){if(this.assertActive(),e.device!==this.device)throw new Error("Secondary-motion runtime was created for a different GPU device");if(this.autoAdvance){const e=.001*performance.now();null!=this.lastExecuteSeconds&&this.advance(e-this.lastExecuteSeconds),this.lastExecuteSeconds=e}const i=this.pendingSteps;if(this.pendingSteps=0,0===this.regions.size)return;const n=e.encoder.beginComputePass({label:"secondary-motion-simulation"});for(let e=0;e<i;e++)for(const e of this.regions.values())if(!e.disposed&&0!==e.particleCount){if(n.setPipeline(this.integrationKernel.pipeline),n.setBindGroup(0,e.integrationBindGroups[e.state]),n.dispatchWorkgroups(Math.ceil(e.particleCount/t)),e.state=0===e.state?1:0,e.constraintBatches.length>0){n.setPipeline(this.constraintKernel.pipeline);for(let i=0;i<this.constraintIterations;i++)for(const i of e.constraintBatches)n.setBindGroup(0,i.bindGroups[e.state]),n.dispatchWorkgroups(Math.ceil(i.count/t))}n.setPipeline(this.finalizeKernel.pipeline),n.setBindGroup(0,e.finalizeBindGroups[e.state]),n.dispatchWorkgroups(Math.ceil(e.particleCount/t)),n.setPipeline(this.collisionKernel.pipeline),n.setBindGroup(0,this.getCollisionBindGroup(e)),n.dispatchWorkgroups(Math.ceil(e.particleCount/t))}for(const e of this.regions.values())e.disposed||0===e.particleCount||null==e.renderGeometry||(n.setPipeline(this.packKernel.pipeline),n.setBindGroup(0,e.packBindGroups[e.state]),n.dispatchWorkgroups(Math.ceil(e.renderVertexCount/t)));n.end();for(const t of this.regions.values())if(!t.disposed&&null!=t.renderGeometry){const i=e.getGeometryVertexBuffer(t.renderGeometry,"position");e.encoder.copyBufferToBuffer(t.renderPositions,0,i,0,12*t.renderVertexCount)}}dispose(){if(!this.disposed){for(const e of Array.from(this.regions.values()))this.removeRegion(e);this.integrationParams.destroy(),this.collisionSpheres.destroy(),this.previousCollisionSpheres.destroy(),this.collisionParams.destroy(),this.collisionBindGroups.clear(),this.disposed=!0}}resetRegion(e,t){this.writeTargets(e.targets,t,e.particleCount);const i=function(e,t){if(e.length!==3*t)throw new Error(`Expected ${3*t} secondary-motion position values, received ${e.length}`);return r(e)}(t,e.particleCount);for(const t of e.positions)this.device.queue.writeBuffer(t,0,i);this.device.queue.writeBuffer(e.velocities,0,new Float32Array(4*e.particleCount)),e.state=0,this.fixedStep.reset(),this.pendingSteps=0}writeTargets(e,t,i){if(t.length!==3*i)throw new Error(`Expected ${3*i} secondary-motion target values, received ${t.length}`);this.device.queue.writeBuffer(e,0,t)}removeRegion(e){if(!e.disposed){e.disposed=!0,this.regions.delete(e.id);for(const t of e.positions)this.collisionBindGroups.delete(t);for(const t of e.positions)t.destroy();e.velocities.destroy(),e.targets.destroy(),e.inverseMass.destroy(),e.renderPositions.destroy(),e.renderVertexIndices.destroy(),e.constraints?.destroy(),e.constraintRest?.destroy();for(const t of e.constraintBatches)t.params.destroy()}}createStorageBuffer(e,t){const i=this.device.createBuffer({label:e,size:Math.max(4,t.byteLength+3&-4),usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC});return t.byteLength>0&&this.device.queue.writeBuffer(i,0,t.buffer,t.byteOffset,t.byteLength),i}getCollisionBindGroup(e){const t=e.positions[e.state];let i=this.collisionBindGroups.get(t);return null==i&&(i=this.collisionKernel.createBindGroup(this.device,[n(0,t),n(1,e.positions[1-e.state]),n(2,e.inverseMass),n(3,this.collisionSpheres),n(4,this.previousCollisionSpheres),n(5,e.velocities),n(6,this.collisionParams)],`${e.id}-sphere-collision-${e.state}`),this.collisionBindGroups.set(t,i)),i}assertActive(){if(this.disposed)throw new Error("Secondary-motion runtime is disposed")}writeFrameVector(e,t){this.integrationParamsView.setFloat32(e,t?.[0]??0,!0),this.integrationParamsView.setFloat32(e+4,t?.[1]??0,!0),this.integrationParamsView.setFloat32(e+8,t?.[2]??0,!0)}}export function createSecondaryMotionRenderGraphExtension(e,t="SecondaryMotionSimulation"){const i=i=>{i.addPass({name:t,execute:t=>e.execute(t)})};return i.stage="beforeScene",i}export class SecondaryMotionFixedStep{constructor(e={}){this.accumulator=0,this.step=1/(e.frequency??60),this.maxSubsteps=e.maxSubsteps??4,this.maxFrameDelta=e.maxFrameDelta??.1}consume(e){if(!Number.isFinite(e)||e<0||e>this.maxFrameDelta)return this.accumulator=0,0;this.accumulator=Math.min(this.accumulator+e,this.step*this.maxSubsteps);const t=Math.min(Math.floor(this.accumulator/this.step),this.maxSubsteps);return this.accumulator-=t*this.step,t}reset(){this.accumulator=0}}export function selectSecondaryMotionLod(e,t,i){return t?i?"hero":e<8?"near":e<20?"mid":e<40?"far":"sleep":"sleep"}export function secondaryMotionTransformDiscontinuous(e,t,i=2,n=.5){if(e.length<7||t.length<7)return!0;const r=t[0]-e[0],o=t[1]-e[1],s=t[2]-e[2];if(r*r+o*o+s*s>i*i)return!0;return Math.abs(e[3]*t[3]+e[4]*t[4]+e[5]*t[5]+e[6]*t[6])<n}function i(e,t){return{binding:e,visibility:GPUShaderStage.COMPUTE,buffer:{type:t?"read-only-storage":"storage"}}}function n(e,t){return{binding:e,resource:{buffer:t}}}function r(e){const t=new Float32Array(e.length/3*4);for(let i=0,n=0;i<e.length;i+=3,n+=4)t[n]=e[i],t[n+1]=e[i+1],t[n+2]=e[i+2],t[n+3]=1;return t}const o="\nstruct IntegrationParams {\n deltaTime: f32,\n damping: f32,\n attachment: f32,\n _padding: f32,\n gravity: vec3<f32>,\n _padding2: f32,\n frameLinearAcceleration: vec3<f32>,\n _padding3: f32,\n frameAngularVelocity: vec3<f32>,\n _padding4: f32,\n frameAngularAcceleration: vec3<f32>,\n maxFrameAcceleration: f32,\n}\n@group(0) @binding(0) var<storage, read> currentPositions: array<vec4<f32>>;\n@group(0) @binding(1) var<storage, read_write> velocities: array<vec4<f32>>;\n@group(0) @binding(2) var<storage, read_write> outputPositions: array<vec4<f32>>;\nstruct PackedPosition { x: f32, y: f32, z: f32 }\n@group(0) @binding(3) var<storage, read> targetPositions: array<PackedPosition>;\n@group(0) @binding(4) var<storage, read> inverseMass: array<f32>;\n@group(0) @binding(5) var<uniform> params: IntegrationParams;\n\n@compute @workgroup_size(64)\nfn main(@builtin(global_invocation_id) invocation: vec3<u32>) {\n let index = invocation.x;\n if (index >= arrayLength(&inverseMass)) { return; }\n let packedTarget = targetPositions[index];\n let targetPosition = vec3<f32>(packedTarget.x, packedTarget.y, packedTarget.z);\n if (inverseMass[index] <= 0.0) {\n velocities[index] = vec4(0.0);\n outputPositions[index] = vec4(targetPosition, 1.0);\n return;\n }\n let current = currentPositions[index].xyz;\n // Fully simulated cloth should be driven through its structural connection\n // to the animated roots. Pulling every free particle toward its skinned rest\n // pose makes collision sandwich it against the character like shrink-wrap.\n let animationInfluence = 1.0 - clamp(inverseMass[index], 0.0, 1.0);\n let targetAcceleration = (targetPosition - current) * params.attachment * animationInfluence;\n let previousVelocity = velocities[index].xyz;\n let rotationalAcceleration =\n cross(params.frameAngularAcceleration, current) +\n cross(params.frameAngularVelocity, cross(params.frameAngularVelocity, current)) +\n 2.0 * cross(params.frameAngularVelocity, previousVelocity);\n var frameAcceleration = params.frameLinearAcceleration + rotationalAcceleration;\n let frameAccelerationLength = length(frameAcceleration);\n if (frameAccelerationLength > params.maxFrameAcceleration) {\n frameAcceleration *= params.maxFrameAcceleration / frameAccelerationLength;\n }\n let acceleration = params.gravity + targetAcceleration - frameAcceleration;\n let velocity = previousVelocity * params.damping + acceleration * params.deltaTime;\n let next = current + velocity * params.deltaTime;\n velocities[index] = vec4(velocity, 0.0);\n outputPositions[index] = vec4(next, 1.0);\n}\n",s="\nstruct ConstraintParams {\n offset: u32,\n count: u32,\n stiffness: f32,\n _padding: f32,\n}\n@group(0) @binding(0) var<storage, read_write> positions: array<vec4<f32>>;\n@group(0) @binding(1) var<storage, read> inverseMass: array<f32>;\n@group(0) @binding(2) var<storage, read> pairs: array<vec2<u32>>;\n@group(0) @binding(3) var<storage, read> restLengths: array<f32>;\n@group(0) @binding(4) var<uniform> params: ConstraintParams;\n\n@compute @workgroup_size(64)\nfn main(@builtin(global_invocation_id) invocation: vec3<u32>) {\n if (invocation.x >= params.count) { return; }\n let constraintIndex = params.offset + invocation.x;\n let pair = pairs[constraintIndex];\n let weightA = inverseMass[pair.x];\n let weightB = inverseMass[pair.y];\n let weight = weightA + weightB;\n if (weight <= 0.0) { return; }\n let delta = positions[pair.y].xyz - positions[pair.x].xyz;\n let length = length(delta);\n if (length <= 0.000001) { return; }\n let correction = delta * ((length - restLengths[constraintIndex]) / length) * params.stiffness;\n positions[pair.x] = vec4(positions[pair.x].xyz + correction * (weightA / weight), 1.0);\n positions[pair.y] = vec4(positions[pair.y].xyz - correction * (weightB / weight), 1.0);\n}\n",a="\nstruct PackedPosition { x: f32, y: f32, z: f32 }\n@group(0) @binding(0) var<storage, read> positions: array<vec4<f32>>;\n@group(0) @binding(1) var<storage, read> particleByRenderVertex: array<u32>;\n@group(0) @binding(2) var<storage, read_write> output: array<PackedPosition>;\n\n@compute @workgroup_size(64)\nfn main(@builtin(global_invocation_id) invocation: vec3<u32>) {\n let index = invocation.x;\n if (index >= arrayLength(&particleByRenderVertex)) { return; }\n let position = positions[particleByRenderVertex[index]];\n output[index].x = position.x; output[index].y = position.y; output[index].z = position.z;\n}\n",c="\nstruct CollisionParams { count: u32, _padding1: u32, _padding2: u32, _padding3: u32 }\n@group(0) @binding(0) var<storage, read_write> positions: array<vec4<f32>>;\nstruct Ellipsoid { center: vec4<f32>, radii: vec4<f32>, rotation: vec4<f32> }\n@group(0) @binding(1) var<storage, read> previousPositions: array<vec4<f32>>;\n@group(0) @binding(2) var<storage, read> inverseMass: array<f32>;\n@group(0) @binding(3) var<storage, read> ellipsoids: array<Ellipsoid>;\n@group(0) @binding(4) var<storage, read> previousEllipsoids: array<Ellipsoid>;\n@group(0) @binding(5) var<storage, read_write> velocities: array<vec4<f32>>;\n@group(0) @binding(6) var<uniform> params: CollisionParams;\n\nfn rotateByQuaternion(value: vec3<f32>, rotation: vec4<f32>) -> vec3<f32> {\n return value + 2.0 * cross(rotation.xyz, cross(rotation.xyz, value) + rotation.w * value);\n}\n\nfn toEllipsoidSpace(value: vec3<f32>, shape: Ellipsoid) -> vec3<f32> {\n return rotateByQuaternion(value - shape.center.xyz, vec4<f32>(-shape.rotation.xyz, shape.rotation.w)) / shape.radii.xyz;\n}\n\nfn fromEllipsoidSpace(value: vec3<f32>, shape: Ellipsoid) -> vec3<f32> {\n return shape.center.xyz + rotateByQuaternion(value * shape.radii.xyz, shape.rotation);\n}\n\n@compute @workgroup_size(64)\nfn main(@builtin(global_invocation_id) invocation: vec3<u32>) {\n let index = invocation.x;\n if (index >= arrayLength(&inverseMass) || inverseMass[index] <= 0.0) { return; }\n var position = positions[index].xyz;\n var velocity = velocities[index].xyz;\n for (var collider = 0u; collider < params.count; collider++) {\n let shape = ellipsoids[collider];\n if (all(shape.radii.xyz > vec3<f32>(0.0))) {\n let scaled = toEllipsoidSpace(position, shape);\n let scaledLengthSquared = dot(scaled, scaled);\n if (scaledLengthSquared < 1.0) {\n let direction = select(vec3<f32>(0.0, 0.0, 1.0), scaled * inverseSqrt(scaledLengthSquared), scaledLengthSquared > 0.00000001);\n position = fromEllipsoidSpace(direction * 1.02, shape);\n let normal = normalize(rotateByQuaternion(direction / shape.radii.xyz, shape.rotation));\n velocity -= normal * min(dot(velocity, normal), 0.0);\n } else {\n let previousShape = previousEllipsoids[collider];\n let start = toEllipsoidSpace(previousPositions[index].xyz, previousShape);\n let travel = scaled - start;\n let a = dot(travel, travel);\n let b = 2.0 * dot(start, travel);\n let c = dot(start, start) - 1.0;\n let discriminant = b * b - 4.0 * a * c;\n if (a > 0.00000001 && discriminant >= 0.0) {\n let hit = (-b - sqrt(discriminant)) / (2.0 * a);\n if (hit > 0.0001 && hit <= 1.0) {\n let direction = normalize(start + travel * hit);\n position = fromEllipsoidSpace(direction * 1.02, shape);\n let normal = normalize(rotateByQuaternion(direction / shape.radii.xyz, shape.rotation));\n velocity -= normal * min(dot(velocity, normal), 0.0);\n }\n }\n }\n }\n }\n positions[index] = vec4(position, 1.0);\n velocities[index] = vec4(velocity, 0.0);\n}\n",l="\nstruct IntegrationParams {\n deltaTime: f32,\n damping: f32,\n attachment: f32,\n _padding: f32,\n gravity: vec3<f32>,\n _padding2: f32,\n}\n@group(0) @binding(0) var<storage, read> previousPositions: array<vec4<f32>>;\n@group(0) @binding(1) var<storage, read> constrainedPositions: array<vec4<f32>>;\n@group(0) @binding(2) var<storage, read_write> velocities: array<vec4<f32>>;\n@group(0) @binding(3) var<uniform> params: IntegrationParams;\n\n@compute @workgroup_size(64)\nfn main(@builtin(global_invocation_id) invocation: vec3<u32>) {\n let index = invocation.x;\n if (index >= arrayLength(&velocities)) { return; }\n velocities[index] = vec4(\n (constrainedPositions[index].xyz - previousPositions[index].xyz) / params.deltaTime,\n 0.0,\n );\n}\n";/*
|
|
1
|
+
import{createWebGpuComputeKernel as e}from"../rendering/webgpu-runtime-bridge.js";import{isSharedClothRegionData as t}from"./cache.js";import{createSkinningTargetKernels as i,SkinnedSecondaryMotionTargets as n}from"./skinned-targets.js";const r=64,s=new WeakMap;export function prepareSecondaryMotionRuntime(e){o(e),i(e)}function o(t){const i=s.get(t);if(i)return i;const n={integration:e(t,{label:"secondary-motion-integrate",code:u,bindGroupLayoutEntries:[a(0,!0),a(1,!1),a(2,!1),a(3,!0),a(4,!0),{binding:5,visibility:GPUShaderStage.COMPUTE,buffer:{type:"uniform"}}]}),constraint:e(t,{label:"secondary-motion-distance-constraints",code:p,bindGroupLayoutEntries:[a(0,!1),a(1,!0),a(2,!0),a(3,!0),{binding:4,visibility:GPUShaderStage.COMPUTE,buffer:{type:"uniform"}}]}),pack:e(t,{label:"secondary-motion-pack-render-positions",code:g,bindGroupLayoutEntries:[a(0,!0),a(1,!0),a(2,!1)]}),finalize:e(t,{label:"secondary-motion-finalize-velocity",code:f,bindGroupLayoutEntries:[a(0,!0),a(1,!0),a(2,!1),{binding:3,visibility:GPUShaderStage.COMPUTE,buffer:{type:"uniform"}}]}),collision:e(t,{label:"secondary-motion-sphere-collision",code:h,bindGroupLayoutEntries:[a(0,!1),a(1,!0),a(2,!0),a(3,!0),a(4,!0),a(5,!1),{binding:6,visibility:GPUShaderStage.COMPUTE,buffer:{type:"uniform"}}]})};return s.set(t,n),n}export class WebGpuSecondaryMotionRuntime{constructor(e,t={}){this.device=e,this.collisionColliderData=new Float32Array(96),this.collisionNextData=new Float32Array(96),this.collisionCountData=new Uint32Array(4),this.collisionCollidersInitialized=!1,this.collisionBindGroups=new Map,this.integrationParamsData=new ArrayBuffer(80),this.integrationParamsView=new DataView(this.integrationParamsData),this.regions=new Map,this.pendingSteps=0,this.disposed=!1,this._enabled=!0,this.lastExecuteSeconds=null,this.skinningTargetKernels=null,this.fixedStep=new SecondaryMotionFixedStep(t),this.constraintIterations=Math.max(0,Math.trunc(t.constraintIterations??4)),this.constraintStiffness=Math.max(0,Math.min(1,t.constraintStiffness??.9)),this.autoAdvance=t.autoAdvance??!0;const i=o(e);this.integrationKernel=i.integration,this.constraintKernel=i.constraint,this.packKernel=i.pack,this.finalizeKernel=i.finalize,this.collisionKernel=i.collision,this.integrationParams=e.createBuffer({label:"secondary-motion-integration-params",size:80,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.collisionSpheres=e.createBuffer({label:"secondary-motion-collision-spheres",size:384,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),this.previousCollisionSpheres=e.createBuffer({label:"secondary-motion-previous-collision-spheres",size:384,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),this.collisionParams=e.createBuffer({label:"secondary-motion-collision-params",size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),e.queue.writeBuffer(this.collisionParams,0,new Uint32Array(4));const n=this.integrationParamsView,r=t.gravity??[0,-9.81,0];n.setFloat32(0,this.fixedStep.step,!0),n.setFloat32(4,Math.max(0,Math.min(1,t.damping??.985)),!0),n.setFloat32(8,Math.max(0,t.attachment??12),!0),n.setFloat32(16,r[0],!0),n.setFloat32(20,r[1],!0),n.setFloat32(24,r[2],!0),n.setFloat32(76,Math.max(1,4*Math.hypot(r[0],r[1],r[2])),!0),e.queue.writeBuffer(this.integrationParams,0,this.integrationParamsData)}get enabled(){return this._enabled}setEnabled(e){if(this._enabled!==e&&(this._enabled=e,this.pendingSteps=0,this.fixedStep.reset(),this.lastExecuteSeconds=null,this.collisionCollidersInitialized=!1,e))for(const e of this.regions.values())e.skinningTargets?.requestReset(),e.state=0}setFrameMotion(e){this.writeFrameVector(32,e.linearAcceleration),this.writeFrameVector(48,e.angularVelocity),this.writeFrameVector(64,e.angularAcceleration),this.device.queue.writeBuffer(this.integrationParams,32,this.integrationParamsData,32,48)}setSphereColliders(e){this.setEllipsoidColliders(e.map(e=>({center:e.center,radii:[e.radius,e.radius,e.radius]})))}setEllipsoidColliders(e){const t=Math.min(e.length,8),i=this.collisionNextData;i.fill(0);for(let n=0;n<t;n++){const t=e[n],r=12*n;i[r]=t.center[0],i[r+1]=t.center[1],i[r+2]=t.center[2],i[r+4]=Math.max(0,t.radii[0]),i[r+5]=Math.max(0,t.radii[1]),i[r+6]=Math.max(0,t.radii[2]),i[r+8]=t.rotation?.[0]??0,i[r+9]=t.rotation?.[1]??0,i[r+10]=t.rotation?.[2]??0,i[r+11]=t.rotation?.[3]??1}this.collisionCollidersInitialized?this.device.queue.writeBuffer(this.previousCollisionSpheres,0,this.collisionColliderData):(this.device.queue.writeBuffer(this.previousCollisionSpheres,0,i),this.collisionCollidersInitialized=!0),this.collisionColliderData.set(i),this.device.queue.writeBuffer(this.collisionSpheres,0,this.collisionColliderData),this.collisionCountData[0]=t,this.device.queue.writeBuffer(this.collisionParams,0,this.collisionCountData)}advance(e){const t=this.fixedStep.consume(e);return this.pendingSteps=Math.min(this.pendingSteps+t,this.fixedStep.maxSubsteps),t}addRegion(e){if(this.assertActive(),this.regions.has(e.id))throw new Error(`Secondary-motion region "${e.id}" is already registered`);const r=e.particleInverseMass.length,s=e.renderVertexIndices.length;if(e.particlePositions.length!==3*r)throw new Error("Secondary-motion particle positions must contain three values per particle");const o=l(e.particlePositions),a=[this.createStorageBuffer(`${e.id}-positions-a`,o),this.createStorageBuffer(`${e.id}-positions-b`,o)],u=this.createStorageBuffer(`${e.id}-velocities`,new Float32Array(4*r)),p=this.createStorageBuffer(`${e.id}-targets`,e.particlePositions),g=this.createStorageBuffer(`${e.id}-inverse-mass`,e.particleInverseMass),h=this.createStorageBuffer(`${e.id}-render-positions`,new Float32Array(3*s)),f=this.createStorageBuffer(`${e.id}-render-vertex-indices`,e.renderVertexIndices),m=[0,1].map(t=>this.integrationKernel.createBindGroup(this.device,[c(0,a[t]),c(1,u),c(2,a[1-t]),c(3,p),c(4,g),c(5,this.integrationParams)],`${e.id}-integration-${t}`)),v=a.map(e=>this.packKernel.createBindGroup(this.device,[c(0,e),c(1,f),c(2,h)])),y=[0,1].map(e=>this.finalizeKernel.createBindGroup(this.device,[c(0,a[1-e]),c(1,a[e]),c(2,u),c(3,this.integrationParams)])),x=function(e,i){if(0===e.constraints.length)return null;const n=t(e),r=n?d.get(e):null;if(r)return r;if(e.constraints.length%2!=0)throw new Error("Secondary-motion distance constraints must contain particle pairs");const s=e.constraints.length/2;if(e.constraintRest.length!==s||e.constraintColors.length!==s)throw new Error("Secondary-motion constraint arrays have inconsistent lengths");const o=Array.from({length:s},(e,t)=>t).sort((t,i)=>e.constraintColors[t]-e.constraintColors[i]),a=new Uint32Array(e.constraints.length),c=new Float32Array(s),l=[];let u=-1;for(let t=0;t<s;t++){const n=o[t],r=e.constraintColors[n],s=e.constraints[2*n],d=e.constraints[2*n+1];if(s>=i||d>=i)throw new Error("Secondary-motion constraint references an invalid particle");a[2*t]=s,a[2*t+1]=d,c[t]=e.constraintRest[n],r!==u?(l.push({offset:t,count:1}),u=r):l[l.length-1].count++}const p={pairs:a,rest:c,batches:l};n&&d.set(e,p);return p}(e,r),b=x?this.createStorageBuffer(`${e.id}-constraints`,x.pairs):null,S=x?this.createStorageBuffer(`${e.id}-constraint-rest`,x.rest):null,w=[];if(x&&b&&S)for(const t of x.batches){const i=this.device.createBuffer({label:`${e.id}-constraint-params`,size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),n=new ArrayBuffer(16),r=new DataView(n);r.setUint32(0,t.offset,!0),r.setUint32(4,t.count,!0),r.setFloat32(8,this.constraintStiffness,!0),this.device.queue.writeBuffer(i,0,n),w.push({count:t.count,params:i,bindGroups:a.map(e=>this.constraintKernel.createBindGroup(this.device,[c(0,e),c(1,g),c(2,b),c(3,S),c(4,i)]))})}const P={id:e.id,particleCount:r,renderVertexCount:s,positions:a,velocities:u,targets:p,inverseMass:g,renderPositions:h,renderVertexIndices:f,integrationBindGroups:m,packBindGroups:v,finalizeBindGroups:y,constraints:b,constraintRest:S,constraintBatches:w,state:0,disposed:!1,renderGeometry:null,skinningTargets:null,resetThisFrame:!1};this.regions.set(e.id,P);const B=this;return{id:e.id,particleCount:r,renderVertexCount:s,get positionBuffer(){return P.positions[P.state]},setRenderGeometry(e){P.renderGeometry=e},updateTargets(e){B.writeTargets(P.targets,e,r)},setSkinningTargets(e){if(B.assertActive(),P.disposed)throw new Error("Secondary-motion region is disposed");const t=B.skinningTargetKernels??(B.skinningTargetKernels=i(B.device)),s=new n(B.device,e,t,P.targets,P.positions,P.velocities,r);P.skinningTargets?.dispose(),P.skinningTargets=s},resetToSkinningTargets(){if(B.assertActive(),P.disposed||!P.skinningTargets)throw new Error("Secondary-motion region has no skinning targets");P.skinningTargets.requestReset(),P.state=0,B.fixedStep.reset(),B.pendingSteps=0},reset(t=e.particlePositions){B.resetRegion(P,t)},dispose(){B.removeRegion(P)}}}execute(e){if(this.assertActive(),!this._enabled)return;if(e.device!==this.device)throw new Error("Secondary-motion runtime was created for a different GPU device");if(this.autoAdvance){const e=.001*performance.now();null!=this.lastExecuteSeconds&&this.advance(e-this.lastExecuteSeconds),this.lastExecuteSeconds=e}const t=this.pendingSteps;if(this.pendingSteps=0,0===this.regions.size)return;const i=e.encoder.beginComputePass({label:"secondary-motion-simulation"});for(const t of this.regions.values())t.resetThisFrame=!1,!t.disposed&&t.particleCount>0&&(t.resetThisFrame=t.skinningTargets?.execute(e,i)??!1);for(let e=0;e<t;e++)for(const e of this.regions.values())if(!e.disposed&&0!==e.particleCount&&!e.resetThisFrame){if(i.setPipeline(this.integrationKernel.pipeline),i.setBindGroup(0,e.integrationBindGroups[e.state]),i.dispatchWorkgroups(Math.ceil(e.particleCount/r)),e.state=0===e.state?1:0,e.constraintBatches.length>0){i.setPipeline(this.constraintKernel.pipeline);for(let t=0;t<this.constraintIterations;t++)for(const t of e.constraintBatches)i.setBindGroup(0,t.bindGroups[e.state]),i.dispatchWorkgroups(Math.ceil(t.count/r))}i.setPipeline(this.finalizeKernel.pipeline),i.setBindGroup(0,e.finalizeBindGroups[e.state]),i.dispatchWorkgroups(Math.ceil(e.particleCount/r)),i.setPipeline(this.collisionKernel.pipeline),i.setBindGroup(0,this.getCollisionBindGroup(e)),i.dispatchWorkgroups(Math.ceil(e.particleCount/r))}for(const e of this.regions.values())e.disposed||0===e.particleCount||null==e.renderGeometry||(i.setPipeline(this.packKernel.pipeline),i.setBindGroup(0,e.packBindGroups[e.state]),i.dispatchWorkgroups(Math.ceil(e.renderVertexCount/r)));i.end();for(const t of this.regions.values())if(!t.disposed&&null!=t.renderGeometry){const i=e.getGeometryVertexBuffer(t.renderGeometry,"position");e.encoder.copyBufferToBuffer(t.renderPositions,0,i,0,12*t.renderVertexCount)}}dispose(){if(!this.disposed){for(const e of Array.from(this.regions.values()))this.removeRegion(e);this.integrationParams.destroy(),this.collisionSpheres.destroy(),this.previousCollisionSpheres.destroy(),this.collisionParams.destroy(),this.collisionBindGroups.clear(),this.disposed=!0}}resetRegion(e,t){this.writeTargets(e.targets,t,e.particleCount);const i=function(e,t){if(e.length!==3*t)throw new Error(`Expected ${3*t} secondary-motion position values, received ${e.length}`);return l(e)}(t,e.particleCount);for(const t of e.positions)this.device.queue.writeBuffer(t,0,i);this.device.queue.writeBuffer(e.velocities,0,new Float32Array(4*e.particleCount)),e.state=0,this.fixedStep.reset(),this.pendingSteps=0}writeTargets(e,t,i){if(t.length!==3*i)throw new Error(`Expected ${3*i} secondary-motion target values, received ${t.length}`);this.device.queue.writeBuffer(e,0,t)}removeRegion(e){if(!e.disposed){e.disposed=!0,this.regions.delete(e.id),e.skinningTargets?.dispose();for(const t of e.positions)this.collisionBindGroups.delete(t);for(const t of e.positions)t.destroy();e.velocities.destroy(),e.targets.destroy(),e.inverseMass.destroy(),e.renderPositions.destroy(),e.renderVertexIndices.destroy(),e.constraints?.destroy(),e.constraintRest?.destroy();for(const t of e.constraintBatches)t.params.destroy()}}createStorageBuffer(e,t){const i=this.device.createBuffer({label:e,size:Math.max(4,t.byteLength+3&-4),usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC});return t.byteLength>0&&this.device.queue.writeBuffer(i,0,t.buffer,t.byteOffset,t.byteLength),i}getCollisionBindGroup(e){const t=e.positions[e.state];let i=this.collisionBindGroups.get(t);return null==i&&(i=this.collisionKernel.createBindGroup(this.device,[c(0,t),c(1,e.positions[1-e.state]),c(2,e.inverseMass),c(3,this.collisionSpheres),c(4,this.previousCollisionSpheres),c(5,e.velocities),c(6,this.collisionParams)],`${e.id}-sphere-collision-${e.state}`),this.collisionBindGroups.set(t,i)),i}assertActive(){if(this.disposed)throw new Error("Secondary-motion runtime is disposed")}writeFrameVector(e,t){this.integrationParamsView.setFloat32(e,t?.[0]??0,!0),this.integrationParamsView.setFloat32(e+4,t?.[1]??0,!0),this.integrationParamsView.setFloat32(e+8,t?.[2]??0,!0)}}export function createSecondaryMotionRenderGraphExtension(e,t="SecondaryMotionSimulation"){const i=i=>{!1!==e.enabled&&i.addPass({name:t,execute:t=>e.execute(t)})};return i.stage="beforeScene",i}export class SecondaryMotionFixedStep{constructor(e={}){this.accumulator=0,this.step=1/(e.frequency??60),this.maxSubsteps=e.maxSubsteps??4,this.maxFrameDelta=e.maxFrameDelta??.1}consume(e){if(!Number.isFinite(e)||e<0||e>this.maxFrameDelta)return this.accumulator=0,0;this.accumulator=Math.min(this.accumulator+e,this.step*this.maxSubsteps);const t=Math.min(Math.floor(this.accumulator/this.step),this.maxSubsteps);return this.accumulator-=t*this.step,t}reset(){this.accumulator=0}}export function selectSecondaryMotionLod(e,t,i){return t?i?"hero":e<8?"near":e<20?"mid":e<40?"far":"sleep":"sleep"}export function secondaryMotionTransformDiscontinuous(e,t,i=2,n=.5){if(e.length<7||t.length<7)return!0;const r=t[0]-e[0],s=t[1]-e[1],o=t[2]-e[2];if(r*r+s*s+o*o>i*i)return!0;return Math.abs(e[3]*t[3]+e[4]*t[4]+e[5]*t[5]+e[6]*t[6])<n}function a(e,t){return{binding:e,visibility:GPUShaderStage.COMPUTE,buffer:{type:t?"read-only-storage":"storage"}}}function c(e,t){return{binding:e,resource:{buffer:t}}}function l(e){const t=new Float32Array(e.length/3*4);for(let i=0,n=0;i<e.length;i+=3,n+=4)t[n]=e[i],t[n+1]=e[i+1],t[n+2]=e[i+2],t[n+3]=1;return t}const d=new WeakMap;const u="\nstruct IntegrationParams {\n deltaTime: f32,\n damping: f32,\n attachment: f32,\n _padding: f32,\n gravity: vec3<f32>,\n _padding2: f32,\n frameLinearAcceleration: vec3<f32>,\n _padding3: f32,\n frameAngularVelocity: vec3<f32>,\n _padding4: f32,\n frameAngularAcceleration: vec3<f32>,\n maxFrameAcceleration: f32,\n}\n@group(0) @binding(0) var<storage, read> currentPositions: array<vec4<f32>>;\n@group(0) @binding(1) var<storage, read_write> velocities: array<vec4<f32>>;\n@group(0) @binding(2) var<storage, read_write> outputPositions: array<vec4<f32>>;\nstruct PackedPosition { x: f32, y: f32, z: f32 }\n@group(0) @binding(3) var<storage, read> targetPositions: array<PackedPosition>;\n@group(0) @binding(4) var<storage, read> inverseMass: array<f32>;\n@group(0) @binding(5) var<uniform> params: IntegrationParams;\n\n@compute @workgroup_size(64)\nfn main(@builtin(global_invocation_id) invocation: vec3<u32>) {\n let index = invocation.x;\n if (index >= arrayLength(&inverseMass)) { return; }\n let packedTarget = targetPositions[index];\n let targetPosition = vec3<f32>(packedTarget.x, packedTarget.y, packedTarget.z);\n if (inverseMass[index] <= 0.0) {\n velocities[index] = vec4(0.0);\n outputPositions[index] = vec4(targetPosition, 1.0);\n return;\n }\n let current = currentPositions[index].xyz;\n // Fully simulated cloth should be driven through its structural connection\n // to the animated roots. Pulling every free particle toward its skinned rest\n // pose makes collision sandwich it against the character like shrink-wrap.\n let animationInfluence = 1.0 - clamp(inverseMass[index], 0.0, 1.0);\n let targetAcceleration = (targetPosition - current) * params.attachment * animationInfluence;\n let previousVelocity = velocities[index].xyz;\n let rotationalAcceleration =\n cross(params.frameAngularAcceleration, current) +\n cross(params.frameAngularVelocity, cross(params.frameAngularVelocity, current)) +\n 2.0 * cross(params.frameAngularVelocity, previousVelocity);\n var frameAcceleration = params.frameLinearAcceleration + rotationalAcceleration;\n let frameAccelerationLength = length(frameAcceleration);\n if (frameAccelerationLength > params.maxFrameAcceleration) {\n frameAcceleration *= params.maxFrameAcceleration / frameAccelerationLength;\n }\n let acceleration = params.gravity + targetAcceleration - frameAcceleration;\n let velocity = previousVelocity * params.damping + acceleration * params.deltaTime;\n let next = current + velocity * params.deltaTime;\n velocities[index] = vec4(velocity, 0.0);\n outputPositions[index] = vec4(next, 1.0);\n}\n",p="\nstruct ConstraintParams {\n offset: u32,\n count: u32,\n stiffness: f32,\n _padding: f32,\n}\n@group(0) @binding(0) var<storage, read_write> positions: array<vec4<f32>>;\n@group(0) @binding(1) var<storage, read> inverseMass: array<f32>;\n@group(0) @binding(2) var<storage, read> pairs: array<vec2<u32>>;\n@group(0) @binding(3) var<storage, read> restLengths: array<f32>;\n@group(0) @binding(4) var<uniform> params: ConstraintParams;\n\n@compute @workgroup_size(64)\nfn main(@builtin(global_invocation_id) invocation: vec3<u32>) {\n if (invocation.x >= params.count) { return; }\n let constraintIndex = params.offset + invocation.x;\n let pair = pairs[constraintIndex];\n let weightA = inverseMass[pair.x];\n let weightB = inverseMass[pair.y];\n let weight = weightA + weightB;\n if (weight <= 0.0) { return; }\n let delta = positions[pair.y].xyz - positions[pair.x].xyz;\n let length = length(delta);\n if (length <= 0.000001) { return; }\n let correction = delta * ((length - restLengths[constraintIndex]) / length) * params.stiffness;\n positions[pair.x] = vec4(positions[pair.x].xyz + correction * (weightA / weight), 1.0);\n positions[pair.y] = vec4(positions[pair.y].xyz - correction * (weightB / weight), 1.0);\n}\n",g="\nstruct PackedPosition { x: f32, y: f32, z: f32 }\n@group(0) @binding(0) var<storage, read> positions: array<vec4<f32>>;\n@group(0) @binding(1) var<storage, read> particleByRenderVertex: array<u32>;\n@group(0) @binding(2) var<storage, read_write> output: array<PackedPosition>;\n\n@compute @workgroup_size(64)\nfn main(@builtin(global_invocation_id) invocation: vec3<u32>) {\n let index = invocation.x;\n if (index >= arrayLength(&particleByRenderVertex)) { return; }\n let position = positions[particleByRenderVertex[index]];\n output[index].x = position.x; output[index].y = position.y; output[index].z = position.z;\n}\n",h="\nstruct CollisionParams { count: u32, _padding1: u32, _padding2: u32, _padding3: u32 }\n@group(0) @binding(0) var<storage, read_write> positions: array<vec4<f32>>;\nstruct Ellipsoid { center: vec4<f32>, radii: vec4<f32>, rotation: vec4<f32> }\n@group(0) @binding(1) var<storage, read> previousPositions: array<vec4<f32>>;\n@group(0) @binding(2) var<storage, read> inverseMass: array<f32>;\n@group(0) @binding(3) var<storage, read> ellipsoids: array<Ellipsoid>;\n@group(0) @binding(4) var<storage, read> previousEllipsoids: array<Ellipsoid>;\n@group(0) @binding(5) var<storage, read_write> velocities: array<vec4<f32>>;\n@group(0) @binding(6) var<uniform> params: CollisionParams;\n\nfn rotateByQuaternion(value: vec3<f32>, rotation: vec4<f32>) -> vec3<f32> {\n return value + 2.0 * cross(rotation.xyz, cross(rotation.xyz, value) + rotation.w * value);\n}\n\nfn toEllipsoidSpace(value: vec3<f32>, shape: Ellipsoid) -> vec3<f32> {\n return rotateByQuaternion(value - shape.center.xyz, vec4<f32>(-shape.rotation.xyz, shape.rotation.w)) / shape.radii.xyz;\n}\n\nfn fromEllipsoidSpace(value: vec3<f32>, shape: Ellipsoid) -> vec3<f32> {\n return shape.center.xyz + rotateByQuaternion(value * shape.radii.xyz, shape.rotation);\n}\n\n@compute @workgroup_size(64)\nfn main(@builtin(global_invocation_id) invocation: vec3<u32>) {\n let index = invocation.x;\n if (index >= arrayLength(&inverseMass) || inverseMass[index] <= 0.0) { return; }\n var position = positions[index].xyz;\n var velocity = velocities[index].xyz;\n for (var collider = 0u; collider < params.count; collider++) {\n let shape = ellipsoids[collider];\n if (all(shape.radii.xyz > vec3<f32>(0.0))) {\n let scaled = toEllipsoidSpace(position, shape);\n let scaledLengthSquared = dot(scaled, scaled);\n if (scaledLengthSquared < 1.0) {\n let direction = select(vec3<f32>(0.0, 0.0, 1.0), scaled * inverseSqrt(scaledLengthSquared), scaledLengthSquared > 0.00000001);\n position = fromEllipsoidSpace(direction * 1.02, shape);\n let normal = normalize(rotateByQuaternion(direction / shape.radii.xyz, shape.rotation));\n velocity -= normal * min(dot(velocity, normal), 0.0);\n } else {\n let previousShape = previousEllipsoids[collider];\n let start = toEllipsoidSpace(previousPositions[index].xyz, previousShape);\n let travel = scaled - start;\n let a = dot(travel, travel);\n let b = 2.0 * dot(start, travel);\n let c = dot(start, start) - 1.0;\n let discriminant = b * b - 4.0 * a * c;\n if (a > 0.00000001 && discriminant >= 0.0) {\n let hit = (-b - sqrt(discriminant)) / (2.0 * a);\n if (hit > 0.0001 && hit <= 1.0) {\n let direction = normalize(start + travel * hit);\n position = fromEllipsoidSpace(direction * 1.02, shape);\n let normal = normalize(rotateByQuaternion(direction / shape.radii.xyz, shape.rotation));\n velocity -= normal * min(dot(velocity, normal), 0.0);\n }\n }\n }\n }\n }\n positions[index] = vec4(position, 1.0);\n velocities[index] = vec4(velocity, 0.0);\n}\n",f="\nstruct IntegrationParams {\n deltaTime: f32,\n damping: f32,\n attachment: f32,\n _padding: f32,\n gravity: vec3<f32>,\n _padding2: f32,\n}\n@group(0) @binding(0) var<storage, read> previousPositions: array<vec4<f32>>;\n@group(0) @binding(1) var<storage, read> constrainedPositions: array<vec4<f32>>;\n@group(0) @binding(2) var<storage, read_write> velocities: array<vec4<f32>>;\n@group(0) @binding(3) var<uniform> params: IntegrationParams;\n\n@compute @workgroup_size(64)\nfn main(@builtin(global_invocation_id) invocation: vec3<u32>) {\n let index = invocation.x;\n if (index >= arrayLength(&velocities)) { return; }\n velocities[index] = vec4(\n (constrainedPositions[index].xyz - previousPositions[index].xyz) / params.deltaTime,\n 0.0,\n );\n}\n";/*
|
|
2
2
|
* Copyright (©) 2026 Hology Interactive AB. All rights reserved.
|
|
3
3
|
* See the LICENSE.md file for details.
|
|
4
4
|
*/
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { type SkinnedMesh } from 'three';
|
|
2
|
+
import type { RendererCustomPassContext } from '@hology/webgpu-renderer';
|
|
3
|
+
import { type WebGpuComputeKernel } from '../rendering/webgpu-runtime-bridge.js';
|
|
4
|
+
export interface SecondaryMotionSkinningTargets {
|
|
5
|
+
readonly mesh: SkinnedMesh;
|
|
6
|
+
readonly bindPositions: Float32Array;
|
|
7
|
+
readonly skinIndices: Uint16Array | Uint32Array;
|
|
8
|
+
readonly skinWeights: Float32Array;
|
|
9
|
+
/** Includes movable particles and pinned particles touched by constraints. */
|
|
10
|
+
readonly activeParticles: Uint32Array;
|
|
11
|
+
}
|
|
12
|
+
export declare function createSkinningTargetKernels(device: GPUDevice): readonly [WebGpuComputeKernel, WebGpuComputeKernel];
|
|
13
|
+
/** Persistent particle inputs; pose matrices come from the renderer's shared palette. */
|
|
14
|
+
export declare class SkinnedSecondaryMotionTargets {
|
|
15
|
+
private readonly device;
|
|
16
|
+
private readonly source;
|
|
17
|
+
private readonly kernels;
|
|
18
|
+
private readonly targets;
|
|
19
|
+
private readonly buffers;
|
|
20
|
+
private readonly uniformData;
|
|
21
|
+
private readonly inverseWorld;
|
|
22
|
+
private readonly uniforms;
|
|
23
|
+
private readonly resetBindGroup;
|
|
24
|
+
private bindGroup;
|
|
25
|
+
private palette;
|
|
26
|
+
private pendingReset;
|
|
27
|
+
private readonly inputs;
|
|
28
|
+
constructor(device: GPUDevice, source: SecondaryMotionSkinningTargets, kernels: readonly [WebGpuComputeKernel, WebGpuComputeKernel], targets: GPUBuffer, positions: readonly [GPUBuffer, GPUBuffer], velocities: GPUBuffer, particleCount: number);
|
|
29
|
+
requestReset(): void;
|
|
30
|
+
execute(context: RendererCustomPassContext, pass: GPUComputePassEncoder): boolean;
|
|
31
|
+
dispose(): void;
|
|
32
|
+
}
|
|
33
|
+
export declare const SKIN_TARGETS_WGSL = "\nstruct Transforms { inverseWorld: mat4x4<f32>, bind: mat4x4<f32> }\n@group(0) @binding(0) var<storage, read> bindPositions: array<f32>;\n@group(0) @binding(1) var<storage, read> indices: array<vec4<u32>>;\n@group(0) @binding(2) var<storage, read> weights: array<vec4<f32>>;\n@group(0) @binding(3) var<storage, read> activeParticles: array<u32>;\n@group(0) @binding(4) var<storage, read> bones: array<mat4x4<f32>>;\n@group(0) @binding(5) var<storage, read_write> targets: array<f32>;\n@group(0) @binding(6) var<uniform> transforms: Transforms;\n@compute @workgroup_size(64)\nfn main(@builtin(global_invocation_id) invocation: vec3<u32>) {\n if (invocation.x >= arrayLength(&activeParticles)) { return; }\n let particle = activeParticles[invocation.x];\n let offset = particle * 3u;\n let original = vec3<f32>(bindPositions[offset], bindPositions[offset + 1u], bindPositions[offset + 2u]);\n let bound = transforms.bind * vec4<f32>(original, 1.0);\n var result = vec3<f32>(0.0);\n var total = 0.0;\n for (var influence = 0u; influence < 4u; influence++) {\n let weight = weights[particle][influence];\n let bone = indices[particle][influence];\n if (weight > 0.0 && bone < arrayLength(&bones)) {\n result += (transforms.inverseWorld * bones[bone] * bound).xyz * weight;\n total += weight;\n }\n }\n if (total <= 0.000001) { result = original; }\n targets[offset] = result.x; targets[offset + 1u] = result.y; targets[offset + 2u] = result.z;\n}\n";
|
|
34
|
+
export declare const RESET_TARGETS_WGSL = "\n@group(0) @binding(0) var<storage, read> targets: array<f32>;\n@group(0) @binding(1) var<storage, read_write> positionsA: array<vec4<f32>>;\n@group(0) @binding(2) var<storage, read_write> positionsB: array<vec4<f32>>;\n@group(0) @binding(3) var<storage, read_write> velocities: array<vec4<f32>>;\n@compute @workgroup_size(64)\nfn main(@builtin(global_invocation_id) invocation: vec3<u32>) {\n let particle = invocation.x;\n if (particle >= arrayLength(&positionsA)) { return; }\n let offset = particle * 3u;\n let value = vec4<f32>(targets[offset], targets[offset + 1u], targets[offset + 2u], 1.0);\n positionsA[particle] = value; positionsB[particle] = value; velocities[particle] = vec4<f32>(0.0);\n}\n";
|
|
35
|
+
//# sourceMappingURL=skinned-targets.d.ts.map
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{Matrix4 as e}from"three";import{createWebGpuComputeKernel as t}from"../rendering/webgpu-runtime-bridge.js";const i=new WeakMap;export function createSkinningTargetKernels(e){const n=i.get(e);if(n)return n;const r=(e,t)=>({binding:e,visibility:GPUShaderStage.COMPUTE,buffer:{type:t?"read-only-storage":"storage"}}),s=[t(e,{label:"secondary-motion-skin-targets",code:SKIN_TARGETS_WGSL,bindGroupLayoutEntries:[r(0,!0),r(1,!0),r(2,!0),r(3,!0),r(4,!0),r(5,!1),{binding:6,visibility:GPUShaderStage.COMPUTE,buffer:{type:"uniform"}}]}),t(e,{label:"secondary-motion-reset-skinned-targets",code:RESET_TARGETS_WGSL,bindGroupLayoutEntries:[r(0,!0),r(1,!1),r(2,!1),r(3,!1)]})];return i.set(e,s),s}export class SkinnedSecondaryMotionTargets{constructor(t,i,r,s,o,a,u){if(this.device=t,this.source=i,this.kernels=r,this.targets=s,this.buffers=[],this.uniformData=new Float32Array(32),this.inverseWorld=new e,this.bindGroup=null,this.palette=null,this.pendingReset=!0,i.bindPositions.length!==3*u||i.skinIndices.length!==4*u||i.skinWeights.length!==4*u)throw new Error("Secondary-motion skinning input lengths do not match particles");const c=new Set;for(const e of i.activeParticles){if(e>=u||c.has(e))throw new Error("Secondary-motion active particles must be unique and in range");c.add(e);for(let t=0;t<4;t++){const n=4*e+t;if(i.skinWeights[n]>0&&i.skinIndices[n]>=i.mesh.skeleton.bones.length)throw new Error("Secondary-motion skinning references an unavailable bone")}}const f=(e,i)=>{const n=t.createBuffer({label:e,size:Math.max(4,i.byteLength),usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST});return i.byteLength&&t.queue.writeBuffer(n,0,i.buffer,i.byteOffset,i.byteLength),this.buffers.push(n),n},l=f("secondary-motion-bind-positions",i.bindPositions),g=f("secondary-motion-skin-indices",new Uint32Array(i.skinIndices)),d=f("secondary-motion-skin-weights",i.skinWeights),h=f("secondary-motion-active-particles",i.activeParticles);this.uniforms=t.createBuffer({label:"secondary-motion-skin-transform",size:128,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.buffers.push(this.uniforms),this.inputs=[n(0,l),n(1,g),n(2,d),n(3,h),n(4,s),n(5,s),n(6,this.uniforms)],this.resetBindGroup=r[1].createBindGroup(t,[n(0,s),n(1,o[0]),n(2,o[1]),n(3,a)])}requestReset(){this.pendingReset=!0}execute(e,t){const i=this.source.mesh,r=e.getSkeletonBoneBuffer(i.skeleton);this.palette!==r&&(this.inputs[4]=n(4,r),this.bindGroup=this.kernels[0].createBindGroup(this.device,this.inputs),this.palette=r),this.inverseWorld.copy(i.matrixWorld).invert(),this.uniformData.set(this.inverseWorld.elements,0),this.uniformData.set(i.bindMatrix.elements,16),this.device.queue.writeBuffer(this.uniforms,0,this.uniformData),this.source.activeParticles.length>0&&(t.setPipeline(this.kernels[0].pipeline),t.setBindGroup(0,this.bindGroup),t.dispatchWorkgroups(Math.ceil(this.source.activeParticles.length/64)));const s=this.pendingReset;return s&&(t.setPipeline(this.kernels[1].pipeline),t.setBindGroup(0,this.resetBindGroup),t.dispatchWorkgroups(Math.ceil(this.source.bindPositions.length/3/64)),this.pendingReset=!1),s}dispose(){for(const e of this.buffers)e.destroy()}}function n(e,t){return{binding:e,resource:{buffer:t}}}export const SKIN_TARGETS_WGSL="\nstruct Transforms { inverseWorld: mat4x4<f32>, bind: mat4x4<f32> }\n@group(0) @binding(0) var<storage, read> bindPositions: array<f32>;\n@group(0) @binding(1) var<storage, read> indices: array<vec4<u32>>;\n@group(0) @binding(2) var<storage, read> weights: array<vec4<f32>>;\n@group(0) @binding(3) var<storage, read> activeParticles: array<u32>;\n@group(0) @binding(4) var<storage, read> bones: array<mat4x4<f32>>;\n@group(0) @binding(5) var<storage, read_write> targets: array<f32>;\n@group(0) @binding(6) var<uniform> transforms: Transforms;\n@compute @workgroup_size(64)\nfn main(@builtin(global_invocation_id) invocation: vec3<u32>) {\n if (invocation.x >= arrayLength(&activeParticles)) { return; }\n let particle = activeParticles[invocation.x];\n let offset = particle * 3u;\n let original = vec3<f32>(bindPositions[offset], bindPositions[offset + 1u], bindPositions[offset + 2u]);\n let bound = transforms.bind * vec4<f32>(original, 1.0);\n var result = vec3<f32>(0.0);\n var total = 0.0;\n for (var influence = 0u; influence < 4u; influence++) {\n let weight = weights[particle][influence];\n let bone = indices[particle][influence];\n if (weight > 0.0 && bone < arrayLength(&bones)) {\n result += (transforms.inverseWorld * bones[bone] * bound).xyz * weight;\n total += weight;\n }\n }\n if (total <= 0.000001) { result = original; }\n targets[offset] = result.x; targets[offset + 1u] = result.y; targets[offset + 2u] = result.z;\n}\n";export const RESET_TARGETS_WGSL="\n@group(0) @binding(0) var<storage, read> targets: array<f32>;\n@group(0) @binding(1) var<storage, read_write> positionsA: array<vec4<f32>>;\n@group(0) @binding(2) var<storage, read_write> positionsB: array<vec4<f32>>;\n@group(0) @binding(3) var<storage, read_write> velocities: array<vec4<f32>>;\n@compute @workgroup_size(64)\nfn main(@builtin(global_invocation_id) invocation: vec3<u32>) {\n let particle = invocation.x;\n if (particle >= arrayLength(&positionsA)) { return; }\n let offset = particle * 3u;\n let value = vec4<f32>(targets[offset], targets[offset + 1u], targets[offset + 2u], 1.0);\n positionsA[particle] = value; positionsB[particle] = value; velocities[particle] = vec4<f32>(0.0);\n}\n";/*
|
|
2
|
+
* Copyright (©) 2026 Hology Interactive AB. All rights reserved.
|
|
3
|
+
* See the LICENSE.md file for details.
|
|
4
|
+
*/
|