@naanouff/w3dts-path-tracer 0.0.0-stage → 0.1.18
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/README.md +44 -3
- package/dist/PathTracer2Project.d.ts +17 -0
- package/dist/PathTracer2Project.d.ts.map +1 -0
- package/dist/PathTracerFrameUploadController.d.ts +186 -0
- package/dist/PathTracerFrameUploadController.d.ts.map +1 -0
- package/dist/PathTracerProject.d.ts +19 -0
- package/dist/PathTracerProject.d.ts.map +1 -0
- package/dist/SceneToRayData.d.ts +72 -0
- package/dist/SceneToRayData.d.ts.map +1 -0
- package/dist/bloomSubgraph.d.ts +14 -0
- package/dist/bloomSubgraph.d.ts.map +1 -0
- package/dist/buildPathTracerBvh.d.ts +34 -0
- package/dist/buildPathTracerBvh.d.ts.map +1 -0
- package/dist/buildPathTracerTwoLevel.d.ts +66 -0
- package/dist/buildPathTracerTwoLevel.d.ts.map +1 -0
- package/dist/emissiveTriangles.d.ts +28 -0
- package/dist/emissiveTriangles.d.ts.map +1 -0
- package/dist/fsr1EasuConstants.d.ts +7 -0
- package/dist/fsr1EasuConstants.d.ts.map +1 -0
- package/dist/hybridAtrous.d.ts +25 -0
- package/dist/hybridAtrous.d.ts.map +1 -0
- package/dist/hybridOidn.d.ts +15 -0
- package/dist/hybridOidn.d.ts.map +1 -0
- package/dist/hybridTemporal.d.ts +59 -0
- package/dist/hybridTemporal.d.ts.map +1 -0
- package/dist/index.d.ts +32 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/khronosPathTraceReference.d.ts +143 -0
- package/dist/khronosPathTraceReference.d.ts.map +1 -0
- package/dist/pathTracerBackplate.d.ts +29 -0
- package/dist/pathTracerBackplate.d.ts.map +1 -0
- package/dist/pathTracerBaselineMetrics.d.ts +98 -0
- package/dist/pathTracerBaselineMetrics.d.ts.map +1 -0
- package/dist/pathTracerBounceBudget.d.ts +32 -0
- package/dist/pathTracerBounceBudget.d.ts.map +1 -0
- package/dist/pathTracerCameraLens.d.ts +12 -0
- package/dist/pathTracerCameraLens.d.ts.map +1 -0
- package/dist/pathTracerConstants.d.ts +165 -0
- package/dist/pathTracerConstants.d.ts.map +1 -0
- package/dist/pathTracerDielectric.d.ts +30 -0
- package/dist/pathTracerDielectric.d.ts.map +1 -0
- package/dist/pathTracerEnvMap.d.ts +83 -0
- package/dist/pathTracerEnvMap.d.ts.map +1 -0
- package/dist/pathTracerGraphDefinition.d.ts +11 -0
- package/dist/pathTracerGraphDefinition.d.ts.map +1 -0
- package/dist/pathTracerInteractionEpoch.d.ts +11 -0
- package/dist/pathTracerInteractionEpoch.d.ts.map +1 -0
- package/dist/pathTracerInterleave.d.ts +74 -0
- package/dist/pathTracerInterleave.d.ts.map +1 -0
- package/dist/pathTracerLightFingerprint.d.ts +26 -0
- package/dist/pathTracerLightFingerprint.d.ts.map +1 -0
- package/dist/pathTracerMaterialTable.d.ts +63 -0
- package/dist/pathTracerMaterialTable.d.ts.map +1 -0
- package/dist/pathTracerMaterialTextureArrays.d.ts +58 -0
- package/dist/pathTracerMaterialTextureArrays.d.ts.map +1 -0
- package/dist/pathTracerOidnDenoiser.d.ts +43 -0
- package/dist/pathTracerOidnDenoiser.d.ts.map +1 -0
- package/dist/pathTracerPost.d.ts +137 -0
- package/dist/pathTracerPost.d.ts.map +1 -0
- package/dist/pathTracerRuntimeConfig.d.ts +6 -0
- package/dist/pathTracerRuntimeConfig.d.ts.map +1 -0
- package/dist/pathTracerSceneCache.d.ts +32 -0
- package/dist/pathTracerSceneCache.d.ts.map +1 -0
- package/dist/pathTracerSceneSettings.d.ts +43 -0
- package/dist/pathTracerSceneSettings.d.ts.map +1 -0
- package/dist/progressiveRenderState.d.ts +34 -0
- package/dist/progressiveRenderState.d.ts.map +1 -0
- package/dist/w3dts-path-tracer.es.js +4555 -0
- package/dist/w3dts-path-tracer.umd.js +46 -0
- package/package.json +55 -3
- package/shaders/clear_composite.compute.wgsl +20 -0
- package/shaders/clear_composite_layers.compute.wgsl +32 -0
- package/shaders/clear_path_trace_tile.compute.wgsl +30 -0
- package/shaders/copy_accum.compute.wgsl +15 -0
- package/shaders/denoise.compute.wgsl +88 -0
- package/shaders/denoise_atrous.compute.wgsl +104 -0
- package/shaders/display_grade.wgsl +74 -0
- package/shaders/fsr1_easu_path.compute.wgsl +240 -0
- package/shaders/fsr1_rcas_path.compute.wgsl +84 -0
- package/shaders/hole_fill.compute.wgsl +57 -0
- package/shaders/hybrid_atrous.compute.wgsl +239 -0
- package/shaders/hybrid_copy_aov.compute.wgsl +24 -0
- package/shaders/hybrid_gbuffer.wgsl +150 -0
- package/shaders/hybrid_history_copy.compute.wgsl +35 -0
- package/shaders/hybrid_primary_aov.compute.wgsl +784 -0
- package/shaders/hybrid_taa.compute.wgsl +131 -0
- package/shaders/hybrid_temporal.compute.wgsl +507 -0
- package/shaders/path_trace.compute.wgsl +923 -0
- package/shaders/path_trace_common.wgsl +1738 -0
- package/shaders/pt_bloom.compute.wgsl +91 -0
- package/shaders/pt_bloom_down.compute.wgsl +88 -0
- package/shaders/pt_bloom_up.compute.wgsl +76 -0
- package/shaders/pt_display.frag.wgsl +29 -0
- package/shaders/tile_composite.compute.wgsl +22 -0
- package/shaders/tile_composite_layers.compute.wgsl +86 -0
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
(function(f,M){typeof exports=="object"&&typeof module<"u"?M(exports,require("@naanouff/w3dts-core"),require("@naanouff/w3dts-logger")):typeof define=="function"&&define.amd?define(["exports","@naanouff/w3dts-core","@naanouff/w3dts-logger"],M):(f=typeof globalThis<"u"?globalThis:f||self,M(f.W3dtsPathTracer={},f.W3dtsCore,f.W3dtsLogger))})(this,function(f,M,bt){"use strict";var rc=Object.defineProperty;var nc=(f,M,bt)=>M in f?rc(f,M,{enumerable:!0,configurable:!0,writable:!0,value:bt}):f[M]=bt;var y=(f,M,bt)=>nc(f,typeof M!="symbol"?M+"":M,bt);var vs=1e-6,yt=typeof Float32Array<"u"?Float32Array:Array;Math.hypot||(Math.hypot=function(){for(var t=0,e=arguments.length;e--;)t+=arguments[e]*arguments[e];return Math.sqrt(t)});function Fs(){var t=new yt(9);return yt!=Float32Array&&(t[1]=0,t[2]=0,t[3]=0,t[5]=0,t[6]=0,t[7]=0),t[0]=1,t[4]=1,t[8]=1,t}function Ke(){var t=new yt(16);return yt!=Float32Array&&(t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0),t[0]=1,t[5]=1,t[10]=1,t[15]=1,t}function er(t){var e=new yt(16);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],e}function Cs(t,e){if(t===e){var a=e[1],r=e[2],n=e[3],s=e[6],o=e[7],i=e[11];t[1]=e[4],t[2]=e[8],t[3]=e[12],t[4]=a,t[6]=e[9],t[7]=e[13],t[8]=r,t[9]=s,t[11]=e[14],t[12]=n,t[13]=o,t[14]=i}else t[0]=e[0],t[1]=e[4],t[2]=e[8],t[3]=e[12],t[4]=e[1],t[5]=e[5],t[6]=e[9],t[7]=e[13],t[8]=e[2],t[9]=e[6],t[10]=e[10],t[11]=e[14],t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15];return t}function ar(t,e){var a=e[0],r=e[1],n=e[2],s=e[3],o=e[4],i=e[5],c=e[6],l=e[7],u=e[8],h=e[9],d=e[10],p=e[11],S=e[12],T=e[13],g=e[14],b=e[15],E=a*i-r*o,A=a*c-n*o,R=a*l-s*o,C=r*c-n*i,P=r*l-s*i,N=n*l-s*c,m=u*T-h*S,_=u*g-d*S,v=u*b-p*S,L=h*g-d*T,x=h*b-p*T,B=d*b-p*g,I=E*B-A*x+R*L+C*v-P*_+N*m;return I?(I=1/I,t[0]=(i*B-c*x+l*L)*I,t[1]=(n*x-r*B-s*L)*I,t[2]=(T*N-g*P+b*C)*I,t[3]=(d*P-h*N-p*C)*I,t[4]=(c*v-o*B-l*_)*I,t[5]=(a*B-n*v+s*_)*I,t[6]=(g*R-S*N-b*A)*I,t[7]=(u*N-d*R+p*A)*I,t[8]=(o*x-i*v+l*m)*I,t[9]=(r*v-a*x-s*m)*I,t[10]=(S*P-T*R+b*E)*I,t[11]=(h*R-u*P-p*E)*I,t[12]=(i*_-o*L-c*m)*I,t[13]=(a*L-r*_+n*m)*I,t[14]=(T*A-S*C-g*E)*I,t[15]=(u*C-h*A+d*E)*I,t):null}function xt(){var t=new yt(3);return yt!=Float32Array&&(t[0]=0,t[1]=0,t[2]=0),t}function Is(t){var e=t[0],a=t[1],r=t[2];return Math.hypot(e,a,r)}function oe(t,e,a){var r=new yt(3);return r[0]=t,r[1]=e,r[2]=a,r}function rr(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t}function ut(t,e,a,r){return t[0]=e,t[1]=a,t[2]=r,t}function xs(t,e){var a=e[0]-t[0],r=e[1]-t[1],n=e[2]-t[2];return Math.hypot(a,r,n)}function ie(t,e){var a=e[0],r=e[1],n=e[2],s=a*a+r*r+n*n;return s>0&&(s=1/Math.sqrt(s)),t[0]=e[0]*s,t[1]=e[1]*s,t[2]=e[2]*s,t}function nr(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}function Ze(t,e,a){var r=e[0],n=e[1],s=e[2],o=a[0],i=a[1],c=a[2];return t[0]=n*c-s*i,t[1]=s*o-r*c,t[2]=r*i-n*o,t}function Wt(t,e,a){var r=e[0],n=e[1],s=e[2],o=a[3]*r+a[7]*n+a[11]*s+a[15];return o=o||1,t[0]=(a[0]*r+a[4]*n+a[8]*s+a[12])/o,t[1]=(a[1]*r+a[5]*n+a[9]*s+a[13])/o,t[2]=(a[2]*r+a[6]*n+a[10]*s+a[14])/o,t}var Bs=Is;(function(){var t=xt();return function(e,a,r,n,s,o){var i,c;for(a||(a=3),r||(r=0),n?c=Math.min(n*a+r,e.length):c=e.length,i=r;i<c;i+=a)t[0]=e[i],t[1]=e[i+1],t[2]=e[i+2],s(t,t,o),e[i]=t[0],e[i+1]=t[1],e[i+2]=t[2];return e}})();function Ns(){var t=new yt(4);return yt!=Float32Array&&(t[0]=0,t[1]=0,t[2]=0,t[3]=0),t}function Ls(t,e){var a=e[0],r=e[1],n=e[2],s=e[3],o=a*a+r*r+n*n+s*s;return o>0&&(o=1/Math.sqrt(o)),t[0]=a*o,t[1]=r*o,t[2]=n*o,t[3]=s*o,t}(function(){var t=Ns();return function(e,a,r,n,s,o){var i,c;for(a||(a=4),r||(r=0),n?c=Math.min(n*a+r,e.length):c=e.length,i=r;i<c;i+=a)t[0]=e[i],t[1]=e[i+1],t[2]=e[i+2],t[3]=e[i+3],s(t,t,o),e[i]=t[0],e[i+1]=t[1],e[i+2]=t[2],e[i+3]=t[3];return e}})();function sr(){var t=new yt(4);return yt!=Float32Array&&(t[0]=0,t[1]=0,t[2]=0),t[3]=1,t}function Ae(t,e,a){a=a*.5;var r=Math.sin(a);return t[0]=r*e[0],t[1]=r*e[1],t[2]=r*e[2],t[3]=Math.cos(a),t}function Je(t,e,a,r){var n=e[0],s=e[1],o=e[2],i=e[3],c=a[0],l=a[1],u=a[2],h=a[3],d,p,S,T,g;return p=n*c+s*l+o*u+i*h,p<0&&(p=-p,c=-c,l=-l,u=-u,h=-h),1-p>vs?(d=Math.acos(p),S=Math.sin(d),T=Math.sin((1-r)*d)/S,g=Math.sin(r*d)/S):(T=1-r,g=r),t[0]=T*n+g*c,t[1]=T*s+g*l,t[2]=T*o+g*u,t[3]=T*i+g*h,t}function ws(t,e){var a=e[0]+e[4]+e[8],r;if(a>0)r=Math.sqrt(a+1),t[3]=.5*r,r=.5/r,t[0]=(e[5]-e[7])*r,t[1]=(e[6]-e[2])*r,t[2]=(e[1]-e[3])*r;else{var n=0;e[4]>e[0]&&(n=1),e[8]>e[n*3+n]&&(n=2);var s=(n+1)%3,o=(n+2)%3;r=Math.sqrt(e[n*3+n]-e[s*3+s]-e[o*3+o]+1),t[n]=.5*r,r=.5/r,t[3]=(e[s*3+o]-e[o*3+s])*r,t[s]=(e[s*3+n]+e[n*3+s])*r,t[o]=(e[o*3+n]+e[n*3+o])*r}return t}var or=Ls;(function(){var t=xt(),e=oe(1,0,0),a=oe(0,1,0);return function(r,n,s){var o=nr(n,s);return o<-.999999?(Ze(t,e,n),Bs(t)<1e-6&&Ze(t,a,n),ie(t,t),Ae(r,t,Math.PI),r):o>.999999?(r[0]=0,r[1]=0,r[2]=0,r[3]=1,r):(Ze(t,n,s),r[0]=t[0],r[1]=t[1],r[2]=t[2],r[3]=1+o,or(r,r))}})(),function(){var t=sr(),e=sr();return function(a,r,n,s,o,i){return Je(t,r,o,i),Je(e,n,s,i),Je(a,t,e,2*i*(1-i)),a}}(),function(){var t=Fs();return function(e,a,r,n){return t[0]=r[0],t[3]=r[1],t[6]=r[2],t[1]=n[0],t[4]=n[1],t[7]=n[2],t[2]=-a[0],t[5]=-a[1],t[8]=-a[2],or(e,ws(e,t))}}();const Mt=57,ft=256,Hs=1024,ir=512*1024*1024,cr=64,Bt=524288,lr=4096,Os=16+lr*16,Qe=Bt*Mt*4,Nt=65535,Ds=ft*4,hr=Bt*2*32,Xt=4096,ce=144,ur=Xt*ce,ta=24,fr=1,Gs=ta*4,dr=8,mr=dr*4,lt=512,gt=256,le=2,Us=128,pr=80,ea=Us,aa=ea+le*lt*gt*4,ra=aa+le*gt,na=ra+le*gt*lt,zs=na*4,_e=128,Tr=64,br=256;function sa(t){const e=Math.floor(Number.isFinite(t)?t:_e);return Math.max(Tr,Math.min(br,e))}const oa=64,Ee=80,Ws=1,Vs=2,ks=4,$s=8,Ys=16,Xs=32,yr=64,gr=128,Sr=256,Mr=32,Ar=64,js={floatsPerTriangle:Mt,maxTextureSlots:ft,maxTriangles:Bt,sceneTrianglesBufferBytes:Qe,materialSlotNone:Nt,tileInfoBufferBytes:oa,bvhNodesBufferBytes:hr},Vt=20,he=4096,_r=he*Vt*4,Er={texSlot:0,bsdfKind:1,envSlot:2,alphaMode:3,specularFactor:4,specularColor:5,transmission:8,opacity:9,ior:10,dispersion:11,attenuationColor:12,attenuationDistance:15,clearcoat:16,clearcoatRoughness:17,catcherReflect:18,shadowCatcherCutoff:19},V=Er,qs=2,ia=3;function Pe(t){var a,r;if(!t)return!1;if(t.shadingModel==="unlit"||((r=(a=t.properties)==null?void 0:a.get)==null?void 0:r.call(a,"bsdfKind"))===ia)return!0;const e=t.shaderGraph;return Array.isArray(e==null?void 0:e.nodes)&&e.nodes.some(n=>(n==null?void 0:n.type)==="UnlitMasterNode")}function Ks(t){var r,n,s,o;const e=(n=(r=t.properties)==null?void 0:r.get)==null?void 0:n.call(r,"alphaMode"),a=t.alphaMode??(typeof e=="string"?e:"OPAQUE");if(a==="MASK"){const i=(o=(s=t.properties)==null?void 0:s.get)==null?void 0:o.call(s,"alphaCutoff"),c=t.alphaCutoff??i,l=typeof c=="number"&&Number.isFinite(c)&&c>0?c:.5;return Math.min(l,1)}return a==="BLEND"||a==="MULTIPLY"?-1:0}let Pr=!1;function _t(t,e,a,r,n){var o,i;const s=(i=(o=t.properties)==null?void 0:o.get)==null?void 0:i.call(o,e);return typeof s!="number"||!Number.isFinite(s)?a:Math.max(r,Math.min(n,s))}function Rr(t,e,a){var n,s;const r=(s=(n=t.properties)==null?void 0:n.get)==null?void 0:s.call(n,e);return r==null||typeof r[0]!="number"?[a,a,a]:[Number(r[0]),Number(r[1]??a),Number(r[2]??a)]}function Zs(t){var r,n,s,o;const e=(n=(r=t.properties)==null?void 0:r.get)==null?void 0:n.call(r,"opacity");if(typeof e=="number"&&Number.isFinite(e))return Math.max(0,Math.min(1,e));const a=(o=(s=t.properties)==null?void 0:s.get)==null?void 0:o.call(s,"baseColor");return a!=null&&typeof a[3]=="number"?Math.max(0,Math.min(1,a[3])):1}function vr(t,e){t.fill(0,e,e+Vt),t[e+V.texSlot]=Nt,t[e+V.specularFactor]=1,t[e+V.specularColor]=1,t[e+V.specularColor+1]=1,t[e+V.specularColor+2]=1,t[e+V.opacity]=1,t[e+V.ior]=1.5,t[e+V.attenuationColor]=1,t[e+V.attenuationColor+1]=1,t[e+V.attenuationColor+2]=1}function Js(t,e,a,r){var i,c;vr(t,e),t[e+V.texSlot]=r,t[e+V.alphaMode]=Ks(a);const n=(c=(i=a.properties)==null?void 0:i.get)==null?void 0:c.call(i,"bsdfKind"),s=typeof n=="number"&&Number.isFinite(n)?Math.max(0,Math.min(255,Math.floor(n))):null;t[e+V.bsdfKind]=s!==null&&s!==0?s:Pe(a)?ia:0,t[e+V.envSlot]=Math.floor(_t(a,"envSlot",0,0,255)),t[e+V.specularFactor]=_t(a,"specularFactor",1,0,4),t.set(Rr(a,"specularColorFactor",1),e+V.specularColor),t[e+V.transmission]=_t(a,"transmissionFactor",0,0,1),t[e+V.opacity]=Zs(a),t[e+V.ior]=_t(a,"ior",1.5,1,4),t[e+V.dispersion]=_t(a,"dispersionFactor",0,0,10),t.set(Rr(a,"attenuationColor",1),e+V.attenuationColor);const o=_t(a,"attenuationDistance",0,0,1/0);t[e+V.attenuationDistance]=o>=1e30?0:o,t[e+V.clearcoat]=_t(a,"clearcoatFactor",0,0,1),t[e+V.clearcoatRoughness]=_t(a,"clearcoatRoughnessFactor",0,0,1),t[e+V.catcherReflect]=_t(a,"catcherReflect",0,0,1),t[e+V.shadowCatcherCutoff]=_t(a,"shadowCatcherCutoff",0,0,1)}class Fr{constructor(){y(this,"data",new Float32Array(he*Vt));y(this,"indexById",new Map);y(this,"nextIndex",1);y(this,"transmissive",!1);vr(this.data,0)}reset(){this.indexById.clear(),this.nextIndex=1,this.transmissive=!1}get hasTransmission(){return this.transmissive}get count(){return this.nextIndex}get byteLength(){return this.nextIndex*Vt*4}getIndex(e,a){const r=typeof e.id=="number"?e.id:-1;if(r<0)return 0;const n=this.indexById.get(r);if(n!==void 0)return n;if(this.nextIndex>=he)return Pr||(Pr=!0,console.warn(`[PathTracer] More than ${he-1} materials; extra materials use the default material in path trace.`)),this.indexById.set(r,0),0;const s=this.nextIndex++;this.indexById.set(r,s);const o=s*Vt;return Js(this.data,o,e,a),this.data[o+V.transmission]>0&&(this.transmissive=!0),s}}const Cr=31,Ir=8;function ue(t,e){const a=Math.floor(Number.isFinite(t)?t:0);return Math.max(e,Math.min(Cr,a))}function xr(t,e){const a=t==null?void 0:t.totalBounces;if(typeof a=="number"&&Number.isFinite(a)&&a>0){const n=ue(a,1),s=Math.min(n,ue((t==null?void 0:t.diffuseBounces)??n,0)),o=Math.min(n,ue((t==null?void 0:t.glossyBounces)??n,0));return{diffuse:s,glossy:o,opaque:Math.min(n,s+o),total:n}}const r=ue(e,1);return{diffuse:r,glossy:r,opaque:r,total:ue(r+Ir,1)}}function Br(t){return(t.diffuse&255|(t.glossy&255)<<8|(t.opaque&255)<<16|(t.total&255)<<24)>>>0}let ca=null,Nr=0,Lr=null;function Qs(t){if(!t){ca=null;return}ca={...t,...t.bloom?{bloom:{...t.bloom}}:{}}}function la(){return ca}function to(t){Lr=t,Nr+=1}function wr(){return{serial:Nr,data:Lr}}const ha=16,eo=1,ua=ha*4,Re=16,Hr=3,Or=.25,Dr=8,ao=.6,Gr={threshold:4.5,glare:0,size:0,numRays:0,rotation:0};function Et(t,e){return typeof t=="number"&&Number.isFinite(t)?t:e}function fa(t){return 2**(Number.isFinite(t)?t:0)}function ro(t){const e=Math.min(1,Math.max(0,t)),a=e<=.0031308?12.92*e:1.055*e**(1/2.4)-.055;return Math.round(Math.min(1,Math.max(0,a))*255)}function no(t,e){const a=Math.max(0,t),r=Math.max(0,e),n=.5*r;if(!(n>1e-8))return Math.max(0,a-r);const s=Math.max(0,a-r+n)*Math.max(0,a-r+n)/(4*n);return a>=r+n?a-r:Math.min(s,n)}const da=[.125,.125,.125,.125,.125,.0625,.0625,.0625,.0625,.03125,.03125,.03125,.03125];function so(t){let e=0,a=0;for(let r=0;r<da.length;r++){const n=Math.max(0,t[r]??0),s=da[r]/(1+n);e+=n*s,a+=s}return e/Math.max(a,1e-6)}function oo(t,e){return Math.max(0,t)/Math.max(1,e)}function ma(t){return typeof t!="string"||!t.endsWith("-srgb")}function Ur(t){const o=t*(2.51*t+.03),i=t*(2.43*t+.59)+.14;return i!==0?o/i:0}function pa(t,e,a){return .2126*t+.7152*e+.0722*a}function io(t){if(t.length===0)return 0;const e=t.slice().sort((a,r)=>a-r);return e[Math.min(e.length-1,Math.floor(.95*(e.length-1)))]}function Ta(t,e,a){let r=0,n=0,s=0,o=0;for(let i=0;i<t.length;i++)r=Math.max(r,t[i]),n=Math.max(n,e[i]),t[i]>a&&s++,e[i]>a&&o++;return{count:t.length,maxLuma:r,p95Luma:io(t),maxChannel:n,aboveLumaThreshold:s,aboveMaxChannel:o}}function co(t,e,a,r){const n=[],s=[],o=[],i=[],c=[],l=[];let u=0,h=0,d=0;const p=Math.max(0,Math.min(e*a,Math.floor(t.length/4)));for(let S=0;S<p;S++){const T=S*4,g=t[T+3]??0,b=Math.min(1,Math.max(g,0));let E=t[T]??0,A=t[T+1]??0,R=t[T+2]??0;b>1e-6?(E/=b,A/=b,R/=b):(E=0,A=0,R=0);const C=pa(E,A,R),P=Math.max(E,A,R),N=Math.min(E,A,R);u=Math.max(u,C),C>r&&h++,P>r&&d++,A>=E&&A>=R&&A>E*1.15&&A>R*1.15&&A>.5?(n.push(C),s.push(P)):R>=E&&R>=A&&R>E*1.15&&R>A*1.15&&R>.5?(o.push(C),i.push(P)):P>1.5&&P-N<=.15*P&&(c.push(C),l.push(P))}return{width:e,height:a,threshold:r,maxLuma:u,aboveLumaThreshold:h,aboveMaxChannel:d,green:Ta(n,s,r),blue:Ta(o,i,r),neutral:Ta(c,l,r)}}function zr(t,e){return t>e}function Wr(t,e,a){const r=Math.max(1,Math.floor(e));return a+t*Math.PI/r}const jt={exposure:0,contrast:0,saturation:1,colorBalanceMode:3},Vr=-12,kr=6;function ve(t){return Number.isFinite(t)?Math.max(Vr,Math.min(kr,t)):jt.exposure}function lo(){const t=typeof globalThis<"u"?globalThis.__W3DTS_PATH_TRACER_CONFIG:void 0,e=t==null?void 0:t.exposure,a=t==null?void 0:t.contrast,r=t==null?void 0:t.saturation,n=t==null?void 0:t.colorBalanceMode;return{exposure:typeof e=="number"&&Number.isFinite(e)?ve(e):jt.exposure,contrast:typeof a=="number"&&Number.isFinite(a)?Math.max(-1,Math.min(1,a)):jt.contrast,saturation:typeof r=="number"&&Number.isFinite(r)?Math.max(0,Math.min(2,r)):jt.saturation,colorBalanceMode:typeof n=="number"&&Number.isFinite(n)?Math.max(0,Math.min(3,Math.floor(n))):jt.colorBalanceMode}}function $r(t,e,a=lo()){const r=t??void 0;return Yr({...r,exposure:typeof(r==null?void 0:r.exposure)=="number"?r.exposure:a.exposure,contrast:typeof(r==null?void 0:r.contrast)=="number"?r.contrast:a.contrast,saturation:typeof(r==null?void 0:r.saturation)=="number"?r.saturation:a.saturation,colorBalanceMode:typeof(r==null?void 0:r.colorBalanceMode)=="number"?r.colorBalanceMode:a.colorBalanceMode},e)}function Yr(t,e){const a=t==null?void 0:t.bloom,r=e==="Converged"||e==="Denoised",n=a?Math.max(0,Math.min(Dr,Math.floor(a.numRays))):0,s=a?Et(a.glare,0):0,o=a?Et(a.size,0):0,i=(a==null?void 0:a.mode)==="pyramid"?"pyramid":"glare",u=!!(a&&r&&n>0&&s!==0&&o>0&&i==="glare")||!!(a&&r&&i==="pyramid")?1:0,h=Math.max(1,Math.min(5,Math.floor(Et(a==null?void 0:a.levels,5))));return{exposureEv:Et(t==null?void 0:t.exposure,0),contrast:Et(t==null?void 0:t.contrast,0),saturation:Et(t==null?void 0:t.saturation,1),colorBalanceMode:Et(t==null?void 0:t.colorBalanceMode,2),bloomMix:u,bloom:a?{threshold:Et(a.threshold,Gr.threshold),glare:s,size:o,numRays:n,rotation:Et(a.rotation,0),mode:i,intensity:Math.max(0,Et(a.intensity,1)),levels:h}:{...Gr,mode:"glare",intensity:1,levels:5}}}function ho(t,e){const a=fa(e.exposureEv),r=e.colorBalanceMode,n=[t[0]*a,t[1]*a,t[2]*a],s=r>=2.5?[...M.pbrNeutralToneMapping(n)]:[ba(n[0],r),ba(n[1],r),ba(n[2],r)],o=Math.max(0,1+e.contrast),i=s.map(l=>(l-.5)*o+.5),c=pa(i[0],i[1],i[2]);return i.map(l=>c+(l-c)*e.saturation)}function ba(t,e){const a=Math.max(t,0);return e>=1.5?Ur(a*ao):e>=.5?a/(1+a):Math.min(1,a)}function Xr(t,e,a=!1){t[0]=fa(e.exposureEv),t[1]=e.contrast,t[2]=e.saturation,t[3]=e.colorBalanceMode,t[4]=e.bloomMix,t[5]=e.bloom.threshold,t[6]=e.bloom.glare,t[7]=e.bloom.size,t[8]=e.bloom.numRays,t[9]=e.bloom.rotation,t[10]=a?1:0,t[11]=0,t.length>14&&(t[12]=e.bloom.mode==="pyramid"?eo:0,t[13]=Number.isFinite(e.bloom.intensity)?e.bloom.intensity:1,t[14]=Number.isFinite(e.bloom.levels)?e.bloom.levels:5,t[15]=0)}function uo(t,e,a,r,n,s){if(r<0||n<0||r>=e||n>=a)return null;const o=(n*e+r)*4,i=t[o+3]??0,c=Math.min(1,Math.max(i,0));let l=t[o]??0,u=t[o+1]??0,h=t[o+2]??0;c>1e-6?(l/=c,u/=c,h/=c):(l=0,u=0,h=0);const d=pa(l,u,h);if(!zr(d,s))return null;const p=(d-s)/d;return[l*p,u*p,h*p]}function fo(t,e,a,r){const n=new Float32Array(Math.max(0,e*a*3)),s=Math.max(0,Math.min(Dr,Math.floor(r.numRays)));if(s<1||!(r.size>0)||r.glare===0||e<1||a<1)return n;const o=r.size*Math.min(e,a);for(let i=0;i<a;i++)for(let c=0;c<e;c++){let l=0,u=0,h=0;for(let p=0;p<s;p++){const S=Wr(p,s,r.rotation),T=Math.cos(S),g=Math.sin(S);for(let b=1;b<=Re;b++){const E=b/Re,A=E*o,R=r.glare*Math.exp(-Hr*E)/Re*Or;for(const C of[1,-1]){const P=Math.trunc(C*T*A),N=Math.trunc(C*g*A);if(P===0&&N===0)continue;const m=uo(t,e,a,c+P,i+N,r.threshold);m&&(l+=m[0]*R,u+=m[1]*R,h+=m[2]*R)}}}const d=(i*e+c)*3;n[d]=l,n[d+1]=u,n[d+2]=h}return n}function mo(t,e,a,r=.18){const n=Math.min(Math.floor(t.length/4),Math.max(0,e*a));if(n<1)return 0;let s=0,o=0;for(let l=0;l<n;l++){const u=l*4,h=t[u+3];if(!(h>1e-4)||!Number.isFinite(h))continue;const d=1/Math.min(h,1),p=t[u]*d,S=t[u+1]*d,T=t[u+2]*d,g=.2126*p+.7152*S+.0722*T;if(!Number.isFinite(g))continue;const b=Math.max(1e-4,Math.min(1e6,g));s+=Math.log(b),o++}if(o===0)return 0;const i=Math.exp(s/o),c=Math.log2(Math.max(1e-4,r)/i);return ve(Math.round(c*10)/10)}function po(t,e){if(t.length===0)return null;const a=Math.max(.5,.25*(Number.isFinite(e)&&e>0?e:4)),r=1/(a*a);let n=0;for(const o of t){if(!Number.isFinite(o.intensity)||o.intensity<=0)continue;const i=Number(o.color[0]??1),c=Number(o.color[1]??1),l=Number(o.color[2]??1),u=Math.max(.05,.2126*i+.7152*c+.0722*l);if(o.kind==="directional")n+=o.intensity*u;else if(o.kind==="area"){const h=o.area&&o.area>0?o.area:1;n+=o.intensity*u*h*r}else n+=o.intensity*u*r}if(!(n>8))return null;const s=-Math.log2(n/2.5);return ve(Math.round(s*10)/10)}const jr=["BloomDown0","BloomDown1","BloomDown2","BloomDown3","BloomDown4","BloomUp3","BloomUp2","BloomUp1","BloomUp0","BloomComposite"],ya=[.5,.25,.125,.0625,.03125];function qr(t,e,a){return{name:t,type:"texture",format:"rgba16float",sizeType:"relative",width:e,height:e,relativeSizeRef:a,usage:12}}function fe(t,e,a,r){return{name:`BloomDown${t}`,type:"compute",shaderPath:"/shaders/path-tracer/pt_bloom_down.compute.wgsl",entryPoint:"main",dispatchMode:"auto",workgroupSize:[8,8,1],dispatchTextureHandle:a,constants:{PREFILTER:r?1:0,LEVEL:t},bufferBindings:{0:{handle:"pathTracerPostParams",type:"read-only-storage"}},textureBindings:{1:{handle:e,access:"read",format:"rgba16float"},2:{handle:a,access:"write",format:"rgba16float"}},inputs:[e],outputs:[a]}}function de(t,e,a,r,n,s){return{name:t,type:"compute",shaderPath:"/shaders/path-tracer/pt_bloom_up.compute.wgsl",entryPoint:"main",dispatchMode:"auto",workgroupSize:[8,8,1],dispatchTextureHandle:r,constants:{LEVEL:n,COMPOSITE:s?1:0},bufferBindings:{0:{handle:"pathTracerPostParams",type:"read-only-storage"}},textureBindings:{1:{handle:e,access:"read",format:"rgba16float"},2:{handle:a,access:"read",format:"rgba16float"},3:{handle:r,access:"write",format:"rgba16float"}},inputs:[e,a],outputs:[r]}}function ga(t){const e=t.relativeSizeRef??"graph",a=[{name:"pathTracerPostParams",type:"buffer",sizeType:"fixed",size:ua,usage:136}];for(let n=0;n<ya.length;n++)a.push(qr(`bloomMip${n}`,ya[n],e));for(let n=0;n<4;n++)a.push(qr(`bloomAcc${n}`,ya[n],e));const r=[fe(0,t.input,"bloomMip0",!0),fe(1,"bloomMip0","bloomMip1",!1),fe(2,"bloomMip1","bloomMip2",!1),fe(3,"bloomMip2","bloomMip3",!1),fe(4,"bloomMip3","bloomMip4",!1),de("BloomUp3","bloomMip4","bloomMip3","bloomAcc3",3,!1),de("BloomUp2","bloomAcc3","bloomMip2","bloomAcc2",2,!1),de("BloomUp1","bloomAcc2","bloomMip1","bloomAcc1",1,!1),de("BloomUp0","bloomAcc1","bloomMip0","bloomAcc0",0,!1),de("BloomComposite","bloomAcc0","bloomAcc0",t.output,0,!0)];return{resources:a,passes:r}}function Kr(t,e,a,r,n,s,o){const i=l=>1/Math.max(l,1e-20),c=(o==null?void 0:o.length)===16?o:new Float32Array(16);return c[0]=t*i(n),c[1]=e*i(s),c[2]=.5*t*i(n)-.5,c[3]=.5*e*i(s)-.5,c[4]=i(a),c[5]=i(r),c[6]=1*i(a),c[7]=-1*i(r),c[8]=-1*i(a),c[9]=2*i(r),c[10]=1*i(a),c[11]=2*i(r),c[12]=0*i(a),c[13]=4*i(r),c[14]=0,c[15]=0,c}const Zr=[64,512];class Jr{constructor(e={}){y(this,"sppMilestones");y(this,"interactiveEwmaAlpha");y(this,"sessionStartMs",0);y(this,"started",!1);y(this,"lastTickMs",0);y(this,"interactiveUntilMs",0);y(this,"interactiveEwmaMs",0);y(this,"interactiveSampleCount",0);y(this,"timeToFirstSampleMs",null);y(this,"timeToFirstFullCoverageMs",null);y(this,"timeToConvergedMs",null);y(this,"timeToSppMs",new Map);y(this,"lastSamplesPerSecond",null);y(this,"lastAverageSpp",0);y(this,"lastSceneW",0);y(this,"lastSceneH",0);y(this,"lastTotalTiles",0);y(this,"lastMaxSamples",0);y(this,"lastConverged",!1);y(this,"lastSamplesDone",0);this.sppMilestones=e.sppMilestones??[...Zr],this.interactiveEwmaAlpha=e.interactiveEwmaAlpha??.15;for(const a of this.sppMilestones)this.timeToSppMs.set(a,null)}start(e){this.sessionStartMs=e,this.started=!0,this.lastTickMs=e,this.interactiveUntilMs=0,this.interactiveEwmaMs=0,this.interactiveSampleCount=0,this.timeToFirstSampleMs=null,this.timeToFirstFullCoverageMs=null,this.timeToConvergedMs=null,this.lastSamplesPerSecond=null,this.lastAverageSpp=0,this.lastConverged=!1,this.lastSamplesDone=0,this.timeToSppMs.clear();for(const a of this.sppMilestones)this.timeToSppMs.set(a,null)}markInteractive(e,a=250){this.interactiveUntilMs=Math.max(this.interactiveUntilMs,e+a)}tick(e,a){if(!e)return this.report();this.started||this.start(a),(e.samplesDone<this.lastSamplesDone||this.lastSamplesDone>0&&e.samplesDone===0)&&this.start(a),this.lastSamplesDone=e.samplesDone;const r=Math.max(0,a-this.sessionStartMs),n=Math.max(0,a-this.lastTickMs);this.lastTickMs=a,a<this.interactiveUntilMs&&n>0&&n<2e3&&(this.interactiveSampleCount+=1,this.interactiveEwmaMs=this.interactiveSampleCount===1?n:this.interactiveEwmaMs*(1-this.interactiveEwmaAlpha)+n*this.interactiveEwmaAlpha),this.lastSceneW=e.sceneWidth,this.lastSceneH=e.sceneHeight,this.lastTotalTiles=e.totalTiles,this.lastMaxSamples=e.maxSamples,this.lastConverged=e.converged,e.samplesPerSecond!==void 0&&e.samplesPerSecond>0&&(this.lastSamplesPerSecond=e.samplesPerSecond);const s=Math.max(1,e.totalTiles),o=e.samplesDone/s;this.lastAverageSpp=o,this.timeToFirstSampleMs===null&&e.samplesDone>0&&e.accumFrameIndex>=1&&(this.timeToFirstSampleMs=r);const i=e.converged||e.totalTiles>0&&e.tileIndex>=e.totalTiles-1&&e.accumFrameIndex>=1;this.timeToFirstFullCoverageMs===null&&i&&(this.timeToFirstFullCoverageMs=r),this.timeToConvergedMs===null&&e.converged&&(this.timeToConvergedMs=r);for(const c of this.sppMilestones)this.timeToSppMs.get(c)==null&&o>=c&&this.timeToSppMs.set(c,r);return this.report()}report(){const e={};for(const a of this.sppMilestones)e[a]=this.timeToSppMs.get(a)??null;return{timeToFirstSampleMs:this.timeToFirstSampleMs,timeToFirstFullCoverageMs:this.timeToFirstFullCoverageMs,timeToConvergedMs:this.timeToConvergedMs,interactiveMsPerFrame:this.interactiveSampleCount>0?this.interactiveEwmaMs:null,samplesPerSecond:this.lastSamplesPerSecond,averageSpp:this.lastAverageSpp,timeToSppMs:e,sceneWidth:this.lastSceneW,sceneHeight:this.lastSceneH,totalTiles:this.lastTotalTiles,maxSamples:this.lastMaxSamples,converged:this.lastConverged}}toJSON(){return this.report()}}function To(t){const e=(r,n=1)=>r==null||!Number.isFinite(r)?"—":`${r.toFixed(n)} ms`,a=[`Path tracer baseline (${t.sceneWidth}×${t.sceneHeight}, ${t.totalTiles} tiles, maxSamples=${t.maxSamples})`,` timeToFirstSample: ${e(t.timeToFirstSampleMs)}`,` timeToFirstFullCoverage: ${e(t.timeToFirstFullCoverageMs)}`,` timeToConverged: ${e(t.timeToConvergedMs)}`,` interactiveMs/frame: ${e(t.interactiveMsPerFrame)}`,` samplesPerSecond: ${t.samplesPerSecond==null?"—":t.samplesPerSecond.toFixed(1)}`,` averageSpp: ${t.averageSpp.toFixed(2)}`];for(const[r,n]of Object.entries(t.timeToSppMs))a.push(` timeTo${r}spp: ${e(n??null)}`);return a.push(` converged: ${t.converged}`),a.join(`
|
|
2
|
+
`)}const bo=4294967295,Sa=2147483648,Ma=4,nt=16,yo=4294967294;function Qr(t){return(Sa|t&2147483647)>>>0}function tn(t){return(t&Sa)!==0&&t!==yo}const Aa=32,go=1;function _a(t,e,a,r,n,s){const o=Math.max(0,r-t),i=Math.max(0,n-e),c=Math.max(0,s-a);return 2*(o*i+i*c+c*o)}function en(t,e,a,r){const n=e*Aa,s=new DataView(t);a[0]=s.getFloat32(n,!0),a[1]=s.getFloat32(n+4,!0),a[2]=s.getFloat32(n+8,!0),r[0]=s.getFloat32(n+16,!0),r[1]=s.getFloat32(n+20,!0),r[2]=s.getFloat32(n+24,!0)}function Ea(t,e){if(e<=0)return null;const a=Mt,r=new Array(e);for(let m=0;m<e;m++){const _=m*a;let v=1/0,L=1/0,x=1/0,B=-1/0,I=-1/0,w=-1/0;for(let D=0;D<3;D++){const O=_+D*3,tt=t[O],et=t[O+1],k=t[O+2];v=Math.min(v,tt),L=Math.min(L,et),x=Math.min(x,k),B=Math.max(B,tt),I=Math.max(I,et),w=Math.max(w,k)}r[m]={oldIndex:m,minX:v,minY:L,minZ:x,maxX:B,maxY:I,maxZ:w,cx:(v+B)*.5,cy:(L+I)*.5,cz:(x+w)*.5}}const n=Math.max(1,e*2),s=new ArrayBuffer(n*Aa),o=new DataView(s);let i=0;const c=new Uint32Array(e),l=new Float32Array(3),u=new Float32Array(3),h=new Float32Array(3),d=new Float32Array(3);function p(m,_,v,L,x,B,I,w){const D=i++,O=D*Aa;return o.setFloat32(O,m,!0),o.setFloat32(O+4,_,!0),o.setFloat32(O+8,v,!0),o.setUint32(O+12,I>>>0,!0),o.setFloat32(O+16,L,!0),o.setFloat32(O+20,x,!0),o.setFloat32(O+24,B,!0),o.setUint32(O+28,w>>>0,!0),D}function S(m,_){let v=1/0,L=1/0,x=1/0,B=-1/0,I=-1/0,w=-1/0;for(let D=m;D<_;D++){const O=r[D];v=Math.min(v,O.minX),L=Math.min(L,O.minY),x=Math.min(x,O.minZ),B=Math.max(B,O.maxX),I=Math.max(I,O.maxY),w=Math.max(w,O.maxZ)}return[v,L,x,B,I,w]}function T(m,_){return _===0?m.cx:_===1?m.cy:m.cz}function g(m,_){const[v,L,x,B,I,w]=S(m,_),D=_a(v,L,x,B,I,w);if(D<=1e-20)return null;let O=null;for(let tt=0;tt<3;tt++){let et=1/0,k=-1/0;for(let U=m;U<_;U++){const ot=T(r[U],tt);et=Math.min(et,ot),k=Math.max(k,ot)}const W=k-et;if(W<1e-12)continue;const Y=new Int32Array(nt),G=new Float32Array(nt),at=new Float32Array(nt),J=new Float32Array(nt),$=new Float32Array(nt),wt=new Float32Array(nt),mt=new Float32Array(nt);G.fill(1/0),at.fill(1/0),J.fill(1/0),$.fill(-1/0),wt.fill(-1/0),mt.fill(-1/0);for(let U=m;U<_;U++){const ot=r[U];let j=Math.floor((T(ot,tt)-et)/W*nt);j<0&&(j=0),j>=nt&&(j=nt-1),Y[j]+=1,G[j]=Math.min(G[j],ot.minX),at[j]=Math.min(at[j],ot.minY),J[j]=Math.min(J[j],ot.minZ),$[j]=Math.max($[j],ot.maxX),wt[j]=Math.max(wt[j],ot.maxY),mt[j]=Math.max(mt[j],ot.maxZ)}let Jt=0,F=1/0,Qt=1/0,ge=1/0,kt=-1/0,te=-1/0,it=-1/0;const ht=new Int32Array(nt),$t=new Float32Array(nt);for(let U=0;U<nt;U++)Y[U]>0&&(Jt+=Y[U],F=Math.min(F,G[U]),Qt=Math.min(Qt,at[U]),ge=Math.min(ge,J[U]),kt=Math.max(kt,$[U]),te=Math.max(te,wt[U]),it=Math.max(it,mt[U])),ht[U]=Jt,$t[U]=Jt>0?_a(F,Qt,ge,kt,te,it):0;let ee=0,Ht=1/0,X=1/0,rt=1/0,Q=-1/0,Ot=-1/0,Dt=-1/0;for(let U=nt-1;U>=1;U--){Y[U]>0&&(ee+=Y[U],Ht=Math.min(Ht,G[U]),X=Math.min(X,at[U]),rt=Math.min(rt,J[U]),Q=Math.max(Q,$[U]),Ot=Math.max(Ot,wt[U]),Dt=Math.max(Dt,mt[U]));const ot=ht[U-1];if(ot===0||ee===0)continue;const j=go+(ot*$t[U-1]+ee*_a(Ht,X,rt,Q,Ot,Dt))/D;(!O||j<O.cost)&&(O={axis:tt,bin:U,c0:et,extent:W,cost:j})}}return O}function b(m,_){let v=1/0,L=-1/0,x=1/0,B=-1/0,I=1/0,w=-1/0;for(let W=m;W<_;W++){const Y=r[W];v=Math.min(v,Y.cx),L=Math.max(L,Y.cx),x=Math.min(x,Y.cy),B=Math.max(B,Y.cy),I=Math.min(I,Y.cz),w=Math.max(w,Y.cz)}const D=L-v,O=B-x,tt=w-I,et=O>=D&&O>=tt?1:tt>=D&&tt>=O?2:0,k=r.slice(m,_);k.sort((W,Y)=>T(W,et)-T(Y,et));for(let W=0;W<k.length;W++)r[m+W]=k[W];return m+Math.max(1,Math.floor((_-m)/2))}function E(m,_,v){let L=m;for(let x=m;x<_;x++){let B=Math.floor((T(r[x],v.axis)-v.c0)/v.extent*nt);if(B<0&&(B=0),B>=nt&&(B=nt-1),B<v.bin){const I=r[x];r[x]=r[L],r[L]=I,L++}}return L<=m||L>=_?b(m,_):L}function A(m,_){const v=_-m,[L,x,B,I,w,D]=S(m,_);for(let O=m;O<_;O++)c[O]=r[O].oldIndex;return p(L,x,B,I,w,D,Qr(v),m)}function R(m,_){const v=_-m;if(v<=1)return A(m,_);const L=g(m,_);if(!L){if(v<=Ma)return A(m,_);const w=b(m,_),D=R(m,w),O=R(w,_);return C(D,O)}if(v<=Ma&&L.cost>=v)return A(m,_);const x=E(m,_,L),B=R(m,x),I=R(x,_);return C(B,I)}function C(m,_){return en(s,m,l,u),en(s,_,h,d),p(Math.min(l[0],h[0]),Math.min(l[1],h[1]),Math.min(l[2],h[2]),Math.max(u[0],d[0]),Math.max(u[1],d[1]),Math.max(u[2],d[2]),m,_)}const P=R(0,e),N=t.slice(0,e*a);for(let m=0;m<e;m++){const _=c[m]*a;t.set(N.subarray(_,_+a),m*a)}return{nodeCount:i,rootIndex:P,nodes:s,permutation:c}}const an=4294967294,me=32;function Pa(t,e,a,r){const n=e*me,s=new DataView(t);a[0]=s.getFloat32(n,!0),a[1]=s.getFloat32(n+4,!0),a[2]=s.getFloat32(n+8,!0),r[0]=s.getFloat32(n+16,!0),r[1]=s.getFloat32(n+20,!0),r[2]=s.getFloat32(n+24,!0)}function rn(t,e,a,r,n){const s=t;r[0]=1/0,r[1]=1/0,r[2]=1/0,n[0]=-1/0,n[1]=-1/0,n[2]=-1/0;const o=xt();for(let i=0;i<8;i++)o[0]=i&1?a[0]:e[0],o[1]=i&2?a[1]:e[1],o[2]=i&4?a[2]:e[2],Wt(o,o,s),r[0]=Math.min(r[0],o[0]),r[1]=Math.min(r[1],o[1]),r[2]=Math.min(r[2],o[2]),n[0]=Math.max(n[0],o[0]),n[1]=Math.max(n[1],o[1]),n[2]=Math.max(n[2],o[2])}function So(t,e,a,r){const n=new DataView(a.nodes),s=new DataView(t);for(let o=0;o<a.nodeCount;o++){const i=o*me,c=(e+o)*me;s.setFloat32(c,n.getFloat32(i,!0),!0),s.setFloat32(c+4,n.getFloat32(i+4,!0),!0),s.setFloat32(c+8,n.getFloat32(i+8,!0),!0),s.setFloat32(c+16,n.getFloat32(i+16,!0),!0),s.setFloat32(c+20,n.getFloat32(i+20,!0),!0),s.setFloat32(c+24,n.getFloat32(i+24,!0),!0);const l=n.getUint32(i+12,!0),u=n.getUint32(i+28,!0);tn(l)?(s.setUint32(c+12,l>>>0,!0),s.setUint32(c+28,u+r>>>0,!0)):(s.setUint32(c+12,l+e>>>0,!0),s.setUint32(c+28,u+e>>>0,!0))}return e+a.nodeCount}function Mo(t,e,a){const r=t.length;if(r<=0)return null;const n=new Float32Array(r*3);for(let b=0;b<r;b++){const E=t[b];n[b*3]=(E.worldMin[0]+E.worldMax[0])*.5,n[b*3+1]=(E.worldMin[1]+E.worldMax[1])*.5,n[b*3+2]=(E.worldMin[2]+E.worldMax[2])*.5}const s=new DataView(e);let o=0;const i=new Float32Array(3),c=new Float32Array(3),l=new Float32Array(3),u=new Float32Array(3),h=new Float32Array(3),d=new Float32Array(3);function p(b,E,A,R){if(o>=a)return 0;const C=o++,P=C*me;return s.setFloat32(P,b[0],!0),s.setFloat32(P+4,b[1],!0),s.setFloat32(P+8,b[2],!0),s.setUint32(P+12,A>>>0,!0),s.setFloat32(P+16,E[0],!0),s.setFloat32(P+20,E[1],!0),s.setFloat32(P+24,E[2],!0),s.setUint32(P+28,R>>>0,!0),C}function S(b){if(b.length===1){const B=b[0],I=t[B];return p(I.worldMin,I.worldMax,an,B)}let E=0,A=0,R=0;for(const B of b)E+=n[B*3],A+=n[B*3+1],R+=n[B*3+2];const C=1/b.length;E*=C,A*=C,R*=C;let P=0,N=0,m=0;for(const B of b){const I=n[B*3]-E,w=n[B*3+1]-A,D=n[B*3+2]-R;P+=I*I,N+=w*w,m+=D*D}let _=0;N>=P&&N>=m?_=1:m>=P&&m>=N&&(_=2),b.sort((B,I)=>n[B*3+_]-n[I*3+_]);const v=Math.max(1,Math.floor(b.length/2)),L=S(b.slice(0,v)),x=S(b.slice(v));return Pa(e,L,l,u),Pa(e,x,h,d),i[0]=Math.min(l[0],h[0]),i[1]=Math.min(l[1],h[1]),i[2]=Math.min(l[2],h[2]),c[0]=Math.max(u[0],d[0]),c[1]=Math.max(u[1],d[1]),c[2]=Math.max(u[2],d[2]),p(i,c,L,x)}const T=Array.from({length:r},(b,E)=>E),g=S(T);return{nodeCount:o,rootIndex:g,nodes:e}}function Ao(t){const e=new ArrayBuffer(t.length*ce),a=new DataView(e);for(let r=0;r<t.length;r++){const n=t[r],s=r*ce;for(let o=0;o<16;o++)a.setFloat32(s+o*4,n.worldFromObject[o],!0),a.setFloat32(s+64+o*4,n.objectFromWorld[o],!0);a.setUint32(s+128,n.triBase>>>0,!0),a.setUint32(s+132,n.triCount>>>0,!0),a.setUint32(s+136,n.blasRoot>>>0,!0),a.setUint32(s+140,0,!0)}return e}function nn(t,e){if(e<=0)return null;const a=Ea(t,e);if(!a)return null;const r=new Float32Array(3),n=new Float32Array(3);return Pa(a.nodes,a.rootIndex,r,n),{triangleFloats:t.slice(0,e*Mt),triCount:e,bvh:a,bmin:r,bmax:n}}function sn(t){const e=Math.min(t.length,Xt);if(e<=0)return null;const a=t.slice(0,e),r=Math.max(1,e*2),n=new Set;let s=0;for(const d of a)n.has(d.blasNodes)||(n.add(d.blasNodes),s+=d.blasNodeCount);const o=r+s,i=new ArrayBuffer(o*me),c=Mo(a,i,r);if(!c)return null;let l=c.nodeCount;const u=new Map,h=[];for(const d of a){let p=u.get(d.blasNodes);p===void 0&&(p=l,So(i,p,{nodeCount:d.blasNodeCount,rootIndex:d.blasRootLocal,nodes:d.blasNodes},d.triBase),u.set(d.blasNodes,p),l+=d.blasNodeCount),h.push({worldFromObject:d.worldFromObject,objectFromWorld:d.objectFromWorld,triBase:d.triBase,triCount:d.triCount,blasRoot:p+d.blasRootLocal})}return{bvh:{nodeCount:l,rootIndex:c.rootIndex,nodes:i},instancesBuffer:Ao(h),instanceCount:h.length}}const on=4294967295,Ra=53,cn=16,ln=16;function _o(t,e,a){return .2126*t+.7152*e+.0722*a}function Eo(t,e){return!(t>0)||!(e>0)?0:Math.PI*t/e}function va(t,e,a,r){const n=t[3]*e+t[7]*a+t[11]*r+t[15],s=n!==0?1/n:1;return[(t[0]*e+t[4]*a+t[8]*r+t[12])*s,(t[1]*e+t[5]*a+t[9]*r+t[13])*s,(t[2]*e+t[6]*a+t[10]*r+t[14])*s]}function Po(t,e,a,r,n,s,o,i,c){const l=r-t,u=n-e,h=s-a,d=o-t,p=i-e,S=c-a,T=u*S-h*p,g=h*d-l*S,b=l*p-u*d;return .5*Math.hypot(T,g,b)}function hn(t,e,a,r,n){if(t.length>=lr)return;const s=a*Mt,o=_o(e[s+Ra]??0,e[s+Ra+1]??0,e[s+Ra+2]??0);if(!(o>0))return;let i=e[s]??0,c=e[s+1]??0,l=e[s+2]??0,u=e[s+3]??0,h=e[s+4]??0,d=e[s+5]??0,p=e[s+6]??0,S=e[s+7]??0,T=e[s+8]??0;n&&([i,c,l]=va(n,i,c,l),[u,h,d]=va(n,u,h,d),[p,S,T]=va(n,p,S,T));const g=Po(i,c,l,u,h,d,p,S,T);g>0&&t.push({tri:a,inst:r,area:g,power:Math.PI*g*o})}function un(t,e,a){const r=[];if(a)for(let l=0;l<a.length;l++){const u=a[l];for(let h=0;h<u.triCount;h++)hn(r,t,u.triBase+h,l,u.worldFromObject)}else for(let l=0;l<e;l++)hn(r,t,l,on,null);const n=r.length;let s=0;for(const l of r)s+=l.power;const o=new ArrayBuffer(cn+Math.max(1,n)*ln),i=new DataView(o);i.setUint32(0,n,!0),i.setFloat32(4,s,!0);let c=0;for(let l=0;l<n;l++){const u=r[l];c+=u.power;const h=l===n-1||s<=0?1:c/s,d=cn+l*ln;i.setUint32(d,u.tri,!0),i.setUint32(d+4,u.inst,!0),i.setFloat32(d+8,h,!0),i.setFloat32(d+12,u.area,!0)}return{bytes:o,count:n,totalPower:s}}function fn(t,e){return t^=e>>>0,Math.imul(t,16777619)>>>0}function dn(t,e){let a=2166136261;a=fn(a,t|0);const r=Number.isFinite(e)?Math.round(e*1e4):0;return a=fn(a,r|0),a>>>0}const Fa=20,mn=Mt*4;let Fe=null,pn=!1,Ca="";function Ro(t,e){var r,n,s,o;let a=0;for(const i of t){const c=((n=(r=i.mesh)==null?void 0:r.indices)==null?void 0:n.length)??0;a+=Math.floor(c/3)}if(e)for(const i of e){const c=((o=(s=i.mesh)==null?void 0:s.indices)==null?void 0:o.length)??0;c>0&&i.count>0&&(a+=Math.floor(c/3)*i.count)}return a}let Ia=null;function vo(){return Ia??(Ia=new Fr),Ia.reset(),Ia}function Fo(t){return(!Fe||Fe.byteLength<t)&&(Fe=new ArrayBuffer(t)),Fe}function qt(t,e,a,r,n){t[0]=n[0]*e+n[4]*a+n[8]*r,t[1]=n[1]*e+n[5]*a+n[9]*r,t[2]=n[2]*e+n[6]*a+n[10]*r;const s=Math.hypot(t[0],t[1],t[2]);s>1e-20&&(t[0]/=s,t[1]/=s,t[2]/=s)}const Tn=36;let bn=!1;function Ce(t){if(t){if(typeof t=="object"&&t!==null&&"texture"in t){const e=t.texture;if(e&&typeof e=="object"&&e!==null&&"label"in e)return e}if(typeof t=="object"&&t!==null&&"label"in t)return t}}function Co(t){var a,r;const e=(r=(a=t.properties)==null?void 0:a.get)==null?void 0:r.call(a,"normalScale");return typeof e=="number"&&Number.isFinite(e)?Math.max(0,Math.min(4,e)):1}const xa={ox:0,oy:0,sx:1,sy:1,cos:1,sin:0,uvSet:0},Ba={ox:0,oy:0,sx:1,sy:1,cos:1,sin:0,uvSet:1};function pe(t,e,a,r=0){var p,S,T,g;const n=(S=(p=t==null?void 0:t.properties)==null?void 0:p.get)==null?void 0:S.call(p,e),s=(g=(T=t==null?void 0:t.properties)==null?void 0:T.get)==null?void 0:g.call(T,a),o=n!=null&&Number.isFinite(Number(n[0]))?Number(n[0]):0,i=n!=null&&Number.isFinite(Number(n[1]))?Number(n[1]):0,c=n!=null&&Number.isFinite(Number(n[2]))?Number(n[2]):1,l=n!=null&&Number.isFinite(Number(n[3]))?Number(n[3]):1,u=s!=null&&Number.isFinite(Number(s[0]))?Number(s[0]):1,h=s!=null&&Number.isFinite(Number(s[1]))?Number(s[1]):0,d=s!=null&&Number.isFinite(Number(s[2]))?Number(s[2]):r;return{ox:o,oy:i,sx:c,sy:l,cos:u,sin:h,uvSet:d>=.5?1:0}}function yn(t,e){return t.uvSet===e.uvSet&&Math.abs(t.ox-e.ox)<=1e-6&&Math.abs(t.oy-e.oy)<=1e-6&&Math.abs(t.sx-e.sx)<=1e-6&&Math.abs(t.sy-e.sy)<=1e-6&&Math.abs(t.cos-e.cos)<=1e-6&&Math.abs(t.sin-e.sin)<=1e-6}function Kt(t,e,a,r,n){const s=n.uvSet===1?a:t,o=n.uvSet===1?r:e,i=s*n.sx,c=o*n.sy;return[n.cos*i+n.sin*c+n.ox,-n.sin*i+n.cos*c+n.oy]}function Ie(t){if(!t)return{uv0Tf:xa,uv1Tf:Ba,ormUsesUv1Slot:!1,emissiveUsesUv1Slot:!1};const{albedo:e,orm:a,normal:r,emissive:n}=Mn(t),s=e?pe(t,"uvTfAlbedoOs","uvTfAlbedoRs",0):r?pe(t,"uvTfNormalOs","uvTfNormalRs",0):n?pe(t,"uvTfEmissiveOs","uvTfEmissiveRs",0):xa,o=Io(t)?1:0,i=a?pe(t,"uvTfOrmMrOs","uvTfOrmMrRs",o):null,c=i!==null&&!yn(s,i),l=n?pe(t,"uvTfEmissiveOs","uvTfEmissiveRs",0):null,u=l!==null&&!yn(s,l)&&!c;return{uv0Tf:s,uv1Tf:c?i:u?l:Ba,ormUsesUv1Slot:c,emissiveUsesUv1Slot:u}}function gn(t){return`${t.uvSet},${t.ox},${t.oy},${t.sx},${t.sy},${t.cos},${t.sin}`}function Io(t){var a,r;const e=(r=(a=t.properties)==null?void 0:a.get)==null?void 0:r.call(a,"ormMrUvSet");return e===1||e===1}function xe(t){const e=t==null?void 0:t.shaderGraph;return!e||!Array.isArray(e.nodes)?!1:e.nodes.some(a=>(a==null?void 0:a.type)==="MeshMaps")}function Na(t){var n,s;if(Pe(t))return[0,0,0];const e=(s=(n=t.properties)==null?void 0:n.get)==null?void 0:s.call(n,"emissiveColor");if(e!=null&&typeof e[0]=="number")return[Number(e[0]),Number(e[1]??0),Number(e[2]??0)];const r=t.emissiveColor;return r!=null&&typeof r[0]=="number"?[Number(r[0]),Number(r[1]??0),Number(r[2]??0)]:[0,0,0]}const Sn=new WeakMap;let xo=1;function Be(t){if(!t)return 0;const e=t;let a=Sn.get(e);return a===void 0&&(a=xo++,Sn.set(e,a)),a}function Mn(t){var c,l,u,h,d,p,S,T,g,b;const e=t.diffuseTexture,a=Ce((l=(c=t.properties)==null?void 0:c.get)==null?void 0:l.call(c,"baseColorTexture")),r=e??a;if(Pe(t))return{albedo:r};const s=((h=(u=t.properties)==null?void 0:u.get)==null?void 0:h.call(u,"ormHasMrTex"))===0?void 0:Ce((p=(d=t.properties)==null?void 0:d.get)==null?void 0:p.call(d,"metallicRoughnessTexture")),o=t.normalTexture??Ce((T=(S=t.properties)==null?void 0:S.get)==null?void 0:T.call(S,"normalTexture")),i=Ce((b=(g=t.properties)==null?void 0:g.get)==null?void 0:b.call(g,"emissiveTexture"));return{albedo:r,orm:s,normal:o,emissive:i}}class Bo{constructor(){y(this,"slotByMaterialId",new Map);y(this,"slotByTupleKey",new Map);y(this,"textureSlotFlags",new Uint32Array(ft));y(this,"textureSlots",Array.from({length:ft},()=>({})));y(this,"matNormalScales",new Float32Array(ft));y(this,"nextSlot",0);this.matNormalScales.fill(1)}getSlotIndex(e){const a=typeof e.id=="number"?e.id:-1;if(a<0)return Nt;const r=this.slotByMaterialId.get(a);if(r!==void 0)return r;const{albedo:n,orm:s,normal:o,emissive:i}=Mn(e);if(!n&&!s&&!o&&!i)return this.slotByMaterialId.set(a,Nt),Nt;let c=0;n&&(c|=1),s&&(c|=2),o&&(c|=4),i&&(c|=8);const l=Ie(e);s&&l.ormUsesUv1Slot&&(c|=Mr),i&&l.emissiveUsesUv1Slot&&(c|=Ar);const u=o?Co(e):1,h=`${Be(n)}:${Be(s)}:${Be(o)}:${Be(i)}:${c}:${Math.round(u*1e4)}`,d=this.slotByTupleKey.get(h);if(d!==void 0)return this.slotByMaterialId.set(a,d),d;if(this.nextSlot>=ft)return bn||(bn=!0,console.warn(`[PathTracer] More than ${ft} distinct material texture tuples; only the first ${ft} bind in path trace — extras use factors only (can look flat vs raster). Unrelated to triangle cap.`)),this.slotByMaterialId.set(a,Nt),Nt;const p=this.nextSlot++;return this.slotByMaterialId.set(a,p),this.slotByTupleKey.set(h,p),this.textureSlots[p]={albedo:n,orm:s,normal:o,emissive:i},this.textureSlotFlags[p]=c,this.matNormalScales[p]=u,p}get texturedSlotsUsed(){return this.nextSlot}}function La(t,e){if(e+19>=t.length)return[1,1,1];const a=t[e+16],r=t[e+17],n=t[e+18],s=t[e+19];return a===0&&r===0&&n===0&&s===0?[1,1,1]:[a,r,n]}function wa(t,e,a,r,n,s,o,i,c,l,u,h,d=!0,p=xa,S=Ba){const T=xt(),g=xt(),b=xt(),E=xt(),A=s;for(let R=0;R+2<n.length&&!(e>=a);R+=3){const C=n[R]*Fa,P=n[R+1]*Fa,N=n[R+2]*Fa,m=e*Mt;ut(T,r[C],r[C+1],r[C+2]),Wt(T,T,A),t[m+0]=T[0],t[m+1]=T[1],t[m+2]=T[2],ut(T,r[P],r[P+1],r[P+2]),Wt(T,T,A),t[m+3]=T[0],t[m+4]=T[1],t[m+5]=T[2],ut(T,r[N],r[N+1],r[N+2]),Wt(T,T,A),t[m+6]=T[0],t[m+7]=T[1],t[m+8]=T[2],ut(g,r[C+7],r[C+8],r[C+9]),Wt(g,g,o),ie(g,g),t[m+9]=g[0],t[m+10]=g[1],t[m+11]=g[2],ut(g,r[P+7],r[P+8],r[P+9]),Wt(g,g,o),ie(g,g),t[m+12]=g[0],t[m+13]=g[1],t[m+14]=g[2],ut(g,r[N+7],r[N+8],r[N+9]),Wt(g,g,o),ie(g,g),t[m+15]=g[0],t[m+16]=g[1],t[m+17]=g[2],qt(b,r[C+10],r[C+11],r[C+12],A),t[m+18]=b[0],t[m+19]=b[1],t[m+20]=b[2],qt(b,r[P+10],r[P+11],r[P+12],A),t[m+21]=b[0],t[m+22]=b[1],t[m+23]=b[2],qt(b,r[N+10],r[N+11],r[N+12],A),t[m+24]=b[0],t[m+25]=b[1],t[m+26]=b[2],qt(E,r[C+13],r[C+14],r[C+15],A),t[m+27]=E[0],t[m+28]=E[1],t[m+29]=E[2],qt(E,r[P+13],r[P+14],r[P+15],A),t[m+30]=E[0],t[m+31]=E[1],t[m+32]=E[2],qt(E,r[N+13],r[N+14],r[N+15],A),t[m+33]=E[0],t[m+34]=E[1],t[m+35]=E[2];const[_,v]=Kt(r[C+3],r[C+4],r[C+5],r[C+6],p),[L,x]=Kt(r[P+3],r[P+4],r[P+5],r[P+6],p),[B,I]=Kt(r[N+3],r[N+4],r[N+5],r[N+6],p);t[m+36]=_,t[m+37]=v,t[m+38]=L,t[m+39]=x,t[m+40]=B,t[m+41]=I;const[w,D]=Kt(r[C+3],r[C+4],r[C+5],r[C+6],S),[O,tt]=Kt(r[P+3],r[P+4],r[P+5],r[P+6],S),[et,k]=Kt(r[N+3],r[N+4],r[N+5],r[N+6],S);t[m+42]=w,t[m+43]=D,t[m+44]=O,t[m+45]=tt,t[m+46]=et,t[m+47]=k;let W=1,Y=1,G=1;if(d){const at=La(r,C),J=La(r,P),$=La(r,N);W=(at[0]+J[0]+$[0])/3,Y=(at[1]+J[1]+$[1])/3,G=(at[2]+J[2]+$[2])/3}t[m+48]=i[0]*W,t[m+49]=i[1]*Y,t[m+50]=i[2]*G,t[m+51]=c,t[m+52]=l,t[m+53]=u[0],t[m+54]=u[1],t[m+55]=u[2],t[m+56]=h,e++}return e}const An=new WeakMap;let No=1;function _n(t){let e=An.get(t);return e===void 0&&(e=No++,An.set(t,e)),e}function En(t,e,a=Bt){const r=a*mn,n=Fo(r),s=new Float32Array(n);let o=0;const i=Ke(),c=new Bo,l=vo(),u=_=>_?l.getIndex(_,c.getSlotIndex(_)):0,h=Ro(t,e),d=[];if(e)for(const _ of e){if(d.length>=Xt)break;const{mesh:v,instanceData:L,count:x,material:B}=_;if(!(!L||!(v!=null&&v.vertices)||!(v!=null&&v.indices)))for(let I=0;I<x&&!(d.length>=Xt);I++){const w=I*Tn;d.push({vertices:v.vertices,indices:v.indices,material:B,worldFromObject:L.subarray(w,w+16)})}}for(const _ of t){if(d.length>=Xt)break;d.push({vertices:_.mesh.vertices,indices:_.mesh.indices,material:_.material,worldFromObject:_.transform})}const p=new Map,S=[],T=new Float32Array(3),g=new Float32Array(3),b=Ke();for(const _ of d){if(o>=a)break;const v=_.material,L=v?M.readMaterialBaseColor(v):[.5,.5,.5],x=v?M.readMaterialMetallic(v):0,B=v?M.readMaterialRoughness(v):.5,I=v?Na(v):[0,0,0],w=!xe(v),D=u(v),O=Ie(v),tt=typeof(v==null?void 0:v.id)=="number"?v.id:-1,et=`${_n(_.vertices)}|${_n(_.indices)}|${tt}|${L[0]},${L[1]},${L[2]}|${x}|${B}|${I[0]},${I[1]},${I[2]}|${w?1:0}|${D}|${gn(O.uv0Tf)}|${gn(O.uv1Tf)}`;let k=p.get(et);if(!k){const Y=o,G=o;o=wa(s,o,a,_.vertices,_.indices,i,i,L,x,B,I,D,w,O.uv0Tf,O.uv1Tf);const at=o-G;if(at<=0)continue;const J=s.subarray(Y*Mt,o*Mt),$=nn(J,at);if(!$)continue;k={triBase:Y,triCount:at,blasNodes:$.bvh.nodes,blasNodeCount:$.bvh.nodeCount,blasRootLocal:$.bvh.rootIndex,bmin:$.bmin,bmax:$.bmax},p.set(et,k)}const W=_.worldFromObject;ar(b,W),rn(W,k.bmin,k.bmax,T,g),S.push({worldFromObject:er(W),objectFromWorld:er(b),triBase:k.triBase,triCount:k.triCount,blasRootLocal:k.blasRootLocal,blasNodes:k.blasNodes,blasNodeCount:k.blasNodeCount,worldMin:new Float32Array(T),worldMax:new Float32Array(g)})}let E=null,A=null,R=0,C=!1;const P=sn(S);if(P&&P.instanceCount>0)E=P.bvh,A=P.instancesBuffer,R=P.instanceCount,C=!0;else if(o>0){o=0;const _=Ke();if(e)for(const L of e){if(o>=a)break;const{mesh:x,instanceData:B,count:I,material:w}=L;if(!B||!(x!=null&&x.vertices)||!(x!=null&&x.indices))continue;const D=w,O=D?M.readMaterialBaseColor(D):[.5,.5,.5],tt=D?M.readMaterialMetallic(D):0,et=D?M.readMaterialRoughness(D):.5,k=D?Na(D):[0,0,0],W=!xe(D),Y=u(D),G=Ie(D);for(let at=0;at<I&&!(o>=a);at++){const J=at*Tn;o=wa(s,o,a,x.vertices,x.indices,B.subarray(J,J+16),B.subarray(J+16,J+32),O,tt,et,k,Y,W,G.uv0Tf,G.uv1Tf)}}for(const L of t){if(o>=a)break;ar(_,L.transform),Cs(_,_);const x=L.material,B=Ie(x);o=wa(s,o,a,L.mesh.vertices,L.mesh.indices,L.transform,_,M.readMaterialBaseColor(x),M.readMaterialMetallic(x),M.readMaterialRoughness(x),Na(x),u(x),!xe(x),B.uv0Tf,B.uv1Tf)}const v=s.subarray(0,o*Mt);E=Ea(v,o)}const N=a>=1024&&o>=a&&h>o;if(!pn&&N&&(pn=!0,console.warn(`[PathTracer] Triangle count hit the GPU cap (${a}): ${o} uploaded, scene demand ~${h}. Extra geometry is dropped (holes / broken edges). Simplify the GLB or raise PATH_TRACER_MAX_TRIANGLES (check GPU maxStorageBufferBindingSize).`)),o===0)Ca="";else{const _=`${o}|${h}|${a}|${c.texturedSlotsUsed}|tl=${C?1:0}|inst=${R}`;_!==Ca&&(Ca=_,console.info(`[PathTracer] Scene: ${o.toLocaleString()} tris uploaded (cap ${a.toLocaleString()}), demand ~${h.toLocaleString()}, textured material slots ${c.texturedSlotsUsed}/${ft}`+(C?`, TLAS ${R} instances`:", flat BVH")+(N?" — geometry truncated at triangle cap.":".")))}const m=un(s,o,C?S.map(_=>({triBase:_.triBase,triCount:_.triCount,worldFromObject:_.worldFromObject})):null);return{data:n,triangleDataBytes:o*mn,emissiveCatalog:m.bytes,emissiveCount:m.count,emissiveTotalPower:m.totalPower,triangleCount:o,sceneTriangleDemand:h,textureSlotFlags:c.textureSlotFlags,textureSlots:c.textureSlots,matNormalScales:c.matNormalScales,materialTable:l.data,materialCount:l.count,hasTransmission:l.hasTransmission,texturedMaterialSlotsUsed:c.texturedSlotsUsed,bvh:E,instances:A,instanceCount:R,useTwoLevel:C}}const Lo=36;function dt(t,e){return t^=e>>>0,Math.imul(t,16777619)>>>0}function K(t,e){const a=Math.round(e*1e4);return dt(t,a|0)}function Pn(t,e){if(!e||typeof e!="object")return dt(t,0);const a=e;if(typeof a.id=="number"&&(t=dt(t,a.id|0)),typeof a.shadingModel=="string")for(let s=0;s<a.shadingModel.length;s++)t=dt(t,a.shadingModel.charCodeAt(s));typeof a.metallic=="number"&&(t=K(t,a.metallic)),typeof a.roughness=="number"&&(t=K(t,a.roughness));const r=a.diffuseColor;r&&r.length>=3&&(t=K(t,r[0]),t=K(t,r[1]),t=K(t,r[2]));const n=a.properties;if(n instanceof Map){const s=n.get("baseColor");Array.isArray(s)&&s.length>=3&&(t=K(t,Number(s[0])),t=K(t,Number(s[1])),t=K(t,Number(s[2])));const o=n.get("emissiveColor");Array.isArray(o)&&o.length>=3&&(t=K(t,Number(o[0])),t=K(t,Number(o[1])),t=K(t,Number(o[2])));const i=n.get("specularColorFactor");Array.isArray(i)&&i.length>=3&&(t=K(t,Number(i[0])),t=K(t,Number(i[1])),t=K(t,Number(i[2])));for(const c of["metallic","roughness","emissive","clearcoatFactor","clearcoatRoughnessFactor","specularFactor","transmissionFactor","ior","opacity","alphaCutoff","bsdfKind","ormHasMrTex","ormMrUvSet"]){const l=n.get(c);typeof l=="number"&&(t=K(t,l))}for(const c of["uvTfAlbedoOs","uvTfAlbedoRs","uvTfEmissiveOs","uvTfEmissiveRs","uvTfOrmMrOs","uvTfOrmMrRs","uvTfNormalOs","uvTfNormalRs"]){const l=n.get(c);if(Array.isArray(l))for(let u=0;u<Math.min(l.length,4);u++)t=K(t,Number(l[u]))}for(const c of["baseColorTexture","metallicRoughnessTexture","normalTexture","emissiveTexture"])t=dt(t,n.get(c)?1:0)}return t}function Rn(t,e){for(let a=0;a<16;a++)t=K(t,e[a]);return t}function vn(t,e){var r,n;if(e.name)for(let s=0;s<e.name.length;s++)t=dt(t,e.name.charCodeAt(s));t=dt(t,((r=e.vertices)==null?void 0:r.length)??0),t=dt(t,((n=e.indices)==null?void 0:n.length)??0);const a=e.vertices;return a&&a.length>=3&&(t=K(t,a[0]),t=K(t,a[1]),t=K(t,a[2]),t=K(t,a[a.length-3]),t=K(t,a[a.length-2]),t=K(t,a[a.length-1])),t}function Fn(t,e,a){let r=2166136261;if(r=dt(r,a>>>0),r=dt(r,t.length>>>0),r=dt(r,(e==null?void 0:e.length)??0),e)for(const n of e){r=vn(r,n.mesh??{}),r=Pn(r,n.material),r=dt(r,n.count>>>0);const s=n.instanceData;if(s)for(let o=0;o<n.count;o++){const i=o*Lo;r=Rn(r,s.subarray(i,i+16))}}for(const n of t)r=dt(r,n.entityId>>>0),r=vn(r,n.mesh),r=Pn(r,n.material),r=Rn(r,n.transform);return r>>>0}class Cn{constructor(){y(this,"cached",null);y(this,"cachedFingerprint",0);y(this,"stats",{buildsRequested:0,rebuilds:0,cacheHits:0,lastFingerprint:0})}getStats(){return{...this.stats}}clear(){this.cached=null,this.cachedFingerprint=0}buildOrReuse(e,a,r){this.stats.buildsRequested+=1;const n=Fn(e,a,r);return this.stats.lastFingerprint=n,this.cached&&n===this.cachedFingerprint?(this.stats.cacheHits+=1,this.cached):(this.stats.rebuilds+=1,this.cached=En(e,a,r),this.cachedFingerprint=n,this.cached)}}function Zt(t,e){return t^=e>>>0,Math.imul(t,16777619)>>>0}function Lt(t,e){const a=Number.isFinite(e)?Math.round(e*1e4):0;return Zt(t,a|0)}function wo(t){const e=[...t].sort((r,n)=>r.id-n.id||r.type-n.type);let a=2166136261;a=Zt(a,e.length);for(const r of e){a=Zt(a,r.id|0),a=Zt(a,r.type|0);for(let n=0;n<16;n++)a=Lt(a,r.transform[n]??0);a=Lt(a,r.color[0]??0),a=Lt(a,r.color[1]??0),a=Lt(a,r.color[2]??0),a=Lt(a,r.intensity),a=Lt(a,r.range),a=Lt(a,r.inner),a=Lt(a,r.outer),a=Zt(a,r.shadows?1:0),a=Zt(a,r.shape|0)}return a>>>0}const Ho=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];function Ne(t,e,a,r,n,s,o,i,c,l){return{id:t,type:e,transform:a??Ho,color:r,intensity:n,range:s,inner:o,outer:i,shadows:c?1:0,shape:l}}function Oo(t){const e=[];for(const[a,[r,n]]of t.query([M.DirectionalLightComponent,M.TransformComponent]).iter())M.isEntityEffectivelyVisible(t,a)&&e.push(Ne(a,0,n.worldTransform,r.color,r.intensity,0,0,0,r.shadowsEnabled,0));for(const[a,[r,n]]of t.query([M.PointLightComponent,M.TransformComponent]).iter())M.isEntityEffectivelyVisible(t,a)&&e.push(Ne(a,1,n.worldTransform,r.color,r.intensity,r.range,0,0,r.shadowsEnabled,0));for(const[a,[r,n]]of t.query([M.SpotLightComponent,M.TransformComponent]).iter())M.isEntityEffectivelyVisible(t,a)&&e.push(Ne(a,2,n.worldTransform,r.color,r.intensity,r.range,r.innerAngle,r.outerAngle,r.shadowsEnabled,0));for(const[a,[r,n]]of t.query([M.AreaLightComponent,M.TransformComponent]).iter())M.isEntityEffectivelyVisible(t,a)&&e.push(Ne(a,3,n.worldTransform,r.color,r.intensity,0,r.width,r.height,r.shadowsEnabled,r.shape==="disk"?1:0));return e}const Do=`
|
|
3
|
+
struct VsOut {
|
|
4
|
+
@builtin(position) pos: vec4<f32>,
|
|
5
|
+
@location(0) uv: vec2<f32>,
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
@vertex
|
|
9
|
+
fn vs(@builtin(vertex_index) vertexIndex: u32) -> VsOut {
|
|
10
|
+
let pos = array<vec2<f32>, 3>(
|
|
11
|
+
vec2<f32>(-1.0, -1.0),
|
|
12
|
+
vec2<f32>(3.0, -1.0),
|
|
13
|
+
vec2<f32>(-1.0, 3.0)
|
|
14
|
+
);
|
|
15
|
+
let uv = array<vec2<f32>, 3>(
|
|
16
|
+
vec2<f32>(0.0, 1.0),
|
|
17
|
+
vec2<f32>(2.0, 1.0),
|
|
18
|
+
vec2<f32>(0.0, -1.0)
|
|
19
|
+
);
|
|
20
|
+
var output: VsOut;
|
|
21
|
+
output.pos = vec4<f32>(pos[vertexIndex], 0.0, 1.0);
|
|
22
|
+
output.uv = uv[vertexIndex];
|
|
23
|
+
return output;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
@group(0) @binding(0) var srcTex: texture_2d<f32>;
|
|
27
|
+
@group(0) @binding(1) var srcSamp: sampler;
|
|
28
|
+
|
|
29
|
+
fn srgb_to_linear_vec3(c: vec3<f32>) -> vec3<f32> {
|
|
30
|
+
let x = clamp(c, vec3<f32>(0.0), vec3<f32>(1.0));
|
|
31
|
+
let lo = x / 12.92;
|
|
32
|
+
let hi = pow((x + vec3<f32>(0.055)) / 1.055, vec3<f32>(2.4));
|
|
33
|
+
return select(lo, hi, x > vec3<f32>(0.04045));
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
@fragment
|
|
37
|
+
fn fs(input: VsOut) -> @location(0) vec4<f32> {
|
|
38
|
+
return textureSampleLevel(srcTex, srcSamp, input.uv, 0.0);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
@fragment
|
|
42
|
+
fn fs_srgb_decode(input: VsOut) -> @location(0) vec4<f32> {
|
|
43
|
+
let s = textureSampleLevel(srcTex, srcSamp, input.uv, 0.0);
|
|
44
|
+
return vec4<f32>(srgb_to_linear_vec3(s.rgb), s.a);
|
|
45
|
+
}
|
|
46
|
+
`;function In(t,e,a){if(!a)return{targetFormat:"rgba8unorm",decodeSrgbInShader:!1};if(typeof t=="string"&&t.endsWith("-srgb"))return{targetFormat:"rgba8unorm-srgb",decodeSrgbInShader:!1};if(e&&typeof t=="string"){const r=M.TextureLoader.getSrgbViewFormat(t);if(r)return{targetFormat:"rgba8unorm-srgb",sourceViewFormat:r,decodeSrgbInShader:!1}}return typeof t=="string"&&t.includes("float")?{targetFormat:"rgba8unorm-srgb",decodeSrgbInShader:!1}:{targetFormat:"rgba8unorm-srgb",decodeSrgbInShader:!0}}const Go=20;function xn(t,e,a=Hs,r=ir){let n=0;for(let h=0;h<e.length;h++)(e[h]??0)!==0&&(n=h+1);if(n===0)return{totalSlots:0,channelLayers:[0,0,0,0],channelEdges:[0,0,0,0],totalBytes:0};const s=[0,0,0,0],o=[1,1,1,1];for(let h=0;h<n;h++){const d=t[h],p=e[h]??0,S=[p&1?d==null?void 0:d.albedo:void 0,p&2?d==null?void 0:d.orm:void 0,p&4?d==null?void 0:d.normal:void 0,p&8?d==null?void 0:d.emissive:void 0];for(let T=0;T<4;T=T+1){const g=S[T];g&&(s[T]=h+1,o[T]=Math.max(o[T],g.width||1,g.height||1))}}const i=[Math.max(1,s[0]),Math.max(1,s[1]),Math.max(1,s[2]),Math.max(1,s[3])],c=[s[0]>0?Math.min(a,Math.max(1,o[0])):1,s[1]>0?Math.min(a,Math.max(1,o[1])):1,s[2]>0?Math.min(a,Math.max(1,o[2])):1,s[3]>0?Math.min(a,Math.max(1,o[3])):1],l=()=>(c[0]*c[0]*i[0]+c[1]*c[1]*i[1]+c[2]*c[2]*i[2]+c[3]*c[3]*i[3])*4,u=64;for(;l()>r;){let h=-1,d=0;for(let p=0;p<4;p++){const S=c[p];if(S<=u)continue;const T=S*S*i[p]*4;T>d&&(d=T,h=p)}if(h<0)break;c[h]=Math.max(u,Math.floor(c[h]/2))}return{totalSlots:n,channelLayers:i,channelEdges:c,totalBytes:l()}}class Bn{constructor(){y(this,"device",null);y(this,"pipelineLinear",null);y(this,"pipelineSrgbLinearSrc",null);y(this,"pipelineSrgbDecodeSrc",null);y(this,"sampler",null);y(this,"bindGroupLayout",null);y(this,"albedo",null);y(this,"orm",null);y(this,"normal",null);y(this,"emissive",null);y(this,"sources",[]);y(this,"channelEdges",[0,0,0,0]);y(this,"channelLayers",[0,0,0,0]);y(this,"warned",!1)}sync(e,a,r){const n=xn(a,r);if(n.totalSlots===0)return;const{totalSlots:s,channelEdges:o,channelLayers:i}=n,c=new Array(s*4);for(let u=0;u<s;u++){const h=a[u],d=r[u]??0;c[u*4+0]=d&1?(h==null?void 0:h.albedo)??null:null,c[u*4+1]=d&2?(h==null?void 0:h.orm)??null:null,c[u*4+2]=d&4?(h==null?void 0:h.normal)??null:null,c[u*4+3]=d&8?(h==null?void 0:h.emissive)??null:null}if(!(this.device===e&&this.albedo!==null&&this.channelEdges.every((u,h)=>u===o[h])&&this.channelLayers.every((u,h)=>u===i[h])&&this.sources.length===c.length&&this.sources.every((u,h)=>u===c[h])))try{this.rebuild(e,c,s,o,i)}catch(u){this.warned||(this.warned=!0,console.warn("[PathTracer] Material texture array pack failed; maps past the bind stay factors-only.",u))}}bind(e){!this.albedo||!this.orm||!this.normal||!this.emissive||(e.setOutput("pathTracerTexAlbedo",this.albedo),e.setOutput("pathTracerTexOrm",this.orm),e.setOutput("pathTracerTexNormal",this.normal),e.setOutput("pathTracerTexEmissive",this.emissive))}ensurePipeline(e){if(this.device===e&&this.pipelineLinear&&this.pipelineSrgbLinearSrc&&this.pipelineSrgbDecodeSrc&&this.sampler&&this.bindGroupLayout)return;this.device=e,this.pipelineLinear=null,this.pipelineSrgbLinearSrc=null,this.pipelineSrgbDecodeSrc=null,this.bindGroupLayout=e.createBindGroupLayout({label:"pathTracerTexArrayBlit",entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float",viewDimension:"2d"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}}]});const a=e.createShaderModule({label:"pathTracerTexArrayBlit",code:Do}),r=e.createPipelineLayout({bindGroupLayouts:[this.bindGroupLayout]});this.pipelineLinear=e.createRenderPipeline({label:"pathTracerTexArrayBlitLinear",layout:r,vertex:{module:a,entryPoint:"vs"},fragment:{module:a,entryPoint:"fs",targets:[{format:"rgba8unorm"}]},primitive:{topology:"triangle-list"}}),this.pipelineSrgbLinearSrc=e.createRenderPipeline({label:"pathTracerTexArrayBlitSrgb",layout:r,vertex:{module:a,entryPoint:"vs"},fragment:{module:a,entryPoint:"fs",targets:[{format:"rgba8unorm-srgb"}]},primitive:{topology:"triangle-list"}}),this.pipelineSrgbDecodeSrc=e.createRenderPipeline({label:"pathTracerTexArrayBlitSrgbDecode",layout:r,vertex:{module:a,entryPoint:"vs"},fragment:{module:a,entryPoint:"fs_srgb_decode",targets:[{format:"rgba8unorm-srgb"}]},primitive:{topology:"triangle-list"}}),this.sampler=e.createSampler({label:"pathTracerTexArrayBlit",magFilter:"linear",minFilter:"linear",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"})}rebuild(e,a,r,n,s){this.ensurePipeline(e);const o=this.pipelineLinear,i=this.pipelineSrgbLinearSrc,c=this.pipelineSrgbDecodeSrc,l=this.sampler,u=this.bindGroupLayout;if(!o||!i||!c||!l||!u)return;const h=[this.albedo,this.orm,this.normal,this.emissive].filter(A=>A!==null),d=(A,R,C,P)=>e.createTexture({label:A,size:[C,C,P],format:R,usage:Go}),p=d("pathTracerTexAlbedo","rgba8unorm-srgb",n[0],s[0]),S=d("pathTracerTexOrm","rgba8unorm",n[1],s[1]),T=d("pathTracerTexNormal","rgba8unorm",n[2],s[2]),g=d("pathTracerTexEmissive","rgba8unorm-srgb",n[3],s[3]),b=[p,S,T,g],E=e.createCommandEncoder({label:"pathTracerTexArrayBlit"});for(let A=0;A<4;A++){const R=A===0||A===3,C=s[A];for(let P=0;P<Math.min(r,C);P++){const N=a[P*4+A]??null;if(!N)continue;const m=b[A].createView({dimension:"2d",baseArrayLayer:P,arrayLayerCount:1}),_=E.beginRenderPass({colorAttachments:[{view:m,loadOp:"clear",storeOp:"store",clearValue:{r:1,g:1,b:1,a:1}}]}),v=In(N.format,M.TextureLoader.supportsSrgbView(N),R),L=v.sourceViewFormat?N.createView({format:v.sourceViewFormat}):N.createView(),x=e.createBindGroup({layout:u,entries:[{binding:0,resource:L},{binding:1,resource:l}]}),B=R?v.decodeSrgbInShader?c:i:o;_.setPipeline(B),_.setBindGroup(0,x),_.draw(3),_.end()}}e.queue.submit([E.finish()]),this.albedo=p,this.orm=S,this.normal=T,this.emissive=g,this.sources=a,this.channelEdges=[...n],this.channelLayers=[...s],e.queue.onSubmittedWorkDone().then(()=>{for(const A of h)A.destroy()})}}const Uo=[[0,0],[1,1],[1,0],[0,1]],zo=[[0,0],[2,2],[2,0],[0,2],[1,1],[3,3],[3,1],[1,3],[1,0],[3,2],[3,0],[1,2],[0,1],[2,3],[2,1],[0,3]];function Nn(t,e){const a=Math.max(1,Math.min(4,Math.floor(t)));if(a<=1)return{ox:0,oy:0};const r=a*a,n=(e%r+r)%r;if(a===2){const[i,c]=Uo[n];return{ox:i,oy:c}}if(a===3){const i=n%3,c=Math.floor(n/3);return{ox:i,oy:c}}const[s,o]=zo[n];return{ox:s,oy:o}}function Ln(t,e,a){const r=Math.max(1,Math.floor(a));return{dispatchW:Math.max(1,Math.ceil(t/r)),dispatchH:Math.max(1,Math.ceil(e/r))}}function Wo(t,e,a,r=8){const{dispatchW:n,dispatchH:s}=Ln(t,e,a),o=Math.max(1,Math.floor(r));return[Math.ceil(n/o),Math.ceil(s/o),1]}function Vo(t,e){const a=Math.max(1,Math.floor(e));return t+1/(a*a)}function wn(t,e){const a=Math.max(1,Math.floor(t));return a<=1?!0:e>0&&e%(a*a)===0}const Ha=1,Oa=4,Da=1e3/30,ko=1e3/45;class Hn{constructor(e=2){y(this,"ewmaMs",Da);y(this,"stride",2);y(this,"alpha",.12);this.stride=Math.max(Ha,Math.min(Oa,Math.floor(e)))}getStride(){return this.stride}setStride(e){this.stride=Math.max(Ha,Math.min(Oa,Math.floor(e)))}tick(e){return!Number.isFinite(e)||e<=0?this.stride:(this.ewmaMs=this.ewmaMs<=0?e:this.ewmaMs*(1-this.alpha)+e*this.alpha,this.ewmaMs>Da*1.08?this.stride=Math.min(Oa,this.stride+1):this.ewmaMs<ko&&this.stride>Ha&&(this.stride=this.stride-1),this.stride)}reset(){this.ewmaMs=Da}}const $o=8,Yo=9,Xo=10,jo=11,qo=12,Ko=13,Zo=14,Jo=15;function On(t){switch(t){case"albedo":return 1;case"normal":return 2;case"depth":return 3;case"objectId":return 4;default:return 0}}const Qo=8;function Ga(t){const e=Math.floor(Number.isFinite(t)?t:4);return Math.max(1,Math.min(8,e))}class Dn{constructor(e=Qo){y(this,"phase","Interactive");y(this,"stillFrames",0);y(this,"refiningHysteresis");y(this,"maxBouncesCap",4);this.refiningHysteresis=Math.max(1,Math.floor(e))}setMaxBouncesCap(e){this.maxBouncesCap=Ga(e)}getPhase(){return this.phase}isPreview(){return this.phase==="Interactive"}getMaxBounces(){return this.phase==="Interactive"?Math.min(2,this.maxBouncesCap):this.maxBouncesCap}reset(){this.phase="Interactive",this.stillFrames=0}tick(e){if(e.interaction)return this.phase="Interactive",this.stillFrames=0,this.phase;switch(this.stillFrames+=1,this.phase){case"Interactive":this.stillFrames>=this.refiningHysteresis&&(this.phase="Refining");break;case"Refining":e.converged&&(this.phase="Converged");break;case"Converged":e.denoised&&(this.phase="Denoised");break}return this.phase}}const Gn=256;function Un(t,e){let a=t,r=e;const n=1-Math.abs(a)-Math.abs(r),s=Math.max(-n,0);a+=a>=0?-s:s,r+=r>=0?-s:s;const o=Math.hypot(a,r,n)||1;return[a/o,r/o,n/o]}function ti(t,e,a){const r=new Uint8ClampedArray(e*a*4),n=e*a;for(let s=0;s<n;s++){const[o,i,c]=Un(t[s*4],t[s*4+1]),l=s*4;r[l]=Math.round((o*.5+.5)*255),r[l+1]=Math.round((i*.5+.5)*255),r[l+2]=Math.round((c*.5+.5)*255),r[l+3]=255}return r}function zn(t,e,a){return e||a?0:t+1}function ei(t,e,a){if(a)return!1;const r=typeof e=="number"&&Number.isFinite(e)&&e>0?e:Gn;return t>=r}function Wn(){return globalThis}function ai(){return Wn().__W3DTS_PATH_TRACER_INTERACTION_EPOCH__??0}function Le(){const t=Wn();t.__W3DTS_PATH_TRACER_INTERACTION_EPOCH__=(t.__W3DTS_PATH_TRACER_INTERACTION_EPOCH__??0)+1}const Vn=1e-6;function ri(t){return{fov:t.fov,projectionMode:t.projectionMode,orthographicHalfHeight:t.orthographicHalfHeight}}function ni(t,e){return t.projectionMode!==e.projectionMode?!0:e.projectionMode==="orthographic"?Math.abs(t.orthographicHalfHeight-e.orthographicHalfHeight)>Vn:Math.abs(t.fov-e.fov)>Vn}const si=1e-4,oi=1e-6,kn=.005,$n=1e-4,ii=512,ci=1;function li(){var e;const t=(e=globalThis.__W3DTS_PATH_TRACER_CONFIG)==null?void 0:e.hybridTraceScale;return t===.25||t===.5||t===1?t:.5}function Yn(){const t=typeof globalThis<"u"?globalThis.__W3DTS_PATH_TRACER_CONFIG:void 0,e=(t==null?void 0:t.progressiveFrameStride)??1,a=(t==null?void 0:t.denoiserKernelRadius)??3,r=(t==null?void 0:t.fsrRcasSharpness)??.35,n=t==null?void 0:t.softSunAngularRadius,s=t==null?void 0:t.denoiserAlgorithm,o=s==="atrous"||s==="off"||s==="spatial"?s:"spatial",i=t==null?void 0:t.atrousBlend;return{maxSamples:Math.max(cr,Math.min(4096,(t==null?void 0:t.maxSamples)??ii)),mirrorBouncesWhenStatic:Math.max(0,Math.min(4,(t==null?void 0:t.mirrorBouncesWhenStatic)??ci)),progressiveFrameStride:Math.max(1,Math.min(16,Math.floor(e))),tileSize:sa((t==null?void 0:t.tileSize)??_e),enableGI:(t==null?void 0:t.enableGI)??!0,enableAO:(t==null?void 0:t.enableAO)??!0,enableReflection:(t==null?void 0:t.enableReflection)??!0,enableShadow:(t==null?void 0:t.enableShadow)??!0,denoiserKernelRadius:Math.max(1,Math.min(16,Math.floor(a))),spatialDenoiserEnabled:(t==null?void 0:t.spatialDenoiserEnabled)!==!1,fsrEasuEnabled:(t==null?void 0:t.fsrEasuEnabled)!==!1,fsrRcasEnabled:(t==null?void 0:t.fsrRcasEnabled)!==!1,fsrRcasSharpness:Math.max(0,Math.min(2,Number.isFinite(r)?r:.35)),useBvh:(t==null?void 0:t.useBvh)!==!1,useEnvCubemap:(t==null?void 0:t.useEnvCubemap)!==!1,softSunAngularRadius:typeof n=="number"&&Number.isFinite(n)?Math.max(0,Math.min(.5,n)):.004,softSunExtraRay:(t==null?void 0:t.softSunExtraRay)===!0,guidedDenoise:(t==null?void 0:t.guidedDenoise)!==!1,denoiserFireflySuppress:(t==null?void 0:t.denoiserFireflySuppress)!==!1,ggxReflection:(t==null?void 0:t.ggxReflection)!==!1,pathTraceTriangleBudget:Math.max(0,Math.floor((t==null?void 0:t.pathTraceTriangleBudget)??0)),realtimeTargetFps:Math.max(0,Math.floor((t==null?void 0:t.realtimeTargetFps)??0)),envIblIntensity:(()=>{const c=t==null?void 0:t.envIblIntensity;return typeof c=="number"&&Number.isFinite(c)?Math.max(.05,Math.min(8,c)):1})(),emissiveIntensity:(()=>{const c=t==null?void 0:t.emissiveIntensity;return typeof c=="number"&&Number.isFinite(c)?Math.max(0,Math.min(20,c)):1})(),emissiveBounceScale:(()=>{const c=t==null?void 0:t.emissiveBounceScale;return typeof c=="number"&&Number.isFinite(c)?Math.max(0,Math.min(5,c)):1})(),denoiserAlgorithm:o,atrousBlend:typeof i=="number"&&Number.isFinite(i)?Math.max(.05,Math.min(1,i)):.45,transparentBackground:(t==null?void 0:t.transparentBackground)===!0,unlitAsDiffuse:(t==null?void 0:t.unlitMode)==="diffuse",progressiveSpatial:(t==null?void 0:t.progressiveSpatial)!==!1,maxBounces:Ga((t==null?void 0:t.maxBounces)??4),aovDebugView:(()=>{const c=t==null?void 0:t.aovDebugView;return c==="albedo"||c==="normal"||c==="depth"||c==="objectId"?c:"off"})(),hybridReflRoughnessMax:fi(t==null?void 0:t.hybridReflRoughnessMax),hybridAoRadius:hi(t==null?void 0:t.hybridAoRadius),hybridLightRadius:ui(t==null?void 0:t.hybridLightRadius)}}function hi(t){return typeof t!="number"||!Number.isFinite(t)?1:Math.max(0,Math.min(10,t))}function ui(t){return typeof t!="number"||!Number.isFinite(t)?0:Math.max(0,Math.min(5,t))}function fi(t){return typeof t!="number"||!Number.isFinite(t)||t<=0?.5:Math.min(1,t)}function Pt(t){const e=new Float32Array(1);return e[0]=t,new Uint32Array(e.buffer)[0]}function Ua(t){return Math.max(.25,Math.min(1,t))}function za(t,e,a){const r=typeof globalThis<"u"?globalThis.__W3DTS_PATH_TRACER_CONFIG:void 0;let n;return a?typeof(r==null?void 0:r.pathTraceResolutionScale)=="number"&&Number.isFinite(r.pathTraceResolutionScale)?n=Ua(r.pathTraceResolutionScale):typeof(r==null?void 0:r.resolutionScale)=="number"&&Number.isFinite(r.resolutionScale)?n=Ua(r.resolutionScale):n=1:n=typeof(r==null?void 0:r.resolutionScale)=="number"&&Number.isFinite(r.resolutionScale)?Ua(r.resolutionScale):1,n<1?{w:Math.max(1,Math.floor(t*n)),h:Math.max(1,Math.floor(e*n))}:{w:t,h:e}}function Wa(){if((typeof globalThis<"u"?globalThis.__W3DTS_ACTIVE_PROJECT??"":"")!=="PathTracerStudio")return null;const e=M.getGameViewRenderModeFromGlobal();if(e!=="pathtrace"&&e!=="hybrid")return null;const a=M.getGameViewSurfacePixelSize();return a.width<=0||a.height<=0?null:{baseW:a.width,baseH:a.height}}function Xn(t,e){const a=Wa();if(a)return za(a.baseW,a.baseH,e);const r=t.webGPUContext.canvas.width,n=t.webGPUContext.canvas.height;return za(r,n,e)}function di(t,e){for(const a of[t.renderGraph,t.gameRenderGraph]){const r=a.getPasses().find(c=>c.name==="04e_HybridDenoisedSelect");if(!r||r.type!=="fullscreen"||!r.uniforms)continue;const n=r.uniforms.useDenoised;if(!n)continue;const s=a.getTexture("sceneColor"),o=a.getTexture("hybridDenoisedBeauty"),i=s!=null&&o!=null&&s.width>1&&s.width===o.width&&s.height===o.height;n.value=e>0&&i?1:0}}function jn(t){typeof globalThis>"u"||(globalThis.__W3DTS_PATH_TRACER_PROGRESS__=t)}function mi(t){const e=Yn(),a=e.maxSamples,r=Math.max(1,e.progressiveFrameStride),n=Xn(t,!1),s=n.w,o=n.h,i=e.tileSize,c=Math.max(1,Math.ceil(s/i)),l=Math.max(1,Math.ceil(o/i)),u=c*l;return{progress:0,progressPercent:0,samplesDone:0,samplesTotal:u*a,tileIndex:0,totalTiles:u,gridCols:c,gridRows:l,accumFrameIndex:0,maxSamples:a,converged:!1,traceThisFrame:!0,progressiveStride:r,estimatedSecondsRemaining:null,sceneWidth:s,sceneHeight:o,progressiveSpatial:e.progressiveSpatial!==!1}}function qn(t){typeof globalThis>"u"||globalThis.__W3DTS_PATH_TRACER_PROGRESS__!==void 0||jn(mi(t))}const Kn="__W3DTS_PATH_TRACER_ACCUM_PAUSED__";function Zn(){return typeof globalThis>"u"?!1:globalThis[Kn]===!0}function pi(t){typeof globalThis>"u"||(globalThis[Kn]=t)}function Ti(t,e){if(e<=0)return 2166136261;const a=e>>>2,r=new Uint32Array(t,0,a);let n=2166136261;for(let s=0;s<r.length;s++)n^=r[s],n=Math.imul(n,16777619);return n>>>0}class Va{constructor(){y(this,"baselineMetrics",new Jr);y(this,"sceneCache",new Cn);y(this,"uploadedScenePerGraph",new WeakMap);y(this,"lastCameraPosition",xt());y(this,"lastCameraForward",xt());y(this,"lastCameraLens",null);y(this,"hasLastCamera",!1);y(this,"lastViewProj",new Float32Array(16));y(this,"hasHybridViewProj",!1);y(this,"hybridStaticFrames",0);y(this,"hybridBeautyW",-1);y(this,"hybridBeautyH",-1);y(this,"lastResetReasons",[]);y(this,"resetCounts",{});y(this,"lastTriangleHash",0);y(this,"lastLightHash",0);y(this,"hasLightHash",!1);y(this,"lastEmissiveHash",null);y(this,"lastShadowsEnabled",!1);y(this,"frameIndex",0);y(this,"sppCoverage",0);y(this,"rngFrame",0);y(this,"lastEnableGI",!0);y(this,"lastEnableAO",!0);y(this,"lastEnableReflection",!0);y(this,"lastEnableShadow",!0);y(this,"pathTracerLightEntityId",null);y(this,"progressivePhase",0);y(this,"decoupleTraceResolution",!1);y(this,"traceMode","beauty");y(this,"tileIndex",0);y(this,"lastSceneW",-1);y(this,"lastSceneH",-1);y(this,"interleavePhase",0);y(this,"spatialBudget",new Hn(2));y(this,"lastFrameWallMs",0);y(this,"progressiveState",new Dn);y(this,"holdDisplayUntilRound",!1);y(this,"holdRoundStartPhase",0);y(this,"ewmaSamplesPerSec",0);y(this,"lastEwmaSampleDone",-1);y(this,"lastEwmaWallMs",0);y(this,"lastEnvironmentCubemap",null);y(this,"lastEnvIblIntensity",Number.NaN);y(this,"lastEmissiveIntensity",Number.NaN);y(this,"lastEmissiveBounceScale",Number.NaN);y(this,"lastTransparentBackground",!1);y(this,"lastUnlitAsDiffuse",!1);y(this,"lastTriangleStats",{count:0,demand:0,cap:Bt});y(this,"matFactorsPad",new Float32Array(ft));y(this,"materialTextureArrays",new Bn);y(this,"tileInfoScratch",new Uint32Array(16));y(this,"denoiserParamsScratch",new Uint32Array(8));y(this,"paramsScratch",new Uint32Array(ta));y(this,"envEmptyHeader",new Float32Array(4));y(this,"envWrittenSerial",new WeakMap);y(this,"postParamsScratch",new Float32Array(ha));y(this,"fsrParamsScratch");y(this,"fsrParamsDataView");y(this,"fsrEasuFloats");this.fsrParamsScratch=new ArrayBuffer(Ee),this.fsrParamsDataView=new DataView(this.fsrParamsScratch),this.fsrEasuFloats=new Float32Array(this.fsrParamsScratch,0,16)}setPreferredLightEntity(e){this.pathTracerLightEntityId=e}setDecoupleTraceResolution(e){this.decoupleTraceResolution=e}setTraceMode(e){this.traceMode!==e&&(this.traceMode=e,this.resetAccumulationState())}getSceneCacheStats(){return this.sceneCache.getStats()}resetAccumulationState(){this.sceneCache.clear(),this.hasLastCamera=!1,this.hasHybridViewProj=!1,this.hybridStaticFrames=0,this.lastTriangleHash=0,this.lastLightHash=0,this.hasLightHash=!1,this.lastEmissiveHash=null,this.frameIndex=0,this.sppCoverage=0,this.rngFrame=0,this.progressivePhase=0,this.tileIndex=0,this.interleavePhase=0,this.spatialBudget.reset(),this.lastFrameWallMs=0,this.progressiveState.reset(),Le(),this.holdDisplayUntilRound=!1,this.holdRoundStartPhase=0,this.lastSceneW=-1,this.lastSceneH=-1,this.ewmaSamplesPerSec=0,this.lastEwmaSampleDone=-1,this.lastEwmaWallMs=0,this.lastEnvironmentCubemap=null,this.lastEnvIblIntensity=Number.NaN,this.lastEmissiveIntensity=Number.NaN,this.lastEmissiveBounceScale=Number.NaN,this.lastTransparentBackground=!1,this.lastUnlitAsDiffuse=!1,this.lastResetReasons=[],this.resetCounts={}}tick(e){var Rs;qn(e);const{maxSamples:a,mirrorBouncesWhenStatic:r,progressiveFrameStride:n,tileSize:s,enableGI:o,enableAO:i,enableReflection:c,enableShadow:l,denoiserKernelRadius:u,spatialDenoiserEnabled:h,fsrEasuEnabled:d,fsrRcasEnabled:p,fsrRcasSharpness:S,useBvh:T,useEnvCubemap:g,softSunAngularRadius:b,softSunExtraRay:E,guidedDenoise:A,denoiserFireflySuppress:R,ggxReflection:C,pathTraceTriangleBudget:P,realtimeTargetFps:N,envIblIntensity:m,emissiveIntensity:_,emissiveBounceScale:v,denoiserAlgorithm:L,atrousBlend:x,transparentBackground:B,unlitAsDiffuse:I,progressiveSpatial:w,maxBounces:D,aovDebugView:O,hybridReflRoughnessMax:tt,hybridAoRadius:et,hybridLightRadius:k}=Yn(),W=la(),Y=(W==null?void 0:W.maxRadiance)??0;this.progressiveState.setMaxBouncesCap(D);const G=this.traceMode==="hybridAov",at=w||G?1:Math.max(1,n),J=Zn();let $=!J&&this.progressivePhase===0;J||(this.progressivePhase=(this.progressivePhase+1)%at);const wt=typeof performance<"u"?performance.now():0;!J&&w&&!G&&this.lastFrameWallMs>0&&this.spatialBudget.tick(wt-this.lastFrameWallMs),this.lastFrameWallMs=wt;const mt=G||!w?1:this.spatialBudget.getStride(),Jt=P>0?Math.min(Bt,P>>>0):Bt,F=$?this.sceneCache.buildOrReuse(e.renderQueue,e.renderList,Jt):null,Qt=(F==null?void 0:F.data)??new ArrayBuffer(0),ge=(F==null?void 0:F.triangleCount)??0;F&&(this.lastTriangleStats={count:F.triangleCount,demand:F.sceneTriangleDemand,cap:Jt});const kt=this.sceneCache.getStats().lastFingerprint,te=Xn(e,this.decoupleTraceResolution),it=te.w,ht=te.h,$t=Math.max(1,Math.ceil(it/s)),ee=Math.max(1,Math.ceil(ht/s)),Ht=$t*ee;let X=0;const rt=[];let Q=!1,Ot=!1,Dt=!1;(it!==this.lastSceneW||ht!==this.lastSceneH)&&(this.lastSceneW=it,this.lastSceneH=ht,X=1,rt.push("resize"),Q=!0,this.tileIndex=0,this.holdDisplayUntilRound=!1);const U=e.renderer.getEnvironmentCubemap(),ot=g?U:null;ot!==this.lastEnvironmentCubemap&&(X=1,rt.push("environment"),Q=!0,this.tileIndex=0,this.holdDisplayUntilRound=!1),this.lastEnvironmentCubemap=ot,Number.isFinite(this.lastEnvIblIntensity)&&Math.abs(m-this.lastEnvIblIntensity)>1e-5&&(X=1,rt.push("envIntensity"),Q=!0,this.tileIndex=0,this.holdDisplayUntilRound=!1),this.lastEnvIblIntensity=m,(Number.isFinite(this.lastEmissiveIntensity)&&Math.abs(_-this.lastEmissiveIntensity)>1e-5||Number.isFinite(this.lastEmissiveBounceScale)&&Math.abs(v-this.lastEmissiveBounceScale)>1e-5)&&(X=1,rt.push("emissiveIntensity"),Q=!0,this.tileIndex=0,this.holdDisplayUntilRound=!1),this.lastEmissiveIntensity=_,this.lastEmissiveBounceScale=v,B!==this.lastTransparentBackground&&(X=1,rt.push("background"),Q=!0,this.tileIndex=0,this.holdDisplayUntilRound=!1),this.lastTransparentBackground=B,I!==this.lastUnlitAsDiffuse&&(X=1,rt.push("features"),Q=!0,this.tileIndex=0,this.holdDisplayUntilRound=!1),this.lastUnlitAsDiffuse=I;const j=(F==null?void 0:F.triangleDataBytes)??0;if($&&kt!==this.lastTriangleHash){const q=kt!==0?kt:Ti(Qt,j);X=1,rt.push("scene"),Q=!0,this.tileIndex=0,this.holdDisplayUntilRound=!1,this.lastTriangleHash=q}const fs=wo(Oo(e.ecsWorld));if(this.hasLightHash&&fs!==this.lastLightHash&&(X=1,rt.push("lights"),Q=!0,this.tileIndex=0,this.holdDisplayUntilRound=!1),this.lastLightHash=fs,this.hasLightHash=!0,$&&F){const H=dn(F.emissiveCount,F.emissiveTotalPower);this.lastEmissiveHash!==null&&H!==this.lastEmissiveHash&&(X=1,rt.push("scene"),Q=!0,this.tileIndex=0,this.holdDisplayUntilRound=!1),this.lastEmissiveHash=H}const $i=Wa()!=null?e.getGameCameraEntityId():null,Ja=(G?e.getGameCameraEntityId():null)??$i??e.cameraControllerManager.getCameraEntity();if(Ja!==null){const H=e.ecsWorld.getComponent(Ja,M.TransformComponent);if(H){const q=H.position,st=H.worldTransform,ct=oe(-st[8],-st[9],-st[10]);ie(ct,ct);const Ut=typeof globalThis<"u"&&globalThis.__W3DTS_E2E_LOCK_PATHTRACER_STUDIO_PATHTRACE__===!0,pt=e.ecsWorld.getComponent(Ja,M.CameraComponent),Se=pt!=null&&this.lastCameraLens!=null&&ni(this.lastCameraLens,pt);if(pt&&(this.lastCameraLens=ri(pt)),this.hasLastCamera){const zt=xs(q,this.lastCameraPosition),Ct=nr(ct,this.lastCameraForward),ne=G?kn:si,se=G?$n:oi;if(G&&(zt>kn||1-Ct>$n||Se)&&(Dt=!0),!G&&!Ut&&(zt>ne||1-Ct>se||Se)){X=1,rt.push("camera"),Ot=!0,this.tileIndex=0,this.holdDisplayUntilRound=!1,this.holdRoundStartPhase=0;const qe=typeof performance<"u"?performance.now():0;this.baselineMetrics.markInteractive(qe)}}else X=1,rt.push("cameraInit"),Q=!0,this.tileIndex=0,this.holdDisplayUntilRound=!1;if(rr(this.lastCameraPosition,q),rr(this.lastCameraForward,ct),this.hasLastCamera=!0,pt){const zt=pt.viewProjectionMatrix;if(this.hasHybridViewProj)for(let Ct=0;Ct<16;Ct++)Math.abs(zt[Ct]-this.lastViewProj[Ct])>.001&&(Dt=!0);this.lastViewProj.set(zt),this.hasHybridViewProj=!0}}}let We=!1,Yt=null;if(this.pathTracerLightEntityId!==null){const H=e.ecsWorld.getComponent(this.pathTracerLightEntityId,M.DirectionalLightComponent);H&&(Yt=H)}if(!Yt){const H=e.ecsWorld.query([M.DirectionalLightComponent]);for(const[,[q]]of H.iter()){if(q.shadowsEnabled){Yt=q;break}Yt||(Yt=q)}}Yt&&(We=Yt.shadowsEnabled),We!==this.lastShadowsEnabled&&(X=1,rt.push("shadows"),Q=!0,this.tileIndex=0,this.lastShadowsEnabled=We),(o!==this.lastEnableGI||i!==this.lastEnableAO||c!==this.lastEnableReflection||l!==this.lastEnableShadow)&&(X=1,rt.push("features"),Q=!0,this.tileIndex=0,this.lastEnableGI=o,this.lastEnableAO=i,this.lastEnableReflection=c,this.lastEnableShadow=l),!w&&!G&&!Q&&$&&this.frameIndex>=a&&this.tileIndex<Ht-1&&(this.tileIndex++,X=1,rt.push("tile"));const Yi=Q||Ot?1:0;if(X===1){this.lastResetReasons=rt;for(const H of rt)this.resetCounts[H]=(this.resetCounts[H]??0)+1;this.frameIndex=0,this.sppCoverage=0,this.rngFrame=0,this.interleavePhase=0,Ot&&w&&(this.holdRoundStartPhase=0)}$&&(w||G?(this.interleavePhase+=1,this.sppCoverage=Vo(this.sppCoverage,mt),this.rngFrame=this.interleavePhase,this.holdDisplayUntilRound&&wn(mt,this.interleavePhase-this.holdRoundStartPhase)&&(this.holdDisplayUntilRound=!1)):(this.frameIndex++,this.rngFrame=this.frameIndex,this.holdDisplayUntilRound=!1));const Xi=X===1?0:r,ds=Q||Ot;if((ds||G&&Dt)&&(this.progressiveState.tick({interaction:!0,converged:!1}),Le(),typeof globalThis<"u"&&(globalThis.__W3DTS_PATH_TRACER_FINAL_DENOISED__=!1)),G){const H=e.gameRenderGraph.getTexture("sceneColor"),q=(H==null?void 0:H.width)??0,st=(H==null?void 0:H.height)??0;(q!==this.hybridBeautyW||st!==this.hybridBeautyH)&&(this.hybridBeautyW>0&&Le(),typeof globalThis<"u"&&(globalThis.__W3DTS_PATH_TRACER_FINAL_DENOISED__=!1)),this.hybridBeautyW=q,this.hybridBeautyH=st;const Ut=q<2||st<2;this.hybridStaticFrames=zn(this.hybridStaticFrames,Dt||Ut,X===1);const pt=typeof globalThis<"u"&&globalThis.__W3DTS_PATH_TRACER_FINAL_DENOISED__===!0;di(e,pt?1:0)}const ms=!G&&typeof globalThis<"u"&&globalThis.__W3DTS_PATH_TRACER_FINAL_DENOISED__===!0;if(!G){const H={PREVIEW_MODE:this.progressiveState.isPreview(),MAX_BOUNCES:this.progressiveState.getMaxBounces()};e.renderGraph.setComputePassConstants("PathTrace",H),e.gameRenderGraph.setComputePassConstants("PathTrace",H)}const ps=!h||L==="off",Ts=h&&L==="atrous",ji=h&&L==="spatial",bs=w&&mt>1,Qa=X===1||ps||Ts||!ji||bs?1:0,qi=A&&Qa===0?1:0,Ki=R&&Qa===0?1:0,Zi=Ts&&!ps&&!bs?1:0;this.denoiserParamsScratch[0]=Qa,this.denoiserParamsScratch[1]=u,this.denoiserParamsScratch[2]=qi,this.denoiserParamsScratch[3]=Ki,this.denoiserParamsScratch[4]=Zi,this.denoiserParamsScratch[5]=Pt(x),this.denoiserParamsScratch[6]=0,this.denoiserParamsScratch[7]=0;const Ji=l&&We,ys=Nn(mt,Math.max(0,this.interleavePhase-1));let Ve,ke,$e,Ye;if(w||G)Ve=0,ke=0,$e=it,Ye=ht,this.tileIndex=0;else{const H=this.tileIndex%$t,q=Math.floor(this.tileIndex/$t);Ve=H*s,ke=q*s,$e=Math.min(s,Math.max(0,it-Ve)),Ye=Math.min(s,Math.max(0,ht-ke))}const gs=G||!w?null:Wo($e,Ye,mt);if(!G)e.renderGraph.setComputePassWorkgroupCount("PathTrace",gs),e.gameRenderGraph.setComputePassWorkgroupCount("PathTrace",gs);else{const H=e.gameRenderGraph.getTexture("hybridShadowAov"),q=(H==null?void 0:H.width)??it,st=(H==null?void 0:H.height)??ht,ct=X===1?1:li(),Ut=Math.max(1,Math.ceil(q*ct)),pt=Math.max(1,Math.ceil(st*ct));e.gameRenderGraph.setComputePassWorkgroupCount("HybridPrimaryAov",[Math.ceil(Ut/8),Math.ceil(pt/8),1])}this.tileInfoScratch.fill(0),this.tileInfoScratch[0]=Ve,this.tileInfoScratch[1]=ke,this.tileInfoScratch[2]=it,this.tileInfoScratch[3]=ht,this.tileInfoScratch[4]=$e,this.tileInfoScratch[5]=Ye,this.tileInfoScratch[6]=Yi,this.tileInfoScratch[7]=w&&this.holdDisplayUntilRound&&!Q?1:0,this.tileInfoScratch[$o]=w&&!G?mt:1,this.tileInfoScratch[Yo]=w&&!G?ys.ox:0,this.tileInfoScratch[Xo]=w&&!G?ys.oy:0,this.tileInfoScratch[jo]=w||G?1:0,this.tileInfoScratch[qo]=On(O),this.tileInfoScratch[Ko]=ms?1:0,this.tileInfoScratch[Zo]=G?Pt(tt):0,this.tileInfoScratch[Jo]=G?Pt(20):0;let vt=0;T&&(F!=null&&F.bvh)&&F.bvh.nodeCount>0&&(vt|=Ws),T&&(F!=null&&F.useTwoLevel)&&(F.instanceCount??0)>0&&(vt|=gr),g&&U&&(vt|=Vs),b>0&&(vt|=ks),E&&(vt|=Ys),A&&(vt|=$s),C&&(vt|=Xs),B&&(vt|=yr),I&&(vt|=Sr);const Ss=T&&(F!=null&&F.bvh)?F.bvh.nodeCount>>>0:0,Qi=T&&(F!=null&&F.bvh)&&Ss>0?F.bvh.rootIndex>>>0:0;this.paramsScratch[0]=X,this.paramsScratch[1]=Ji?1:0,this.paramsScratch[2]=this.rngFrame,this.paramsScratch[3]=a,this.paramsScratch[4]=Xi,this.paramsScratch[5]=o?1:0,this.paramsScratch[6]=i?1:0,this.paramsScratch[7]=c?1:0,this.paramsScratch[8]=$?1:0,this.paramsScratch[9]=vt>>>0,this.paramsScratch[10]=Ss,this.paramsScratch[11]=Qi,this.paramsScratch[12]=ge>>>0,this.paramsScratch[13]=Pt(m),this.paramsScratch[14]=((F==null?void 0:F.instanceCount)??0)>>>0,this.paramsScratch[15]=this.progressiveState.getMaxBounces()>>>0,this.paramsScratch[16]=Br(xr(W??void 0,D)),this.paramsScratch[17]=Number.isFinite(Y)&&Y>0?Pt(Y):0,this.paramsScratch[18]=F!=null&&F.hasTransmission?fr:0,this.paramsScratch[19]=Pt(Math.max(b,0)),this.paramsScratch[20]=Pt(et),this.paramsScratch[21]=Pt(k),this.paramsScratch[22]=Pt(_-1),this.paramsScratch[23]=Pt(v-1);const ae=Wa(),tc=(ae==null?void 0:ae.baseW)??e.webGPUContext.canvas.width,ec=(ae==null?void 0:ae.baseH)??e.webGPUContext.canvas.height;Kr(it,ht,it,ht,tc,ec,this.fsrEasuFloats);const Xe=this.fsrParamsDataView;Xe.setUint32(64,d?1:0,!0),Xe.setUint32(68,p?1:0,!0),Xe.setFloat32(72,Math.pow(2,-S),!0),Xe.setUint32(76,0,!0);const St=e.webGPUContext.device.queue;$&&F&&this.materialTextureArrays.sync(e.webGPUContext.device,F.textureSlots,F.textureSlotFlags);for(const H of[e.renderGraph,e.gameRenderGraph]){const q=H.getBuffer("sceneTriangles"),st=H.getBuffer("pathTracerParams"),ct=H.getBuffer("pathTracerSunDirection"),Ut=H.getBuffer("pathTracerDenoiserParams"),pt=H.getBuffer("pathTracerFsrParams"),Se=H.getBuffer("pathTracerTexSlotFlags"),zt=H.getBuffer("pathTracerMatFactors"),Ct=H.getBuffer("pathTracerMaterials"),ne=H.getBuffer("pathTracerBvhNodes"),se=H.getBuffer("pathTracerInstances"),qe=H.getBuffer("pathTracerTileInfo");if(q){if($){const It=this.uploadedScenePerGraph.get(H),Me=F!==null&&((It==null?void 0:It.scene)!==F||It.triangles!==q||It.bvhNodes!==ne||It.instances!==se);if(Me&&j>0&&St.writeBuffer(q,0,Qt,0,j),F&&Se){const Tt=F.textureSlotFlags;St.writeBuffer(Se,0,Tt.buffer,Tt.byteOffset,Tt.byteLength)}if(F&&zt&&(this.matFactorsPad.fill(0),this.matFactorsPad.set(F.matNormalScales.subarray(0,ft)),St.writeBuffer(zt,0,this.matFactorsPad)),F&&Ct){const Tt=F.materialTable;St.writeBuffer(Ct,0,Tt.buffer,Tt.byteOffset,F.materialCount*Vt*4)}if(Me&&ne&&(F!=null&&F.bvh)&&T&&F.bvh.nodeCount>0){const Tt=F.bvh.nodeCount*32;St.writeBuffer(ne,0,F.bvh.nodes,0,Tt)}if(Me&&se&&(F!=null&&F.useTwoLevel)&&F.instances&&F.instanceCount>0){const Tt=Math.min(F.instances.byteLength,F.instanceCount*ce);St.writeBuffer(se,0,F.instances,0,Tt)}if(Me&&F){const Tt=H.getBuffer("pathTracerEmissive");Tt&&F.emissiveCatalog&&St.writeBuffer(Tt,0,F.emissiveCatalog,0,F.emissiveCatalog.byteLength),this.uploadedScenePerGraph.set(H,{scene:F,triangles:q,bvhNodes:ne,instances:se})}F&&this.materialTextureArrays.bind(H),g&&U&&H.setOutput("pathTracerEnvCubemap",U)}if(st&&St.writeBuffer(st,0,this.paramsScratch),ct){const It=wr();(this.envWrittenSerial.get(ct)??-1)!==It.serial&&(St.writeBuffer(ct,0,It.data??this.envEmptyHeader),this.envWrittenSerial.set(ct,It.serial))}Ut&&St.writeBuffer(Ut,0,this.denoiserParamsScratch),pt&&St.writeBuffer(pt,0,this.fsrParamsScratch,0,Ee),qe&&St.writeBuffer(qe,0,this.tileInfoScratch.buffer,this.tileInfoScratch.byteOffset,this.tileInfoScratch.byteLength)}}const Ms=Math.max(1,it*ht);let Gt,Ft,re;if(w||G){Gt=Ms*a;const H=Math.min(this.sppCoverage,a);Ft=Math.min(Gt,H*Ms),re=a>0&&this.sppCoverage>=a}else{Gt=Ht*a;const H=Math.min(this.frameIndex,a);Ft=Math.min(Gt,this.tileIndex*a+H),re=a>0&&this.tileIndex>=Ht-1&&this.frameIndex>=a}const As=Gt>0?Ft/Gt:0,je=typeof performance<"u"?performance.now():0;if(Q)this.ewmaSamplesPerSec=0,this.lastEwmaSampleDone=Ft,this.lastEwmaWallMs=je;else if(Ft>this.lastEwmaSampleDone)if(this.lastEwmaSampleDone<0)this.lastEwmaSampleDone=Ft,this.lastEwmaWallMs=je;else{const H=(je-this.lastEwmaWallMs)/1e3;if(H>.05){const st=(Ft-this.lastEwmaSampleDone)/H;this.ewmaSamplesPerSec=this.ewmaSamplesPerSec<=0?st:this.ewmaSamplesPerSec*.88+st*.12,this.lastEwmaSampleDone=Ft,this.lastEwmaWallMs=je}}const _s=Math.max(0,Gt-Ft);let tr=null;if(re?tr=0:_s>0&&this.ewmaSamplesPerSec>1e-6&&(tr=_s/this.ewmaSamplesPerSec),!ds&&(this.progressiveState.tick({interaction:!1,converged:re,denoised:ms}),!G)){const H={PREVIEW_MODE:this.progressiveState.isPreview(),MAX_BOUNCES:this.progressiveState.getMaxBounces()};e.renderGraph.setComputePassConstants("PathTrace",H),e.gameRenderGraph.setComputePassConstants("PathTrace",H)}const Es=this.progressiveState.getPhase(),ac=this.progressiveState.isPreview();this.uploadDisplayPost(e,Es);const Ps={progress:As,progressPercent:Math.round(As*1e3)/10,samplesDone:Ft,samplesTotal:Gt,tileIndex:this.tileIndex,totalTiles:Ht,gridCols:$t,gridRows:ee,accumFrameIndex:w||G?Math.min(a,Math.floor(this.sppCoverage)):this.frameIndex,maxSamples:a,converged:re,traceThisFrame:$,progressiveStride:w?mt:at,estimatedSecondsRemaining:tr,sceneWidth:it,sceneHeight:ht,triangleCount:this.lastTriangleStats.count,sceneTriangleDemand:this.lastTriangleStats.demand,triangleCap:this.lastTriangleStats.cap,bvhNodeCount:(Rs=F==null?void 0:F.bvh)==null?void 0:Rs.nodeCount,samplesPerSecond:this.ewmaSamplesPerSec>0?this.ewmaSamplesPerSec:void 0,pathTraceTriangleBudget:P>0?P:void 0,realtimeTargetFps:N>0?N:void 0,progressivePhase:Es,previewMode:ac,progressiveSpatial:w,accumPaused:J,hybridStaticFrames:this.hybridStaticFrames,lastResetReasons:this.lastResetReasons,resetCounts:{...this.resetCounts}};if(typeof globalThis<"u"){const H=a,q=w?Math.min(H,Math.floor(this.sppCoverage)):this.frameIndex;globalThis.__W3DTS_PATH_TRACER_E2E__={accumFrameIndex:q,maxSamples:H,converged:re,traceThisFrame:$},jn(Ps);const st=typeof performance<"u"?performance.now():0,ct=this.baselineMetrics.tick(Ps,st);globalThis.__W3DTS_PATH_TRACER_BASELINE__=ct}}uploadDisplayPost(e,a){var c,l,u,h,d;const r=$r(la(),a);Xr(this.postParamsScratch,r,ma(e.webGPUContext.canvasFormat));const n=r.bloom.mode==="pyramid",s=n&&r.bloomMix>0,o=!n&&r.bloomMix>0,i=e.webGPUContext.device.queue;for(const p of[e.renderGraph,e.gameRenderGraph]){for(const A of jr){const R=A==="BloomComposite"?n:s;p.setComputePassWorkgroupCount(A,R?null:[1,1,1])}p.setComputePassWorkgroupCount("PathTracerBloom",o?null:[1,1,1]);const S=p.getBuffer("pathTracerPostParams");S&&i.writeBuffer(S,0,this.postParamsScratch);const T=p.getPasses().find(A=>A.name==="BlitToScreen");if(T&&T.type==="fullscreen"){const A=(l=(c=T.uniforms)==null?void 0:c.post)==null?void 0:l.value;if(Array.isArray(A))for(let R=0;R<this.postParamsScratch.length&&R<A.length;R++)A[R]=this.postParamsScratch[R]}const g=p.getPasses().find(A=>A.name==="05_ToneMapping");if(g&&g.type==="fullscreen"){const A=(h=(u=g.uniforms)==null?void 0:u.post)==null?void 0:h.value;if(Array.isArray(A)){for(let R=0;R<this.postParamsScratch.length&&R<A.length;R++)A[R]=this.postParamsScratch[R];A.length>10&&(A[10]=0)}}const b=p.getPasses().find(A=>A.name==="07_FXAA"||A.name==="07_HybridEncode"),E=(d=b==null?void 0:b.uniforms)==null?void 0:d.encodeSrgb;E&&typeof E.value=="number"&&(E.value=ma(e.webGPUContext.canvasFormat)?1:0)}}}const Jn=4,Te=15;function we(t,e="rgba8unorm"){return{name:t,type:"texture",format:e,sizeType:"absolute",width:1,height:1,arrayLayers:1,sampledViewDimension:"2d-array",usage:Jn}}const bi=[we("pathTracerTexAlbedo","rgba8unorm-srgb"),we("pathTracerTexOrm","rgba8unorm"),we("pathTracerTexNormal","rgba8unorm"),we("pathTracerTexEmissive","rgba8unorm-srgb")],Qn={8:{handle:"pathTracerTexAlbedo",viewDimension:"2d-array"},9:{handle:"pathTracerTexOrm",viewDimension:"2d-array"},10:{handle:"pathTracerTexNormal",viewDimension:"2d-array"},11:{handle:"pathTracerTexEmissive",viewDimension:"2d-array"}};function be(t){return{name:"PathTracerGraph",resources:[{name:"sceneTriangles",type:"buffer",sizeType:"fixed",size:Qe,usage:136},{name:"pathTracerParams",type:"buffer",sizeType:"fixed",size:Gs,usage:136},{name:"pathTracerTexSlotFlags",type:"buffer",sizeType:"fixed",size:ft*4,usage:136},{name:"pathTracerMatFactors",type:"buffer",sizeType:"fixed",size:Ds,usage:136},{name:"pathTracerMaterials",type:"buffer",sizeType:"fixed",size:_r,usage:136},{name:"pathTracerBvhNodes",type:"buffer",sizeType:"fixed",size:hr,usage:136},{name:"pathTracerInstances",type:"buffer",sizeType:"fixed",size:ur,usage:136},{name:"pathTracerEmissive",type:"buffer",sizeType:"fixed",size:Os,usage:136},{name:"pathTracerDenoiserParams",type:"buffer",sizeType:"fixed",size:mr,usage:136},{name:"pathTracerFsrParams",type:"buffer",sizeType:"fixed",size:Ee,usage:136},{name:"pathTracerPostParams",type:"buffer",sizeType:"fixed",size:ua,usage:136},{name:"pathTracerSunDirection",type:"buffer",sizeType:"fixed",size:zs,usage:136},{name:"pathTracerTileInfo",type:"buffer",sizeType:"fixed",size:oa,usage:136},{name:"pathTraceAccumRead",type:"texture",format:"rgba32float",sizeType:"relative",width:1,height:1,usage:12},{name:"pathTraceAccumWrite",type:"texture",format:"rgba32float",sizeType:"relative",width:1,height:1,usage:12},{name:"pathTraceOutput",type:"texture",format:"rgba32float",sizeType:"relative",width:1,height:1,usage:12},{name:"pathTraceGuide",type:"texture",format:"rgba16float",sizeType:"relative",width:1,height:1,usage:12},{name:"pathTraceAlbedo",type:"texture",format:"rgba16float",sizeType:"relative",width:1,height:1,usage:12},{name:"pathTraceObjectId",type:"texture",format:"rgba16float",sizeType:"relative",width:1,height:1,usage:12},{name:"denoisedOutput",type:"texture",format:"rgba16float",sizeType:"relative",width:1,height:1,usage:12},{name:"denoiseAtrousTmp0",type:"texture",format:"rgba16float",sizeType:"relative",width:1,height:1,usage:12},{name:"denoiseAtrousTmp1",type:"texture",format:"rgba16float",sizeType:"relative",width:1,height:1,usage:12},{name:"holeFilledBeauty",type:"texture",format:"rgba16float",sizeType:"relative",width:1,height:1,usage:12},{name:"pathTraceComposite",type:"texture",format:"rgba16float",sizeType:"relative",width:1,height:1,usage:Te},{name:"pathTraceNoisyComposite",type:"texture",format:"rgba16float",sizeType:"relative",width:1,height:1,usage:Te},{name:"pathTraceGuideComposite",type:"texture",format:"rgba16float",sizeType:"relative",width:1,height:1,usage:Te},{name:"pathTraceAlbedoComposite",type:"texture",format:"rgba16float",sizeType:"relative",width:1,height:1,usage:Te},{name:"pathTraceObjectIdComposite",type:"texture",format:"rgba16float",sizeType:"relative",width:1,height:1,usage:Te},{name:"pathTracerFsrEasuOut",type:"texture",format:"rgba16float",sizeType:"relative",width:1,height:1,relativeSizeRef:"canvas",usage:12},{name:"pathTracerFsrRcasOut",type:"texture",format:"rgba16float",sizeType:"relative",width:1,height:1,relativeSizeRef:"canvas",usage:12},{name:"pathTracerBloom",type:"texture",format:"rgba16float",sizeType:"relative",width:1,height:1,relativeSizeRef:"canvas",usage:12},...ga({input:"pathTracerFsrRcasOut",output:"pathTracerBloom",relativeSizeRef:"canvas"}).resources.filter(e=>e.name!=="pathTracerPostParams"),{name:"pathTracerEnvCubemap",type:"texture",format:"rgba8unorm",sizeType:"absolute",width:1,height:1,cubemapFaceSize:1,sampledViewDimension:"cube",usage:Jn},...bi],passes:[{name:"ClearPathTraceComposite",type:"compute",shaderPath:"/shaders/path-tracer/clear_composite_layers.compute.wgsl",entryPoint:"main",dispatchMode:"auto",workgroupSize:[8,8,1],bufferBindings:{0:{handle:"pathTracerTileInfo",type:"read-only-storage"},1:{handle:"pathTracerParams",type:"read-only-storage"}},textureBindings:{2:{handle:"pathTraceComposite",access:"write",format:"rgba16float"},3:{handle:"pathTraceNoisyComposite",access:"write",format:"rgba16float"},4:{handle:"pathTraceGuideComposite",access:"write",format:"rgba16float"},5:{handle:"pathTraceAlbedoComposite",access:"write",format:"rgba16float"},6:{handle:"pathTraceObjectIdComposite",access:"write",format:"rgba16float"}},inputs:[],outputs:["pathTraceComposite","pathTraceNoisyComposite","pathTraceGuideComposite","pathTraceAlbedoComposite","pathTraceObjectIdComposite"]},{name:"ClearPathTraceTile",type:"compute",shaderPath:"/shaders/path-tracer/clear_path_trace_tile.compute.wgsl",entryPoint:"main",dispatchMode:"auto",workgroupSize:[8,8,1],bufferBindings:{0:{handle:"pathTracerParams",type:"read-only-storage"}},textureBindings:{1:{handle:"pathTraceOutput",access:"write",format:"rgba32float"},2:{handle:"pathTraceAccumWrite",access:"write",format:"rgba32float"},3:{handle:"pathTraceGuide",access:"write",format:"rgba16float"},4:{handle:"pathTraceAlbedo",access:"write",format:"rgba16float"},5:{handle:"pathTraceObjectId",access:"write",format:"rgba16float"}},inputs:[],outputs:["pathTraceOutput","pathTraceAccumWrite","pathTraceGuide","pathTraceAlbedo","pathTraceObjectId"]},{name:"PathTrace",type:"compute",shaderPath:"/shaders/path-tracer/path_trace.compute.wgsl",entryPoint:"main",dispatchMode:"auto",workgroupSize:[8,8,1],useFrameUniforms:!0,constants:{PREVIEW_MODE:!1,MAX_BOUNCES:4},bufferBindings:{1:{handle:"sceneTriangles",type:"read-only-storage"},2:{handle:"pathTracerParams",type:"read-only-storage"},6:{handle:"pathTracerSunDirection",type:"read-only-storage"},7:{handle:"pathTracerTexSlotFlags",type:"read-only-storage"},52:{handle:"pathTracerMatFactors",type:"read-only-storage"},53:{handle:"pathTracerInstances",type:"read-only-storage"},54:{handle:"pathTracerBvhNodes",type:"read-only-storage"},57:{handle:"pathTracerTileInfo",type:"read-only-storage"},61:{handle:"pathTracerMaterials",type:"read-only-storage"},74:{handle:"pathTracerEmissive",type:"read-only-storage"}},textureBindings:{3:{handle:"pathTraceOutput",access:"write",format:"rgba32float"},5:{handle:"pathTraceAccumWrite",access:"write",format:"rgba32float"},59:{handle:"pathTraceGuide",access:"write",format:"rgba16float"},60:{handle:"pathTraceAlbedo",access:"write",format:"rgba16float"},63:{handle:"pathTraceObjectId",access:"write",format:"rgba16float"}},sampledTextureBindings:{4:{handle:"pathTraceAccumRead",sampleType:"unfilterable-float"},64:{handle:"pathTraceAlbedoComposite"},65:{handle:"pathTraceGuideComposite"},...Qn,58:{handle:"pathTracerEnvCubemap",viewDimension:"cube"}},samplerBindings:{56:!0},inputs:["pathTraceAccumRead","pathTraceAlbedoComposite","pathTraceGuideComposite"],outputs:["pathTraceOutput","pathTraceAccumWrite","pathTraceGuide","pathTraceAlbedo","pathTraceObjectId"]},{name:"CopyAccum",type:"compute",shaderPath:"/shaders/path-tracer/copy_accum.compute.wgsl",entryPoint:"main",dispatchMode:"auto",workgroupSize:[8,8,1],textureBindings:{0:{handle:"pathTraceAccumWrite",access:"read",format:"rgba32float"},1:{handle:"pathTraceAccumRead",access:"write",format:"rgba32float"}},inputs:["pathTraceAccumWrite"],outputs:["pathTraceAccumRead"]},{name:"Denoise",type:"compute",shaderPath:"/shaders/path-tracer/denoise.compute.wgsl",entryPoint:"main",dispatchMode:"auto",workgroupSize:[8,8,1],bufferBindings:{3:{handle:"pathTracerDenoiserParams",type:"read-only-storage"}},textureBindings:{0:{handle:"pathTraceOutput",access:"read",format:"rgba32float"},1:{handle:"pathTraceGuide",access:"read",format:"rgba16float"},2:{handle:"denoisedOutput",access:"write",format:"rgba16float"}},inputs:["pathTraceOutput","pathTraceGuide"],outputs:["denoisedOutput"]},{name:"DenoiseAtrousS1",type:"compute",shaderPath:"/shaders/path-tracer/denoise_atrous.compute.wgsl",entryPoint:"main_s1",dispatchMode:"auto",workgroupSize:[8,8,1],bufferBindings:{3:{handle:"pathTracerDenoiserParams",type:"read-only-storage"},44:{handle:"pathTracerTileInfo",type:"read-only-storage"}},textureBindings:{0:{handle:"denoisedOutput",access:"read",format:"rgba16float"},1:{handle:"pathTraceGuide",access:"read",format:"rgba16float"},2:{handle:"denoiseAtrousTmp0",access:"write",format:"rgba16float"}},inputs:["denoisedOutput","pathTraceGuide"],outputs:["denoiseAtrousTmp0"]},{name:"DenoiseAtrousS2",type:"compute",shaderPath:"/shaders/path-tracer/denoise_atrous.compute.wgsl",entryPoint:"main_s2",dispatchMode:"auto",workgroupSize:[8,8,1],bufferBindings:{3:{handle:"pathTracerDenoiserParams",type:"read-only-storage"},44:{handle:"pathTracerTileInfo",type:"read-only-storage"}},textureBindings:{0:{handle:"denoiseAtrousTmp0",access:"read",format:"rgba16float"},1:{handle:"pathTraceGuide",access:"read",format:"rgba16float"},2:{handle:"denoisedOutput",access:"write",format:"rgba16float"}},inputs:["denoiseAtrousTmp0","pathTraceGuide"],outputs:["denoisedOutput"]},{name:"HoleFill",type:"compute",shaderPath:"/shaders/path-tracer/hole_fill.compute.wgsl",entryPoint:"main",dispatchMode:"auto",workgroupSize:[8,8,1],bufferBindings:{0:{handle:"pathTracerTileInfo",type:"read-only-storage"}},textureBindings:{2:{handle:"holeFilledBeauty",access:"write",format:"rgba16float"}},sampledTextureBindings:{1:{handle:"denoisedOutput"}},inputs:["denoisedOutput"],outputs:["holeFilledBeauty"]},{name:"TileComposite",type:"compute",shaderPath:"/shaders/path-tracer/tile_composite_layers.compute.wgsl",entryPoint:"main",dispatchMode:"auto",workgroupSize:[8,8,1],dispatchTextureHandle:"holeFilledBeauty",bufferBindings:{0:{handle:"pathTracerTileInfo",type:"read-only-storage"}},textureBindings:{5:{handle:"pathTraceComposite",access:"write",format:"rgba16float"},6:{handle:"pathTraceNoisyComposite",access:"write",format:"rgba16float"},7:{handle:"pathTraceGuideComposite",access:"write",format:"rgba16float"},8:{handle:"pathTraceAlbedoComposite",access:"write",format:"rgba16float"},10:{handle:"pathTraceObjectIdComposite",access:"write",format:"rgba16float"}},sampledTextureBindings:{1:{handle:"holeFilledBeauty"},2:{handle:"pathTraceOutput"},3:{handle:"pathTraceGuide"},4:{handle:"pathTraceAlbedo"},9:{handle:"pathTraceObjectId"}},inputs:["holeFilledBeauty","pathTraceOutput","pathTraceGuide","pathTraceAlbedo","pathTraceObjectId"],outputs:["pathTraceComposite","pathTraceNoisyComposite","pathTraceGuideComposite","pathTraceAlbedoComposite","pathTraceObjectIdComposite"]},{name:"FsrEasuPath",type:"compute",shaderPath:"/shaders/path-tracer/fsr1_easu_path.compute.wgsl",entryPoint:"main",dispatchMode:"auto",workgroupSize:[8,8,1],dispatchTextureHandle:"pathTracerFsrEasuOut",bufferBindings:{0:{handle:"pathTracerFsrParams",type:"read-only-storage"}},textureBindings:{1:{handle:"pathTraceComposite",access:"read",format:"rgba16float"},2:{handle:"pathTracerFsrEasuOut",access:"write",format:"rgba16float"}},inputs:["pathTraceComposite"],outputs:["pathTracerFsrEasuOut"]},{name:"FsrRcasPath",type:"compute",shaderPath:"/shaders/path-tracer/fsr1_rcas_path.compute.wgsl",entryPoint:"main",dispatchMode:"auto",workgroupSize:[8,8,1],dispatchTextureHandle:"pathTracerFsrRcasOut",bufferBindings:{0:{handle:"pathTracerFsrParams",type:"read-only-storage"}},textureBindings:{1:{handle:"pathTracerFsrEasuOut",access:"read",format:"rgba16float"},2:{handle:"pathTracerFsrRcasOut",access:"write",format:"rgba16float"}},inputs:["pathTracerFsrEasuOut"],outputs:["pathTracerFsrRcasOut"]},...ga({input:"pathTracerFsrRcasOut",output:"pathTracerBloom",relativeSizeRef:"canvas"}).passes,{name:"PathTracerBloom",type:"compute",shaderPath:"/shaders/path-tracer/pt_bloom.compute.wgsl",entryPoint:"main",dispatchMode:"auto",workgroupSize:[8,8,1],dispatchTextureHandle:"pathTracerBloom",bufferBindings:{0:{handle:"pathTracerPostParams",type:"read-only-storage"}},textureBindings:{1:{handle:"pathTracerFsrRcasOut",access:"read",format:"rgba16float"},2:{handle:"pathTracerBloom",access:"write",format:"rgba16float"}},inputs:["pathTracerFsrRcasOut"],outputs:["pathTracerBloom"]},{name:"BlitToScreen",type:"fullscreen",shaderPath:"/shaders/path-tracer/pt_display.frag.wgsl",inputs:["pathTracerFsrRcasOut","pathTracerBloom"],outputs:["FINAL_OUTPUT"],uniforms:{post:{type:"struct",value:[1,0,1,2,0,4.5,0,0,0,0,1,0]}}}]}}const yi=be(),gi=new Set(["sceneTriangles","pathTracerParams","pathTracerTexSlotFlags","pathTracerMatFactors","pathTracerMaterials","pathTracerBvhNodes","pathTracerInstances","pathTracerEmissive","pathTracerSunDirection","pathTracerTileInfo","pathTracerEnvCubemap","pathTracerTexAlbedo","pathTracerTexOrm","pathTracerTexNormal","pathTracerTexEmissive"]),Si=[1,2,4,8,16];function ye(t,e,a){const r=Si[t]??1,n=o=>`hybrid${o}${e}`,s=o=>`hybrid${o}${a}`;return{name:`HybridAtrous${t}`,type:"compute",shaderPath:"/shaders/path-tracer/hybrid_atrous.compute.wgsl",entryPoint:"main",dispatchMode:"auto",workgroupSize:[8,8,1],dispatchTextureHandle:s("Shadow"),constants:{STEP:r,PASS:t},bufferBindings:{0:{handle:"hybridHistoryParams",type:"read-only-storage"},9:{handle:"pathTracerParams",type:"read-only-storage"}},textureBindings:{20:{handle:s("Shadow"),access:"write",format:"rgba16float"},21:{handle:s("Refl"),access:"write",format:"rgba16float"},22:{handle:s("Gi"),access:"write",format:"rgba16float"},23:{handle:s("LightVis"),access:"write",format:"rgba16float"}},sampledTextureBindings:{1:{handle:n("Shadow"),sampleType:"unfilterable-float"},2:{handle:n("Refl"),sampleType:"unfilterable-float"},3:{handle:n("Gi"),sampleType:"unfilterable-float"},4:{handle:n("LightVis"),sampleType:"unfilterable-float"},5:{handle:"hybridGDist",sampleType:"unfilterable-float"},6:{handle:"hybridGNormal",sampleType:"unfilterable-float"},7:{handle:"hybridMomentsFilt",sampleType:"unfilterable-float"},8:{handle:"hybridReflAov",sampleType:"unfilterable-float"}},inputs:[n("Shadow"),n("Refl"),n("Gi"),n("LightVis"),"hybridGDist","hybridGNormal","hybridMomentsFilt","hybridReflAov","hybridHistoryParams","pathTracerParams"],outputs:[s("Shadow"),s("Refl"),s("Gi"),s("LightVis")]}}const z=t=>({name:t,type:"texture",format:"rgba16float",sizeType:"relative",width:1,height:1,usage:13});function ts(t){return{name:"HybridAovSubgraph",resources:[...be().resources.filter(a=>gi.has(a.name)),z("hybridShadowPrev"),z("hybridShadowAov"),z("hybridReflPrev"),z("hybridReflAov"),z("hybridGiPrev"),z("hybridGiAov"),z("hybridLightVisPrev"),z("hybridLightVisAov"),z("hybridShadowFilt"),z("hybridReflFilt"),z("hybridGiFilt"),z("hybridLightVisFilt"),z("hybridFastFilt"),z("hybridMomentsFilt"),z("hybridShadowAtA"),z("hybridReflAtA"),z("hybridGiAtA"),z("hybridLightVisAtA"),z("hybridShadowAtB"),z("hybridReflAtB"),z("hybridGiAtB"),z("hybridLightVisAtB"),z("hybridShadowDen"),z("hybridReflDen"),z("hybridGiDen"),z("hybridLightVisDen"),z("hybridShadowHist"),z("hybridReflHist"),z("hybridGiHist"),z("hybridLightVisHist"),{name:"hybridGDistPrev",type:"texture",format:"r32float",sizeType:"relative",width:1,height:1,usage:12},{name:"hybridGNormalPrev",type:"texture",format:"rgba16float",sizeType:"relative",width:1,height:1,usage:12},{name:"hybridFastHist",type:"texture",format:"rgba16float",sizeType:"relative",width:1,height:1,usage:15},{name:"hybridMomentsHist",type:"texture",format:"rgba16float",sizeType:"relative",width:1,height:1,usage:15}],passes:[{name:"HybridPrimaryAov",type:"compute",shaderPath:"/shaders/path-tracer/hybrid_primary_aov.compute.wgsl",entryPoint:"main",dispatchMode:"auto",workgroupSize:[8,8,1],dispatchTextureHandle:"hybridShadowAov",useFrameUniforms:!0,bufferBindings:{1:{handle:"sceneTriangles",type:"read-only-storage"},2:{handle:"pathTracerParams",type:"read-only-storage"},6:{handle:"pathTracerSunDirection",type:"read-only-storage"},7:{handle:"pathTracerTexSlotFlags",type:"read-only-storage"},52:{handle:"pathTracerMatFactors",type:"read-only-storage"},53:{handle:"pathTracerInstances",type:"read-only-storage"},54:{handle:"pathTracerBvhNodes",type:"read-only-storage"},57:{handle:"pathTracerTileInfo",type:"read-only-storage"},61:{handle:"pathTracerMaterials",type:"read-only-storage"},71:{handle:"hybridHistoryParams",type:"read-only-storage"},74:{handle:"pathTracerEmissive",type:"read-only-storage"}},textureBindings:{3:{handle:"hybridShadowAov",access:"write",format:"rgba16float"},5:{handle:"hybridReflAov",access:"write",format:"rgba16float"},67:{handle:"hybridGiAov",access:"write",format:"rgba16float"},69:{handle:"hybridLightVisAov",access:"write",format:"rgba16float"}},sampledTextureBindings:{4:{handle:"hybridShadowPrev",sampleType:"unfilterable-float"},66:{handle:"hybridReflPrev",sampleType:"unfilterable-float"},68:{handle:"hybridGiPrev",sampleType:"unfilterable-float"},70:{handle:"hybridLightVisPrev",sampleType:"unfilterable-float"},72:{handle:"hybridGDist",sampleType:"unfilterable-float"},73:{handle:"hybridGNormal",sampleType:"unfilterable-float"},...Qn,58:{handle:"pathTracerEnvCubemap",viewDimension:"cube"}},samplerBindings:{56:!0},inputs:["hybridShadowPrev","hybridReflPrev","hybridGiPrev","hybridLightVisPrev","hybridGDist","hybridGNormal"],outputs:["hybridShadowAov","hybridReflAov","hybridGiAov","hybridLightVisAov"]},{name:"HybridTemporal",type:"compute",shaderPath:"/shaders/path-tracer/hybrid_temporal.compute.wgsl",entryPoint:"main",dispatchMode:"auto",workgroupSize:[8,8,1],dispatchTextureHandle:"hybridShadowFilt",bufferBindings:{0:{handle:"hybridHistoryParams",type:"read-only-storage"},14:{handle:"pathTracerParams",type:"read-only-storage"}},textureBindings:{20:{handle:"hybridShadowFilt",access:"write",format:"rgba16float"},21:{handle:"hybridReflFilt",access:"write",format:"rgba16float"},22:{handle:"hybridGiFilt",access:"write",format:"rgba16float"},23:{handle:"hybridLightVisFilt",access:"write",format:"rgba16float"},24:{handle:"hybridFastFilt",access:"write",format:"rgba16float"},25:{handle:"hybridMomentsFilt",access:"write",format:"rgba16float"}},sampledTextureBindings:{1:{handle:"hybridShadowAov",sampleType:"unfilterable-float"},2:{handle:"hybridReflAov",sampleType:"unfilterable-float"},3:{handle:"hybridGiAov",sampleType:"unfilterable-float"},4:{handle:"hybridLightVisAov",sampleType:"unfilterable-float"},5:{handle:"hybridShadowHist",sampleType:"unfilterable-float"},6:{handle:"hybridReflHist",sampleType:"unfilterable-float"},7:{handle:"hybridGiHist",sampleType:"unfilterable-float"},8:{handle:"hybridLightVisHist",sampleType:"unfilterable-float"},9:{handle:"hybridGDist",sampleType:"unfilterable-float"},10:{handle:"hybridGNormal",sampleType:"unfilterable-float"},11:{handle:"hybridGMotion",sampleType:"unfilterable-float"},12:{handle:"hybridGDistPrev",sampleType:"unfilterable-float"},13:{handle:"hybridGNormalPrev",sampleType:"unfilterable-float"},15:{handle:"hybridFastHist",sampleType:"unfilterable-float"},16:{handle:"hybridMomentsHist",sampleType:"unfilterable-float"}},inputs:["hybridShadowAov","hybridReflAov","hybridGiAov","hybridLightVisAov","hybridShadowHist","hybridReflHist","hybridGiHist","hybridLightVisHist","hybridGDist","hybridGNormal","hybridGMotion","hybridGDistPrev","hybridGNormalPrev","hybridFastHist","hybridMomentsHist","hybridHistoryParams","pathTracerParams"],outputs:["hybridShadowFilt","hybridReflFilt","hybridGiFilt","hybridLightVisFilt","hybridFastFilt","hybridMomentsFilt"]},{name:"HybridCopyAov",type:"compute",shaderPath:"/shaders/path-tracer/hybrid_copy_aov.compute.wgsl",entryPoint:"main",dispatchMode:"auto",workgroupSize:[8,8,1],dispatchTextureHandle:"hybridShadowPrev",textureBindings:{0:{handle:"hybridShadowAov",access:"read",format:"rgba16float"},1:{handle:"hybridShadowPrev",access:"write",format:"rgba16float"},2:{handle:"hybridReflAov",access:"read",format:"rgba16float"},3:{handle:"hybridReflPrev",access:"write",format:"rgba16float"},4:{handle:"hybridGiAov",access:"read",format:"rgba16float"},5:{handle:"hybridGiPrev",access:"write",format:"rgba16float"},6:{handle:"hybridLightVisAov",access:"read",format:"rgba16float"},7:{handle:"hybridLightVisPrev",access:"write",format:"rgba16float"}},inputs:["hybridShadowAov","hybridReflAov","hybridGiAov","hybridLightVisAov"],outputs:["hybridShadowPrev","hybridReflPrev","hybridGiPrev","hybridLightVisPrev"]},ye(0,"Filt","AtA"),{name:"HybridHistoryCopy",type:"compute",shaderPath:"/shaders/path-tracer/hybrid_history_copy.compute.wgsl",entryPoint:"main",dispatchMode:"auto",workgroupSize:[8,8,1],dispatchTextureHandle:"hybridShadowHist",bufferBindings:{12:{handle:"pathTracerParams",type:"read-only-storage"}},textureBindings:{4:{handle:"hybridShadowHist",access:"write",format:"rgba16float"},5:{handle:"hybridReflHist",access:"write",format:"rgba16float"},6:{handle:"hybridGiHist",access:"write",format:"rgba16float"},7:{handle:"hybridLightVisHist",access:"write",format:"rgba16float"},10:{handle:"hybridGDistPrev",access:"write",format:"r32float"},11:{handle:"hybridGNormalPrev",access:"write",format:"rgba16float"}},sampledTextureBindings:{0:{handle:"hybridShadowAtA",sampleType:"unfilterable-float"},1:{handle:"hybridReflAtA",sampleType:"unfilterable-float"},2:{handle:"hybridGiAtA",sampleType:"unfilterable-float"},3:{handle:"hybridLightVisAtA",sampleType:"unfilterable-float"},8:{handle:"hybridGDist",sampleType:"unfilterable-float"},9:{handle:"hybridGNormal",sampleType:"unfilterable-float"}},inputs:["hybridShadowAtA","hybridReflAtA","hybridGiAtA","hybridLightVisAtA","hybridGDist","hybridGNormal","pathTracerParams"],outputs:["hybridShadowHist","hybridReflHist","hybridGiHist","hybridLightVisHist","hybridGDistPrev","hybridGNormalPrev"]},ye(1,"AtA","AtB"),ye(2,"AtB","AtA"),ye(3,"AtA","AtB"),ye(4,"AtB","Den"),{name:"HybridFastCopy",type:"copy-texture",inputs:["hybridFastFilt"],outputs:["hybridFastHist"]},{name:"HybridMomentsCopy",type:"copy-texture",inputs:["hybridMomentsFilt"],outputs:["hybridMomentsHist"]}]}}function Mi(t){return ts()}function ka(){const t=typeof globalThis<"u"?globalThis.__W3DTS_PATH_TRACER_CONFIG:void 0;return sa((t==null?void 0:t.tileSize)??_e)}class Ai extends M.AbstractProject{constructor(){super("PathTracer");y(this,"logger",null);y(this,"engine",null);y(this,"uploadController",new Va);y(this,"pathTracerLightEntityId",null)}setStudioKeyLightEnabled(a){!this.engine||this.pathTracerLightEntityId===null||M.setEntityLocallyVisible(this.engine.ecsWorld,this.pathTracerLightEntityId,a)}async initializeScene(a){const{logger:r,engine:n,scene:s,world:o}=a;this.logger=r,this.engine=n;let i;try{const w=await fetch("/shader-graphs/PBRGraph.json");if(!w.ok)throw new Error(`HTTP ${w.status}`);i=await w.json()}catch(w){r.warn(bt.LogChannel.EngineLifecycle,"PathTracer: PBR graph not found, scene will be empty.",w);return}const c=M.PrimitiveFactory.createCube(1),l=M.PrimitiveFactory.createSphere(.5,24,24),u=M.PrimitiveFactory.createPlane(10,10);n.resourceManager.uploadMesh(c),n.resourceManager.uploadMesh(l),n.resourceManager.uploadMesh(u);const h=(w,D)=>{const O=new M.Material({name:w,shadingModel:"pbr",shaderGraph:i,properties:{baseColor:D,roughness:.9,metallic:0}});return n.resourceManager.uploadMaterial(O),O},d=h("PT_Cube",[.8,.2,.2]),p=h("PT_Floor",[.2,.7,.2]),S=h("PT_LeftWall",[.8,.15,.15]),T=h("PT_RightWall",[.15,.15,.8]),g=h("PT_BackWall",[.85,.85,.85]),b=new M.Material({name:"PT_Sphere",shadingModel:"pbr",shaderGraph:i,properties:{baseColor:[.92,.92,.98],roughness:.05,metallic:1}});n.resourceManager.uploadMaterial(b);const E=new M.SceneNode("Floor",o,u,p);s.add(E);const A=new M.SceneNode("Cube",o,c,d),R=o.getComponent(A.entityId,M.TransformComponent);R&&(ut(R.position,0,.5,0),R.updateLocalTransform()),s.add(A);const C=new M.SceneNode("Sphere",o,l,b),P=o.getComponent(C.entityId,M.TransformComponent);P&&(ut(P.position,2,.5,0),P.updateLocalTransform()),s.add(C);const N=new M.SceneNode("LeftWall",o,u,S),m=o.getComponent(N.entityId,M.TransformComponent);m&&(ut(m.position,-5,5,0),Ae(m.rotation,[0,0,1],-Math.PI/2),m.updateLocalTransform()),s.add(N);const _=new M.SceneNode("RightWall",o,u,T),v=o.getComponent(_.entityId,M.TransformComponent);v&&(ut(v.position,5,5,0),Ae(v.rotation,[0,0,1],Math.PI/2),v.updateLocalTransform()),s.add(_);const L=new M.SceneNode("BackWall",o,u,g),x=o.getComponent(L.entityId,M.TransformComponent);x&&(ut(x.position,0,5,-5),Ae(x.rotation,[1,0,0],Math.PI/2),x.updateLocalTransform()),s.add(L);const B=o.createEntity(),I=new M.TransformComponent;ut(I.position,5,10,5),I.updateLocalTransform(),o.addComponent(B,I),o.addComponent(B,new M.DirectionalLightComponent({color:oe(1,1,.95),intensity:1,shadowsEnabled:!0})),this.pathTracerLightEntityId=B,this.uploadController.setPreferredLightEntity(B),r.info(bt.LogChannel.EngineLifecycle,"PathTracer: Cornell box scene initialized.")}async configureRenderGraph(a,r,n){if(!this.logger)return;this.logger.info(bt.LogChannel.RenderGraph,"Loading PathTracerGraph..."),new M.GraphLoader(this.logger).loadFromData(be(ka()),a),this.logger.info(bt.LogChannel.RenderGraph,"PathTracerGraph loaded (SceneDirector will compile).")}update(a,r){this.engine&&this.uploadController.tick(this.engine)}updateTime(a){}}class _i extends M.AbstractProject{constructor(){super("PathTracer2");y(this,"logger",null);y(this,"engine",null);y(this,"uploadController",new Va);y(this,"pathTracerLightEntityId",null)}setStudioKeyLightEnabled(a){!this.engine||this.pathTracerLightEntityId===null||M.setEntityLocallyVisible(this.engine.ecsWorld,this.pathTracerLightEntityId,a)}async initializeScene(a){const{logger:r,world:n}=a;this.logger=r,this.engine=a.engine;const s=n.createEntity(),o=new M.TransformComponent;ut(o.position,2,4,4),o.updateLocalTransform(),n.addComponent(s,o),n.addComponent(s,new M.DirectionalLightComponent({color:oe(1,1,.95),intensity:1.2,shadowsEnabled:!0})),this.pathTracerLightEntityId=s,this.uploadController.setPreferredLightEntity(s),r.info(bt.LogChannel.EngineLifecycle,"PathTracer2: scene ready. Use Import GLB to load models.")}async configureRenderGraph(a,r,n){if(!this.logger)return;this.logger.info(bt.LogChannel.RenderGraph,"Loading PathTracerGraph (PathTracer2)..."),new M.GraphLoader(this.logger).loadFromData(be(ka()),a),this.logger.info(bt.LogChannel.RenderGraph,"PathTracerGraph loaded (SceneDirector will compile).")}update(a,r){this.engine&&this.uploadController.tick(this.engine)}updateTime(a){}}const Ei=[[1.70507958,-.62189138,-.08318821],[-.13025642,1.14080405,-.01054763],[-.02400336,-.12896897,1.15297233]],Pi=4,Ri=12,vi=32,$a=16;function es(t,e,a){const r=Ei;return[r[0][0]*t+r[0][1]*e+r[0][2]*a,r[1][0]*t+r[1][1]*e+r[1][2]*a,r[2][0]*t+r[2][1]*e+r[2][2]*a]}function Ya(t,e,a){return .2126*t+.7152*e+.0722*a}function Fi(t,e){const a=Math.cos(t),r=Math.sin(t),n=Math.cos(e),o=Math.sin(e)*a,i=n*a,c=-r,l=Math.hypot(o,i,c)||1;return[o/l,i/l,c/l]}function Ci(t){const e=Math.min(Math.PI,Math.max(0,t*.5));return 2*Math.PI*(1-Math.cos(e))}function as(t,e){return!(t>0)||!(e>0)?0:t}function rs(t,e,a,r,n){if(!(a>0)||t<0)return 0;let s=a;if(r>=3){const l=2*Math.PI/r,u=e/l-Math.floor(e/l),h=Math.abs(u-.5)*l;s=a*Math.cos(Math.PI/r)/Math.max(Math.cos(h),.001)}const o=Math.min(Math.max(n,0),1),i=s*(1-o);if(t>=s)return 0;if(t<=i)return 1;const c=(s-t)/Math.max(s-i,1e-6);return c*c*(3-2*c)}function Ii(t,e,a,r,n,s,o){const i=Math.hypot(t[0],t[1],t[2])||1,c=Math.hypot(e[0],e[1],e[2])||1,l=t[0]/i,u=t[1]/i,h=t[2]/i,d=e[0]/c,p=e[1]/c,S=e[2]/c,T=Math.min(1,Math.max(-1,l*d+u*p+h*S));let g,b,E;Math.abs(p)>=.999?(g=0,b=S,E=-p):(g=-S,b=0,E=d);const A=Math.hypot(g,b,E)||1;g/=A,b/=A,E/=A;const R=p*E-S*b,C=S*g-d*E,P=d*b-p*g,N=Math.atan2(l*R+u*C+h*P,l*g+u*b+h*E),m=rs(Math.acos(T),N,n,s,o);return[a*r[0]*m,a*r[1]*m,a*r[2]*m]}function ns(t,e,a){const r=new Float32Array(a),n=new Float32Array(e*a),s=new Float32Array(a);let o=0;for(let c=0;c<a;c++){const l=Math.sin((c+.5)/a*Math.PI);let u=0;const h=c*e;for(let p=0;p<e;p++){const S=(h+p)*3,T=Ya(t[S]??0,t[S+1]??0,t[S+2]??0)*l;u+=T,n[h+p]=u}s[c]=u,o+=u;const d=u>0?1/u:0;for(let p=0;p<e;p++)n[h+p]=u>0?(n[h+p]??0)*d:(p+1)/e}let i=0;for(let c=0;c<a;c++)i+=s[c]??0,r[c]=o>0?i/o:(c+1)/a;return{width:e,height:a,marginal:r,conditional:n,sumWeight:o}}function xi(t,e,a,r){return!(t>0)||!(r>0)||e<1||a<1?0:t*e*a/(r*2*Math.PI*Math.PI)}function Bi(t,e){const[a,r,n]=e;let s=t[0],o=t[1],i=t[2];const c=Math.cos(-r),l=Math.sin(-r),u=c*s+l*i,h=-l*s+c*i,d=Math.cos(-a),p=Math.sin(-a),S=d*o-p*h,T=p*o+d*h,g=Math.cos(-n),b=Math.sin(-n);return[g*u-b*S,b*u+g*S,T]}function Ni(t,e,a,r,n){const s=(r%1+1)%1*e-.5,o=Math.min(Math.max(n,0),1)*a-.5,i=Math.floor(s),c=Math.floor(o),l=s-i,u=o-c,h=b=>(b%e+e)%e,d=b=>Math.min(a-1,Math.max(0,b)),p=(b,E)=>{const A=(d(E)*e+h(b))*4;return[t[A]??0,t[A+1]??0,t[A+2]??0]},S=(b,E,A)=>[b[0]+(E[0]-b[0])*A,b[1]+(E[1]-b[1])*A,b[2]+(E[2]-b[2])*A],T=S(p(i,c),p(i+1,c),l),g=S(p(i,c+1),p(i+1,c+1),l);return S(T,g,u)}function Li(t,e,a,r){const n=lt,s=gt,o=new Float32Array(n*s*3),i=Number.isFinite(r.powerScale)?r.powerScale:1,c=e===n&&a===s;for(let l=0;l<s;l++)for(let u=0;u<n;u++){let h,d,p;if(c){const T=(l*e+u)*4;h=t[T]??0,d=t[T+1]??0,p=t[T+2]??0}else{const T=Ni(t,e,a,(u+.5)/n,(l+.5)/s);h=T[0],d=T[1],p=T[2]}if(r.acescg){const T=es(h,d,p);h=T[0],d=T[1],p=T[2]}const S=(l*n+u)*3;o[S]=h*i,o[S+1]=d*i,o[S+2]=p*i}return o}function ss(){return{rgb:new Float32Array(lt*gt*3),rotation:[0,0,0],lights:[]}}function wi(t){const e=new Float32Array(na);let a=0;for(let n=0;n<Math.min(t.length,le);n++)t[n]&&(a=n+1);e[0]=a,e[1]=lt,e[2]=gt;const r=[];for(let n=0;n<a;n++){const s=t[n]??ss(),o=s.rotation;e[$a+n*4]=o[0]??0,e[$a+n*4+1]=o[1]??0,e[$a+n*4+2]=o[2]??0;const i=ns(s.rgb,lt,gt);e[4+n]=i.sumWeight;const c=ea+n*lt*gt*4,l=aa+n*gt,u=ra+n*gt*lt;for(let h=0;h<gt;h++){e[l+h]=i.marginal[h]??0;for(let d=0;d<lt;d++){const p=(h*lt+d)*3,S=s.rgb[p]??0,T=s.rgb[p+1]??0,g=s.rgb[p+2]??0,b=c+(h*lt+d)*4;e[b]=S,e[b+1]=T,e[b+2]=g,e[b+3]=Ya(S,T,g),e[u+h*lt+d]=i.conditional[h*lt+d]??0}}for(const h of s.lights)h.enabled&&r.length<Pi&&r.push(h)}e[3]=r.length;for(let n=0;n<r.length;n++){const s=r[n],o=vi+n*Ri;e[o]=s.direction[0],e[o+1]=s.direction[1],e[o+2]=s.direction[2],e[o+3]=as(s.power,s.angleSize),e[o+4]=s.color[0],e[o+5]=s.color[1],e[o+6]=s.color[2],e[o+7]=s.angleSize*.5,e[o+8]=s.sides,e[o+9]=s.falloff,e[o+10]=s.slot,e[o+11]=s.enabled?1:0}return e}function He(t,e,a){return Math.min(a,Math.max(e,t))}function Hi(t,e){const a=e.finalPoint[0]-e.startPoint[0],r=e.finalPoint[1]-e.startPoint[1],n=a*a+r*r;if(n<1e-12)return 0;const s=((t[0]-e.startPoint[0])*a+(t[1]-e.startPoint[1])*r)/n,o=He(s,0,1),i=He(e.stretching,.025,4)*2;return Math.pow(o,i)}function Oi(t,e){const a=Hi(t,e);return[e.startColor[0]+(e.finalColor[0]-e.startColor[0])*a,e.startColor[1]+(e.finalColor[1]-e.startColor[1])*a,e.startColor[2]+(e.finalColor[2]-e.startColor[2])*a]}function Di(t,e,a){if(!(e>1e-6))return 1;const r=He(t/e,0,1),n=He(a,0,1);return r*(1-n)+n}function Gi(t,e){const a=pr;if(!(a+12>t.length)){if(!e){t[a]=0;return}t[a]=1,t[a+1]=e.startColor[0],t[a+2]=e.startColor[1],t[a+3]=e.startColor[2],t[a+4]=e.finalColor[0],t[a+5]=e.finalColor[1],t[a+6]=e.finalColor[2],t[a+7]=e.startPoint[0],t[a+8]=e.startPoint[1],t[a+9]=e.finalPoint[0],t[a+10]=e.finalPoint[1],t[a+11]=e.stretching}}const Oe=Math.PI,Xa=1/Math.PI,Rt=.001,Ui=[.999924,-.092669,-1.258395,1.634141,-.499105,1.353028,-3.099099,3.07122,-1.805599,-.36945,-.974641,1.35962,.001272,.070821,.051172,.160882,-1.47429,.923568,.319898,-.25319,1.128278,-.803447,-.207593,.358534],zi=[-.002175,-.917854,.836308,-.095839,.553706,-4.49085,6.554465,5.833246,-3.481972,1.340061,-5.427445,3.102214,1.007613,.808866,-.964218,-.898438,9.808558,-5.132795,-7.785251,2.926538,-1.691786,-2.049945,3.756339,-3.624991];function Z(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}function De(t,e){return[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]]}function At(t){const e=Math.hypot(t[0],t[1],t[2]);return e<=1e-12?[0,0,1]:[t[0]/e,t[1]/e,t[2]/e]}function Wi(t,e){const a=2*Z(t,e);return[t[0]-a*e[0],t[1]-a*e[1],t[2]-a*e[2]]}function ja(t){const e=Math.abs(t[1])<.999?[0,1,0]:[1,0,0],a=At(De(t,e)),r=De(t,a);return[a,r,t]}function Ge(t,e){const a=Math.max(t*t,1e-8);return .5*(-1+Math.sqrt(1+e*e*(1-a)/a))}function Ue(t,e){const a=M.clampScalar(t,1e-4,1),r=M.clampScalar(e,0,1),n=Math.pow(1-a,5);if(r<=1e-4)return{a:1-n,b:n,ess:1};const s=r*r,o=s*s,i=s/Math.sqrt(a*a*(1-o)+o+1e-12),c=i*i,l=c*i,u=c*c,h=a*a,d=[1,i,c,l,u,s,s*i,s*c,s*l,o,o*i,o*c,n,n*i,n*c,n*s,a*i,a*c,a*s,a*o,r*i,r*c,h*s,h*o];let p=0,S=0;for(let b=0;b<24;b++)p+=Ui[b]*d[b],S+=zi[b]*d[b];const T=M.clampScalar(p,.01,1),g=M.clampScalar(S,0,T);return{a:T-g,b:g,ess:T}}function ze(t,e,a,r){const n=Math.max(Z(t,e),1e-4);if(Z(t,a)<=0)return 0;const o=Math.max(r,Math.sqrt(Rt)),i=o*o,c=At([e[0]+a[0],e[1]+a[1],e[2]+a[2]]),l=Math.max(Z(t,c),0),u=M.distributionGGX(l,o);return 1/(1+Ge(n,i))*u/(4*n)}function qa(t,e,a,r,n){const s=Math.max(a,Math.sqrt(Rt)),o=s*s,[i,c,l]=ja(t),u=[Z(i,e),Z(c,e),Math.max(Z(l,e),1e-4)],h=At([o*u[0],o*u[1],u[2]]),d=h[0]*h[0]+h[1]*h[1],p=d>1e-6?[-h[1]/Math.sqrt(d),h[0]/Math.sqrt(d),0]:[1,0,0],S=De(h,p),T=Math.sqrt(M.clampScalar(r,0,1)),g=2*Oe*n,b=T*Math.cos(g);let E=T*Math.sin(g);const A=.5*(1+h[2]);E=(1-A)*Math.sqrt(Math.max(0,1-b*b))+A*E;const R=Math.sqrt(Math.max(0,1-b*b-E*E)),C=[b*p[0]+E*S[0]+R*h[0],b*p[1]+E*S[1]+R*h[1],Math.max(0,b*p[2]+E*S[2]+R*h[2])],P=[o*C[0],o*C[1],C[2]],N=At([i[0]*P[0]+c[0]*P[1]+l[0]*P[2],i[1]*P[0]+c[1]*P[1]+l[1]*P[2],i[2]*P[0]+c[2]*P[1]+l[2]*P[2]]),m=[-e[0],-e[1],-e[2]],_=At(Wi(m,N)),v=Z(t,_);if(v<=0)return{l:_,h:N,g2OverG1:0,pdf:0};const L=Math.max(Z(t,e),1e-4),x=Ge(L,o),B=Ge(v,o),I=(1+x)/(1+x+B),w=ze(t,e,_,s);return{l:_,h:N,g2OverG1:I,pdf:w}}function os(t,e,a){const r=2*Oe*e,n=Math.sqrt(M.clampScalar(1-a,0,1)),s=Math.sqrt(M.clampScalar(a,0,1)),[o,i,c]=ja(t),l=Math.cos(r)*s,u=Math.sin(r)*s,h=At([o[0]*l+i[0]*u+c[0]*n,o[1]*l+i[1]*u+c[1]*n,o[2]*l+i[2]*u+c[2]*n]);return{l:h,pdf:Math.max(Z(t,h),0)*Xa}}function Ka(t){const e=Math.max(t.ior??1.5,1),a=(e-1)/(e+1),r=a*a,n=M.clampScalar(t.specularFactor??1,0,1),s=t.specularColorFactor??[1,1,1],o=[Math.min(r*s[0],1)*n,Math.min(r*s[1],1)*n,Math.min(r*s[2],1)*n],i=M.clampScalar(t.metallic,0,1),c=M.mixVec3(o,t.baseColor,i),l=M.mixVec3([n,n,n],[1,1,1],i);return{f0:c,f90:l}}function is(t,e,a,r){const n=Math.max(Z(t,a),0),s=Math.max(Z(t,e),1e-4);if(n<=0)return[0,0,0];const o=Math.max(M.clampScalar(r.roughness,0,1),Math.sqrt(Rt)),{f0:i,f90:c}=Ka(r),l=M.clampScalar(r.metallic,0,1),u=At([e[0]+a[0],e[1]+a[1],e[2]+a[2]]),h=Math.max(Z(t,u),0),d=Math.max(Z(e,u),0),p=M.distributionGGX(h,o),S=M.vGGXCorrelated(n,s,o),T=M.fresnelSchlickF90(d,i,c),g=Ue(s,o),b=1-g.ess,E=[i[0]+(c[0]-i[0])/21,i[1]+(c[1]-i[1])/21,i[2]+(c[2]-i[2])/21],A=[1/Math.max(1-E[0]*b,1e-4),1/Math.max(1-E[1]*b,1e-4),1/Math.max(1-E[2]*b,1e-4)],R=[i[0]*g.a+c[0]*g.b,i[1]*g.a+c[1]*g.b,i[2]*g.a+c[2]*g.b],C=[M.clampScalar(R[0]*A[0],0,1),M.clampScalar(R[1]*A[1],0,1),M.clampScalar(R[2]*A[2],0,1)],P=[p*S*T[0]*A[0]*n,p*S*T[1]*A[1]*n,p*S*T[2]*A[2]*n],N=[(1-C[0])*(1-l),(1-C[1])*(1-l),(1-C[2])*(1-l)],m=Xa*n;return[P[0]+N[0]*r.baseColor[0]*m,P[1]+N[1]*r.baseColor[1]*m,P[2]+N[2]*r.baseColor[2]*m]}function cs(t,e,a,r,n){const s=M.clampScalar(r,0,1);if(s<=1e-5)return{coatCos:0,baseAttenuation:1};const o=Math.max(Z(t,e),1e-4),i=Math.max(M.clampScalar(n,0,1),Math.sqrt(Rt)),c=Ue(o,i),l=M.clampScalar(.04*c.a+c.b,0,1),u=1-s*l,h=Math.max(Z(t,a),0);if(h<=0)return{coatCos:0,baseAttenuation:u};const d=At([e[0]+a[0],e[1]+a[1],e[2]+a[2]]),p=Math.max(Z(t,d),0),S=Math.max(Z(e,d),0),T=M.distributionGGX(p,i),g=M.vGGXCorrelated(h,o,i),b=.04+.96*Math.pow(1-S,5);return{coatCos:s*T*g*b*h,baseAttenuation:u}}function ls(t,e,a,r){const n=is(t,e,a,r),s=cs(t,e,a,r.clearcoatFactor??0,r.clearcoatRoughness??0);return[n[0]*s.baseAttenuation+s.coatCos,n[1]*s.baseAttenuation+s.coatCos,n[2]*s.baseAttenuation+s.coatCos]}function Za(t,e,a){const r=Math.max(Z(t,e),1e-4),n=M.clampScalar(a.clearcoatFactor??0,0,1);Math.max(M.clampScalar(a.clearcoatRoughness??0,0,1),Math.sqrt(Rt));const s=n>1e-4?M.clampScalar(n*(.04+.96*Math.pow(1-r,5)),.05*n,.85):0,o=1-s,{f0:i,f90:c}=Ka(a),l=M.clampScalar(a.metallic,0,1),u=Math.max(M.clampScalar(a.roughness,0,1),Math.sqrt(Rt)),h=Ue(r,u),d=Math.max(i[0]*h.a+c[0]*h.b,i[1]*h.a+c[1]*h.b,i[2]*h.a+c[2]*h.b),p=(1-l)*Math.max(a.baseColor[0],a.baseColor[1],a.baseColor[2],.001);let S;return l>=.999?S=1:d<=1e-6?S=0:S=M.clampScalar(d/(d+p),.05,.95),{pCoat:s,pSpec:o*S,pDiff:o*(1-S)}}function hs(t,e,a,r){const n=Z(t,a);if(n<=0)return 0;const s=Za(t,e,r),o=Math.max(M.clampScalar(r.roughness,0,1),Math.sqrt(Rt)),i=Math.max(M.clampScalar(r.clearcoatRoughness??0,0,1),Math.sqrt(Rt));let c=s.pDiff*(n*Xa);return s.pSpec>0&&(c+=s.pSpec*ze(t,e,a,o)),s.pCoat>0&&(c+=s.pCoat*ze(t,e,a,i)),c}function Vi(t,e,a,r,n,s){const o=Za(t,e,a),i=Math.max(M.clampScalar(a.roughness,0,1),Math.sqrt(Rt)),c=Math.max(M.clampScalar(a.clearcoatRoughness??0,0,1),Math.sqrt(Rt));let l;if(r<o.pCoat?l=qa(t,e,c,n,s).l:r<o.pCoat+o.pSpec?l=qa(t,e,i,n,s).l:l=os(t,n,s).l,Z(t,l)<=0)return{l,pdf:0,weight:[0,0,0]};const u=hs(t,e,l,a);if(u<=1e-8)return{l,pdf:0,weight:[0,0,0]};const h=ls(t,e,l,a);return{l,pdf:u,weight:M.clampVec3([h[0]/u,h[1]/u,h[2]/u],0,64)}}function us(t,e,a,r){const n=At(e.direction),s=At(e.tangent),o=At(De(s,n)),i=.5*Math.max(e.width,1e-4),c=.5*Math.max(e.height,1e-4);let l,u,h;if(e.isDisk){const m=Math.sqrt(M.clampScalar(a,0,1)),_=2*Oe*r;l=m*Math.cos(_)*i,u=m*Math.sin(_)*c,h=Oe*i*c}else l=(2*M.clampScalar(a,0,1)-1)*i,u=(2*M.clampScalar(r,0,1)-1)*c,h=4*i*c;const d=[e.position[0]+s[0]*l+o[0]*u,e.position[1]+s[1]*l+o[1]*u,e.position[2]+s[2]*l+o[2]*u],p=d[0]-t[0],S=d[1]-t[1],T=d[2]-t[2],g=p*p+S*S+T*T;if(g<=1e-8)return{dir:[0,1,0],distance:0,radianceOverPdf:[0,0,0],valid:!1};const b=Math.sqrt(g),E=[p/b,S/b,T/b],A=-(n[0]*E[0]+n[1]*E[1]+n[2]*E[2]);if(A<=1e-5)return{dir:E,distance:b,radianceOverPdf:[0,0,0],valid:!1};let R=1;const C=e.range??0;if(C>0){const m=b/C,_=m*m;R=M.clampScalar(1-_*_,0,1)}const P=h*A*R/g,N=e.intensity*P;return{dir:E,distance:b,radianceOverPdf:[e.color[0]*N,e.color[1]*N,e.color[2]*N],valid:N>0}}function ki(t,e,a,r=16){const n=Math.max(1,Math.floor(r)),s=n*n;let o=0,i=0,c=0;for(let u=0;u<n;u++)for(let h=0;h<n;h++){const d=(h+.5)/n,p=(u+.5)/n,S=us(t,a,d,p);if(!S.valid)continue;const T=Math.max(Z(e,S.dir),0);T<=0||(o+=S.radianceOverPdf[0]*T,i+=S.radianceOverPdf[1]*T,c+=S.radianceOverPdf[2]*T)}const l=1/s;return[o*l,i*l,c*l]}Object.defineProperty(f,"evalKhrPunctualAttenuation",{enumerable:!0,get:()=>M.evalKhrPunctualAttenuation}),Object.defineProperty(f,"evalKhrSpotAttenuation",{enumerable:!0,get:()=>M.evalKhrSpotAttenuation}),f.BLOOM_DOWNSAMPLE_WEIGHTS=da,f.BLOOM_PYRAMID_PASS_NAMES=jr,f.HYBRID_OIDN_FRAMES_DEFAULT=Gn,f.PATH_TRACER_BACKPLATE_OFFSET=pr,f.PATH_TRACER_BASELINE_SPP_MILESTONES=Zr,f.PATH_TRACER_BLOOM_FALLOFF=Hr,f.PATH_TRACER_BLOOM_STEPS=Re,f.PATH_TRACER_BLOOM_WEIGHT_SCALE=Or,f.PATH_TRACER_BSDF_SHADOW_CATCHER=qs,f.PATH_TRACER_BSDF_UNLIT=ia,f.PATH_TRACER_BUILD_CONSTANTS=js,f.PATH_TRACER_BVH_BIN_COUNT=nt,f.PATH_TRACER_BVH_INSTANCE_LEAF=an,f.PATH_TRACER_BVH_LEAF_SENTINEL=bo,f.PATH_TRACER_BVH_MAX_LEAF_TRIS=Ma,f.PATH_TRACER_BVH_TRI_LEAF_BIT=Sa,f.PATH_TRACER_DEFAULT_DISPLAY_GRADE=jt,f.PATH_TRACER_DENOISER_PARAMS_BUFFER_BYTES=mr,f.PATH_TRACER_DENOISER_PARAMS_BUFFER_U32S=dr,f.PATH_TRACER_EMISSIVE_INSTANCE_NONE=on,f.PATH_TRACER_ENV_BUFFER_FLOATS=na,f.PATH_TRACER_ENV_CONDITIONAL_OFFSET=ra,f.PATH_TRACER_ENV_HEIGHT=gt,f.PATH_TRACER_ENV_LAYERS=le,f.PATH_TRACER_ENV_MARGINAL_OFFSET=aa,f.PATH_TRACER_ENV_RADIANCE_OFFSET=ea,f.PATH_TRACER_ENV_WIDTH=lt,f.PATH_TRACER_EXPOSURE_MAX_EV=kr,f.PATH_TRACER_EXPOSURE_MIN_EV=Vr,f.PATH_TRACER_FLAG_TRANSPARENT_BG=yr,f.PATH_TRACER_FLAG_UNLIT_AS_DIFFUSE=Sr,f.PATH_TRACER_FLAG_USE_TLAS=gr,f.PATH_TRACER_FLOATS_PER_TRIANGLE=Mt,f.PATH_TRACER_FSR_PARAMS_BUFFER_BYTES=Ee,f.PATH_TRACER_INSTANCES_BUFFER_BYTES=ur,f.PATH_TRACER_INSTANCE_BYTES=ce,f.PATH_TRACER_MATERIALS_BUFFER_BYTES=_r,f.PATH_TRACER_MATERIAL_FIELD=Er,f.PATH_TRACER_MATERIAL_FLOATS=Vt,f.PATH_TRACER_MATERIAL_SLOT_NONE=Nt,f.PATH_TRACER_MAX_INSTANCES=Xt,f.PATH_TRACER_MAX_MATERIALS=he,f.PATH_TRACER_MAX_PATH_BOUNCES=Cr,f.PATH_TRACER_MAX_TEXTURE_SLOTS=ft,f.PATH_TRACER_MAX_TRIANGLES=Bt,f.PATH_TRACER_MIN_SAMPLES_PER_TILE=cr,f.PATH_TRACER_PARAMS_BUFFER_U32S=ta,f.PATH_TRACER_POST_PARAMS_BUFFER_BYTES=ua,f.PATH_TRACER_POST_PARAMS_FLOATS=ha,f.PATH_TRACER_SCENE_FLAG_HAS_TRANSMISSION=fr,f.PATH_TRACER_SCENE_TRIANGLES_BUFFER_BYTES=Qe,f.PATH_TRACER_TEX_ARRAY_MAX_VRAM_BYTES=ir,f.PATH_TRACER_TEX_FLAG_EMISSIVE_UV1=Ar,f.PATH_TRACER_TEX_FLAG_ORM_UV1=Mr,f.PATH_TRACER_TILE_INFO_BUFFER_BYTES=oa,f.PATH_TRACER_TILE_SIZE=_e,f.PATH_TRACER_TILE_SIZE_MAX=br,f.PATH_TRACER_TILE_SIZE_MIN=Tr,f.PATH_TRACER_TRANSMISSION_HEADROOM=Ir,f.PathTracer2Project=_i,f.PathTracerBaselineMetricsCollector=Jr,f.PathTracerFrameUploadController=Va,f.PathTracerMaterialTable=Fr,f.PathTracerMaterialTextureArrays=Bn,f.PathTracerProject=Ai,f.PathTracerSceneCache=Cn,f.ProgressiveRenderState=Dn,f.SpatialBudgetController=Hn,f.accumulateGlare=fo,f.acesFittedChannel=Ur,f.acescgToLinearSrgb=es,f.applyPathTracerDisplayGrade=ho,f.assembleTwoLevelBvh=sn,f.backplateColor=Oi,f.bayerOffsetForPhase=Nn,f.bloomCompositeGain=oo,f.bloomExceedsThreshold=zr,f.bloomKarisPrefilter=so,f.bloomSoftExcess=no,f.buildEmissiveCatalog=un,f.buildEnvImportance=ns,f.buildMeshBlasFromObjectTriangles=nn,f.buildOrthonormalBasis=ja,f.buildPathTracerBvhFromTriangles=Ea,f.buildSceneTriangles=En,f.bumpPathTracerInteractionEpoch=Le,f.canvasFormatNeedsSrgbEncode=ma,f.clampPathTracerExposureEv=ve,f.clampPathTracerMaxBounces=Ga,f.clampPathTracerTileSize=sa,f.computeAutoExposureEvFromHdr=mo,f.computeBsdfLobeProbabilities=Za,f.computeFsrEasuCon=Kr,f.computeKhronosF0F90=Ka,f.computeMaterialTextureArrayDimensions=xn,f.computePathTracerSceneFingerprint=Fn,f.computePathTracerTracePixelDimensions=za,f.coneSolidAngle=Ci,f.createBloomSubgraph=ga,f.createHybridAovSubgraph=ts,f.createPathTracerGraphDefinition=be,f.createPathTracerSubgraphForHybrid=Mi,f.decodeHybridOctNormal=Un,f.emissiveAreaPdf=Eo,f.emptyEnvLayer=ss,f.ensurePathTracerProgressGlobal=qn,f.envLuminance=Ya,f.envSolidAnglePdf=xi,f.environmentLightDirection=Fi,f.equirectToEnvRgb=Li,f.estimateInitialExposureEvForPunctualLights=po,f.evalBsdfMixturePdf=hs,f.evalClearcoatLayer=cs,f.evalLayeredOpaqueBsdfCos=ls,f.evalOneSampleMisBounce=Vi,f.evalOpaqueBsdfCos=is,f.evalRectAreaLightIrradiance=ki,f.exposureMultiplier=fa,f.formatPathTracerBaselineReport=To,f.getPathTracerEnvironmentUpload=wr,f.getPathTracerInteractionEpoch=ai,f.getPathTracerSceneRenderSettings=la,f.getPathTracerTileSizeFromGlobal=ka,f.ggxDirectionalAlbedoFit=Ue,f.glareRayAngle=Wr,f.hashEmissiveCatalog=dn,f.hybridOctNormalToBytes=ti,f.hybridOidnConverged=ei,f.interleaveDispatchSize=Ln,f.interleaveRoundComplete=wn,f.isPathTracerAccumPaused=Zn,f.isPathTracerTriangleLeaf=tn,f.isUnlitMaterialLike=Pe,f.linearToSrgbByte=ro,f.mapDirectionForLookup=Bi,f.materialUsesMeshMaps=xe,f.nextHybridStaticFrames=zn,f.packPathTracerBounceBudget=Br,f.packPathTracerEnvironments=wi,f.pathTracerAovDebugMode=On,f.pathTracerGraphDefinition=yi,f.pathTracerTriangleLeafWord=Qr,f.resolveMaterialBlitSourceStrategy=In,f.resolvePathTracerBounceBudget=xr,f.resolvePathTracerDisplayPost=$r,f.resolvePathTracerPost=Yr,f.sampleCosineHemisphere=os,f.sampleGgxVndf=qa,f.sampleRectAreaLight=us,f.setPathTracerAccumPaused=pi,f.setPathTracerEnvironmentBuffer=to,f.setPathTracerSceneRenderSettings=Qs,f.shadowCatcherFactor=Di,f.smithLambda=Ge,f.softboxEmissionAlong=Ii,f.softboxRadiance=as,f.softboxWeight=rs,f.summarizePathTracerHdrHighlights=co,f.transformAabbByMat4=rn,f.vndfReflectionPdf=ze,f.writeBackplate=Gi,f.writePathTracerPostParams=Xr,Object.defineProperty(f,Symbol.toStringTag,{value:"Module"})});
|
package/package.json
CHANGED
|
@@ -1,6 +1,58 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@naanouff/w3dts-path-tracer",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.18",
|
|
4
|
+
"description": "Path tracing with denoiser for the W3DTS WebGPU engine.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"path-tracing",
|
|
7
|
+
"denoiser",
|
|
8
|
+
"webgpu",
|
|
9
|
+
"w3dts"
|
|
10
|
+
],
|
|
11
|
+
"author": "Cyril TARRIET <cyril.tarriet@gmail.com>",
|
|
12
|
+
"license": "UNLICENSED",
|
|
13
|
+
"homepage": "https://github.com/naanouff/w3dts",
|
|
14
|
+
"repository": {
|
|
15
|
+
"type": "git",
|
|
16
|
+
"url": "git+https://github.com/naanouff/w3dts.git"
|
|
17
|
+
},
|
|
18
|
+
"type": "module",
|
|
19
|
+
"main": "./dist/w3dts-path-tracer.umd.js",
|
|
20
|
+
"module": "./dist/w3dts-path-tracer.es.js",
|
|
21
|
+
"types": "./dist/index.d.ts",
|
|
22
|
+
"publishConfig": {
|
|
23
|
+
"access": "public",
|
|
24
|
+
"registry": "https://registry.npmjs.org"
|
|
25
|
+
},
|
|
26
|
+
"exports": {
|
|
27
|
+
".": {
|
|
28
|
+
"types": "./dist/index.d.ts",
|
|
29
|
+
"import": "./dist/w3dts-path-tracer.es.js",
|
|
30
|
+
"require": "./dist/w3dts-path-tracer.umd.js"
|
|
31
|
+
}
|
|
32
|
+
},
|
|
33
|
+
"files": [
|
|
34
|
+
"dist",
|
|
35
|
+
"shaders",
|
|
36
|
+
"graphs"
|
|
37
|
+
],
|
|
38
|
+
"dependencies": {
|
|
39
|
+
"gl-matrix": "^3.4.3",
|
|
40
|
+
"@naanouff/w3dts-core": "0.0.38",
|
|
41
|
+
"@naanouff/w3dts-logger": "0.0.23"
|
|
42
|
+
},
|
|
43
|
+
"optionalDependencies": {
|
|
44
|
+
"oidn-web": "^0.5.0"
|
|
45
|
+
},
|
|
46
|
+
"devDependencies": {
|
|
47
|
+
"typescript": "^5.5.4",
|
|
48
|
+
"vite": "^5.4.21",
|
|
49
|
+
"vite-plugin-dts": "^4.0.3",
|
|
50
|
+
"vitest": "^3.2.7"
|
|
51
|
+
},
|
|
52
|
+
"scripts": {
|
|
53
|
+
"build": "vite build",
|
|
54
|
+
"dev": "vite build --watch",
|
|
55
|
+
"test": "vitest run",
|
|
56
|
+
"check": "tsc --noEmit"
|
|
57
|
+
}
|
|
6
58
|
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Clears the full-resolution path trace composite when a full scene/camera reset occurs.
|
|
3
|
+
* u32[6] in pathTracerTileInfo: 1 = clear this frame, 0 = skip (threads exit immediately).
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
@group(0) @binding(0) var<storage, read> pathTracerTileInfo: array<u32>;
|
|
7
|
+
@group(0) @binding(1) var pathTraceComposite: texture_storage_2d<rgba16float, write>;
|
|
8
|
+
|
|
9
|
+
@compute @workgroup_size(8, 8, 1)
|
|
10
|
+
fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
11
|
+
if (pathTracerTileInfo[6] == 0u) {
|
|
12
|
+
return;
|
|
13
|
+
}
|
|
14
|
+
let dims = textureDimensions(pathTraceComposite);
|
|
15
|
+
if (gid.x >= dims.x || gid.y >= dims.y) {
|
|
16
|
+
return;
|
|
17
|
+
}
|
|
18
|
+
let p = vec2<i32>(i32(gid.x), i32(gid.y));
|
|
19
|
+
textureStore(pathTraceComposite, p, vec4<f32>(0.0, 0.0, 0.0, 1.0));
|
|
20
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Clears full-resolution path trace composites when pathTracerTileInfo[6] != 0.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
@group(0) @binding(0) var<storage, read> pathTracerTileInfo: array<u32>;
|
|
6
|
+
@group(0) @binding(1) var<storage, read> pathTracerParams: array<u32>;
|
|
7
|
+
@group(0) @binding(2) var pathTraceComposite: texture_storage_2d<rgba16float, write>;
|
|
8
|
+
@group(0) @binding(3) var pathTraceNoisyComposite: texture_storage_2d<rgba16float, write>;
|
|
9
|
+
@group(0) @binding(4) var pathTraceGuideComposite: texture_storage_2d<rgba16float, write>;
|
|
10
|
+
@group(0) @binding(5) var pathTraceAlbedoComposite: texture_storage_2d<rgba16float, write>;
|
|
11
|
+
@group(0) @binding(6) var pathTraceObjectIdComposite: texture_storage_2d<rgba16float, write>;
|
|
12
|
+
|
|
13
|
+
const FLAG_TRANSPARENT_BG = 64u;
|
|
14
|
+
|
|
15
|
+
@compute @workgroup_size(8, 8, 1)
|
|
16
|
+
fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
17
|
+
if (pathTracerTileInfo[6] == 0u) {
|
|
18
|
+
return;
|
|
19
|
+
}
|
|
20
|
+
let dims = textureDimensions(pathTraceComposite);
|
|
21
|
+
if (gid.x >= dims.x || gid.y >= dims.y) {
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
let p = vec2<i32>(i32(gid.x), i32(gid.y));
|
|
25
|
+
let transparent = (pathTracerParams[9] & FLAG_TRANSPARENT_BG) != 0u;
|
|
26
|
+
let z = select(vec4<f32>(0.0, 0.0, 0.0, 1.0), vec4<f32>(0.0), transparent);
|
|
27
|
+
textureStore(pathTraceComposite, p, z);
|
|
28
|
+
textureStore(pathTraceNoisyComposite, p, z);
|
|
29
|
+
textureStore(pathTraceGuideComposite, p, vec4<f32>(0.0));
|
|
30
|
+
textureStore(pathTraceAlbedoComposite, p, vec4<f32>(0.0));
|
|
31
|
+
textureStore(pathTraceObjectIdComposite, p, vec4<f32>(0.0));
|
|
32
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Zeros the path-trace tile buffers when accumulation resets (pathTracerParams[0] != 0).
|
|
3
|
+
* Progressive dispatch only writes the Bayer sublattice, so pixels not traced this frame
|
|
4
|
+
* would otherwise keep the previous view. `pathTraceOutput.a = -1.0` (< 0) marks an untraced
|
|
5
|
+
* hole for HoleFill / TileComposite without colliding with `a = 0.0` transparent background coverage.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
@group(0) @binding(0) var<storage, read> pathTracerParams: array<u32>;
|
|
9
|
+
@group(0) @binding(1) var pathTraceOutput: texture_storage_2d<rgba32float, write>;
|
|
10
|
+
@group(0) @binding(2) var pathTraceAccumWrite: texture_storage_2d<rgba32float, write>;
|
|
11
|
+
@group(0) @binding(3) var pathTraceGuide: texture_storage_2d<rgba16float, write>;
|
|
12
|
+
@group(0) @binding(4) var pathTraceAlbedo: texture_storage_2d<rgba16float, write>;
|
|
13
|
+
@group(0) @binding(5) var pathTraceObjectId: texture_storage_2d<rgba16float, write>;
|
|
14
|
+
|
|
15
|
+
@compute @workgroup_size(8, 8, 1)
|
|
16
|
+
fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
17
|
+
if (pathTracerParams[0] == 0u) {
|
|
18
|
+
return;
|
|
19
|
+
}
|
|
20
|
+
let dims = textureDimensions(pathTraceOutput);
|
|
21
|
+
if (gid.x >= dims.x || gid.y >= dims.y) {
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
let p = vec2<i32>(i32(gid.x), i32(gid.y));
|
|
25
|
+
textureStore(pathTraceOutput, p, vec4<f32>(0.0, 0.0, 0.0, -1.0));
|
|
26
|
+
textureStore(pathTraceAccumWrite, p, vec4<f32>(0.0));
|
|
27
|
+
textureStore(pathTraceGuide, p, vec4<f32>(0.0));
|
|
28
|
+
textureStore(pathTraceAlbedo, p, vec4<f32>(0.0));
|
|
29
|
+
textureStore(pathTraceObjectId, p, vec4<f32>(0.0));
|
|
30
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copy pathTraceAccumWrite -> pathTraceAccumRead for next frame's accumulation.
|
|
3
|
+
* Storage textures: read from one, write to the other (rgba32float does not support read_write).
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
@group(0) @binding(0) var accumSource: texture_storage_2d<rgba32float, read>;
|
|
7
|
+
@group(0) @binding(1) var accumDest: texture_storage_2d<rgba32float, write>;
|
|
8
|
+
|
|
9
|
+
@compute @workgroup_size(8, 8, 1)
|
|
10
|
+
fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
11
|
+
let dims = textureDimensions(accumSource);
|
|
12
|
+
if (gid.x >= dims.x || gid.y >= dims.y) { return; }
|
|
13
|
+
let p = vec2<i32>(gid.xy);
|
|
14
|
+
textureStore(accumDest, p, textureLoad(accumSource, p));
|
|
15
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Spatial denoiser: box blur or edge-aware blend using path trace guide (normal xyz + depth in alpha).
|
|
3
|
+
* denoiserParams[0]: bypass (non-zero → copy input)
|
|
4
|
+
* denoiserParams[1]: kernel radius (pixels), clamped 1–16 when bypass is 0
|
|
5
|
+
* denoiserParams[2]: guided (non-zero → weight neighbors by guide similarity)
|
|
6
|
+
* denoiserParams[3]: firefly suppress (non-zero → pull outliers toward neighbor-weighted mean)
|
|
7
|
+
* denoiserParams[4]: atrous active (used by denoise_atrous; ignored here)
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
@group(0) @binding(0) var pathTraceInput: texture_storage_2d<rgba32float, read>;
|
|
11
|
+
@group(0) @binding(1) var pathTraceGuide: texture_storage_2d<rgba16float, read>;
|
|
12
|
+
@group(0) @binding(2) var denoisedOutput: texture_storage_2d<rgba16float, write>;
|
|
13
|
+
@group(0) @binding(3) var<storage, read> denoiserParams: array<u32, 8>;
|
|
14
|
+
|
|
15
|
+
fn luminance_rgb(c: vec3<f32>) -> f32 {
|
|
16
|
+
return dot(c, vec3<f32>(0.2126, 0.7152, 0.0722));
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
@compute @workgroup_size(8, 8, 1)
|
|
20
|
+
fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
21
|
+
let dims = textureDimensions(pathTraceInput);
|
|
22
|
+
if (gid.x >= dims.x || gid.y >= dims.y) { return; }
|
|
23
|
+
|
|
24
|
+
let xy = vec2<i32>(gid.xy);
|
|
25
|
+
if (denoiserParams[0] != 0u) {
|
|
26
|
+
textureStore(denoisedOutput, xy, textureLoad(pathTraceInput, xy));
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
let rad = i32(clamp(denoiserParams[1], 1u, 16u));
|
|
31
|
+
let guided = denoiserParams[2] != 0u;
|
|
32
|
+
let fireflySuppress = denoiserParams[3] != 0u;
|
|
33
|
+
let centerC = textureLoad(pathTraceInput, xy);
|
|
34
|
+
if (centerC.a < 0.0) {
|
|
35
|
+
textureStore(denoisedOutput, xy, centerC);
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
let centerG = textureLoad(pathTraceGuide, xy);
|
|
39
|
+
var sum = vec4<f32>(0.0);
|
|
40
|
+
var wsum = 0.0;
|
|
41
|
+
var sumNeigh = vec4<f32>(0.0);
|
|
42
|
+
var wsumNeigh = 0.0;
|
|
43
|
+
var maxNeighLum = 0.0;
|
|
44
|
+
|
|
45
|
+
for (var dy = -rad; dy <= rad; dy++) {
|
|
46
|
+
for (var dx = -rad; dx <= rad; dx++) {
|
|
47
|
+
let p = xy + vec2<i32>(dx, dy);
|
|
48
|
+
if (p.x >= 0 && p.x < i32(dims.x) && p.y >= 0 && p.y < i32(dims.y)) {
|
|
49
|
+
let c = textureLoad(pathTraceInput, p);
|
|
50
|
+
if (c.a < 0.0) {
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
var w = 1.0;
|
|
54
|
+
if (guided) {
|
|
55
|
+
let g = textureLoad(pathTraceGuide, p);
|
|
56
|
+
let dn = g.xyz - centerG.xyz;
|
|
57
|
+
let dz = g.w - centerG.w;
|
|
58
|
+
let dist = dot(dn, dn) * 4.0 + dz * dz * 400.0;
|
|
59
|
+
w = exp(-dist * 2.0);
|
|
60
|
+
}
|
|
61
|
+
sum += c * w;
|
|
62
|
+
wsum += w;
|
|
63
|
+
let isCenter = (dx == 0 && dy == 0);
|
|
64
|
+
if (!isCenter) {
|
|
65
|
+
sumNeigh += c * w;
|
|
66
|
+
wsumNeigh += w;
|
|
67
|
+
maxNeighLum = max(maxNeighLum, luminance_rgb(c.rgb));
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
var outC = sum / max(wsum, 1e-6);
|
|
74
|
+
if (fireflySuppress && wsumNeigh > 1e-5) {
|
|
75
|
+
let neighMean = sumNeigh / wsumNeigh;
|
|
76
|
+
let meanNeighLum = luminance_rgb(neighMean.rgb);
|
|
77
|
+
let cLum = luminance_rgb(centerC.rgb);
|
|
78
|
+
let outLum = luminance_rgb(outC.rgb);
|
|
79
|
+
let refLum = max(maxNeighLum, 0.02);
|
|
80
|
+
var pull = false;
|
|
81
|
+
if (cLum > 6.5 * refLum) { pull = true; }
|
|
82
|
+
if (meanNeighLum > 0.008 && outLum > meanNeighLum * 4.5 + 0.06) { pull = true; }
|
|
83
|
+
if (pull) {
|
|
84
|
+
outC = mix(outC, neighMean, 0.86);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
textureStore(denoisedOutput, xy, outC);
|
|
88
|
+
}
|