softbox 4.0.0

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.
@@ -0,0 +1,3977 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const l=require("three"),T=require("./index-C4Chx9Wl.cjs");function $e(s){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const t in s)if(t!=="default"){const r=Object.getOwnPropertyDescriptor(s,t);Object.defineProperty(e,t,r.get?r:{enumerable:!0,get:()=>s[t]})}}return e.default=s,Object.freeze(e)}const A=$e(l);function je(s){switch(s){case 1:return"R";case 2:return"RG";case 3:return"RGBA";case 4:return"RGBA"}throw new Error}function Ye(s){switch(s){case 1:return l.RedFormat;case 2:return l.RGFormat;case 3:return l.RGBAFormat;case 4:return l.RGBAFormat}}function de(s){switch(s){case 1:return l.RedIntegerFormat;case 2:return l.RGIntegerFormat;case 3:return l.RGBAIntegerFormat;case 4:return l.RGBAIntegerFormat}}class Oe extends l.DataTexture{constructor(){super(),this.minFilter=l.NearestFilter,this.magFilter=l.NearestFilter,this.generateMipmaps=!1,this.overrideItemSize=null,this._forcedType=null}updateFrom(e){const t=this.overrideItemSize,r=e.itemSize,i=e.count;if(t!==null){if(r*i%t!==0)throw new Error("VertexAttributeTexture: overrideItemSize must divide evenly into buffer length.");e.itemSize=t,e.count=i*r/t}const o=e.itemSize,a=e.count,c=e.normalized,h=e.array.constructor,d=h.BYTES_PER_ELEMENT;let m=this._forcedType,f=o;if(m===null)switch(h){case Float32Array:m=l.FloatType;break;case Uint8Array:case Uint16Array:case Uint32Array:m=l.UnsignedIntType;break;case Int8Array:case Int16Array:case Int32Array:m=l.IntType;break}let n,x,p,v,u=je(o);switch(m){case l.FloatType:p=1,x=Ye(o),c&&d===1?(v=h,u+="8",h===Uint8Array?n=l.UnsignedByteType:(n=l.ByteType,u+="_SNORM")):(v=Float32Array,u+="32F",n=l.FloatType);break;case l.IntType:u+=d*8+"I",p=c?Math.pow(2,h.BYTES_PER_ELEMENT*8-1):1,x=de(o),d===1?(v=Int8Array,n=l.ByteType):d===2?(v=Int16Array,n=l.ShortType):(v=Int32Array,n=l.IntType);break;case l.UnsignedIntType:u+=d*8+"UI",p=c?Math.pow(2,h.BYTES_PER_ELEMENT*8-1):1,x=de(o),d===1?(v=Uint8Array,n=l.UnsignedByteType):d===2?(v=Uint16Array,n=l.UnsignedShortType):(v=Uint32Array,n=l.UnsignedIntType);break}f===3&&(x===l.RGBAFormat||x===l.RGBAIntegerFormat)&&(f=4);const g=Math.ceil(Math.sqrt(a))||1,y=f*g*g,b=new v(y),w=e.normalized;e.normalized=!1;for(let R=0;R<a;R++){const _=f*R;b[_]=e.getX(R)/p,o>=2&&(b[_+1]=e.getY(R)/p),o>=3&&(b[_+2]=e.getZ(R)/p,f===4&&(b[_+3]=1)),o>=4&&(b[_+3]=e.getW(R)/p)}e.normalized=w,this.internalFormat=u,this.format=x,this.type=n,this.image.width=g,this.image.height=g,this.image.data=b,this.needsUpdate=!0,this.dispose(),e.itemSize=r,e.count=i}}class Be extends Oe{constructor(){super(),this._forcedType=l.UnsignedIntType}}class Ne extends Oe{constructor(){super(),this._forcedType=l.FloatType}}class Xe{constructor(){this.index=new Be,this.position=new Ne,this.bvhBounds=new l.DataTexture,this.bvhContents=new l.DataTexture,this._cachedIndexAttr=null,this.index.overrideItemSize=3}updateFrom(e){const{geometry:t}=e;if(Ke(e,this.bvhBounds,this.bvhContents),this.position.updateFrom(t.attributes.position),e.indirect){const r=e._indirectBuffer;if(this._cachedIndexAttr===null||this._cachedIndexAttr.count!==r.length)if(t.index)this._cachedIndexAttr=t.index.clone();else{const i=T.getIndexArray(T.getVertexCount(t));this._cachedIndexAttr=new l.BufferAttribute(i,1,!1)}Qe(t,r,this._cachedIndexAttr),this.index.updateFrom(this._cachedIndexAttr)}else this.index.updateFrom(t.index)}dispose(){const{index:e,position:t,bvhBounds:r,bvhContents:i}=this;e&&e.dispose(),t&&t.dispose(),r&&r.dispose(),i&&i.dispose()}}function Qe(s,e,t){const r=t.array,i=s.index?s.index.array:null;for(let o=0,a=e.length;o<a;o++){const c=3*o,h=3*e[o];for(let d=0;d<3;d++)r[c+d]=i?i[h+d]:h+d}}function Ke(s,e,t){const r=s._roots;if(r.length!==1)throw new Error("MeshBVHUniformStruct: Multi-root BVHs not supported.");const i=r[0],o=new Uint16Array(i),a=new Uint32Array(i),c=new Float32Array(i),h=i.byteLength/T.BYTES_PER_NODE,d=2*Math.ceil(Math.sqrt(h/2)),m=new Float32Array(4*d*d),f=Math.ceil(Math.sqrt(h)),n=new Uint32Array(2*f*f);for(let x=0;x<h;x++){const p=x*T.BYTES_PER_NODE/4,v=p*2,u=T.BOUNDING_DATA_INDEX(p);for(let g=0;g<3;g++)m[8*x+0+g]=c[u+0+g],m[8*x+4+g]=c[u+3+g];if(T.IS_LEAF(v,o)){const g=T.COUNT(v,o),y=T.OFFSET(p,a),b=T.LEAFNODE_MASK_32|g;n[x*2+0]=b,n[x*2+1]=y}else{const g=a[p+6],y=T.SPLIT_AXIS(p,a);n[x*2+0]=y,n[x*2+1]=g}}e.image.data=m,e.image.width=d,e.image.height=d,e.format=l.RGBAFormat,e.type=l.FloatType,e.internalFormat="RGBA32F",e.minFilter=l.NearestFilter,e.magFilter=l.NearestFilter,e.generateMipmaps=!1,e.needsUpdate=!0,e.dispose(),t.image.data=n,t.image.width=f,t.image.height=f,t.format=l.RGIntegerFormat,t.type=l.UnsignedIntType,t.internalFormat="RG32UI",t.minFilter=l.NearestFilter,t.magFilter=l.NearestFilter,t.generateMipmaps=!1,t.needsUpdate=!0,t.dispose()}const Ze=`
2
+
3
+ // A stack of uint32 indices can can store the indices for
4
+ // a perfectly balanced tree with a depth up to 31. Lower stack
5
+ // depth gets higher performance.
6
+ //
7
+ // However not all trees are balanced. Best value to set this to
8
+ // is the trees max depth.
9
+ #ifndef BVH_STACK_DEPTH
10
+ #define BVH_STACK_DEPTH 60
11
+ #endif
12
+
13
+ #ifndef INFINITY
14
+ #define INFINITY 1e20
15
+ #endif
16
+
17
+ // Utilities
18
+ uvec4 uTexelFetch1D( usampler2D tex, uint index ) {
19
+
20
+ uint width = uint( textureSize( tex, 0 ).x );
21
+ uvec2 uv;
22
+ uv.x = index % width;
23
+ uv.y = index / width;
24
+
25
+ return texelFetch( tex, ivec2( uv ), 0 );
26
+
27
+ }
28
+
29
+ ivec4 iTexelFetch1D( isampler2D tex, uint index ) {
30
+
31
+ uint width = uint( textureSize( tex, 0 ).x );
32
+ uvec2 uv;
33
+ uv.x = index % width;
34
+ uv.y = index / width;
35
+
36
+ return texelFetch( tex, ivec2( uv ), 0 );
37
+
38
+ }
39
+
40
+ vec4 texelFetch1D( sampler2D tex, uint index ) {
41
+
42
+ uint width = uint( textureSize( tex, 0 ).x );
43
+ uvec2 uv;
44
+ uv.x = index % width;
45
+ uv.y = index / width;
46
+
47
+ return texelFetch( tex, ivec2( uv ), 0 );
48
+
49
+ }
50
+
51
+ vec4 textureSampleBarycoord( sampler2D tex, vec3 barycoord, uvec3 faceIndices ) {
52
+
53
+ return
54
+ barycoord.x * texelFetch1D( tex, faceIndices.x ) +
55
+ barycoord.y * texelFetch1D( tex, faceIndices.y ) +
56
+ barycoord.z * texelFetch1D( tex, faceIndices.z );
57
+
58
+ }
59
+
60
+ void ndcToCameraRay(
61
+ vec2 coord, mat4 cameraWorld, mat4 invProjectionMatrix,
62
+ out vec3 rayOrigin, out vec3 rayDirection
63
+ ) {
64
+
65
+ // get camera look direction and near plane for camera clipping
66
+ vec4 lookDirection = cameraWorld * vec4( 0.0, 0.0, - 1.0, 0.0 );
67
+ vec4 nearVector = invProjectionMatrix * vec4( 0.0, 0.0, - 1.0, 1.0 );
68
+ float near = abs( nearVector.z / nearVector.w );
69
+
70
+ // get the camera direction and position from camera matrices
71
+ vec4 origin = cameraWorld * vec4( 0.0, 0.0, 0.0, 1.0 );
72
+ vec4 direction = invProjectionMatrix * vec4( coord, 0.5, 1.0 );
73
+ direction /= direction.w;
74
+ direction = cameraWorld * direction - origin;
75
+
76
+ // slide the origin along the ray until it sits at the near clip plane position
77
+ origin.xyz += direction.xyz * near / dot( direction, lookDirection );
78
+
79
+ rayOrigin = origin.xyz;
80
+ rayDirection = direction.xyz;
81
+
82
+ }
83
+ `,Je=`
84
+
85
+ #ifndef TRI_INTERSECT_EPSILON
86
+ #define TRI_INTERSECT_EPSILON 1e-5
87
+ #endif
88
+
89
+ // Raycasting
90
+ bool intersectsBounds( vec3 rayOrigin, vec3 rayDirection, vec3 boundsMin, vec3 boundsMax, out float dist ) {
91
+
92
+ // https://www.reddit.com/r/opengl/comments/8ntzz5/fast_glsl_ray_box_intersection/
93
+ // https://tavianator.com/2011/ray_box.html
94
+ vec3 invDir = 1.0 / rayDirection;
95
+
96
+ // find intersection distances for each plane
97
+ vec3 tMinPlane = invDir * ( boundsMin - rayOrigin );
98
+ vec3 tMaxPlane = invDir * ( boundsMax - rayOrigin );
99
+
100
+ // get the min and max distances from each intersection
101
+ vec3 tMinHit = min( tMaxPlane, tMinPlane );
102
+ vec3 tMaxHit = max( tMaxPlane, tMinPlane );
103
+
104
+ // get the furthest hit distance
105
+ vec2 t = max( tMinHit.xx, tMinHit.yz );
106
+ float t0 = max( t.x, t.y );
107
+
108
+ // get the minimum hit distance
109
+ t = min( tMaxHit.xx, tMaxHit.yz );
110
+ float t1 = min( t.x, t.y );
111
+
112
+ // set distance to 0.0 if the ray starts inside the box
113
+ dist = max( t0, 0.0 );
114
+
115
+ return t1 >= dist;
116
+
117
+ }
118
+
119
+ bool intersectsTriangle(
120
+ vec3 rayOrigin, vec3 rayDirection, vec3 a, vec3 b, vec3 c,
121
+ out vec3 barycoord, out vec3 norm, out float dist, out float side
122
+ ) {
123
+
124
+ // https://stackoverflow.com/questions/42740765/intersection-between-line-and-triangle-in-3d
125
+ vec3 edge1 = b - a;
126
+ vec3 edge2 = c - a;
127
+ norm = cross( edge1, edge2 );
128
+
129
+ float det = - dot( rayDirection, norm );
130
+ float invdet = 1.0 / det;
131
+
132
+ vec3 AO = rayOrigin - a;
133
+ vec3 DAO = cross( AO, rayDirection );
134
+
135
+ vec4 uvt;
136
+ uvt.x = dot( edge2, DAO ) * invdet;
137
+ uvt.y = - dot( edge1, DAO ) * invdet;
138
+ uvt.z = dot( AO, norm ) * invdet;
139
+ uvt.w = 1.0 - uvt.x - uvt.y;
140
+
141
+ // set the hit information
142
+ barycoord = uvt.wxy; // arranged in A, B, C order
143
+ dist = uvt.z;
144
+ side = sign( det );
145
+ norm = side * normalize( norm );
146
+
147
+ // add an epsilon to avoid misses between triangles
148
+ uvt += vec4( TRI_INTERSECT_EPSILON );
149
+
150
+ return all( greaterThanEqual( uvt, vec4( 0.0 ) ) );
151
+
152
+ }
153
+
154
+ bool intersectTriangles(
155
+ // geometry info and triangle range
156
+ sampler2D positionAttr, usampler2D indexAttr, uint offset, uint count,
157
+
158
+ // ray
159
+ vec3 rayOrigin, vec3 rayDirection,
160
+
161
+ // outputs
162
+ inout float minDistance, inout uvec4 faceIndices, inout vec3 faceNormal, inout vec3 barycoord,
163
+ inout float side, inout float dist
164
+ ) {
165
+
166
+ bool found = false;
167
+ vec3 localBarycoord, localNormal;
168
+ float localDist, localSide;
169
+ for ( uint i = offset, l = offset + count; i < l; i ++ ) {
170
+
171
+ uvec3 indices = uTexelFetch1D( indexAttr, i ).xyz;
172
+ vec3 a = texelFetch1D( positionAttr, indices.x ).rgb;
173
+ vec3 b = texelFetch1D( positionAttr, indices.y ).rgb;
174
+ vec3 c = texelFetch1D( positionAttr, indices.z ).rgb;
175
+
176
+ if (
177
+ intersectsTriangle( rayOrigin, rayDirection, a, b, c, localBarycoord, localNormal, localDist, localSide )
178
+ && localDist < minDistance
179
+ ) {
180
+
181
+ found = true;
182
+ minDistance = localDist;
183
+
184
+ faceIndices = uvec4( indices.xyz, i );
185
+ faceNormal = localNormal;
186
+
187
+ side = localSide;
188
+ barycoord = localBarycoord;
189
+ dist = localDist;
190
+
191
+ }
192
+
193
+ }
194
+
195
+ return found;
196
+
197
+ }
198
+
199
+ bool intersectsBVHNodeBounds( vec3 rayOrigin, vec3 rayDirection, sampler2D bvhBounds, uint currNodeIndex, out float dist ) {
200
+
201
+ uint cni2 = currNodeIndex * 2u;
202
+ vec3 boundsMin = texelFetch1D( bvhBounds, cni2 ).xyz;
203
+ vec3 boundsMax = texelFetch1D( bvhBounds, cni2 + 1u ).xyz;
204
+ return intersectsBounds( rayOrigin, rayDirection, boundsMin, boundsMax, dist );
205
+
206
+ }
207
+
208
+ // use a macro to hide the fact that we need to expand the struct into separate fields
209
+ #define bvhIntersectFirstHit( bvh, rayOrigin, rayDirection, faceIndices, faceNormal, barycoord, side, dist ) _bvhIntersectFirstHit( bvh.position, bvh.index, bvh.bvhBounds, bvh.bvhContents, rayOrigin, rayDirection, faceIndices, faceNormal, barycoord, side, dist )
210
+
211
+ bool _bvhIntersectFirstHit(
212
+ // bvh info
213
+ sampler2D bvh_position, usampler2D bvh_index, sampler2D bvh_bvhBounds, usampler2D bvh_bvhContents,
214
+
215
+ // ray
216
+ vec3 rayOrigin, vec3 rayDirection,
217
+
218
+ // output variables split into separate variables due to output precision
219
+ inout uvec4 faceIndices, inout vec3 faceNormal, inout vec3 barycoord,
220
+ inout float side, inout float dist
221
+ ) {
222
+
223
+ // stack needs to be twice as long as the deepest tree we expect because
224
+ // we push both the left and right child onto the stack every traversal
225
+ int pointer = 0;
226
+ uint stack[ BVH_STACK_DEPTH ];
227
+ stack[ 0 ] = 0u;
228
+
229
+ float triangleDistance = INFINITY;
230
+ bool found = false;
231
+ while ( pointer > - 1 && pointer < BVH_STACK_DEPTH ) {
232
+
233
+ uint currNodeIndex = stack[ pointer ];
234
+ pointer --;
235
+
236
+ // check if we intersect the current bounds
237
+ float boundsHitDistance;
238
+ if (
239
+ ! intersectsBVHNodeBounds( rayOrigin, rayDirection, bvh_bvhBounds, currNodeIndex, boundsHitDistance )
240
+ || boundsHitDistance > triangleDistance
241
+ ) {
242
+
243
+ continue;
244
+
245
+ }
246
+
247
+ uvec2 boundsInfo = uTexelFetch1D( bvh_bvhContents, currNodeIndex ).xy;
248
+ bool isLeaf = bool( boundsInfo.x & 0xffff0000u );
249
+
250
+ if ( isLeaf ) {
251
+
252
+ uint count = boundsInfo.x & 0x0000ffffu;
253
+ uint offset = boundsInfo.y;
254
+
255
+ found = intersectTriangles(
256
+ bvh_position, bvh_index, offset, count,
257
+ rayOrigin, rayDirection, triangleDistance,
258
+ faceIndices, faceNormal, barycoord, side, dist
259
+ ) || found;
260
+
261
+ } else {
262
+
263
+ uint leftIndex = currNodeIndex + 1u;
264
+ uint splitAxis = boundsInfo.x & 0x0000ffffu;
265
+ uint rightIndex = currNodeIndex + boundsInfo.y;
266
+
267
+ bool leftToRight = rayDirection[ splitAxis ] >= 0.0;
268
+ uint c1 = leftToRight ? leftIndex : rightIndex;
269
+ uint c2 = leftToRight ? rightIndex : leftIndex;
270
+
271
+ // set c2 in the stack so we traverse it later. We need to keep track of a pointer in
272
+ // the stack while we traverse. The second pointer added is the one that will be
273
+ // traversed first
274
+ pointer ++;
275
+ stack[ pointer ] = c2;
276
+
277
+ pointer ++;
278
+ stack[ pointer ] = c1;
279
+
280
+ }
281
+
282
+ }
283
+
284
+ return found;
285
+
286
+ }
287
+ `,et=`
288
+ struct BVH {
289
+
290
+ usampler2D index;
291
+ sampler2D position;
292
+
293
+ sampler2D bvhBounds;
294
+ usampler2D bvhContents;
295
+
296
+ };
297
+ `;function ze(s,e,t=0){if(s.isInterleavedBufferAttribute){const r=s.itemSize;for(let i=0,o=s.count;i<o;i++){const a=i+t;e.setX(a,s.getX(i)),r>=2&&e.setY(a,s.getY(i)),r>=3&&e.setZ(a,s.getZ(i)),r>=4&&e.setW(a,s.getW(i))}}else{const r=e.array,i=r.constructor,o=r.BYTES_PER_ELEMENT*s.itemSize*t;new i(r.buffer,o,s.array.length).set(s.array)}}function H(s,e=null){const t=s.array.constructor,r=s.normalized,i=s.itemSize,o=e===null?s.count:e;return new l.BufferAttribute(new t(i*o),i,r)}function N(s,e){if(!s&&!e)return!0;if(!!s!=!!e)return!1;const t=s.count===e.count,r=s.normalized===e.normalized,i=s.array.constructor===e.array.constructor,o=s.itemSize===e.itemSize;return!(!t||!r||!i||!o)}function tt(s){const e=s[0].index!==null,t=new Set(Object.keys(s[0].attributes));if(!s[0].getAttribute("position"))throw new Error("StaticGeometryGenerator: position attribute is required.");for(let r=0;r<s.length;++r){const i=s[r];let o=0;if(e!==(i.index!==null))throw new Error("StaticGeometryGenerator: All geometries must have compatible attributes; make sure index attribute exists among all geometries, or in none of them.");for(const a in i.attributes){if(!t.has(a))throw new Error('StaticGeometryGenerator: All geometries must have compatible attributes; make sure "'+a+'" attribute exists among all geometries, or in none of them.');o++}if(o!==t.size)throw new Error("StaticGeometryGenerator: All geometries must have the same number of attributes.")}}function rt(s){let e=0;for(let t=0,r=s.length;t<r;t++)e+=s[t].getIndex().count;return e}function at(s){let e=0;for(let t=0,r=s.length;t<r;t++)e+=s[t].getAttribute("position").count;return e}function it(s,e,t){s.index&&s.index.count!==e&&s.setIndex(null);const r=s.attributes;for(const i in r)r[i].count!==t&&s.deleteAttribute(i)}function st(s,e={},t=new l.BufferGeometry){const{useGroups:r=!1,forceUpdate:i=!1,skipAssigningAttributes:o=[],overwriteIndex:a=!0}=e;tt(s);const c=s[0].index!==null,h=c?rt(s):-1,d=at(s);if(it(t,h,d),r){let f=0;for(let n=0,x=s.length;n<x;n++){const p=s[n];let v;c?v=p.getIndex().count:v=p.getAttribute("position").count,t.addGroup(f,v,n),f+=v}}if(c){let f=!1;if(t.index||(t.setIndex(new l.BufferAttribute(new Uint32Array(h),1,!1)),f=!0),f||a){let n=0,x=0;const p=t.getIndex();for(let v=0,u=s.length;v<u;v++){const g=s[v],y=g.getIndex();if(!(!i&&!f&&o[v]))for(let w=0;w<y.count;++w)p.setX(n+w,y.getX(w)+x);n+=y.count,x+=g.getAttribute("position").count}}}const m=Object.keys(s[0].attributes);for(let f=0,n=m.length;f<n;f++){let x=!1;const p=m[f];if(!t.getAttribute(p)){const g=s[0].getAttribute(p);t.setAttribute(p,H(g,d)),x=!0}let v=0;const u=t.getAttribute(p);for(let g=0,y=s.length;g<y;g++){const b=s[g],w=!i&&!x&&o[g],R=b.getAttribute(p);w||ze(R,u,v),v+=R.count}}}function ot(s,e,t){const r=s.index,o=s.attributes.position.count,a=r?r.count:o;let c=s.groups;c.length===0&&(c=[{count:a,start:0,materialIndex:0}]);let h=s.getAttribute("materialIndex");if(!h||h.count!==o){let m;t.length<=255?m=new Uint8Array(o):m=new Uint16Array(o),h=new l.BufferAttribute(m,1,!1),s.deleteAttribute("materialIndex"),s.setAttribute("materialIndex",h)}const d=h.array;for(let m=0;m<c.length;m++){const f=c[m],n=f.start,x=f.count,p=Math.min(x,a-n),v=Array.isArray(e)?e[f.materialIndex]:e,u=t.indexOf(v);for(let g=0;g<p;g++){let y=n+g;r&&(y=r.getX(y)),d[y]=u}}}function nt(s,e){if(!s.index){const t=s.attributes.position.count,r=new Array(t);for(let i=0;i<t;i++)r[i]=i;s.setIndex(r)}if(!s.attributes.normal&&e&&e.includes("normal")&&s.computeVertexNormals(),!s.attributes.uv&&e&&e.includes("uv")){const t=s.attributes.position.count;s.setAttribute("uv",new l.BufferAttribute(new Float32Array(t*2),2,!1))}if(!s.attributes.uv2&&e&&e.includes("uv2")){const t=s.attributes.position.count;s.setAttribute("uv2",new l.BufferAttribute(new Float32Array(t*2),2,!1))}if(!s.attributes.tangent&&e&&e.includes("tangent"))if(s.attributes.uv&&s.attributes.normal)s.computeTangents();else{const t=s.attributes.position.count;s.setAttribute("tangent",new l.BufferAttribute(new Float32Array(t*4),4,!1))}if(!s.attributes.color&&e&&e.includes("color")){const t=s.attributes.position.count,r=new Float32Array(t*4);r.fill(1),s.setAttribute("color",new l.BufferAttribute(r,4))}}function se(s){let e=0;if(s.byteLength!==0){const t=new Uint8Array(s);for(let r=0;r<s.byteLength;r++){const i=t[r];e=(e<<5)-e+i,e|=0}}return e}function me(s){let e=s.uuid;const t=Object.values(s.attributes);s.index&&(t.push(s.index),e+=`index|${s.index.version}`);const r=Object.keys(t).sort();for(const i of r){const o=t[i];e+=`${i}_${o.version}|`}return e}function pe(s){const e=s.skeleton;return e?(e.boneTexture||e.computeBoneTexture(),`${se(e.boneTexture.image.data.buffer)}_${e.boneTexture.uuid}`):null}class lt{constructor(e=null){this.matrixWorld=new l.Matrix4,this.geometryHash=null,this.skeletonHash=null,this.primitiveCount=-1,e!==null&&this.updateFrom(e)}updateFrom(e){const t=e.geometry,r=(t.index?t.index.count:t.attributes.position.count)/3;this.matrixWorld.copy(e.matrixWorld),this.geometryHash=me(t),this.primitiveCount=r,this.skeletonHash=pe(e)}didChange(e){const t=e.geometry,r=(t.index?t.index.count:t.attributes.position.count)/3;return!(this.matrixWorld.equals(e.matrixWorld)&&this.geometryHash===me(t)&&this.skeletonHash===pe(e)&&this.primitiveCount===r)}}const M=new l.Vector3,C=new l.Vector3,D=new l.Vector3,ge=new l.Vector4,U=new l.Vector3,J=new l.Vector3,ve=new l.Vector4,xe=new l.Vector4,G=new l.Matrix4,ye=new l.Matrix4;function be(s,e,t){const r=s.skeleton,i=s.geometry,o=r.bones,a=r.boneInverses;ve.fromBufferAttribute(i.attributes.skinIndex,e),xe.fromBufferAttribute(i.attributes.skinWeight,e),G.elements.fill(0);for(let c=0;c<4;c++){const h=xe.getComponent(c);if(h!==0){const d=ve.getComponent(c);ye.multiplyMatrices(o[d].matrixWorld,a[d]),ct(G,ye,h)}}return G.multiply(s.bindMatrix).premultiply(s.bindMatrixInverse),t.transformDirection(G),t}function ee(s,e,t,r,i){U.set(0,0,0);for(let o=0,a=s.length;o<a;o++){const c=e[o],h=s[o];c!==0&&(J.fromBufferAttribute(h,r),t?U.addScaledVector(J,c):U.addScaledVector(J.sub(i),c))}i.add(U)}function ct(s,e,t){const r=s.elements,i=e.elements;for(let o=0,a=i.length;o<a;o++)r[o]+=i[o]*t}function ut(s){const{index:e,attributes:t}=s;if(e)for(let r=0,i=e.count;r<i;r+=3){const o=e.getX(r),a=e.getX(r+2);e.setX(r,a),e.setX(r+2,o)}else for(const r in t){const i=t[r],o=i.itemSize;for(let a=0,c=i.count;a<c;a+=3)for(let h=0;h<o;h++){const d=i.getComponent(a,h),m=i.getComponent(a+2,h);i.setComponent(a,h,m),i.setComponent(a+2,h,d)}}return s}function ft(s,e={},t=new l.BufferGeometry){e={applyWorldTransforms:!0,attributes:[],...e};const r=s.geometry,i=e.applyWorldTransforms,o=e.attributes.includes("normal"),a=e.attributes.includes("tangent"),c=r.attributes,h=t.attributes;for(const y in t.attributes)(!e.attributes.includes(y)||!(y in r.attributes))&&t.deleteAttribute(y);!t.index&&r.index&&(t.index=r.index.clone()),h.position||t.setAttribute("position",H(c.position)),o&&!h.normal&&c.normal&&t.setAttribute("normal",H(c.normal)),a&&!h.tangent&&c.tangent&&t.setAttribute("tangent",H(c.tangent)),N(r.index,t.index),N(c.position,h.position),o&&N(c.normal,h.normal),a&&N(c.tangent,h.tangent);const d=c.position,m=o?c.normal:null,f=a?c.tangent:null,n=r.morphAttributes.position,x=r.morphAttributes.normal,p=r.morphAttributes.tangent,v=r.morphTargetsRelative,u=s.morphTargetInfluences,g=new l.Matrix3;g.getNormalMatrix(s.matrixWorld),r.index&&t.index.array.set(r.index.array);for(let y=0,b=c.position.count;y<b;y++)M.fromBufferAttribute(d,y),m&&C.fromBufferAttribute(m,y),f&&(ge.fromBufferAttribute(f,y),D.fromBufferAttribute(f,y)),u&&(n&&ee(n,u,v,y,M),x&&ee(x,u,v,y,C),p&&ee(p,u,v,y,D)),s.isSkinnedMesh&&(s.applyBoneTransform(y,M),m&&be(s,y,C),f&&be(s,y,D)),i&&M.applyMatrix4(s.matrixWorld),h.position.setXYZ(y,M.x,M.y,M.z),m&&(i&&C.applyNormalMatrix(g),h.normal.setXYZ(y,C.x,C.y,C.z)),f&&(i&&D.transformDirection(s.matrixWorld),h.tangent.setXYZW(y,D.x,D.y,D.z,ge.w));for(const y in e.attributes){const b=e.attributes[y];b==="position"||b==="tangent"||b==="normal"||!(b in c)||(h[b]||t.setAttribute(b,H(c[b])),N(c[b],h[b]),ze(c[b],h[b]))}return s.matrixWorld.determinant()<0&&ut(t),t}class ht extends l.BufferGeometry{constructor(){super(),this.version=0,this.hash=null,this._diff=new lt}isCompatible(e,t){const r=e.geometry;for(let i=0;i<t.length;i++){const o=t[i],a=r.attributes[o],c=this.attributes[o];if(a&&!N(a,c))return!1}return!0}updateFrom(e,t){const r=this._diff;return r.didChange(e)?(ft(e,t,this),r.updateFrom(e),this.version++,this.hash=`${this.uuid}_${this.version}`,!0):!1}}const ae=0,He=1,We=2;function dt(s,e){for(let t=0,r=s.length;t<r;t++)s[t].traverseVisible(o=>{o.isMesh&&e(o)})}function mt(s){const e=[];for(let t=0,r=s.length;t<r;t++){const i=s[t];Array.isArray(i.material)?e.push(...i.material):e.push(i.material)}return e}function pt(s,e,t){if(s.length===0){e.setIndex(null);const r=e.attributes;for(const i in r)e.deleteAttribute(i);for(const i in t.attributes)e.setAttribute(t.attributes[i],new l.BufferAttribute(new Float32Array(0),4,!1))}else st(s,t,e);for(const r in e.attributes)e.attributes[r].needsUpdate=!0}class gt{constructor(e){this.objects=null,this.useGroups=!0,this.applyWorldTransforms=!0,this.generateMissingAttributes=!0,this.overwriteIndex=!0,this.attributes=["position","normal","color","tangent","uv","uv2"],this._intermediateGeometry=new Map,this._geometryMergeSets=new WeakMap,this._mergeOrder=[],this._dummyMesh=null,this.setObjects(e||[])}_getDummyMesh(){if(!this._dummyMesh){const e=new l.MeshBasicMaterial,t=new l.BufferGeometry;t.setAttribute("position",new l.BufferAttribute(new Float32Array(9),3)),this._dummyMesh=new l.Mesh(t,e)}return this._dummyMesh}_getMeshes(){const e=[];return dt(this.objects,t=>{e.push(t)}),e.sort((t,r)=>t.uuid>r.uuid?1:t.uuid<r.uuid?-1:0),e.length===0&&e.push(this._getDummyMesh()),e}_updateIntermediateGeometries(){const{_intermediateGeometry:e}=this,t=this._getMeshes(),r=new Set(e.keys()),i={attributes:this.attributes,applyWorldTransforms:this.applyWorldTransforms};for(let o=0,a=t.length;o<a;o++){const c=t[o],h=c.uuid;r.delete(h);let d=e.get(h);(!d||!d.isCompatible(c,this.attributes))&&(d&&d.dispose(),d=new ht,e.set(h,d)),d.updateFrom(c,i)&&this.generateMissingAttributes&&nt(d,this.attributes)}r.forEach(o=>{e.delete(o)})}setObjects(e){Array.isArray(e)?this.objects=[...e]:this.objects=[e]}generate(e=new l.BufferGeometry){const{useGroups:t,overwriteIndex:r,_intermediateGeometry:i,_geometryMergeSets:o}=this,a=this._getMeshes(),c=[],h=[],d=o.get(e)||[];this._updateIntermediateGeometries();let m=!1;a.length!==d.length&&(m=!0);for(let n=0,x=a.length;n<x;n++){const p=a[n],v=i.get(p.uuid);h.push(v);const u=d[n];!u||u.uuid!==v.uuid?(c.push(!1),m=!0):u.version!==v.version?c.push(!1):c.push(!0)}pt(h,e,{useGroups:t,forceUpdate:m,skipAssigningAttributes:c,overwriteIndex:r}),m&&e.dispose(),o.set(e,h.map(n=>({version:n.version,uuid:n.uuid})));let f=ae;return m?f=We:c.includes(!1)&&(f=He),{changeType:f,materials:mt(a),geometry:e}}}function vt(s){const e=new Set;for(let t=0,r=s.length;t<r;t++){const i=s[t];for(const o in i){const a=i[o];a&&a.isTexture&&e.add(a)}}return Array.from(e)}function xt(s){const e=[],t=new Set;for(let i=0,o=s.length;i<o;i++)s[i].traverse(a=>{a.visible&&(a.isRectAreaLight||a.isSpotLight||a.isPointLight||a.isDirectionalLight)&&(e.push(a),a.iesMap&&t.add(a.iesMap))});const r=Array.from(t).sort((i,o)=>i.uuid<o.uuid?1:i.uuid>o.uuid?-1:0);return{lights:e,iesTextures:r}}class yt{get initialized(){return!!this.bvh}constructor(e){this.bvhOptions={},this.attributes=["position","normal","tangent","color","uv","uv2"],this.generateBVH=!0,this.bvh=null,this.geometry=new l.BufferGeometry,this.staticGeometryGenerator=new gt(e),this._bvhWorker=null,this._pendingGenerate=null,this._buildAsync=!1}setObjects(e){this.staticGeometryGenerator.setObjects(e)}setBVHWorker(e){this._bvhWorker=e}async generateAsync(e=null){if(!this._bvhWorker)throw new Error('PathTracingSceneGenerator: "setBVHWorker" must be called before "generateAsync" can be called.');if(this.bvh instanceof Promise)return this._pendingGenerate||(this._pendingGenerate=new Promise(async()=>(await this.bvh,this._pendingGenerate=null,this.generateAsync(e)))),this._pendingGenerate;{this._buildAsync=!0;const t=this.generate(e);return this._buildAsync=!1,t.bvh=this.bvh=await t.bvh,t}}generate(e=null){const{staticGeometryGenerator:t,geometry:r,attributes:i}=this,o=t.objects;t.attributes=i,o.forEach(f=>{f.traverse(n=>{n.isSkinnedMesh&&n.skeleton&&n.skeleton.update()})});const a=t.generate(r),c=a.materials,h=vt(c),{lights:d,iesTextures:m}=xt(o);if(a.changeType!==ae&&ot(r,c,c),this.generateBVH){if(this.bvh instanceof Promise)throw new Error("PathTracingSceneGenerator: BVH is already building asynchronously.");if(a.changeType===We){const f={strategy:T.SAH,maxLeafTris:1,indirect:!0,onProgress:e,...this.bvhOptions};this._buildAsync?this.bvh=this._bvhWorker.generate(r,f):this.bvh=new T.MeshBVH(r,f)}else a.changeType===He&&this.bvh.refit()}return{bvhChanged:a.changeType!==ae,bvh:this.bvh,lights:d,iesTextures:m,geometry:r,materials:c,textures:h,objects:o}}}const bt=new l.OrthographicCamera(-1,1,1,-1,0,1);class Tt extends l.BufferGeometry{constructor(){super(),this.setAttribute("position",new l.Float32BufferAttribute([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new l.Float32BufferAttribute([0,2,0,0,2,0],2))}}const wt=new Tt;class z{constructor(e){this._mesh=new l.Mesh(wt,e)}dispose(){this._mesh.geometry.dispose()}render(e){e.render(this._mesh,bt)}get material(){return this._mesh.material}set material(e){this._mesh.material=e}}class oe extends l.ShaderMaterial{set needsUpdate(e){super.needsUpdate=!0,this.dispatchEvent({type:"recompilation"})}constructor(e){super(e);for(const t in this.uniforms)Object.defineProperty(this,t,{get(){return this.uniforms[t].value},set(r){this.uniforms[t].value=r}})}setDefine(e,t=void 0){if(t==null){if(e in this.defines)return delete this.defines[e],this.needsUpdate=!0,!0}else if(this.defines[e]!==t)return this.defines[e]=t,this.needsUpdate=!0,!0;return!1}}class Rt extends oe{constructor(e){super({blending:l.NoBlending,uniforms:{target1:{value:null},target2:{value:null},opacity:{value:1}},vertexShader:`
298
+
299
+ varying vec2 vUv;
300
+
301
+ void main() {
302
+
303
+ vUv = uv;
304
+ gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
305
+
306
+ }`,fragmentShader:`
307
+
308
+ uniform float opacity;
309
+
310
+ uniform sampler2D target1;
311
+ uniform sampler2D target2;
312
+
313
+ varying vec2 vUv;
314
+
315
+ void main() {
316
+
317
+ vec4 color1 = texture2D( target1, vUv );
318
+ vec4 color2 = texture2D( target2, vUv );
319
+
320
+ float invOpacity = 1.0 - opacity;
321
+ float totalAlpha = color1.a * invOpacity + color2.a * opacity;
322
+
323
+ if ( color1.a != 0.0 || color2.a != 0.0 ) {
324
+
325
+ gl_FragColor.rgb = color1.rgb * ( invOpacity * color1.a / totalAlpha ) + color2.rgb * ( opacity * color2.a / totalAlpha );
326
+ gl_FragColor.a = totalAlpha;
327
+
328
+ } else {
329
+
330
+ gl_FragColor = vec4( 0.0 );
331
+
332
+ }
333
+
334
+ }`}),this.setValues(e)}}function V(s=1){let e="uint";return s>1&&(e="uvec"+s),`
335
+ ${e} sobolReverseBits( ${e} x ) {
336
+
337
+ x = ( ( ( x & 0xaaaaaaaau ) >> 1 ) | ( ( x & 0x55555555u ) << 1 ) );
338
+ x = ( ( ( x & 0xccccccccu ) >> 2 ) | ( ( x & 0x33333333u ) << 2 ) );
339
+ x = ( ( ( x & 0xf0f0f0f0u ) >> 4 ) | ( ( x & 0x0f0f0f0fu ) << 4 ) );
340
+ x = ( ( ( x & 0xff00ff00u ) >> 8 ) | ( ( x & 0x00ff00ffu ) << 8 ) );
341
+ return ( ( x >> 16 ) | ( x << 16 ) );
342
+
343
+ }
344
+
345
+ ${e} sobolHashCombine( uint seed, ${e} v ) {
346
+
347
+ return seed ^ ( v + ${e}( ( seed << 6 ) + ( seed >> 2 ) ) );
348
+
349
+ }
350
+
351
+ ${e} sobolLaineKarrasPermutation( ${e} x, ${e} seed ) {
352
+
353
+ x += seed;
354
+ x ^= x * 0x6c50b47cu;
355
+ x ^= x * 0xb82f1e52u;
356
+ x ^= x * 0xc7afe638u;
357
+ x ^= x * 0x8d22f6e6u;
358
+ return x;
359
+
360
+ }
361
+
362
+ ${e} nestedUniformScrambleBase2( ${e} x, ${e} seed ) {
363
+
364
+ x = sobolLaineKarrasPermutation( x, seed );
365
+ x = sobolReverseBits( x );
366
+ return x;
367
+
368
+ }
369
+ `}function q(s=1){let e="uint",t="float",r="",i=".r",o="1u";return s>1&&(e="uvec"+s,t="vec"+s,r=s+"",s===2?(i=".rg",o="uvec2( 1u, 2u )"):s===3?(i=".rgb",o="uvec3( 1u, 2u, 3u )"):(i="",o="uvec4( 1u, 2u, 3u, 4u )")),`
370
+
371
+ ${t} sobol${r}( int effect ) {
372
+
373
+ uint seed = sobolGetSeed( sobolBounceIndex, uint( effect ) );
374
+ uint index = sobolPathIndex;
375
+
376
+ uint shuffle_seed = sobolHashCombine( seed, 0u );
377
+ uint shuffled_index = nestedUniformScrambleBase2( sobolReverseBits( index ), shuffle_seed );
378
+ ${t} sobol_pt = sobolGetTexturePoint( shuffled_index )${i};
379
+ ${e} result = ${e}( sobol_pt * 16777216.0 );
380
+
381
+ ${e} seed2 = sobolHashCombine( seed, ${o} );
382
+ result = nestedUniformScrambleBase2( result, seed2 );
383
+
384
+ return SOBOL_FACTOR * ${t}( result >> 8 );
385
+
386
+ }
387
+ `}const Le=`
388
+
389
+ // Utils
390
+ const float SOBOL_FACTOR = 1.0 / 16777216.0;
391
+ const uint SOBOL_MAX_POINTS = 256u * 256u;
392
+
393
+ ${V(1)}
394
+ ${V(2)}
395
+ ${V(3)}
396
+ ${V(4)}
397
+
398
+ uint sobolHash( uint x ) {
399
+
400
+ // finalizer from murmurhash3
401
+ x ^= x >> 16;
402
+ x *= 0x85ebca6bu;
403
+ x ^= x >> 13;
404
+ x *= 0xc2b2ae35u;
405
+ x ^= x >> 16;
406
+ return x;
407
+
408
+ }
409
+
410
+ `,It=`
411
+
412
+ const uint SOBOL_DIRECTIONS_1[ 32 ] = uint[ 32 ](
413
+ 0x80000000u, 0xc0000000u, 0xa0000000u, 0xf0000000u,
414
+ 0x88000000u, 0xcc000000u, 0xaa000000u, 0xff000000u,
415
+ 0x80800000u, 0xc0c00000u, 0xa0a00000u, 0xf0f00000u,
416
+ 0x88880000u, 0xcccc0000u, 0xaaaa0000u, 0xffff0000u,
417
+ 0x80008000u, 0xc000c000u, 0xa000a000u, 0xf000f000u,
418
+ 0x88008800u, 0xcc00cc00u, 0xaa00aa00u, 0xff00ff00u,
419
+ 0x80808080u, 0xc0c0c0c0u, 0xa0a0a0a0u, 0xf0f0f0f0u,
420
+ 0x88888888u, 0xccccccccu, 0xaaaaaaaau, 0xffffffffu
421
+ );
422
+
423
+ const uint SOBOL_DIRECTIONS_2[ 32 ] = uint[ 32 ](
424
+ 0x80000000u, 0xc0000000u, 0x60000000u, 0x90000000u,
425
+ 0xe8000000u, 0x5c000000u, 0x8e000000u, 0xc5000000u,
426
+ 0x68800000u, 0x9cc00000u, 0xee600000u, 0x55900000u,
427
+ 0x80680000u, 0xc09c0000u, 0x60ee0000u, 0x90550000u,
428
+ 0xe8808000u, 0x5cc0c000u, 0x8e606000u, 0xc5909000u,
429
+ 0x6868e800u, 0x9c9c5c00u, 0xeeee8e00u, 0x5555c500u,
430
+ 0x8000e880u, 0xc0005cc0u, 0x60008e60u, 0x9000c590u,
431
+ 0xe8006868u, 0x5c009c9cu, 0x8e00eeeeu, 0xc5005555u
432
+ );
433
+
434
+ const uint SOBOL_DIRECTIONS_3[ 32 ] = uint[ 32 ](
435
+ 0x80000000u, 0xc0000000u, 0x20000000u, 0x50000000u,
436
+ 0xf8000000u, 0x74000000u, 0xa2000000u, 0x93000000u,
437
+ 0xd8800000u, 0x25400000u, 0x59e00000u, 0xe6d00000u,
438
+ 0x78080000u, 0xb40c0000u, 0x82020000u, 0xc3050000u,
439
+ 0x208f8000u, 0x51474000u, 0xfbea2000u, 0x75d93000u,
440
+ 0xa0858800u, 0x914e5400u, 0xdbe79e00u, 0x25db6d00u,
441
+ 0x58800080u, 0xe54000c0u, 0x79e00020u, 0xb6d00050u,
442
+ 0x800800f8u, 0xc00c0074u, 0x200200a2u, 0x50050093u
443
+ );
444
+
445
+ const uint SOBOL_DIRECTIONS_4[ 32 ] = uint[ 32 ](
446
+ 0x80000000u, 0x40000000u, 0x20000000u, 0xb0000000u,
447
+ 0xf8000000u, 0xdc000000u, 0x7a000000u, 0x9d000000u,
448
+ 0x5a800000u, 0x2fc00000u, 0xa1600000u, 0xf0b00000u,
449
+ 0xda880000u, 0x6fc40000u, 0x81620000u, 0x40bb0000u,
450
+ 0x22878000u, 0xb3c9c000u, 0xfb65a000u, 0xddb2d000u,
451
+ 0x78022800u, 0x9c0b3c00u, 0x5a0fb600u, 0x2d0ddb00u,
452
+ 0xa2878080u, 0xf3c9c040u, 0xdb65a020u, 0x6db2d0b0u,
453
+ 0x800228f8u, 0x400b3cdcu, 0x200fb67au, 0xb00ddb9du
454
+ );
455
+
456
+ uint getMaskedSobol( uint index, uint directions[ 32 ] ) {
457
+
458
+ uint X = 0u;
459
+ for ( int bit = 0; bit < 32; bit ++ ) {
460
+
461
+ uint mask = ( index >> bit ) & 1u;
462
+ X ^= mask * directions[ bit ];
463
+
464
+ }
465
+ return X;
466
+
467
+ }
468
+
469
+ vec4 generateSobolPoint( uint index ) {
470
+
471
+ if ( index >= SOBOL_MAX_POINTS ) {
472
+
473
+ return vec4( 0.0 );
474
+
475
+ }
476
+
477
+ // NOTE: this sobol "direction" is also available but we can't write out 5 components
478
+ // uint x = index & 0x00ffffffu;
479
+ uint x = sobolReverseBits( getMaskedSobol( index, SOBOL_DIRECTIONS_1 ) ) & 0x00ffffffu;
480
+ uint y = sobolReverseBits( getMaskedSobol( index, SOBOL_DIRECTIONS_2 ) ) & 0x00ffffffu;
481
+ uint z = sobolReverseBits( getMaskedSobol( index, SOBOL_DIRECTIONS_3 ) ) & 0x00ffffffu;
482
+ uint w = sobolReverseBits( getMaskedSobol( index, SOBOL_DIRECTIONS_4 ) ) & 0x00ffffffu;
483
+
484
+ return vec4( x, y, z, w ) * SOBOL_FACTOR;
485
+
486
+ }
487
+
488
+ `,St=`
489
+
490
+ // Seeds
491
+ uniform sampler2D sobolTexture;
492
+ uint sobolPixelIndex = 0u;
493
+ uint sobolPathIndex = 0u;
494
+ uint sobolBounceIndex = 0u;
495
+
496
+ uint sobolGetSeed( uint bounce, uint effect ) {
497
+
498
+ return sobolHash(
499
+ sobolHashCombine(
500
+ sobolHashCombine(
501
+ sobolHash( bounce ),
502
+ sobolPixelIndex
503
+ ),
504
+ effect
505
+ )
506
+ );
507
+
508
+ }
509
+
510
+ vec4 sobolGetTexturePoint( uint index ) {
511
+
512
+ if ( index >= SOBOL_MAX_POINTS ) {
513
+
514
+ index = index % SOBOL_MAX_POINTS;
515
+
516
+ }
517
+
518
+ uvec2 dim = uvec2( textureSize( sobolTexture, 0 ).xy );
519
+ uint y = index / dim.x;
520
+ uint x = index - y * dim.x;
521
+ vec2 uv = vec2( x, y ) / vec2( dim );
522
+ return texture( sobolTexture, uv );
523
+
524
+ }
525
+
526
+ ${q(1)}
527
+ ${q(2)}
528
+ ${q(3)}
529
+ ${q(4)}
530
+
531
+ `;class _t extends oe{constructor(){super({blending:l.NoBlending,uniforms:{resolution:{value:new l.Vector2}},vertexShader:`
532
+
533
+ varying vec2 vUv;
534
+ void main() {
535
+
536
+ vUv = uv;
537
+ gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
538
+
539
+ }
540
+ `,fragmentShader:`
541
+
542
+ ${Le}
543
+ ${It}
544
+
545
+ varying vec2 vUv;
546
+ uniform vec2 resolution;
547
+ void main() {
548
+
549
+ uint index = uint( gl_FragCoord.y ) * uint( resolution.x ) + uint( gl_FragCoord.x );
550
+ gl_FragColor = generateSobolPoint( index );
551
+
552
+ }
553
+ `})}}class Ft{generate(e,t=256){const r=new l.WebGLRenderTarget(t,t,{type:l.FloatType,format:l.RGBAFormat,minFilter:l.NearestFilter,magFilter:l.NearestFilter,generateMipmaps:!1}),i=e.getRenderTarget();e.setRenderTarget(r);const o=new z(new _t);return o.material.resolution.set(t,t),o.render(e),e.setRenderTarget(i),o.dispose(),r}}class At extends l.PerspectiveCamera{set bokehSize(e){this.fStop=this.getFocalLength()/e}get bokehSize(){return this.getFocalLength()/this.fStop}constructor(...e){super(...e),this.fStop=1.4,this.apertureBlades=0,this.apertureRotation=0,this.focusDistance=25,this.anamorphicRatio=1}copy(e,t){return super.copy(e,t),this.fStop=e.fStop,this.apertureBlades=e.apertureBlades,this.apertureRotation=e.apertureRotation,this.focusDistance=e.focusDistance,this.anamorphicRatio=e.anamorphicRatio,this}}class Mt{constructor(){this.bokehSize=0,this.apertureBlades=0,this.apertureRotation=0,this.focusDistance=10,this.anamorphicRatio=1}updateFrom(e){e instanceof At?(this.bokehSize=e.bokehSize,this.apertureBlades=e.apertureBlades,this.apertureRotation=e.apertureRotation,this.focusDistance=e.focusDistance,this.anamorphicRatio=e.anamorphicRatio):(this.bokehSize=0,this.apertureRotation=0,this.apertureBlades=0,this.focusDistance=10,this.anamorphicRatio=1)}}function te(s){const e=new Uint16Array(s.length);for(let t=0,r=s.length;t<r;++t)e[t]=l.DataUtils.toHalfFloat(s[t]);return e}function Te(s,e,t=0,r=s.length){let i=t,o=t+r-1;for(;i<o;){const a=i+o>>1;s[a]<e?i=a+1:o=a}return i-t}function Ct(s,e,t){return .2126*s+.7152*e+.0722*t}function Dt(s,e=l.HalfFloatType){const t=s.clone();t.source=new l.Source({...t.image});const{width:r,height:i,data:o}=t.image;let a=o;if(t.type!==e){e===l.HalfFloatType?a=new Uint16Array(o.length):a=new Float32Array(o.length);let c;o instanceof Int8Array||o instanceof Int16Array||o instanceof Int32Array?c=2**(8*o.BYTES_PER_ELEMENT-1)-1:c=2**(8*o.BYTES_PER_ELEMENT)-1;for(let h=0,d=o.length;h<d;h++){let m=o[h];t.type===l.HalfFloatType&&(m=l.DataUtils.fromHalfFloat(o[h])),t.type!==l.FloatType&&t.type!==l.HalfFloatType&&(m/=c),e===l.HalfFloatType&&(a[h]=l.DataUtils.toHalfFloat(m))}t.image.data=a,t.type=e}if(t.flipY){const c=a;a=a.slice();for(let h=0;h<i;h++)for(let d=0;d<r;d++){const m=i-h-1,f=4*(h*r+d),n=4*(m*r+d);a[n+0]=c[f+0],a[n+1]=c[f+1],a[n+2]=c[f+2],a[n+3]=c[f+3]}t.flipY=!1,t.image.data=a}return t}class Pt{constructor(){const e=new l.DataTexture(te(new Float32Array([0,0,0,0])),1,1);e.type=l.HalfFloatType,e.format=l.RGBAFormat,e.minFilter=l.LinearFilter,e.magFilter=l.LinearFilter,e.wrapS=l.RepeatWrapping,e.wrapT=l.RepeatWrapping,e.generateMipmaps=!1,e.needsUpdate=!0;const t=new l.DataTexture(te(new Float32Array([0,1])),1,2);t.type=l.HalfFloatType,t.format=l.RedFormat,t.minFilter=l.LinearFilter,t.magFilter=l.LinearFilter,t.generateMipmaps=!1,t.needsUpdate=!0;const r=new l.DataTexture(te(new Float32Array([0,0,1,1])),2,2);r.type=l.HalfFloatType,r.format=l.RedFormat,r.minFilter=l.LinearFilter,r.magFilter=l.LinearFilter,r.generateMipmaps=!1,r.needsUpdate=!0,this.map=e,this.marginalWeights=t,this.conditionalWeights=r,this.totalSum=0}dispose(){this.marginalWeights.dispose(),this.conditionalWeights.dispose(),this.map.dispose()}updateFrom(e){const t=Dt(e);t.wrapS=l.RepeatWrapping,t.wrapT=l.ClampToEdgeWrapping;const{width:r,height:i,data:o}=t.image,a=new Float32Array(r*i),c=new Float32Array(r*i),h=new Float32Array(i),d=new Float32Array(i);let m=0,f=0;for(let u=0;u<i;u++){let g=0;for(let y=0;y<r;y++){const b=u*r+y,w=l.DataUtils.fromHalfFloat(o[4*b+0]),R=l.DataUtils.fromHalfFloat(o[4*b+1]),_=l.DataUtils.fromHalfFloat(o[4*b+2]),F=Ct(w,R,_);g+=F,m+=F,a[b]=F,c[b]=g}if(g!==0)for(let y=u*r,b=u*r+r;y<b;y++)a[y]/=g,c[y]/=g;f+=g,h[u]=g,d[u]=f}if(f!==0)for(let u=0,g=h.length;u<g;u++)h[u]/=f,d[u]/=f;const n=new Uint16Array(i),x=new Uint16Array(r*i);for(let u=0;u<i;u++){const g=(u+1)/i,y=Te(d,g);n[u]=l.DataUtils.toHalfFloat((y+.5)/i)}for(let u=0;u<i;u++)for(let g=0;g<r;g++){const y=u*r+g,b=(g+1)/r,w=Te(c,b,u*r,r);x[y]=l.DataUtils.toHalfFloat((w+.5)/r)}this.dispose();const{marginalWeights:p,conditionalWeights:v}=this;p.image={width:i,height:1,data:n},p.needsUpdate=!0,v.image={width:r,height:i,data:x},v.needsUpdate=!0,this.totalSum=m,this.map=t}}const re=6,Et=0,kt=1,Ot=2,Bt=3,Nt=4,S=new l.Vector3,I=new l.Vector3,we=new l.Matrix4,E=new l.Quaternion,Re=new l.Vector3,k=new l.Vector3,zt=new l.Vector3(0,1,0);class Ht{constructor(){const e=new l.DataTexture(new Float32Array(4),1,1);e.format=l.RGBAFormat,e.type=l.FloatType,e.wrapS=l.ClampToEdgeWrapping,e.wrapT=l.ClampToEdgeWrapping,e.generateMipmaps=!1,e.minFilter=l.NearestFilter,e.magFilter=l.NearestFilter,this.tex=e,this.count=0}updateFrom(e,t=[]){const r=this.tex,i=Math.max(e.length*re,1),o=Math.ceil(Math.sqrt(i));r.image.width!==o&&(r.dispose(),r.image.data=new Float32Array(o*o*4),r.image.width=o,r.image.height=o);const a=r.image.data;for(let h=0,d=e.length;h<d;h++){const m=e[h],f=h*re*4;let n=0;for(let p=0;p<re*4;p++)a[f+p]=0;m.getWorldPosition(I),a[f+n++]=I.x,a[f+n++]=I.y,a[f+n++]=I.z;let x=Et;if(m.isRectAreaLight&&m.isCircular?x=kt:m.isSpotLight?x=Ot:m.isDirectionalLight?x=Bt:m.isPointLight&&(x=Nt),a[f+n++]=x,a[f+n++]=m.color.r,a[f+n++]=m.color.g,a[f+n++]=m.color.b,a[f+n++]=m.intensity,m.getWorldQuaternion(E),m.isRectAreaLight)S.set(m.width,0,0).applyQuaternion(E),a[f+n++]=S.x,a[f+n++]=S.y,a[f+n++]=S.z,n++,I.set(0,m.height,0).applyQuaternion(E),a[f+n++]=I.x,a[f+n++]=I.y,a[f+n++]=I.z,a[f+n++]=S.cross(I).length()*(m.isCircular?Math.PI/4:1);else if(m.isSpotLight){const p=m.radius||0;Re.setFromMatrixPosition(m.matrixWorld),k.setFromMatrixPosition(m.target.matrixWorld),we.lookAt(Re,k,zt),E.setFromRotationMatrix(we),S.set(1,0,0).applyQuaternion(E),a[f+n++]=S.x,a[f+n++]=S.y,a[f+n++]=S.z,n++,I.set(0,1,0).applyQuaternion(E),a[f+n++]=I.x,a[f+n++]=I.y,a[f+n++]=I.z,a[f+n++]=Math.PI*p*p,a[f+n++]=p,a[f+n++]=m.decay,a[f+n++]=m.distance,a[f+n++]=Math.cos(m.angle),a[f+n++]=Math.cos(m.angle*(1-m.penumbra)),a[f+n++]=m.iesMap?t.indexOf(m.iesMap):-1}else if(m.isPointLight){const p=S.setFromMatrixPosition(m.matrixWorld);a[f+n++]=p.x,a[f+n++]=p.y,a[f+n++]=p.z,n++,n+=4,n+=1,a[f+n++]=m.decay,a[f+n++]=m.distance}else if(m.isDirectionalLight){const p=S.setFromMatrixPosition(m.matrixWorld),v=I.setFromMatrixPosition(m.target.matrixWorld);k.subVectors(p,v).normalize(),a[f+n++]=k.x,a[f+n++]=k.y,a[f+n++]=k.z}}this.count=e.length;const c=se(a.buffer);return this.hash!==c?(this.hash=c,r.needsUpdate=!0,!0):!1}}function Ie(s,e,t,r,i){if(e>r)throw new Error;const o=s.length/e,a=s.constructor.BYTES_PER_ELEMENT*8;let c=1;switch(s.constructor){case Uint8Array:case Uint16Array:case Uint32Array:c=2**a-1;break;case Int8Array:case Int16Array:case Int32Array:c=2**(a-1)-1;break}for(let h=0;h<o;h++){const d=4*h,m=e*h;for(let f=0;f<r;f++)t[i+d+f]=e>=f+1?s[m+f]/c:0}}class Wt extends l.DataArrayTexture{constructor(){super(),this._textures=[],this.type=l.FloatType,this.format=l.RGBAFormat,this.internalFormat="RGBA32F"}updateAttribute(e,t){const r=this._textures[e];r.updateFrom(t);const i=r.image,o=this.image;if(i.width!==o.width||i.height!==o.height)throw new Error("FloatAttributeTextureArray: Attribute must be the same dimensions when updating single layer.");const{width:a,height:c,data:h}=o,m=a*c*4*e;let f=t.itemSize;f===3&&(f=4),Ie(r.image.data,f,h,4,m),this.dispose(),this.needsUpdate=!0}setAttributes(e){const t=e[0].count,r=e.length;for(let f=0,n=r;f<n;f++)if(e[f].count!==t)throw new Error("FloatAttributeTextureArray: All attributes must have the same item count.");const i=this._textures;for(;i.length<r;){const f=new Ne;i.push(f)}for(;i.length>r;)i.pop();for(let f=0,n=r;f<n;f++)i[f].updateFrom(e[f]);const a=i[0].image,c=this.image;(a.width!==c.width||a.height!==c.height||a.depth!==r)&&(c.width=a.width,c.height=a.height,c.depth=r,c.data=new Float32Array(c.width*c.height*c.depth*4));const{data:h,width:d,height:m}=c;for(let f=0,n=r;f<n;f++){const x=i[f],v=d*m*4*f;let u=e[f].itemSize;u===3&&(u=4),Ie(x.image.data,u,h,4,v)}this.dispose(),this.needsUpdate=!0}}class Lt extends Wt{updateNormalAttribute(e){this.updateAttribute(0,e)}updateTangentAttribute(e){this.updateAttribute(1,e)}updateUvAttribute(e){this.updateAttribute(2,e)}updateColorAttribute(e){this.updateAttribute(3,e)}updateFrom(e,t,r,i){this.setAttributes([e,t,r,i])}}function ne(s,e){return s.uuid<e.uuid?1:s.uuid>e.uuid?-1:0}function ie(s){return`${s.source.uuid}:${s.colorSpace}`}function Ut(s){const e=new Set,t=[];for(let r=0,i=s.length;r<i;r++){const o=s[r],a=ie(o);e.has(a)||(e.add(a),t.push(o))}return t}function Gt(s){const e=s.map(r=>r.iesMap||null).filter(r=>r),t=new Set(e);return Array.from(t).sort(ne)}function Vt(s){const e=new Set;for(let r=0,i=s.length;r<i;r++){const o=s[r];for(const a in o){const c=o[a];c&&c.isTexture&&e.add(c)}}const t=Array.from(e);return Ut(t).sort(ne)}function qt(s){const e=[];return s.traverse(t=>{t.visible&&(t.isRectAreaLight||t.isSpotLight||t.isPointLight||t.isDirectionalLight)&&e.push(t)}),e.sort(ne)}const Ue=45,Se=Ue*4;class $t{constructor(){this._features={}}isUsed(e){return e in this._features}setUsed(e,t=!0){t===!1?delete this._features[e]:this._features[e]=!0}reset(){this._features={}}}class jt extends l.DataTexture{constructor(){super(new Float32Array(4),1,1),this.format=l.RGBAFormat,this.type=l.FloatType,this.wrapS=l.ClampToEdgeWrapping,this.wrapT=l.ClampToEdgeWrapping,this.minFilter=l.NearestFilter,this.magFilter=l.NearestFilter,this.generateMipmaps=!1,this.features=new $t}updateFrom(e,t){function r(p,v,u=-1){if(v in p&&p[v]){const g=ie(p[v]);return f[g]}else return u}function i(p,v,u){return v in p?p[v]:u}function o(p,v,u,g){const y=p[v]&&p[v].isTexture?p[v]:null;if(y){y.matrixAutoUpdate&&y.updateMatrix();const b=y.matrix.elements;let w=0;u[g+w++]=b[0],u[g+w++]=b[3],u[g+w++]=b[6],w++,u[g+w++]=b[1],u[g+w++]=b[4],u[g+w++]=b[7],w++}return 8}let a=0;const c=e.length*Ue,h=Math.ceil(Math.sqrt(c))||1,{image:d,features:m}=this,f={};for(let p=0,v=t.length;p<v;p++)f[ie(t[p])]=p;d.width!==h&&(this.dispose(),d.data=new Float32Array(h*h*4),d.width=h,d.height=h);const n=d.data;m.reset();for(let p=0,v=e.length;p<v;p++){const u=e[p];if(u.isFogVolumeMaterial){m.setUsed("FOG");for(let b=0;b<Se;b++)n[a+b]=0;n[a+0+0]=u.color.r,n[a+0+1]=u.color.g,n[a+0+2]=u.color.b,n[a+8+3]=i(u,"emissiveIntensity",0),n[a+12+0]=u.emissive.r,n[a+12+1]=u.emissive.g,n[a+12+2]=u.emissive.b,n[a+52+1]=u.density,n[a+52+3]=0,n[a+56+2]=4,a+=Se;continue}n[a++]=u.color.r,n[a++]=u.color.g,n[a++]=u.color.b,n[a++]=r(u,"map"),n[a++]=i(u,"metalness",0),n[a++]=r(u,"metalnessMap"),n[a++]=i(u,"roughness",0),n[a++]=r(u,"roughnessMap"),n[a++]=i(u,"ior",1.5),n[a++]=i(u,"transmission",0),n[a++]=r(u,"transmissionMap"),n[a++]=i(u,"emissiveIntensity",0),"emissive"in u?(n[a++]=u.emissive.r,n[a++]=u.emissive.g,n[a++]=u.emissive.b):(n[a++]=0,n[a++]=0,n[a++]=0),n[a++]=r(u,"emissiveMap"),n[a++]=r(u,"normalMap"),"normalScale"in u?(n[a++]=u.normalScale.x,n[a++]=u.normalScale.y):(n[a++]=1,n[a++]=1),n[a++]=i(u,"clearcoat",0),n[a++]=r(u,"clearcoatMap"),n[a++]=i(u,"clearcoatRoughness",0),n[a++]=r(u,"clearcoatRoughnessMap"),n[a++]=r(u,"clearcoatNormalMap"),"clearcoatNormalScale"in u?(n[a++]=u.clearcoatNormalScale.x,n[a++]=u.clearcoatNormalScale.y):(n[a++]=1,n[a++]=1),a++,n[a++]=i(u,"sheen",0),"sheenColor"in u?(n[a++]=u.sheenColor.r,n[a++]=u.sheenColor.g,n[a++]=u.sheenColor.b):(n[a++]=0,n[a++]=0,n[a++]=0),n[a++]=r(u,"sheenColorMap"),n[a++]=i(u,"sheenRoughness",0),n[a++]=r(u,"sheenRoughnessMap"),n[a++]=r(u,"iridescenceMap"),n[a++]=r(u,"iridescenceThicknessMap"),n[a++]=i(u,"iridescence",0),n[a++]=i(u,"iridescenceIOR",1.3);const g=i(u,"iridescenceThicknessRange",[100,400]);n[a++]=g[0],n[a++]=g[1],"specularColor"in u?(n[a++]=u.specularColor.r,n[a++]=u.specularColor.g,n[a++]=u.specularColor.b):(n[a++]=1,n[a++]=1,n[a++]=1),n[a++]=r(u,"specularColorMap"),n[a++]=i(u,"specularIntensity",1),n[a++]=r(u,"specularIntensityMap");const y=i(u,"thickness",0)===0&&i(u,"attenuationDistance",1/0)===1/0;if(n[a++]=Number(y),a++,"attenuationColor"in u?(n[a++]=u.attenuationColor.r,n[a++]=u.attenuationColor.g,n[a++]=u.attenuationColor.b):(n[a++]=1,n[a++]=1,n[a++]=1),n[a++]=i(u,"attenuationDistance",1/0),n[a++]=r(u,"alphaMap"),n[a++]=u.opacity,n[a++]=u.alphaTest,!y&&u.transmission>0)n[a++]=0;else switch(u.side){case l.FrontSide:n[a++]=1;break;case l.BackSide:n[a++]=-1;break;case l.DoubleSide:n[a++]=0;break}n[a++]=Number(i(u,"matte",!1)),n[a++]=Number(i(u,"castShadow",!0)),n[a++]=Number(u.vertexColors)|Number(u.flatShading)<<1,n[a++]=Number(u.transparent),a+=o(u,"map",n,a),a+=o(u,"metalnessMap",n,a),a+=o(u,"roughnessMap",n,a),a+=o(u,"transmissionMap",n,a),a+=o(u,"emissiveMap",n,a),a+=o(u,"normalMap",n,a),a+=o(u,"clearcoatMap",n,a),a+=o(u,"clearcoatNormalMap",n,a),a+=o(u,"clearcoatRoughnessMap",n,a),a+=o(u,"sheenColorMap",n,a),a+=o(u,"sheenRoughnessMap",n,a),a+=o(u,"iridescenceMap",n,a),a+=o(u,"iridescenceThicknessMap",n,a),a+=o(u,"specularColorMap",n,a),a+=o(u,"specularIntensityMap",n,a)}const x=se(n.buffer);return this.hash!==x?(this.hash=x,this.needsUpdate=!0,!0):!1}}const _e=new l.Color;function Yt(s){return s?`${s.uuid}:${s.version}`:null}function Xt(s,e){for(const t in e)t in s&&(s[t]=e[t])}class Fe extends l.WebGLArrayRenderTarget{constructor(e,t,r){const i={format:l.RGBAFormat,type:l.UnsignedByteType,minFilter:l.LinearFilter,magFilter:l.LinearFilter,wrapS:l.RepeatWrapping,wrapT:l.RepeatWrapping,generateMipmaps:!1,...r};super(e,t,1,i),Xt(this.texture,i),this.texture.setTextures=(...a)=>{this.setTextures(...a)},this.hashes=[null];const o=new z(new Qt);this.fsQuad=o}setTextures(e,t,r=this.width,i=this.height){const o=e.getRenderTarget(),a=e.toneMapping,c=e.getClearAlpha();e.getClearColor(_e);const h=t.length||1;(r!==this.width||i!==this.height||this.depth!==h)&&(this.setSize(r,i,h),this.hashes=new Array(h).fill(null)),e.setClearColor(0,0),e.toneMapping=l.NoToneMapping;const d=this.fsQuad,m=this.hashes;let f=!1;for(let n=0,x=h;n<x;n++){const p=t[n],v=Yt(p);p&&(m[n]!==v||p.isWebGLRenderTarget)&&(p.matrixAutoUpdate=!1,p.matrix.identity(),d.material.map=p,e.setRenderTarget(this,n),d.render(e),p.updateMatrix(),p.matrixAutoUpdate=!0,m[n]=v,f=!0)}return d.material.map=null,e.setClearColor(_e,c),e.setRenderTarget(o),e.toneMapping=a,f}dispose(){super.dispose(),this.fsQuad.dispose()}}class Qt extends l.ShaderMaterial{get map(){return this.uniforms.map.value}set map(e){this.uniforms.map.value=e}constructor(){super({uniforms:{map:{value:null}},vertexShader:`
554
+ varying vec2 vUv;
555
+ void main() {
556
+
557
+ vUv = uv;
558
+ gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
559
+
560
+ }
561
+ `,fragmentShader:`
562
+ uniform sampler2D map;
563
+ varying vec2 vUv;
564
+ void main() {
565
+
566
+ gl_FragColor = texture2D( map, vUv );
567
+
568
+ }
569
+ `})}}function Kt(s,e=Math.random()){for(let t=s.length-1;t>0;t--){const r=Math.floor(e()*(t+1)),i=s[t];s[t]=s[r],s[r]=i}return s}class Zt{constructor(e,t,r=Math.random){const i=e**t,o=new Uint16Array(i);let a=i;for(let c=0;c<i;c++)o[c]=c;this.samples=new Float32Array(t),this.strataCount=e,this.reset=function(){for(let c=0;c<i;c++)o[c]=c;a=0},this.reshuffle=function(){a=0},this.next=function(){const{samples:c}=this;a>=o.length&&(Kt(o,r),this.reshuffle());let h=o[a++];for(let d=0;d<t;d++)c[d]=(h%e+r())/e,h=Math.floor(h/e);return c}}}class Jt{constructor(e,t,r=Math.random){let i=0;for(const h of t)i+=h;const o=new Float32Array(i),a=[];let c=0;for(const h of t){const d=new Zt(e,h,r);d.samples=new Float32Array(o.buffer,c,d.samples.length),c+=d.samples.length*4,a.push(d)}this.samples=o,this.strataCount=e,this.next=function(){for(const h of a)h.next();return o},this.reshuffle=function(){for(const h of a)h.reshuffle()},this.reset=function(){for(const h of a)h.reset()}}}class er{constructor(e=0){this.m=2147483648,this.a=1103515245,this.c=12345,this.seed=e}nextInt(){return this.seed=(this.a*this.seed+this.c)%this.m,this.seed}nextFloat(){return this.nextInt()/(this.m-1)}}class tr extends l.DataTexture{constructor(e=1,t=1,r=8){super(new Float32Array(1),1,1,l.RGBAFormat,l.FloatType),this.minFilter=l.NearestFilter,this.magFilter=l.NearestFilter,this.strata=r,this.sampler=null,this.generator=new er,this.stableNoise=!1,this.random=()=>this.stableNoise?this.generator.nextFloat():Math.random(),this.init(e,t,r)}init(e=this.image.height,t=this.image.width,r=this.strata){const{image:i}=this;if(i.width===t&&i.height===e&&this.sampler!==null)return;const o=new Array(e*t).fill(4),a=new Jt(r,o,this.random);i.width=t,i.height=e,i.data=a.samples,this.sampler=a,this.dispose(),this.next()}next(){this.sampler.next(),this.needsUpdate=!0}reset(){this.sampler.reset(),this.generator.seed=0}}function rr(s,e=Math.random){for(let t=s.length-1;t>0;t--){const r=~~((e()-1e-6)*t),i=s[t];s[t]=s[r],s[r]=i}}function ar(s,e){s.fill(0);for(let t=0;t<e;t++)s[t]=1}class Ae{constructor(e){this.count=0,this.size=-1,this.sigma=-1,this.radius=-1,this.lookupTable=null,this.score=null,this.binaryPattern=null,this.resize(e),this.setSigma(1.5)}findVoid(){const{score:e,binaryPattern:t}=this;let r=1/0,i=-1;for(let o=0,a=t.length;o<a;o++){if(t[o]!==0)continue;const c=e[o];c<r&&(r=c,i=o)}return i}findCluster(){const{score:e,binaryPattern:t}=this;let r=-1/0,i=-1;for(let o=0,a=t.length;o<a;o++){if(t[o]!==1)continue;const c=e[o];c>r&&(r=c,i=o)}return i}setSigma(e){if(e===this.sigma)return;const t=~~(Math.sqrt(20*e**2)+1),r=2*t+1,i=new Float32Array(r*r),o=e*e;for(let a=-t;a<=t;a++)for(let c=-t;c<=t;c++){const h=(t+c)*r+a+t,d=a*a+c*c;i[h]=Math.E**(-d/(2*o))}this.lookupTable=i,this.sigma=e,this.radius=t}resize(e){this.size!==e&&(this.size=e,this.score=new Float32Array(e*e),this.binaryPattern=new Uint8Array(e*e))}invert(){const{binaryPattern:e,score:t,size:r}=this;t.fill(0);for(let i=0,o=e.length;i<o;i++)if(e[i]===0){const a=~~(i/r),c=i-a*r;this.updateScore(c,a,1),e[i]=1}else e[i]=0}updateScore(e,t,r){const{size:i,score:o,lookupTable:a}=this,c=this.radius,h=2*c+1;for(let d=-c;d<=c;d++)for(let m=-c;m<=c;m++){const f=(c+m)*h+d+c,n=a[f];let x=e+d;x=x<0?i+x:x%i;let p=t+m;p=p<0?i+p:p%i;const v=p*i+x;o[v]+=r*n}}addPointIndex(e){this.binaryPattern[e]=1;const t=this.size,r=~~(e/t),i=e-r*t;this.updateScore(i,r,1),this.count++}removePointIndex(e){this.binaryPattern[e]=0;const t=this.size,r=~~(e/t),i=e-r*t;this.updateScore(i,r,-1),this.count--}copy(e){this.resize(e.size),this.score.set(e.score),this.binaryPattern.set(e.binaryPattern),this.setSigma(e.sigma),this.count=e.count}}class ir{constructor(){this.random=Math.random,this.sigma=1.5,this.size=64,this.majorityPointsRatio=.1,this.samples=new Ae(1),this.savedSamples=new Ae(1)}generate(){const{samples:e,savedSamples:t,sigma:r,majorityPointsRatio:i,size:o}=this;e.resize(o),e.setSigma(r);const a=Math.floor(o*o*i),c=e.binaryPattern;ar(c,a),rr(c,this.random);for(let f=0,n=c.length;f<n;f++)c[f]===1&&e.addPointIndex(f);for(;;){const f=e.findCluster();e.removePointIndex(f);const n=e.findVoid();if(f===n){e.addPointIndex(f);break}e.addPointIndex(n)}const h=new Uint32Array(o*o);t.copy(e);let d;for(d=e.count-1;d>=0;){const f=e.findCluster();e.removePointIndex(f),h[f]=d,d--}const m=o*o;for(d=t.count;d<m/2;){const f=t.findVoid();t.addPointIndex(f),h[f]=d,d++}for(t.invert();d<m;){const f=t.findCluster();t.removePointIndex(f),h[f]=d,d++}return{data:h,maxValue:m}}}function sr(s){return s>=3?4:s}function or(s){switch(s){case 1:return l.RedFormat;case 2:return l.RGFormat;default:return l.RGBAFormat}}class nr extends l.DataTexture{constructor(e=64,t=1){super(new Float32Array(4),1,1,l.RGBAFormat,l.FloatType),this.minFilter=l.NearestFilter,this.magFilter=l.NearestFilter,this.size=e,this.channels=t,this.update()}update(){const e=this.channels,t=this.size,r=new ir;r.channels=e,r.size=t;const i=sr(e),o=or(i);(this.image.width!==t||o!==this.format)&&(this.image.width=t,this.image.height=t,this.image.data=new Float32Array(t**2*i),this.format=o,this.dispose());const a=this.image.data;for(let c=0,h=e;c<h;c++){const d=r.generate(),m=d.data,f=d.maxValue;for(let n=0,x=m.length;n<x;n++){const p=m[n]/f;a[n*i+c]=p}}this.needsUpdate=!0}}const lr=`
570
+
571
+ struct PhysicalCamera {
572
+
573
+ float focusDistance;
574
+ float anamorphicRatio;
575
+ float bokehSize;
576
+ int apertureBlades;
577
+ float apertureRotation;
578
+
579
+ };
580
+
581
+ `,cr=`
582
+
583
+ struct EquirectHdrInfo {
584
+
585
+ sampler2D marginalWeights;
586
+ sampler2D conditionalWeights;
587
+ sampler2D map;
588
+
589
+ float totalSum;
590
+
591
+ };
592
+
593
+ `,ur=`
594
+
595
+ #define RECT_AREA_LIGHT_TYPE 0
596
+ #define CIRC_AREA_LIGHT_TYPE 1
597
+ #define SPOT_LIGHT_TYPE 2
598
+ #define DIR_LIGHT_TYPE 3
599
+ #define POINT_LIGHT_TYPE 4
600
+
601
+ struct LightsInfo {
602
+
603
+ sampler2D tex;
604
+ uint count;
605
+
606
+ };
607
+
608
+ struct Light {
609
+
610
+ vec3 position;
611
+ int type;
612
+
613
+ vec3 color;
614
+ float intensity;
615
+
616
+ vec3 u;
617
+ vec3 v;
618
+ float area;
619
+
620
+ // spot light fields
621
+ float radius;
622
+ float near;
623
+ float decay;
624
+ float distance;
625
+ float coneCos;
626
+ float penumbraCos;
627
+ int iesProfile;
628
+
629
+ };
630
+
631
+ Light readLightInfo( sampler2D tex, uint index ) {
632
+
633
+ uint i = index * 6u;
634
+
635
+ vec4 s0 = texelFetch1D( tex, i + 0u );
636
+ vec4 s1 = texelFetch1D( tex, i + 1u );
637
+ vec4 s2 = texelFetch1D( tex, i + 2u );
638
+ vec4 s3 = texelFetch1D( tex, i + 3u );
639
+
640
+ Light l;
641
+ l.position = s0.rgb;
642
+ l.type = int( round( s0.a ) );
643
+
644
+ l.color = s1.rgb;
645
+ l.intensity = s1.a;
646
+
647
+ l.u = s2.rgb;
648
+ l.v = s3.rgb;
649
+ l.area = s3.a;
650
+
651
+ if ( l.type == SPOT_LIGHT_TYPE || l.type == POINT_LIGHT_TYPE ) {
652
+
653
+ vec4 s4 = texelFetch1D( tex, i + 4u );
654
+ vec4 s5 = texelFetch1D( tex, i + 5u );
655
+ l.radius = s4.r;
656
+ l.decay = s4.g;
657
+ l.distance = s4.b;
658
+ l.coneCos = s4.a;
659
+
660
+ l.penumbraCos = s5.r;
661
+ l.iesProfile = int( round( s5.g ) );
662
+
663
+ } else {
664
+
665
+ l.radius = 0.0;
666
+ l.decay = 0.0;
667
+ l.distance = 0.0;
668
+
669
+ l.coneCos = 0.0;
670
+ l.penumbraCos = 0.0;
671
+ l.iesProfile = - 1;
672
+
673
+ }
674
+
675
+ return l;
676
+
677
+ }
678
+
679
+ `,fr=`
680
+
681
+ struct Material {
682
+
683
+ vec3 color;
684
+ int map;
685
+
686
+ float metalness;
687
+ int metalnessMap;
688
+
689
+ float roughness;
690
+ int roughnessMap;
691
+
692
+ float ior;
693
+ float transmission;
694
+ int transmissionMap;
695
+
696
+ float emissiveIntensity;
697
+ vec3 emissive;
698
+ int emissiveMap;
699
+
700
+ int normalMap;
701
+ vec2 normalScale;
702
+
703
+ float clearcoat;
704
+ int clearcoatMap;
705
+ int clearcoatNormalMap;
706
+ vec2 clearcoatNormalScale;
707
+ float clearcoatRoughness;
708
+ int clearcoatRoughnessMap;
709
+
710
+ int iridescenceMap;
711
+ int iridescenceThicknessMap;
712
+ float iridescence;
713
+ float iridescenceIor;
714
+ float iridescenceThicknessMinimum;
715
+ float iridescenceThicknessMaximum;
716
+
717
+ vec3 specularColor;
718
+ int specularColorMap;
719
+
720
+ float specularIntensity;
721
+ int specularIntensityMap;
722
+ bool thinFilm;
723
+
724
+ vec3 attenuationColor;
725
+ float attenuationDistance;
726
+
727
+ int alphaMap;
728
+
729
+ bool castShadow;
730
+ float opacity;
731
+ float alphaTest;
732
+
733
+ float side;
734
+ bool matte;
735
+
736
+ float sheen;
737
+ vec3 sheenColor;
738
+ int sheenColorMap;
739
+ float sheenRoughness;
740
+ int sheenRoughnessMap;
741
+
742
+ bool vertexColors;
743
+ bool flatShading;
744
+ bool transparent;
745
+ bool fogVolume;
746
+
747
+ mat3 mapTransform;
748
+ mat3 metalnessMapTransform;
749
+ mat3 roughnessMapTransform;
750
+ mat3 transmissionMapTransform;
751
+ mat3 emissiveMapTransform;
752
+ mat3 normalMapTransform;
753
+ mat3 clearcoatMapTransform;
754
+ mat3 clearcoatNormalMapTransform;
755
+ mat3 clearcoatRoughnessMapTransform;
756
+ mat3 sheenColorMapTransform;
757
+ mat3 sheenRoughnessMapTransform;
758
+ mat3 iridescenceMapTransform;
759
+ mat3 iridescenceThicknessMapTransform;
760
+ mat3 specularColorMapTransform;
761
+ mat3 specularIntensityMapTransform;
762
+
763
+ };
764
+
765
+ mat3 readTextureTransform( sampler2D tex, uint index ) {
766
+
767
+ mat3 textureTransform;
768
+
769
+ vec4 row1 = texelFetch1D( tex, index );
770
+ vec4 row2 = texelFetch1D( tex, index + 1u );
771
+
772
+ textureTransform[0] = vec3(row1.r, row2.r, 0.0);
773
+ textureTransform[1] = vec3(row1.g, row2.g, 0.0);
774
+ textureTransform[2] = vec3(row1.b, row2.b, 1.0);
775
+
776
+ return textureTransform;
777
+
778
+ }
779
+
780
+ Material readMaterialInfo( sampler2D tex, uint index ) {
781
+
782
+ uint i = index * 45u;
783
+
784
+ vec4 s0 = texelFetch1D( tex, i + 0u );
785
+ vec4 s1 = texelFetch1D( tex, i + 1u );
786
+ vec4 s2 = texelFetch1D( tex, i + 2u );
787
+ vec4 s3 = texelFetch1D( tex, i + 3u );
788
+ vec4 s4 = texelFetch1D( tex, i + 4u );
789
+ vec4 s5 = texelFetch1D( tex, i + 5u );
790
+ vec4 s6 = texelFetch1D( tex, i + 6u );
791
+ vec4 s7 = texelFetch1D( tex, i + 7u );
792
+ vec4 s8 = texelFetch1D( tex, i + 8u );
793
+ vec4 s9 = texelFetch1D( tex, i + 9u );
794
+ vec4 s10 = texelFetch1D( tex, i + 10u );
795
+ vec4 s11 = texelFetch1D( tex, i + 11u );
796
+ vec4 s12 = texelFetch1D( tex, i + 12u );
797
+ vec4 s13 = texelFetch1D( tex, i + 13u );
798
+ vec4 s14 = texelFetch1D( tex, i + 14u );
799
+
800
+ Material m;
801
+ m.color = s0.rgb;
802
+ m.map = int( round( s0.a ) );
803
+
804
+ m.metalness = s1.r;
805
+ m.metalnessMap = int( round( s1.g ) );
806
+ m.roughness = s1.b;
807
+ m.roughnessMap = int( round( s1.a ) );
808
+
809
+ m.ior = s2.r;
810
+ m.transmission = s2.g;
811
+ m.transmissionMap = int( round( s2.b ) );
812
+ m.emissiveIntensity = s2.a;
813
+
814
+ m.emissive = s3.rgb;
815
+ m.emissiveMap = int( round( s3.a ) );
816
+
817
+ m.normalMap = int( round( s4.r ) );
818
+ m.normalScale = s4.gb;
819
+
820
+ m.clearcoat = s4.a;
821
+ m.clearcoatMap = int( round( s5.r ) );
822
+ m.clearcoatRoughness = s5.g;
823
+ m.clearcoatRoughnessMap = int( round( s5.b ) );
824
+ m.clearcoatNormalMap = int( round( s5.a ) );
825
+ m.clearcoatNormalScale = s6.rg;
826
+
827
+ m.sheen = s6.a;
828
+ m.sheenColor = s7.rgb;
829
+ m.sheenColorMap = int( round( s7.a ) );
830
+ m.sheenRoughness = s8.r;
831
+ m.sheenRoughnessMap = int( round( s8.g ) );
832
+
833
+ m.iridescenceMap = int( round( s8.b ) );
834
+ m.iridescenceThicknessMap = int( round( s8.a ) );
835
+ m.iridescence = s9.r;
836
+ m.iridescenceIor = s9.g;
837
+ m.iridescenceThicknessMinimum = s9.b;
838
+ m.iridescenceThicknessMaximum = s9.a;
839
+
840
+ m.specularColor = s10.rgb;
841
+ m.specularColorMap = int( round( s10.a ) );
842
+
843
+ m.specularIntensity = s11.r;
844
+ m.specularIntensityMap = int( round( s11.g ) );
845
+ m.thinFilm = bool( s11.b );
846
+
847
+ m.attenuationColor = s12.rgb;
848
+ m.attenuationDistance = s12.a;
849
+
850
+ m.alphaMap = int( round( s13.r ) );
851
+
852
+ m.opacity = s13.g;
853
+ m.alphaTest = s13.b;
854
+ m.side = s13.a;
855
+
856
+ m.matte = bool( s14.r );
857
+ m.castShadow = bool( s14.g );
858
+ m.vertexColors = bool( int( s14.b ) & 1 );
859
+ m.flatShading = bool( int( s14.b ) & 2 );
860
+ m.fogVolume = bool( int( s14.b ) & 4 );
861
+ m.transparent = bool( s14.a );
862
+
863
+ uint firstTextureTransformIdx = i + 15u;
864
+
865
+ // mat3( 1.0 ) is an identity matrix
866
+ m.mapTransform = m.map == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx );
867
+ m.metalnessMapTransform = m.metalnessMap == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx + 2u );
868
+ m.roughnessMapTransform = m.roughnessMap == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx + 4u );
869
+ m.transmissionMapTransform = m.transmissionMap == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx + 6u );
870
+ m.emissiveMapTransform = m.emissiveMap == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx + 8u );
871
+ m.normalMapTransform = m.normalMap == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx + 10u );
872
+ m.clearcoatMapTransform = m.clearcoatMap == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx + 12u );
873
+ m.clearcoatNormalMapTransform = m.clearcoatNormalMap == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx + 14u );
874
+ m.clearcoatRoughnessMapTransform = m.clearcoatRoughnessMap == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx + 16u );
875
+ m.sheenColorMapTransform = m.sheenColorMap == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx + 18u );
876
+ m.sheenRoughnessMapTransform = m.sheenRoughnessMap == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx + 20u );
877
+ m.iridescenceMapTransform = m.iridescenceMap == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx + 22u );
878
+ m.iridescenceThicknessMapTransform = m.iridescenceThicknessMap == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx + 24u );
879
+ m.specularColorMapTransform = m.specularColorMap == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx + 26u );
880
+ m.specularIntensityMapTransform = m.specularIntensityMap == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx + 28u );
881
+
882
+ return m;
883
+
884
+ }
885
+
886
+ `,hr=`
887
+
888
+ struct SurfaceRecord {
889
+
890
+ // surface type
891
+ bool volumeParticle;
892
+
893
+ // geometry
894
+ vec3 faceNormal;
895
+ bool frontFace;
896
+ vec3 normal;
897
+ mat3 normalBasis;
898
+ mat3 normalInvBasis;
899
+
900
+ // cached properties
901
+ float eta;
902
+ float f0;
903
+
904
+ // material
905
+ float roughness;
906
+ float filteredRoughness;
907
+ float metalness;
908
+ vec3 color;
909
+ vec3 emission;
910
+
911
+ // transmission
912
+ float ior;
913
+ float transmission;
914
+ bool thinFilm;
915
+ vec3 attenuationColor;
916
+ float attenuationDistance;
917
+
918
+ // clearcoat
919
+ vec3 clearcoatNormal;
920
+ mat3 clearcoatBasis;
921
+ mat3 clearcoatInvBasis;
922
+ float clearcoat;
923
+ float clearcoatRoughness;
924
+ float filteredClearcoatRoughness;
925
+
926
+ // sheen
927
+ float sheen;
928
+ vec3 sheenColor;
929
+ float sheenRoughness;
930
+
931
+ // iridescence
932
+ float iridescence;
933
+ float iridescenceIor;
934
+ float iridescenceThickness;
935
+
936
+ // specular
937
+ vec3 specularColor;
938
+ float specularIntensity;
939
+ };
940
+
941
+ struct ScatterRecord {
942
+ float specularPdf;
943
+ float pdf;
944
+ vec3 direction;
945
+ vec3 color;
946
+ };
947
+
948
+ `,dr=`
949
+
950
+ // samples the the given environment map in the given direction
951
+ vec3 sampleEquirectColor( sampler2D envMap, vec3 direction ) {
952
+
953
+ return texture2D( envMap, equirectDirectionToUv( direction ) ).rgb;
954
+
955
+ }
956
+
957
+ // gets the pdf of the given direction to sample
958
+ float equirectDirectionPdf( vec3 direction ) {
959
+
960
+ vec2 uv = equirectDirectionToUv( direction );
961
+ float theta = uv.y * PI;
962
+ float sinTheta = sin( theta );
963
+ if ( sinTheta == 0.0 ) {
964
+
965
+ return 0.0;
966
+
967
+ }
968
+
969
+ return 1.0 / ( 2.0 * PI * PI * sinTheta );
970
+
971
+ }
972
+
973
+ // samples the color given env map with CDF and returns the pdf of the direction
974
+ float sampleEquirect( vec3 direction, inout vec3 color ) {
975
+
976
+ float totalSum = envMapInfo.totalSum;
977
+ if ( totalSum == 0.0 ) {
978
+
979
+ color = vec3( 0.0 );
980
+ return 1.0;
981
+
982
+ }
983
+
984
+ vec2 uv = equirectDirectionToUv( direction );
985
+ color = texture2D( envMapInfo.map, uv ).rgb;
986
+
987
+ float lum = luminance( color );
988
+ ivec2 resolution = textureSize( envMapInfo.map, 0 );
989
+ float pdf = lum / totalSum;
990
+
991
+ return float( resolution.x * resolution.y ) * pdf * equirectDirectionPdf( direction );
992
+
993
+ }
994
+
995
+ // samples a direction of the envmap with color and retrieves pdf
996
+ float sampleEquirectProbability( vec2 r, inout vec3 color, inout vec3 direction ) {
997
+
998
+ // sample env map cdf
999
+ float v = texture2D( envMapInfo.marginalWeights, vec2( r.x, 0.0 ) ).x;
1000
+ float u = texture2D( envMapInfo.conditionalWeights, vec2( r.y, v ) ).x;
1001
+ vec2 uv = vec2( u, v );
1002
+
1003
+ vec3 derivedDirection = equirectUvToDirection( uv );
1004
+ direction = derivedDirection;
1005
+ color = texture2D( envMapInfo.map, uv ).rgb;
1006
+
1007
+ float totalSum = envMapInfo.totalSum;
1008
+ float lum = luminance( color );
1009
+ ivec2 resolution = textureSize( envMapInfo.map, 0 );
1010
+ float pdf = lum / totalSum;
1011
+
1012
+ return float( resolution.x * resolution.y ) * pdf * equirectDirectionPdf( direction );
1013
+
1014
+ }
1015
+ `,mr=`
1016
+
1017
+ float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {
1018
+
1019
+ return smoothstep( coneCosine, penumbraCosine, angleCosine );
1020
+
1021
+ }
1022
+
1023
+ float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {
1024
+
1025
+ // based upon Frostbite 3 Moving to Physically-based Rendering
1026
+ // page 32, equation 26: E[window1]
1027
+ // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
1028
+ float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), EPSILON );
1029
+
1030
+ if ( cutoffDistance > 0.0 ) {
1031
+
1032
+ distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );
1033
+
1034
+ }
1035
+
1036
+ return distanceFalloff;
1037
+
1038
+ }
1039
+
1040
+ float getPhotometricAttenuation( sampler2DArray iesProfiles, int iesProfile, vec3 posToLight, vec3 lightDir, vec3 u, vec3 v ) {
1041
+
1042
+ float cosTheta = dot( posToLight, lightDir );
1043
+ float angle = acos( cosTheta ) / PI;
1044
+
1045
+ return texture2D( iesProfiles, vec3( angle, 0.0, iesProfile ) ).r;
1046
+
1047
+ }
1048
+
1049
+ struct LightRecord {
1050
+
1051
+ float dist;
1052
+ vec3 direction;
1053
+ float pdf;
1054
+ vec3 emission;
1055
+ int type;
1056
+
1057
+ };
1058
+
1059
+ bool intersectLightAtIndex( sampler2D lights, vec3 rayOrigin, vec3 rayDirection, uint l, inout LightRecord lightRec ) {
1060
+
1061
+ bool didHit = false;
1062
+ Light light = readLightInfo( lights, l );
1063
+
1064
+ vec3 u = light.u;
1065
+ vec3 v = light.v;
1066
+
1067
+ // check for backface
1068
+ vec3 normal = normalize( cross( u, v ) );
1069
+ if ( dot( normal, rayDirection ) > 0.0 ) {
1070
+
1071
+ u *= 1.0 / dot( u, u );
1072
+ v *= 1.0 / dot( v, v );
1073
+
1074
+ float dist;
1075
+
1076
+ // MIS / light intersection is not supported for punctual lights.
1077
+ if(
1078
+ ( light.type == RECT_AREA_LIGHT_TYPE && intersectsRectangle( light.position, normal, u, v, rayOrigin, rayDirection, dist ) ) ||
1079
+ ( light.type == CIRC_AREA_LIGHT_TYPE && intersectsCircle( light.position, normal, u, v, rayOrigin, rayDirection, dist ) )
1080
+ ) {
1081
+
1082
+ float cosTheta = dot( rayDirection, normal );
1083
+ didHit = true;
1084
+ lightRec.dist = dist;
1085
+ lightRec.pdf = ( dist * dist ) / ( light.area * cosTheta );
1086
+ lightRec.emission = light.color * light.intensity;
1087
+ lightRec.direction = rayDirection;
1088
+ lightRec.type = light.type;
1089
+
1090
+ }
1091
+
1092
+ }
1093
+
1094
+ return didHit;
1095
+
1096
+ }
1097
+
1098
+ LightRecord randomAreaLightSample( Light light, vec3 rayOrigin, vec2 ruv ) {
1099
+
1100
+ vec3 randomPos;
1101
+ if( light.type == RECT_AREA_LIGHT_TYPE ) {
1102
+
1103
+ // rectangular area light
1104
+ randomPos = light.position + light.u * ( ruv.x - 0.5 ) + light.v * ( ruv.y - 0.5 );
1105
+
1106
+ } else if( light.type == CIRC_AREA_LIGHT_TYPE ) {
1107
+
1108
+ // circular area light
1109
+ float r = 0.5 * sqrt( ruv.x );
1110
+ float theta = ruv.y * 2.0 * PI;
1111
+ float x = r * cos( theta );
1112
+ float y = r * sin( theta );
1113
+
1114
+ randomPos = light.position + light.u * x + light.v * y;
1115
+
1116
+ }
1117
+
1118
+ vec3 toLight = randomPos - rayOrigin;
1119
+ float lightDistSq = dot( toLight, toLight );
1120
+ float dist = sqrt( lightDistSq );
1121
+ vec3 direction = toLight / dist;
1122
+ vec3 lightNormal = normalize( cross( light.u, light.v ) );
1123
+
1124
+ LightRecord lightRec;
1125
+ lightRec.type = light.type;
1126
+ lightRec.emission = light.color * light.intensity;
1127
+ lightRec.dist = dist;
1128
+ lightRec.direction = direction;
1129
+
1130
+ // TODO: the denominator is potentially zero
1131
+ lightRec.pdf = lightDistSq / ( light.area * dot( direction, lightNormal ) );
1132
+
1133
+ return lightRec;
1134
+
1135
+ }
1136
+
1137
+ LightRecord randomSpotLightSample( Light light, sampler2DArray iesProfiles, vec3 rayOrigin, vec2 ruv ) {
1138
+
1139
+ float radius = light.radius * sqrt( ruv.x );
1140
+ float theta = ruv.y * 2.0 * PI;
1141
+ float x = radius * cos( theta );
1142
+ float y = radius * sin( theta );
1143
+
1144
+ vec3 u = light.u;
1145
+ vec3 v = light.v;
1146
+ vec3 normal = normalize( cross( u, v ) );
1147
+
1148
+ float angle = acos( light.coneCos );
1149
+ float angleTan = tan( angle );
1150
+ float startDistance = light.radius / max( angleTan, EPSILON );
1151
+
1152
+ vec3 randomPos = light.position - normal * startDistance + u * x + v * y;
1153
+ vec3 toLight = randomPos - rayOrigin;
1154
+ float lightDistSq = dot( toLight, toLight );
1155
+ float dist = sqrt( lightDistSq );
1156
+
1157
+ vec3 direction = toLight / max( dist, EPSILON );
1158
+ float cosTheta = dot( direction, normal );
1159
+
1160
+ float spotAttenuation = light.iesProfile != - 1 ?
1161
+ getPhotometricAttenuation( iesProfiles, light.iesProfile, direction, normal, u, v ) :
1162
+ getSpotAttenuation( light.coneCos, light.penumbraCos, cosTheta );
1163
+
1164
+ float distanceAttenuation = getDistanceAttenuation( dist, light.distance, light.decay );
1165
+ LightRecord lightRec;
1166
+ lightRec.type = light.type;
1167
+ lightRec.dist = dist;
1168
+ lightRec.direction = direction;
1169
+ lightRec.emission = light.color * light.intensity * distanceAttenuation * spotAttenuation;
1170
+ lightRec.pdf = 1.0;
1171
+
1172
+ return lightRec;
1173
+
1174
+ }
1175
+
1176
+ LightRecord randomLightSample( sampler2D lights, sampler2DArray iesProfiles, uint lightCount, vec3 rayOrigin, vec3 ruv ) {
1177
+
1178
+ LightRecord result;
1179
+
1180
+ // pick a random light
1181
+ uint l = uint( ruv.x * float( lightCount ) );
1182
+ Light light = readLightInfo( lights, l );
1183
+
1184
+ if ( light.type == SPOT_LIGHT_TYPE ) {
1185
+
1186
+ result = randomSpotLightSample( light, iesProfiles, rayOrigin, ruv.yz );
1187
+
1188
+ } else if ( light.type == POINT_LIGHT_TYPE ) {
1189
+
1190
+ vec3 lightRay = light.u - rayOrigin;
1191
+ float lightDist = length( lightRay );
1192
+ float cutoffDistance = light.distance;
1193
+ float distanceFalloff = 1.0 / max( pow( lightDist, light.decay ), 0.01 );
1194
+ if ( cutoffDistance > 0.0 ) {
1195
+
1196
+ distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDist / cutoffDistance ) ) );
1197
+
1198
+ }
1199
+
1200
+ LightRecord rec;
1201
+ rec.direction = normalize( lightRay );
1202
+ rec.dist = length( lightRay );
1203
+ rec.pdf = 1.0;
1204
+ rec.emission = light.color * light.intensity * distanceFalloff;
1205
+ rec.type = light.type;
1206
+ result = rec;
1207
+
1208
+ } else if ( light.type == DIR_LIGHT_TYPE ) {
1209
+
1210
+ LightRecord rec;
1211
+ rec.dist = 1e10;
1212
+ rec.direction = light.u;
1213
+ rec.pdf = 1.0;
1214
+ rec.emission = light.color * light.intensity;
1215
+ rec.type = light.type;
1216
+
1217
+ result = rec;
1218
+
1219
+ } else {
1220
+
1221
+ // sample the light
1222
+ result = randomAreaLightSample( light, rayOrigin, ruv.yz );
1223
+
1224
+ }
1225
+
1226
+ return result;
1227
+
1228
+ }
1229
+
1230
+ `,pr=`
1231
+
1232
+ vec3 sampleHemisphere( vec3 n, vec2 uv ) {
1233
+
1234
+ // https://www.rorydriscoll.com/2009/01/07/better-sampling/
1235
+ // https://graphics.pixar.com/library/OrthonormalB/paper.pdf
1236
+ float sign = n.z == 0.0 ? 1.0 : sign( n.z );
1237
+ float a = - 1.0 / ( sign + n.z );
1238
+ float b = n.x * n.y * a;
1239
+ vec3 b1 = vec3( 1.0 + sign * n.x * n.x * a, sign * b, - sign * n.x );
1240
+ vec3 b2 = vec3( b, sign + n.y * n.y * a, - n.y );
1241
+
1242
+ float r = sqrt( uv.x );
1243
+ float theta = 2.0 * PI * uv.y;
1244
+ float x = r * cos( theta );
1245
+ float y = r * sin( theta );
1246
+ return x * b1 + y * b2 + sqrt( 1.0 - uv.x ) * n;
1247
+
1248
+ }
1249
+
1250
+ vec2 sampleTriangle( vec2 a, vec2 b, vec2 c, vec2 r ) {
1251
+
1252
+ // get the edges of the triangle and the diagonal across the
1253
+ // center of the parallelogram
1254
+ vec2 e1 = a - b;
1255
+ vec2 e2 = c - b;
1256
+ vec2 diag = normalize( e1 + e2 );
1257
+
1258
+ // pick the point in the parallelogram
1259
+ if ( r.x + r.y > 1.0 ) {
1260
+
1261
+ r = vec2( 1.0 ) - r;
1262
+
1263
+ }
1264
+
1265
+ return e1 * r.x + e2 * r.y;
1266
+
1267
+ }
1268
+
1269
+ vec2 sampleCircle( vec2 uv ) {
1270
+
1271
+ float angle = 2.0 * PI * uv.x;
1272
+ float radius = sqrt( uv.y );
1273
+ return vec2( cos( angle ), sin( angle ) ) * radius;
1274
+
1275
+ }
1276
+
1277
+ vec3 sampleSphere( vec2 uv ) {
1278
+
1279
+ float u = ( uv.x - 0.5 ) * 2.0;
1280
+ float t = uv.y * PI * 2.0;
1281
+ float f = sqrt( 1.0 - u * u );
1282
+
1283
+ return vec3( f * cos( t ), f * sin( t ), u );
1284
+
1285
+ }
1286
+
1287
+ vec2 sampleRegularPolygon( int sides, vec3 uvw ) {
1288
+
1289
+ sides = max( sides, 3 );
1290
+
1291
+ vec3 r = uvw;
1292
+ float anglePerSegment = 2.0 * PI / float( sides );
1293
+ float segment = floor( float( sides ) * r.x );
1294
+
1295
+ float angle1 = anglePerSegment * segment;
1296
+ float angle2 = angle1 + anglePerSegment;
1297
+ vec2 a = vec2( sin( angle1 ), cos( angle1 ) );
1298
+ vec2 b = vec2( 0.0, 0.0 );
1299
+ vec2 c = vec2( sin( angle2 ), cos( angle2 ) );
1300
+
1301
+ return sampleTriangle( a, b, c, r.yz );
1302
+
1303
+ }
1304
+
1305
+ // samples an aperture shape with the given number of sides. 0 means circle
1306
+ vec2 sampleAperture( int blades, vec3 uvw ) {
1307
+
1308
+ return blades == 0 ?
1309
+ sampleCircle( uvw.xy ) :
1310
+ sampleRegularPolygon( blades, uvw );
1311
+
1312
+ }
1313
+
1314
+
1315
+ `,gr=`
1316
+
1317
+ bool totalInternalReflection( float cosTheta, float eta ) {
1318
+
1319
+ float sinTheta = sqrt( 1.0 - cosTheta * cosTheta );
1320
+ return eta * sinTheta > 1.0;
1321
+
1322
+ }
1323
+
1324
+ // https://google.github.io/filament/Filament.md.html#materialsystem/diffusebrdf
1325
+ float schlickFresnel( float cosine, float f0 ) {
1326
+
1327
+ return f0 + ( 1.0 - f0 ) * pow( 1.0 - cosine, 5.0 );
1328
+
1329
+ }
1330
+
1331
+ vec3 schlickFresnel( float cosine, vec3 f0 ) {
1332
+
1333
+ return f0 + ( 1.0 - f0 ) * pow( 1.0 - cosine, 5.0 );
1334
+
1335
+ }
1336
+
1337
+ vec3 schlickFresnel( float cosine, vec3 f0, vec3 f90 ) {
1338
+
1339
+ return f0 + ( f90 - f0 ) * pow( 1.0 - cosine, 5.0 );
1340
+
1341
+ }
1342
+
1343
+ float dielectricFresnel( float cosThetaI, float eta ) {
1344
+
1345
+ // https://schuttejoe.github.io/post/disneybsdf/
1346
+ float ni = eta;
1347
+ float nt = 1.0;
1348
+
1349
+ // Check for total internal reflection
1350
+ float sinThetaISq = 1.0f - cosThetaI * cosThetaI;
1351
+ float sinThetaTSq = eta * eta * sinThetaISq;
1352
+ if( sinThetaTSq >= 1.0 ) {
1353
+
1354
+ return 1.0;
1355
+
1356
+ }
1357
+
1358
+ float sinThetaT = sqrt( sinThetaTSq );
1359
+
1360
+ float cosThetaT = sqrt( max( 0.0, 1.0f - sinThetaT * sinThetaT ) );
1361
+ float rParallel = ( ( nt * cosThetaI ) - ( ni * cosThetaT ) ) / ( ( nt * cosThetaI ) + ( ni * cosThetaT ) );
1362
+ float rPerpendicular = ( ( ni * cosThetaI ) - ( nt * cosThetaT ) ) / ( ( ni * cosThetaI ) + ( nt * cosThetaT ) );
1363
+ return ( rParallel * rParallel + rPerpendicular * rPerpendicular ) / 2.0;
1364
+
1365
+ }
1366
+
1367
+ // https://raytracing.github.io/books/RayTracingInOneWeekend.html#dielectrics/schlickapproximation
1368
+ float iorRatioToF0( float eta ) {
1369
+
1370
+ return pow( ( 1.0 - eta ) / ( 1.0 + eta ), 2.0 );
1371
+
1372
+ }
1373
+
1374
+ vec3 evaluateFresnel( float cosTheta, float eta, vec3 f0, vec3 f90 ) {
1375
+
1376
+ if ( totalInternalReflection( cosTheta, eta ) ) {
1377
+
1378
+ return f90;
1379
+
1380
+ }
1381
+
1382
+ return schlickFresnel( cosTheta, f0, f90 );
1383
+
1384
+ }
1385
+
1386
+ // TODO: disney fresnel was removed and replaced with this fresnel function to better align with
1387
+ // the glTF but is causing blown out pixels. Should be revisited
1388
+ // float evaluateFresnelWeight( float cosTheta, float eta, float f0 ) {
1389
+
1390
+ // if ( totalInternalReflection( cosTheta, eta ) ) {
1391
+
1392
+ // return 1.0;
1393
+
1394
+ // }
1395
+
1396
+ // return schlickFresnel( cosTheta, f0 );
1397
+
1398
+ // }
1399
+
1400
+ // https://schuttejoe.github.io/post/disneybsdf/
1401
+ float disneyFresnel( vec3 wo, vec3 wi, vec3 wh, float f0, float eta, float metalness ) {
1402
+
1403
+ float dotHV = dot( wo, wh );
1404
+ if ( totalInternalReflection( dotHV, eta ) ) {
1405
+
1406
+ return 1.0;
1407
+
1408
+ }
1409
+
1410
+ float dotHL = dot( wi, wh );
1411
+ float dielectricFresnel = dielectricFresnel( abs( dotHV ), eta );
1412
+ float metallicFresnel = schlickFresnel( dotHL, f0 );
1413
+
1414
+ return mix( dielectricFresnel, metallicFresnel, metalness );
1415
+
1416
+ }
1417
+
1418
+ `,vr=`
1419
+
1420
+ // Fast arccos approximation used to remove banding artifacts caused by numerical errors in acos.
1421
+ // This is a cubic Lagrange interpolating polynomial for x = [-1, -1/2, 0, 1/2, 1].
1422
+ // For more information see: https://github.com/gkjohnson/three-gpu-pathtracer/pull/171#issuecomment-1152275248
1423
+ float acosApprox( float x ) {
1424
+
1425
+ x = clamp( x, -1.0, 1.0 );
1426
+ return ( - 0.69813170079773212 * x * x - 0.87266462599716477 ) * x + 1.5707963267948966;
1427
+
1428
+ }
1429
+
1430
+ // An acos with input values bound to the range [-1, 1].
1431
+ float acosSafe( float x ) {
1432
+
1433
+ return acos( clamp( x, -1.0, 1.0 ) );
1434
+
1435
+ }
1436
+
1437
+ float saturateCos( float val ) {
1438
+
1439
+ return clamp( val, 0.001, 1.0 );
1440
+
1441
+ }
1442
+
1443
+ float square( float t ) {
1444
+
1445
+ return t * t;
1446
+
1447
+ }
1448
+
1449
+ vec2 square( vec2 t ) {
1450
+
1451
+ return t * t;
1452
+
1453
+ }
1454
+
1455
+ vec3 square( vec3 t ) {
1456
+
1457
+ return t * t;
1458
+
1459
+ }
1460
+
1461
+ vec4 square( vec4 t ) {
1462
+
1463
+ return t * t;
1464
+
1465
+ }
1466
+
1467
+ vec2 rotateVector( vec2 v, float t ) {
1468
+
1469
+ float ac = cos( t );
1470
+ float as = sin( t );
1471
+ return vec2(
1472
+ v.x * ac - v.y * as,
1473
+ v.x * as + v.y * ac
1474
+ );
1475
+
1476
+ }
1477
+
1478
+ // forms a basis with the normal vector as Z
1479
+ mat3 getBasisFromNormal( vec3 normal ) {
1480
+
1481
+ vec3 other;
1482
+ if ( abs( normal.x ) > 0.5 ) {
1483
+
1484
+ other = vec3( 0.0, 1.0, 0.0 );
1485
+
1486
+ } else {
1487
+
1488
+ other = vec3( 1.0, 0.0, 0.0 );
1489
+
1490
+ }
1491
+
1492
+ vec3 ortho = normalize( cross( normal, other ) );
1493
+ vec3 ortho2 = normalize( cross( normal, ortho ) );
1494
+ return mat3( ortho2, ortho, normal );
1495
+
1496
+ }
1497
+
1498
+ `,xr=`
1499
+
1500
+ // Finds the point where the ray intersects the plane defined by u and v and checks if this point
1501
+ // falls in the bounds of the rectangle on that same plane.
1502
+ // Plane intersection: https://lousodrome.net/blog/light/2020/07/03/intersection-of-a-ray-and-a-plane/
1503
+ bool intersectsRectangle( vec3 center, vec3 normal, vec3 u, vec3 v, vec3 rayOrigin, vec3 rayDirection, inout float dist ) {
1504
+
1505
+ float t = dot( center - rayOrigin, normal ) / dot( rayDirection, normal );
1506
+
1507
+ if ( t > EPSILON ) {
1508
+
1509
+ vec3 p = rayOrigin + rayDirection * t;
1510
+ vec3 vi = p - center;
1511
+
1512
+ // check if p falls inside the rectangle
1513
+ float a1 = dot( u, vi );
1514
+ if ( abs( a1 ) <= 0.5 ) {
1515
+
1516
+ float a2 = dot( v, vi );
1517
+ if ( abs( a2 ) <= 0.5 ) {
1518
+
1519
+ dist = t;
1520
+ return true;
1521
+
1522
+ }
1523
+
1524
+ }
1525
+
1526
+ }
1527
+
1528
+ return false;
1529
+
1530
+ }
1531
+
1532
+ // Finds the point where the ray intersects the plane defined by u and v and checks if this point
1533
+ // falls in the bounds of the circle on that same plane. See above URL for a description of the plane intersection algorithm.
1534
+ bool intersectsCircle( vec3 position, vec3 normal, vec3 u, vec3 v, vec3 rayOrigin, vec3 rayDirection, inout float dist ) {
1535
+
1536
+ float t = dot( position - rayOrigin, normal ) / dot( rayDirection, normal );
1537
+
1538
+ if ( t > EPSILON ) {
1539
+
1540
+ vec3 hit = rayOrigin + rayDirection * t;
1541
+ vec3 vi = hit - position;
1542
+
1543
+ float a1 = dot( u, vi );
1544
+ float a2 = dot( v, vi );
1545
+
1546
+ if( length( vec2( a1, a2 ) ) <= 0.5 ) {
1547
+
1548
+ dist = t;
1549
+ return true;
1550
+
1551
+ }
1552
+
1553
+ }
1554
+
1555
+ return false;
1556
+
1557
+ }
1558
+
1559
+ `,yr=`
1560
+
1561
+ // add texel fetch functions for texture arrays
1562
+ vec4 texelFetch1D( sampler2DArray tex, int layer, uint index ) {
1563
+
1564
+ uint width = uint( textureSize( tex, 0 ).x );
1565
+ uvec2 uv;
1566
+ uv.x = index % width;
1567
+ uv.y = index / width;
1568
+
1569
+ return texelFetch( tex, ivec3( uv, layer ), 0 );
1570
+
1571
+ }
1572
+
1573
+ vec4 textureSampleBarycoord( sampler2DArray tex, int layer, vec3 barycoord, uvec3 faceIndices ) {
1574
+
1575
+ return
1576
+ barycoord.x * texelFetch1D( tex, layer, faceIndices.x ) +
1577
+ barycoord.y * texelFetch1D( tex, layer, faceIndices.y ) +
1578
+ barycoord.z * texelFetch1D( tex, layer, faceIndices.z );
1579
+
1580
+ }
1581
+
1582
+ `,Ge=`
1583
+
1584
+ // TODO: possibly this should be renamed something related to material or path tracing logic
1585
+
1586
+ #ifndef RAY_OFFSET
1587
+ #define RAY_OFFSET 1e-4
1588
+ #endif
1589
+
1590
+ // adjust the hit point by the surface normal by a factor of some offset and the
1591
+ // maximum component-wise value of the current point to accommodate floating point
1592
+ // error as values increase.
1593
+ vec3 stepRayOrigin( vec3 rayOrigin, vec3 rayDirection, vec3 offset, float dist ) {
1594
+
1595
+ vec3 point = rayOrigin + rayDirection * dist;
1596
+ vec3 absPoint = abs( point );
1597
+ float maxPoint = max( absPoint.x, max( absPoint.y, absPoint.z ) );
1598
+ return point + offset * ( maxPoint + 1.0 ) * RAY_OFFSET;
1599
+
1600
+ }
1601
+
1602
+ // https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_materials_volume/README.md#attenuation
1603
+ vec3 transmissionAttenuation( float dist, vec3 attColor, float attDist ) {
1604
+
1605
+ vec3 ot = - log( attColor ) / attDist;
1606
+ return exp( - ot * dist );
1607
+
1608
+ }
1609
+
1610
+ vec3 getHalfVector( vec3 wi, vec3 wo, float eta ) {
1611
+
1612
+ // get the half vector - assuming if the light incident vector is on the other side
1613
+ // of the that it's transmissive.
1614
+ vec3 h;
1615
+ if ( wi.z > 0.0 ) {
1616
+
1617
+ h = normalize( wi + wo );
1618
+
1619
+ } else {
1620
+
1621
+ // Scale by the ior ratio to retrieve the appropriate half vector
1622
+ // From Section 2.2 on computing the transmission half vector:
1623
+ // https://blog.selfshadow.com/publications/s2015-shading-course/burley/s2015_pbs_disney_bsdf_notes.pdf
1624
+ h = normalize( wi + wo * eta );
1625
+
1626
+ }
1627
+
1628
+ h *= sign( h.z );
1629
+ return h;
1630
+
1631
+ }
1632
+
1633
+ vec3 getHalfVector( vec3 a, vec3 b ) {
1634
+
1635
+ return normalize( a + b );
1636
+
1637
+ }
1638
+
1639
+ // The discrepancy between interpolated surface normal and geometry normal can cause issues when a ray
1640
+ // is cast that is on the top side of the geometry normal plane but below the surface normal plane. If
1641
+ // we find a ray like that we ignore it to avoid artifacts.
1642
+ // This function returns if the direction is on the same side of both planes.
1643
+ bool isDirectionValid( vec3 direction, vec3 surfaceNormal, vec3 geometryNormal ) {
1644
+
1645
+ bool aboveSurfaceNormal = dot( direction, surfaceNormal ) > 0.0;
1646
+ bool aboveGeometryNormal = dot( direction, geometryNormal ) > 0.0;
1647
+ return aboveSurfaceNormal == aboveGeometryNormal;
1648
+
1649
+ }
1650
+
1651
+ // ray sampling x and z are swapped to align with expected background view
1652
+ vec2 equirectDirectionToUv( vec3 direction ) {
1653
+
1654
+ // from Spherical.setFromCartesianCoords
1655
+ vec2 uv = vec2( atan( direction.z, direction.x ), acos( direction.y ) );
1656
+ uv /= vec2( 2.0 * PI, PI );
1657
+
1658
+ // apply adjustments to get values in range [0, 1] and y right side up
1659
+ uv.x += 0.5;
1660
+ uv.y = 1.0 - uv.y;
1661
+ return uv;
1662
+
1663
+ }
1664
+
1665
+ vec3 equirectUvToDirection( vec2 uv ) {
1666
+
1667
+ // undo above adjustments
1668
+ uv.x -= 0.5;
1669
+ uv.y = 1.0 - uv.y;
1670
+
1671
+ // from Vector3.setFromSphericalCoords
1672
+ float theta = uv.x * 2.0 * PI;
1673
+ float phi = uv.y * PI;
1674
+
1675
+ float sinPhi = sin( phi );
1676
+
1677
+ return vec3( sinPhi * cos( theta ), cos( phi ), sinPhi * sin( theta ) );
1678
+
1679
+ }
1680
+
1681
+ // power heuristic for multiple importance sampling
1682
+ float misHeuristic( float a, float b ) {
1683
+
1684
+ float aa = a * a;
1685
+ float bb = b * b;
1686
+ return aa / ( aa + bb );
1687
+
1688
+ }
1689
+
1690
+ // tentFilter from Peter Shirley's 'Realistic Ray Tracing (2nd Edition)' book, pg. 60
1691
+ // erichlof/THREE.js-PathTracing-Renderer/
1692
+ float tentFilter( float x ) {
1693
+
1694
+ return x < 0.5 ? sqrt( 2.0 * x ) - 1.0 : 1.0 - sqrt( 2.0 - ( 2.0 * x ) );
1695
+
1696
+ }
1697
+ `,Me=`
1698
+
1699
+ // https://www.shadertoy.com/view/wltcRS
1700
+ uvec4 WHITE_NOISE_SEED;
1701
+
1702
+ void rng_initialize( vec2 p, int frame ) {
1703
+
1704
+ // white noise seed
1705
+ WHITE_NOISE_SEED = uvec4( p, uint( frame ), uint( p.x ) + uint( p.y ) );
1706
+
1707
+ }
1708
+
1709
+ // https://www.pcg-random.org/
1710
+ void pcg4d( inout uvec4 v ) {
1711
+
1712
+ v = v * 1664525u + 1013904223u;
1713
+ v.x += v.y * v.w;
1714
+ v.y += v.z * v.x;
1715
+ v.z += v.x * v.y;
1716
+ v.w += v.y * v.z;
1717
+ v = v ^ ( v >> 16u );
1718
+ v.x += v.y*v.w;
1719
+ v.y += v.z*v.x;
1720
+ v.z += v.x*v.y;
1721
+ v.w += v.y*v.z;
1722
+
1723
+ }
1724
+
1725
+ // returns [ 0, 1 ]
1726
+ float pcgRand() {
1727
+
1728
+ pcg4d( WHITE_NOISE_SEED );
1729
+ return float( WHITE_NOISE_SEED.x ) / float( 0xffffffffu );
1730
+
1731
+ }
1732
+
1733
+ vec2 pcgRand2() {
1734
+
1735
+ pcg4d( WHITE_NOISE_SEED );
1736
+ return vec2( WHITE_NOISE_SEED.xy ) / float(0xffffffffu);
1737
+
1738
+ }
1739
+
1740
+ vec3 pcgRand3() {
1741
+
1742
+ pcg4d( WHITE_NOISE_SEED );
1743
+ return vec3( WHITE_NOISE_SEED.xyz ) / float( 0xffffffffu );
1744
+
1745
+ }
1746
+
1747
+ vec4 pcgRand4() {
1748
+
1749
+ pcg4d( WHITE_NOISE_SEED );
1750
+ return vec4( WHITE_NOISE_SEED ) / float( 0xffffffffu );
1751
+
1752
+ }
1753
+ `,br=`
1754
+
1755
+ uniform sampler2D stratifiedTexture;
1756
+ uniform sampler2D stratifiedOffsetTexture;
1757
+
1758
+ uint sobolPixelIndex = 0u;
1759
+ uint sobolPathIndex = 0u;
1760
+ uint sobolBounceIndex = 0u;
1761
+ vec4 pixelSeed = vec4( 0 );
1762
+
1763
+ vec4 rand4( int v ) {
1764
+
1765
+ ivec2 uv = ivec2( v, sobolBounceIndex );
1766
+ vec4 stratifiedSample = texelFetch( stratifiedTexture, uv, 0 );
1767
+ return fract( stratifiedSample + pixelSeed.r ); // blue noise + stratified samples
1768
+
1769
+ }
1770
+
1771
+ vec3 rand3( int v ) {
1772
+
1773
+ return rand4( v ).xyz;
1774
+
1775
+ }
1776
+
1777
+ vec2 rand2( int v ) {
1778
+
1779
+ return rand4( v ).xy;
1780
+
1781
+ }
1782
+
1783
+ float rand( int v ) {
1784
+
1785
+ return rand4( v ).x;
1786
+
1787
+ }
1788
+
1789
+ void rng_initialize( vec2 screenCoord, int frame ) {
1790
+
1791
+ // tile the small noise texture across the entire screen
1792
+ ivec2 noiseSize = ivec2( textureSize( stratifiedOffsetTexture, 0 ) );
1793
+ ivec2 pixel = ivec2( screenCoord.xy ) % noiseSize;
1794
+ vec2 pixelWidth = 1.0 / vec2( noiseSize );
1795
+ vec2 uv = vec2( pixel ) * pixelWidth + pixelWidth * 0.5;
1796
+
1797
+ // note that using "texelFetch" here seems to break Android for some reason
1798
+ pixelSeed = texture( stratifiedOffsetTexture, uv );
1799
+
1800
+ }
1801
+
1802
+ `,Tr=`
1803
+
1804
+ // diffuse
1805
+ float diffuseEval( vec3 wo, vec3 wi, vec3 wh, SurfaceRecord surf, inout vec3 color ) {
1806
+
1807
+ // https://schuttejoe.github.io/post/disneybsdf/
1808
+ float fl = schlickFresnel( wi.z, 0.0 );
1809
+ float fv = schlickFresnel( wo.z, 0.0 );
1810
+
1811
+ float metalFactor = ( 1.0 - surf.metalness );
1812
+ float transFactor = ( 1.0 - surf.transmission );
1813
+ float rr = 0.5 + 2.0 * surf.roughness * fl * fl;
1814
+ float retro = rr * ( fl + fv + fl * fv * ( rr - 1.0f ) );
1815
+ float lambert = ( 1.0f - 0.5f * fl ) * ( 1.0f - 0.5f * fv );
1816
+
1817
+ // TODO: subsurface approx?
1818
+
1819
+ // float F = evaluateFresnelWeight( dot( wo, wh ), surf.eta, surf.f0 );
1820
+ float F = disneyFresnel( wo, wi, wh, surf.f0, surf.eta, surf.metalness );
1821
+ color = ( 1.0 - F ) * transFactor * metalFactor * wi.z * surf.color * ( retro + lambert ) / PI;
1822
+
1823
+ return wi.z / PI;
1824
+
1825
+ }
1826
+
1827
+ vec3 diffuseDirection( vec3 wo, SurfaceRecord surf ) {
1828
+
1829
+ vec3 lightDirection = sampleSphere( rand2( 11 ) );
1830
+ lightDirection.z += 1.0;
1831
+ lightDirection = normalize( lightDirection );
1832
+
1833
+ return lightDirection;
1834
+
1835
+ }
1836
+
1837
+ // specular
1838
+ float specularEval( vec3 wo, vec3 wi, vec3 wh, SurfaceRecord surf, inout vec3 color ) {
1839
+
1840
+ // if roughness is set to 0 then D === NaN which results in black pixels
1841
+ float metalness = surf.metalness;
1842
+ float roughness = surf.filteredRoughness;
1843
+
1844
+ float eta = surf.eta;
1845
+ float f0 = surf.f0;
1846
+
1847
+ vec3 f0Color = mix( f0 * surf.specularColor * surf.specularIntensity, surf.color, surf.metalness );
1848
+ vec3 f90Color = vec3( mix( surf.specularIntensity, 1.0, surf.metalness ) );
1849
+ vec3 F = evaluateFresnel( dot( wo, wh ), eta, f0Color, f90Color );
1850
+
1851
+ vec3 iridescenceF = evalIridescence( 1.0, surf.iridescenceIor, dot( wi, wh ), surf.iridescenceThickness, f0Color );
1852
+ F = mix( F, iridescenceF, surf.iridescence );
1853
+
1854
+ // PDF
1855
+ // See 14.1.1 Microfacet BxDFs in https://www.pbr-book.org/
1856
+ float incidentTheta = acos( wo.z );
1857
+ float G = ggxShadowMaskG2( wi, wo, roughness );
1858
+ float D = ggxDistribution( wh, roughness );
1859
+ float G1 = ggxShadowMaskG1( incidentTheta, roughness );
1860
+ float ggxPdf = D * G1 * max( 0.0, abs( dot( wo, wh ) ) ) / abs ( wo.z );
1861
+
1862
+ color = wi.z * F * G * D / ( 4.0 * abs( wi.z * wo.z ) );
1863
+ return ggxPdf / ( 4.0 * dot( wo, wh ) );
1864
+
1865
+ }
1866
+
1867
+ vec3 specularDirection( vec3 wo, SurfaceRecord surf ) {
1868
+
1869
+ // sample ggx vndf distribution which gives a new normal
1870
+ float roughness = surf.filteredRoughness;
1871
+ vec3 halfVector = ggxDirection(
1872
+ wo,
1873
+ vec2( roughness ),
1874
+ rand2( 12 )
1875
+ );
1876
+
1877
+ // apply to new ray by reflecting off the new normal
1878
+ return - reflect( wo, halfVector );
1879
+
1880
+ }
1881
+
1882
+
1883
+ // transmission
1884
+ /*
1885
+ float transmissionEval( vec3 wo, vec3 wi, vec3 wh, SurfaceRecord surf, inout vec3 color ) {
1886
+
1887
+ // See section 4.2 in https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf
1888
+
1889
+ float filteredRoughness = surf.filteredRoughness;
1890
+ float eta = surf.eta;
1891
+ bool frontFace = surf.frontFace;
1892
+ bool thinFilm = surf.thinFilm;
1893
+
1894
+ color = surf.transmission * surf.color;
1895
+
1896
+ float denom = pow( eta * dot( wi, wh ) + dot( wo, wh ), 2.0 );
1897
+ return ggxPDF( wo, wh, filteredRoughness ) / denom;
1898
+
1899
+ }
1900
+
1901
+ vec3 transmissionDirection( vec3 wo, SurfaceRecord surf ) {
1902
+
1903
+ float filteredRoughness = surf.filteredRoughness;
1904
+ float eta = surf.eta;
1905
+ bool frontFace = surf.frontFace;
1906
+
1907
+ // sample ggx vndf distribution which gives a new normal
1908
+ vec3 halfVector = ggxDirection(
1909
+ wo,
1910
+ vec2( filteredRoughness ),
1911
+ rand2( 13 )
1912
+ );
1913
+
1914
+ vec3 lightDirection = refract( normalize( - wo ), halfVector, eta );
1915
+ if ( surf.thinFilm ) {
1916
+
1917
+ lightDirection = - refract( normalize( - lightDirection ), - vec3( 0.0, 0.0, 1.0 ), 1.0 / eta );
1918
+
1919
+ }
1920
+
1921
+ return normalize( lightDirection );
1922
+
1923
+ }
1924
+ */
1925
+
1926
+ // TODO: This is just using a basic cosine-weighted specular distribution with an
1927
+ // incorrect PDF value at the moment. Update it to correctly use a GGX distribution
1928
+ float transmissionEval( vec3 wo, vec3 wi, vec3 wh, SurfaceRecord surf, inout vec3 color ) {
1929
+
1930
+ color = surf.transmission * surf.color;
1931
+
1932
+ // PDF
1933
+ // float F = evaluateFresnelWeight( dot( wo, wh ), surf.eta, surf.f0 );
1934
+ // float F = disneyFresnel( wo, wi, wh, surf.f0, surf.eta, surf.metalness );
1935
+ // if ( F >= 1.0 ) {
1936
+
1937
+ // return 0.0;
1938
+
1939
+ // }
1940
+
1941
+ // return 1.0 / ( 1.0 - F );
1942
+
1943
+ // reverted to previous to transmission. The above was causing black pixels
1944
+ float eta = surf.eta;
1945
+ float f0 = surf.f0;
1946
+ float cosTheta = min( wo.z, 1.0 );
1947
+ float sinTheta = sqrt( 1.0 - cosTheta * cosTheta );
1948
+ float reflectance = schlickFresnel( cosTheta, f0 );
1949
+ bool cannotRefract = eta * sinTheta > 1.0;
1950
+ if ( cannotRefract ) {
1951
+
1952
+ return 0.0;
1953
+
1954
+ }
1955
+
1956
+ return 1.0 / ( 1.0 - reflectance );
1957
+
1958
+ }
1959
+
1960
+ vec3 transmissionDirection( vec3 wo, SurfaceRecord surf ) {
1961
+
1962
+ float roughness = surf.filteredRoughness;
1963
+ float eta = surf.eta;
1964
+ vec3 halfVector = normalize( vec3( 0.0, 0.0, 1.0 ) + sampleSphere( rand2( 13 ) ) * roughness );
1965
+ vec3 lightDirection = refract( normalize( - wo ), halfVector, eta );
1966
+
1967
+ if ( surf.thinFilm ) {
1968
+
1969
+ lightDirection = - refract( normalize( - lightDirection ), - vec3( 0.0, 0.0, 1.0 ), 1.0 / eta );
1970
+
1971
+ }
1972
+ return normalize( lightDirection );
1973
+
1974
+ }
1975
+
1976
+ // clearcoat
1977
+ float clearcoatEval( vec3 wo, vec3 wi, vec3 wh, SurfaceRecord surf, inout vec3 color ) {
1978
+
1979
+ float ior = 1.5;
1980
+ float f0 = iorRatioToF0( ior );
1981
+ bool frontFace = surf.frontFace;
1982
+ float roughness = surf.filteredClearcoatRoughness;
1983
+
1984
+ float eta = frontFace ? 1.0 / ior : ior;
1985
+ float G = ggxShadowMaskG2( wi, wo, roughness );
1986
+ float D = ggxDistribution( wh, roughness );
1987
+ float F = schlickFresnel( dot( wi, wh ), f0 );
1988
+
1989
+ float fClearcoat = F * D * G / ( 4.0 * abs( wi.z * wo.z ) );
1990
+ color = color * ( 1.0 - surf.clearcoat * F ) + fClearcoat * surf.clearcoat * wi.z;
1991
+
1992
+ // PDF
1993
+ // See equation (27) in http://jcgt.org/published/0003/02/03/
1994
+ return ggxPDF( wo, wh, roughness ) / ( 4.0 * dot( wi, wh ) );
1995
+
1996
+ }
1997
+
1998
+ vec3 clearcoatDirection( vec3 wo, SurfaceRecord surf ) {
1999
+
2000
+ // sample ggx vndf distribution which gives a new normal
2001
+ float roughness = surf.filteredClearcoatRoughness;
2002
+ vec3 halfVector = ggxDirection(
2003
+ wo,
2004
+ vec2( roughness ),
2005
+ rand2( 14 )
2006
+ );
2007
+
2008
+ // apply to new ray by reflecting off the new normal
2009
+ return - reflect( wo, halfVector );
2010
+
2011
+ }
2012
+
2013
+ // sheen
2014
+ vec3 sheenColor( vec3 wo, vec3 wi, vec3 wh, SurfaceRecord surf ) {
2015
+
2016
+ float cosThetaO = saturateCos( wo.z );
2017
+ float cosThetaI = saturateCos( wi.z );
2018
+ float cosThetaH = wh.z;
2019
+
2020
+ float D = velvetD( cosThetaH, surf.sheenRoughness );
2021
+ float G = velvetG( cosThetaO, cosThetaI, surf.sheenRoughness );
2022
+
2023
+ // See equation (1) in http://www.aconty.com/pdf/s2017_pbs_imageworks_sheen.pdf
2024
+ vec3 color = surf.sheenColor;
2025
+ color *= D * G / ( 4.0 * abs( cosThetaO * cosThetaI ) );
2026
+ color *= wi.z;
2027
+
2028
+ return color;
2029
+
2030
+ }
2031
+
2032
+ // bsdf
2033
+ void getLobeWeights(
2034
+ vec3 wo, vec3 wi, vec3 wh, vec3 clearcoatWo, SurfaceRecord surf,
2035
+ inout float diffuseWeight, inout float specularWeight, inout float transmissionWeight, inout float clearcoatWeight
2036
+ ) {
2037
+
2038
+ float metalness = surf.metalness;
2039
+ float transmission = surf.transmission;
2040
+ // float fEstimate = evaluateFresnelWeight( dot( wo, wh ), surf.eta, surf.f0 );
2041
+ float fEstimate = disneyFresnel( wo, wi, wh, surf.f0, surf.eta, surf.metalness );
2042
+
2043
+ float transSpecularProb = mix( max( 0.25, fEstimate ), 1.0, metalness );
2044
+ float diffSpecularProb = 0.5 + 0.5 * metalness;
2045
+
2046
+ diffuseWeight = ( 1.0 - transmission ) * ( 1.0 - diffSpecularProb );
2047
+ specularWeight = transmission * transSpecularProb + ( 1.0 - transmission ) * diffSpecularProb;
2048
+ transmissionWeight = transmission * ( 1.0 - transSpecularProb );
2049
+ clearcoatWeight = surf.clearcoat * schlickFresnel( clearcoatWo.z, 0.04 );
2050
+
2051
+ float totalWeight = diffuseWeight + specularWeight + transmissionWeight + clearcoatWeight;
2052
+ diffuseWeight /= totalWeight;
2053
+ specularWeight /= totalWeight;
2054
+ transmissionWeight /= totalWeight;
2055
+ clearcoatWeight /= totalWeight;
2056
+ }
2057
+
2058
+ float bsdfEval(
2059
+ vec3 wo, vec3 clearcoatWo, vec3 wi, vec3 clearcoatWi, SurfaceRecord surf,
2060
+ float diffuseWeight, float specularWeight, float transmissionWeight, float clearcoatWeight, inout float specularPdf, inout vec3 color
2061
+ ) {
2062
+
2063
+ float metalness = surf.metalness;
2064
+ float transmission = surf.transmission;
2065
+
2066
+ float spdf = 0.0;
2067
+ float dpdf = 0.0;
2068
+ float tpdf = 0.0;
2069
+ float cpdf = 0.0;
2070
+ color = vec3( 0.0 );
2071
+
2072
+ vec3 halfVector = getHalfVector( wi, wo, surf.eta );
2073
+
2074
+ // diffuse
2075
+ if ( diffuseWeight > 0.0 && wi.z > 0.0 ) {
2076
+
2077
+ dpdf = diffuseEval( wo, wi, halfVector, surf, color );
2078
+ color *= 1.0 - surf.transmission;
2079
+
2080
+ }
2081
+
2082
+ // ggx specular
2083
+ if ( specularWeight > 0.0 && wi.z > 0.0 ) {
2084
+
2085
+ vec3 outColor;
2086
+ spdf = specularEval( wo, wi, getHalfVector( wi, wo ), surf, outColor );
2087
+ color += outColor;
2088
+
2089
+ }
2090
+
2091
+ // transmission
2092
+ if ( transmissionWeight > 0.0 && wi.z < 0.0 ) {
2093
+
2094
+ tpdf = transmissionEval( wo, wi, halfVector, surf, color );
2095
+
2096
+ }
2097
+
2098
+ // sheen
2099
+ color *= mix( 1.0, sheenAlbedoScaling( wo, wi, surf ), surf.sheen );
2100
+ color += sheenColor( wo, wi, halfVector, surf ) * surf.sheen;
2101
+
2102
+ // clearcoat
2103
+ if ( clearcoatWi.z >= 0.0 && clearcoatWeight > 0.0 ) {
2104
+
2105
+ vec3 clearcoatHalfVector = getHalfVector( clearcoatWo, clearcoatWi );
2106
+ cpdf = clearcoatEval( clearcoatWo, clearcoatWi, clearcoatHalfVector, surf, color );
2107
+
2108
+ }
2109
+
2110
+ float pdf =
2111
+ dpdf * diffuseWeight
2112
+ + spdf * specularWeight
2113
+ + tpdf * transmissionWeight
2114
+ + cpdf * clearcoatWeight;
2115
+
2116
+ // retrieve specular rays for the shadows flag
2117
+ specularPdf = spdf * specularWeight + cpdf * clearcoatWeight;
2118
+
2119
+ return pdf;
2120
+
2121
+ }
2122
+
2123
+ float bsdfResult( vec3 worldWo, vec3 worldWi, SurfaceRecord surf, inout vec3 color ) {
2124
+
2125
+ if ( surf.volumeParticle ) {
2126
+
2127
+ color = surf.color / ( 4.0 * PI );
2128
+ return 1.0 / ( 4.0 * PI );
2129
+
2130
+ }
2131
+
2132
+ vec3 wo = normalize( surf.normalInvBasis * worldWo );
2133
+ vec3 wi = normalize( surf.normalInvBasis * worldWi );
2134
+
2135
+ vec3 clearcoatWo = normalize( surf.clearcoatInvBasis * worldWo );
2136
+ vec3 clearcoatWi = normalize( surf.clearcoatInvBasis * worldWi );
2137
+
2138
+ vec3 wh = getHalfVector( wo, wi, surf.eta );
2139
+ float diffuseWeight;
2140
+ float specularWeight;
2141
+ float transmissionWeight;
2142
+ float clearcoatWeight;
2143
+ getLobeWeights( wo, wi, wh, clearcoatWo, surf, diffuseWeight, specularWeight, transmissionWeight, clearcoatWeight );
2144
+
2145
+ float specularPdf;
2146
+ return bsdfEval( wo, clearcoatWo, wi, clearcoatWi, surf, diffuseWeight, specularWeight, transmissionWeight, clearcoatWeight, specularPdf, color );
2147
+
2148
+ }
2149
+
2150
+ ScatterRecord bsdfSample( vec3 worldWo, SurfaceRecord surf ) {
2151
+
2152
+ if ( surf.volumeParticle ) {
2153
+
2154
+ ScatterRecord sampleRec;
2155
+ sampleRec.specularPdf = 0.0;
2156
+ sampleRec.pdf = 1.0 / ( 4.0 * PI );
2157
+ sampleRec.direction = sampleSphere( rand2( 16 ) );
2158
+ sampleRec.color = surf.color / ( 4.0 * PI );
2159
+ return sampleRec;
2160
+
2161
+ }
2162
+
2163
+ vec3 wo = normalize( surf.normalInvBasis * worldWo );
2164
+ vec3 clearcoatWo = normalize( surf.clearcoatInvBasis * worldWo );
2165
+ mat3 normalBasis = surf.normalBasis;
2166
+ mat3 invBasis = surf.normalInvBasis;
2167
+ mat3 clearcoatNormalBasis = surf.clearcoatBasis;
2168
+ mat3 clearcoatInvBasis = surf.clearcoatInvBasis;
2169
+
2170
+ float diffuseWeight;
2171
+ float specularWeight;
2172
+ float transmissionWeight;
2173
+ float clearcoatWeight;
2174
+ // using normal and basically-reflected ray since we don't have proper half vector here
2175
+ getLobeWeights( wo, wo, vec3( 0, 0, 1 ), clearcoatWo, surf, diffuseWeight, specularWeight, transmissionWeight, clearcoatWeight );
2176
+
2177
+ float pdf[4];
2178
+ pdf[0] = diffuseWeight;
2179
+ pdf[1] = specularWeight;
2180
+ pdf[2] = transmissionWeight;
2181
+ pdf[3] = clearcoatWeight;
2182
+
2183
+ float cdf[4];
2184
+ cdf[0] = pdf[0];
2185
+ cdf[1] = pdf[1] + cdf[0];
2186
+ cdf[2] = pdf[2] + cdf[1];
2187
+ cdf[3] = pdf[3] + cdf[2];
2188
+
2189
+ if( cdf[3] != 0.0 ) {
2190
+
2191
+ float invMaxCdf = 1.0 / cdf[3];
2192
+ cdf[0] *= invMaxCdf;
2193
+ cdf[1] *= invMaxCdf;
2194
+ cdf[2] *= invMaxCdf;
2195
+ cdf[3] *= invMaxCdf;
2196
+
2197
+ } else {
2198
+
2199
+ cdf[0] = 1.0;
2200
+ cdf[1] = 0.0;
2201
+ cdf[2] = 0.0;
2202
+ cdf[3] = 0.0;
2203
+
2204
+ }
2205
+
2206
+ vec3 wi;
2207
+ vec3 clearcoatWi;
2208
+
2209
+ float r = rand( 15 );
2210
+ if ( r <= cdf[0] ) { // diffuse
2211
+
2212
+ wi = diffuseDirection( wo, surf );
2213
+ clearcoatWi = normalize( clearcoatInvBasis * normalize( normalBasis * wi ) );
2214
+
2215
+ } else if ( r <= cdf[1] ) { // specular
2216
+
2217
+ wi = specularDirection( wo, surf );
2218
+ clearcoatWi = normalize( clearcoatInvBasis * normalize( normalBasis * wi ) );
2219
+
2220
+ } else if ( r <= cdf[2] ) { // transmission / refraction
2221
+
2222
+ wi = transmissionDirection( wo, surf );
2223
+ clearcoatWi = normalize( clearcoatInvBasis * normalize( normalBasis * wi ) );
2224
+
2225
+ } else if ( r <= cdf[3] ) { // clearcoat
2226
+
2227
+ clearcoatWi = clearcoatDirection( clearcoatWo, surf );
2228
+ wi = normalize( invBasis * normalize( clearcoatNormalBasis * clearcoatWi ) );
2229
+
2230
+ }
2231
+
2232
+ ScatterRecord result;
2233
+ result.pdf = bsdfEval( wo, clearcoatWo, wi, clearcoatWi, surf, diffuseWeight, specularWeight, transmissionWeight, clearcoatWeight, result.specularPdf, result.color );
2234
+ result.direction = normalize( surf.normalBasis * wi );
2235
+
2236
+ return result;
2237
+
2238
+ }
2239
+
2240
+ `,wr=`
2241
+
2242
+ // returns the hit distance given the material density
2243
+ float intersectFogVolume( Material material, float u ) {
2244
+
2245
+ // https://raytracing.github.io/books/RayTracingTheNextWeek.html#volumes/constantdensitymediums
2246
+ return material.opacity == 0.0 ? INFINITY : ( - 1.0 / material.opacity ) * log( u );
2247
+
2248
+ }
2249
+
2250
+ ScatterRecord sampleFogVolume( SurfaceRecord surf, vec2 uv ) {
2251
+
2252
+ ScatterRecord sampleRec;
2253
+ sampleRec.specularPdf = 0.0;
2254
+ sampleRec.pdf = 1.0 / ( 2.0 * PI );
2255
+ sampleRec.direction = sampleSphere( uv );
2256
+ sampleRec.color = surf.color;
2257
+ return sampleRec;
2258
+
2259
+ }
2260
+
2261
+ `,Rr=`
2262
+
2263
+ // The GGX functions provide sampling and distribution information for normals as output so
2264
+ // in order to get probability of scatter direction the half vector must be computed and provided.
2265
+ // [0] https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf
2266
+ // [1] https://hal.archives-ouvertes.fr/hal-01509746/document
2267
+ // [2] http://jcgt.org/published/0007/04/01/
2268
+ // [4] http://jcgt.org/published/0003/02/03/
2269
+
2270
+ // trowbridge-reitz === GGX === GTR
2271
+
2272
+ vec3 ggxDirection( vec3 incidentDir, vec2 roughness, vec2 uv ) {
2273
+
2274
+ // TODO: try GGXVNDF implementation from reference [2], here. Needs to update ggxDistribution
2275
+ // function below, as well
2276
+
2277
+ // Implementation from reference [1]
2278
+ // stretch view
2279
+ vec3 V = normalize( vec3( roughness * incidentDir.xy, incidentDir.z ) );
2280
+
2281
+ // orthonormal basis
2282
+ vec3 T1 = ( V.z < 0.9999 ) ? normalize( cross( V, vec3( 0.0, 0.0, 1.0 ) ) ) : vec3( 1.0, 0.0, 0.0 );
2283
+ vec3 T2 = cross( T1, V );
2284
+
2285
+ // sample point with polar coordinates (r, phi)
2286
+ float a = 1.0 / ( 1.0 + V.z );
2287
+ float r = sqrt( uv.x );
2288
+ float phi = ( uv.y < a ) ? uv.y / a * PI : PI + ( uv.y - a ) / ( 1.0 - a ) * PI;
2289
+ float P1 = r * cos( phi );
2290
+ float P2 = r * sin( phi ) * ( ( uv.y < a ) ? 1.0 : V.z );
2291
+
2292
+ // compute normal
2293
+ vec3 N = P1 * T1 + P2 * T2 + V * sqrt( max( 0.0, 1.0 - P1 * P1 - P2 * P2 ) );
2294
+
2295
+ // unstretch
2296
+ N = normalize( vec3( roughness * N.xy, max( 0.0, N.z ) ) );
2297
+
2298
+ return N;
2299
+
2300
+ }
2301
+
2302
+ // Below are PDF and related functions for use in a Monte Carlo path tracer
2303
+ // as specified in Appendix B of the following paper
2304
+ // See equation (34) from reference [0]
2305
+ float ggxLamda( float theta, float roughness ) {
2306
+
2307
+ float tanTheta = tan( theta );
2308
+ float tanTheta2 = tanTheta * tanTheta;
2309
+ float alpha2 = roughness * roughness;
2310
+
2311
+ float numerator = - 1.0 + sqrt( 1.0 + alpha2 * tanTheta2 );
2312
+ return numerator / 2.0;
2313
+
2314
+ }
2315
+
2316
+ // See equation (34) from reference [0]
2317
+ float ggxShadowMaskG1( float theta, float roughness ) {
2318
+
2319
+ return 1.0 / ( 1.0 + ggxLamda( theta, roughness ) );
2320
+
2321
+ }
2322
+
2323
+ // See equation (125) from reference [4]
2324
+ float ggxShadowMaskG2( vec3 wi, vec3 wo, float roughness ) {
2325
+
2326
+ float incidentTheta = acos( wi.z );
2327
+ float scatterTheta = acos( wo.z );
2328
+ return 1.0 / ( 1.0 + ggxLamda( incidentTheta, roughness ) + ggxLamda( scatterTheta, roughness ) );
2329
+
2330
+ }
2331
+
2332
+ // See equation (33) from reference [0]
2333
+ float ggxDistribution( vec3 halfVector, float roughness ) {
2334
+
2335
+ float a2 = roughness * roughness;
2336
+ a2 = max( EPSILON, a2 );
2337
+ float cosTheta = halfVector.z;
2338
+ float cosTheta4 = pow( cosTheta, 4.0 );
2339
+
2340
+ if ( cosTheta == 0.0 ) return 0.0;
2341
+
2342
+ float theta = acosSafe( halfVector.z );
2343
+ float tanTheta = tan( theta );
2344
+ float tanTheta2 = pow( tanTheta, 2.0 );
2345
+
2346
+ float denom = PI * cosTheta4 * pow( a2 + tanTheta2, 2.0 );
2347
+ return ( a2 / denom );
2348
+
2349
+ }
2350
+
2351
+ // See equation (3) from reference [2]
2352
+ float ggxPDF( vec3 wi, vec3 halfVector, float roughness ) {
2353
+
2354
+ float incidentTheta = acos( wi.z );
2355
+ float D = ggxDistribution( halfVector, roughness );
2356
+ float G1 = ggxShadowMaskG1( incidentTheta, roughness );
2357
+
2358
+ return D * G1 * max( 0.0, dot( wi, halfVector ) ) / wi.z;
2359
+
2360
+ }
2361
+
2362
+ `,Ir=`
2363
+
2364
+ // XYZ to sRGB color space
2365
+ const mat3 XYZ_TO_REC709 = mat3(
2366
+ 3.2404542, -0.9692660, 0.0556434,
2367
+ -1.5371385, 1.8760108, -0.2040259,
2368
+ -0.4985314, 0.0415560, 1.0572252
2369
+ );
2370
+
2371
+ vec3 fresnel0ToIor( vec3 fresnel0 ) {
2372
+
2373
+ vec3 sqrtF0 = sqrt( fresnel0 );
2374
+ return ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );
2375
+
2376
+ }
2377
+
2378
+ // Conversion FO/IOR
2379
+ vec3 iorToFresnel0( vec3 transmittedIor, float incidentIor ) {
2380
+
2381
+ return square( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );
2382
+
2383
+ }
2384
+
2385
+ // ior is a value between 1.0 and 3.0. 1.0 is air interface
2386
+ float iorToFresnel0( float transmittedIor, float incidentIor ) {
2387
+
2388
+ return square( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ) );
2389
+
2390
+ }
2391
+
2392
+ // Fresnel equations for dielectric/dielectric interfaces. See https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
2393
+ vec3 evalSensitivity( float OPD, vec3 shift ) {
2394
+
2395
+ float phase = 2.0 * PI * OPD * 1.0e-9;
2396
+
2397
+ vec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
2398
+ vec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
2399
+ vec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
2400
+
2401
+ vec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - square( phase ) * var );
2402
+ xyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * square( phase ) );
2403
+ xyz /= 1.0685e-7;
2404
+
2405
+ vec3 srgb = XYZ_TO_REC709 * xyz;
2406
+ return srgb;
2407
+
2408
+ }
2409
+
2410
+ // See Section 4. Analytic Spectral Integration, A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence, https://hal.archives-ouvertes.fr/hal-01518344/document
2411
+ vec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {
2412
+
2413
+ vec3 I;
2414
+
2415
+ // Force iridescenceIor -> outsideIOR when thinFilmThickness -> 0.0
2416
+ float iridescenceIor = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
2417
+
2418
+ // Evaluate the cosTheta on the base layer (Snell law)
2419
+ float sinTheta2Sq = square( outsideIOR / iridescenceIor ) * ( 1.0 - square( cosTheta1 ) );
2420
+
2421
+ // Handle TIR:
2422
+ float cosTheta2Sq = 1.0 - sinTheta2Sq;
2423
+ if ( cosTheta2Sq < 0.0 ) {
2424
+
2425
+ return vec3( 1.0 );
2426
+
2427
+ }
2428
+
2429
+ float cosTheta2 = sqrt( cosTheta2Sq );
2430
+
2431
+ // First interface
2432
+ float R0 = iorToFresnel0( iridescenceIor, outsideIOR );
2433
+ float R12 = schlickFresnel( cosTheta1, R0 );
2434
+ float R21 = R12;
2435
+ float T121 = 1.0 - R12;
2436
+ float phi12 = 0.0;
2437
+ if ( iridescenceIor < outsideIOR ) {
2438
+
2439
+ phi12 = PI;
2440
+
2441
+ }
2442
+
2443
+ float phi21 = PI - phi12;
2444
+
2445
+ // Second interface
2446
+ vec3 baseIOR = fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) ); // guard against 1.0
2447
+ vec3 R1 = iorToFresnel0( baseIOR, iridescenceIor );
2448
+ vec3 R23 = schlickFresnel( cosTheta2, R1 );
2449
+ vec3 phi23 = vec3( 0.0 );
2450
+ if ( baseIOR[0] < iridescenceIor ) {
2451
+
2452
+ phi23[ 0 ] = PI;
2453
+
2454
+ }
2455
+
2456
+ if ( baseIOR[1] < iridescenceIor ) {
2457
+
2458
+ phi23[ 1 ] = PI;
2459
+
2460
+ }
2461
+
2462
+ if ( baseIOR[2] < iridescenceIor ) {
2463
+
2464
+ phi23[ 2 ] = PI;
2465
+
2466
+ }
2467
+
2468
+ // Phase shift
2469
+ float OPD = 2.0 * iridescenceIor * thinFilmThickness * cosTheta2;
2470
+ vec3 phi = vec3( phi21 ) + phi23;
2471
+
2472
+ // Compound terms
2473
+ vec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );
2474
+ vec3 r123 = sqrt( R123 );
2475
+ vec3 Rs = square( T121 ) * R23 / ( vec3( 1.0 ) - R123 );
2476
+
2477
+ // Reflectance term for m = 0 (DC term amplitude)
2478
+ vec3 C0 = R12 + Rs;
2479
+ I = C0;
2480
+
2481
+ // Reflectance term for m > 0 (pairs of diracs)
2482
+ vec3 Cm = Rs - T121;
2483
+ for ( int m = 1; m <= 2; ++ m ) {
2484
+
2485
+ Cm *= r123;
2486
+ vec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );
2487
+ I += Cm * Sm;
2488
+
2489
+ }
2490
+
2491
+ // Since out of gamut colors might be produced, negative color values are clamped to 0.
2492
+ return max( I, vec3( 0.0 ) );
2493
+
2494
+ }
2495
+
2496
+ `,Sr=`
2497
+
2498
+ // See equation (2) in http://www.aconty.com/pdf/s2017_pbs_imageworks_sheen.pdf
2499
+ float velvetD( float cosThetaH, float roughness ) {
2500
+
2501
+ float alpha = max( roughness, 0.07 );
2502
+ alpha = alpha * alpha;
2503
+
2504
+ float invAlpha = 1.0 / alpha;
2505
+
2506
+ float sqrCosThetaH = cosThetaH * cosThetaH;
2507
+ float sinThetaH = max( 1.0 - sqrCosThetaH, 0.001 );
2508
+
2509
+ return ( 2.0 + invAlpha ) * pow( sinThetaH, 0.5 * invAlpha ) / ( 2.0 * PI );
2510
+
2511
+ }
2512
+
2513
+ float velvetParamsInterpolate( int i, float oneMinusAlphaSquared ) {
2514
+
2515
+ const float p0[5] = float[5]( 25.3245, 3.32435, 0.16801, -1.27393, -4.85967 );
2516
+ const float p1[5] = float[5]( 21.5473, 3.82987, 0.19823, -1.97760, -4.32054 );
2517
+
2518
+ return mix( p1[i], p0[i], oneMinusAlphaSquared );
2519
+
2520
+ }
2521
+
2522
+ float velvetL( float x, float alpha ) {
2523
+
2524
+ float oneMinusAlpha = 1.0 - alpha;
2525
+ float oneMinusAlphaSquared = oneMinusAlpha * oneMinusAlpha;
2526
+
2527
+ float a = velvetParamsInterpolate( 0, oneMinusAlphaSquared );
2528
+ float b = velvetParamsInterpolate( 1, oneMinusAlphaSquared );
2529
+ float c = velvetParamsInterpolate( 2, oneMinusAlphaSquared );
2530
+ float d = velvetParamsInterpolate( 3, oneMinusAlphaSquared );
2531
+ float e = velvetParamsInterpolate( 4, oneMinusAlphaSquared );
2532
+
2533
+ return a / ( 1.0 + b * pow( abs( x ), c ) ) + d * x + e;
2534
+
2535
+ }
2536
+
2537
+ // See equation (3) in http://www.aconty.com/pdf/s2017_pbs_imageworks_sheen.pdf
2538
+ float velvetLambda( float cosTheta, float alpha ) {
2539
+
2540
+ return abs( cosTheta ) < 0.5 ? exp( velvetL( cosTheta, alpha ) ) : exp( 2.0 * velvetL( 0.5, alpha ) - velvetL( 1.0 - cosTheta, alpha ) );
2541
+
2542
+ }
2543
+
2544
+ // See Section 3, Shadowing Term, in http://www.aconty.com/pdf/s2017_pbs_imageworks_sheen.pdf
2545
+ float velvetG( float cosThetaO, float cosThetaI, float roughness ) {
2546
+
2547
+ float alpha = max( roughness, 0.07 );
2548
+ alpha = alpha * alpha;
2549
+
2550
+ return 1.0 / ( 1.0 + velvetLambda( cosThetaO, alpha ) + velvetLambda( cosThetaI, alpha ) );
2551
+
2552
+ }
2553
+
2554
+ float directionalAlbedoSheen( float cosTheta, float alpha ) {
2555
+
2556
+ cosTheta = saturate( cosTheta );
2557
+
2558
+ float c = 1.0 - cosTheta;
2559
+ float c3 = c * c * c;
2560
+
2561
+ return 0.65584461 * c3 + 1.0 / ( 4.16526551 + exp( -7.97291361 * sqrt( alpha ) + 6.33516894 ) );
2562
+
2563
+ }
2564
+
2565
+ float sheenAlbedoScaling( vec3 wo, vec3 wi, SurfaceRecord surf ) {
2566
+
2567
+ float alpha = max( surf.sheenRoughness, 0.07 );
2568
+ alpha = alpha * alpha;
2569
+
2570
+ float maxSheenColor = max( max( surf.sheenColor.r, surf.sheenColor.g ), surf.sheenColor.b );
2571
+
2572
+ float eWo = directionalAlbedoSheen( saturateCos( wo.z ), alpha );
2573
+ float eWi = directionalAlbedoSheen( saturateCos( wi.z ), alpha );
2574
+
2575
+ return min( 1.0 - maxSheenColor * eWo, 1.0 - maxSheenColor * eWi );
2576
+
2577
+ }
2578
+
2579
+ // See Section 5, Layering, in http://www.aconty.com/pdf/s2017_pbs_imageworks_sheen.pdf
2580
+ float sheenAlbedoScaling( vec3 wo, SurfaceRecord surf ) {
2581
+
2582
+ float alpha = max( surf.sheenRoughness, 0.07 );
2583
+ alpha = alpha * alpha;
2584
+
2585
+ float maxSheenColor = max( max( surf.sheenColor.r, surf.sheenColor.g ), surf.sheenColor.b );
2586
+
2587
+ float eWo = directionalAlbedoSheen( saturateCos( wo.z ), alpha );
2588
+
2589
+ return 1.0 - maxSheenColor * eWo;
2590
+
2591
+ }
2592
+
2593
+ `,_r=`
2594
+
2595
+ #ifndef FOG_CHECK_ITERATIONS
2596
+ #define FOG_CHECK_ITERATIONS 30
2597
+ #endif
2598
+
2599
+ // returns whether the given material is a fog material or not
2600
+ bool isMaterialFogVolume( sampler2D materials, uint materialIndex ) {
2601
+
2602
+ uint i = materialIndex * 45u;
2603
+ vec4 s14 = texelFetch1D( materials, i + 14u );
2604
+ return bool( int( s14.b ) & 4 );
2605
+
2606
+ }
2607
+
2608
+ // returns true if we're within the first fog volume we hit
2609
+ bool bvhIntersectFogVolumeHit(
2610
+ vec3 rayOrigin, vec3 rayDirection,
2611
+ usampler2D materialIndexAttribute, sampler2D materials,
2612
+ inout Material material
2613
+ ) {
2614
+
2615
+ material.fogVolume = false;
2616
+
2617
+ for ( int i = 0; i < FOG_CHECK_ITERATIONS; i ++ ) {
2618
+
2619
+ // find nearest hit
2620
+ uvec4 faceIndices = uvec4( 0u );
2621
+ vec3 faceNormal = vec3( 0.0, 0.0, 1.0 );
2622
+ vec3 barycoord = vec3( 0.0 );
2623
+ float side = 1.0;
2624
+ float dist = 0.0;
2625
+ bool hit = bvhIntersectFirstHit( bvh, rayOrigin, rayDirection, faceIndices, faceNormal, barycoord, side, dist );
2626
+ if ( hit ) {
2627
+
2628
+ // if it's a fog volume return whether we hit the front or back face
2629
+ uint materialIndex = uTexelFetch1D( materialIndexAttribute, faceIndices.x ).r;
2630
+ if ( isMaterialFogVolume( materials, materialIndex ) ) {
2631
+
2632
+ material = readMaterialInfo( materials, materialIndex );
2633
+ return side == - 1.0;
2634
+
2635
+ } else {
2636
+
2637
+ // move the ray forward
2638
+ rayOrigin = stepRayOrigin( rayOrigin, rayDirection, - faceNormal, dist );
2639
+
2640
+ }
2641
+
2642
+ } else {
2643
+
2644
+ return false;
2645
+
2646
+ }
2647
+
2648
+ }
2649
+
2650
+ return false;
2651
+
2652
+ }
2653
+
2654
+ `,Fr=`
2655
+
2656
+ // step through multiple surface hits and accumulate color attenuation based on transmissive surfaces
2657
+ // returns true if a solid surface was hit
2658
+ bool attenuateHit(
2659
+ RenderState state,
2660
+ Ray ray, float rayDist,
2661
+ out vec3 color
2662
+ ) {
2663
+
2664
+ // store the original bounce index so we can reset it after
2665
+ uint originalBounceIndex = sobolBounceIndex;
2666
+
2667
+ int traversals = state.traversals;
2668
+ int transmissiveTraversals = state.transmissiveTraversals;
2669
+ bool isShadowRay = state.isShadowRay;
2670
+ Material fogMaterial = state.fogMaterial;
2671
+
2672
+ vec3 startPoint = ray.origin;
2673
+
2674
+ // hit results
2675
+ SurfaceHit surfaceHit;
2676
+
2677
+ color = vec3( 1.0 );
2678
+
2679
+ bool result = true;
2680
+ for ( int i = 0; i < traversals; i ++ ) {
2681
+
2682
+ sobolBounceIndex ++;
2683
+
2684
+ int hitType = traceScene( ray, fogMaterial, surfaceHit );
2685
+
2686
+ if ( hitType == FOG_HIT ) {
2687
+
2688
+ result = true;
2689
+ break;
2690
+
2691
+ } else if ( hitType == SURFACE_HIT ) {
2692
+
2693
+ float totalDist = distance( startPoint, ray.origin + ray.direction * surfaceHit.dist );
2694
+ if ( totalDist > rayDist ) {
2695
+
2696
+ result = false;
2697
+ break;
2698
+
2699
+ }
2700
+
2701
+ // TODO: attenuate the contribution based on the PDF of the resulting ray including refraction values
2702
+ // Should be able to work using the material BSDF functions which will take into account specularity, etc.
2703
+ // TODO: should we account for emissive surfaces here?
2704
+
2705
+ uint materialIndex = uTexelFetch1D( materialIndexAttribute, surfaceHit.faceIndices.x ).r;
2706
+ Material material = readMaterialInfo( materials, materialIndex );
2707
+
2708
+ // adjust the ray to the new surface
2709
+ bool isEntering = surfaceHit.side == 1.0;
2710
+ ray.origin = stepRayOrigin( ray.origin, ray.direction, - surfaceHit.faceNormal, surfaceHit.dist );
2711
+
2712
+ #if FEATURE_FOG
2713
+
2714
+ if ( material.fogVolume ) {
2715
+
2716
+ fogMaterial = material;
2717
+ fogMaterial.fogVolume = surfaceHit.side == 1.0;
2718
+ i -= sign( transmissiveTraversals );
2719
+ transmissiveTraversals --;
2720
+ continue;
2721
+
2722
+ }
2723
+
2724
+ #endif
2725
+
2726
+ if ( ! material.castShadow && isShadowRay ) {
2727
+
2728
+ continue;
2729
+
2730
+ }
2731
+
2732
+ vec2 uv = textureSampleBarycoord( attributesArray, ATTR_UV, surfaceHit.barycoord, surfaceHit.faceIndices.xyz ).xy;
2733
+ vec4 vertexColor = textureSampleBarycoord( attributesArray, ATTR_COLOR, surfaceHit.barycoord, surfaceHit.faceIndices.xyz );
2734
+
2735
+ // albedo
2736
+ vec4 albedo = vec4( material.color, material.opacity );
2737
+ if ( material.map != - 1 ) {
2738
+
2739
+ vec3 uvPrime = material.mapTransform * vec3( uv, 1 );
2740
+ albedo *= texture2D( textures, vec3( uvPrime.xy, material.map ) );
2741
+
2742
+ }
2743
+
2744
+ if ( material.vertexColors ) {
2745
+
2746
+ albedo *= vertexColor;
2747
+
2748
+ }
2749
+
2750
+ // alphaMap
2751
+ if ( material.alphaMap != - 1 ) {
2752
+
2753
+ albedo.a *= texture2D( textures, vec3( uv, material.alphaMap ) ).x;
2754
+
2755
+ }
2756
+
2757
+ // transmission
2758
+ float transmission = material.transmission;
2759
+ if ( material.transmissionMap != - 1 ) {
2760
+
2761
+ vec3 uvPrime = material.transmissionMapTransform * vec3( uv, 1 );
2762
+ transmission *= texture2D( textures, vec3( uvPrime.xy, material.transmissionMap ) ).r;
2763
+
2764
+ }
2765
+
2766
+ // metalness
2767
+ float metalness = material.metalness;
2768
+ if ( material.metalnessMap != - 1 ) {
2769
+
2770
+ vec3 uvPrime = material.metalnessMapTransform * vec3( uv, 1 );
2771
+ metalness *= texture2D( textures, vec3( uvPrime.xy, material.metalnessMap ) ).b;
2772
+
2773
+ }
2774
+
2775
+ float alphaTest = material.alphaTest;
2776
+ bool useAlphaTest = alphaTest != 0.0;
2777
+ float transmissionFactor = ( 1.0 - metalness ) * transmission;
2778
+ if (
2779
+ transmissionFactor < rand( 9 ) && ! (
2780
+ // material sidedness
2781
+ material.side != 0.0 && surfaceHit.side == material.side
2782
+
2783
+ // alpha test
2784
+ || useAlphaTest && albedo.a < alphaTest
2785
+
2786
+ // opacity
2787
+ || material.transparent && ! useAlphaTest && albedo.a < rand( 10 )
2788
+ )
2789
+ ) {
2790
+
2791
+ result = true;
2792
+ break;
2793
+
2794
+ }
2795
+
2796
+ if ( surfaceHit.side == 1.0 && isEntering ) {
2797
+
2798
+ // only attenuate by surface color on the way in
2799
+ color *= mix( vec3( 1.0 ), albedo.rgb, transmissionFactor );
2800
+
2801
+ } else if ( surfaceHit.side == - 1.0 ) {
2802
+
2803
+ // attenuate by medium once we hit the opposite side of the model
2804
+ color *= transmissionAttenuation( surfaceHit.dist, material.attenuationColor, material.attenuationDistance );
2805
+
2806
+ }
2807
+
2808
+ bool isTransmissiveRay = dot( ray.direction, surfaceHit.faceNormal * surfaceHit.side ) < 0.0;
2809
+ if ( ( isTransmissiveRay || isEntering ) && transmissiveTraversals > 0 ) {
2810
+
2811
+ i -= sign( transmissiveTraversals );
2812
+ transmissiveTraversals --;
2813
+
2814
+ }
2815
+
2816
+ } else {
2817
+
2818
+ result = false;
2819
+ break;
2820
+
2821
+ }
2822
+
2823
+ }
2824
+
2825
+ // reset the bounce index
2826
+ sobolBounceIndex = originalBounceIndex;
2827
+ return result;
2828
+
2829
+ }
2830
+
2831
+ `,Ar=`
2832
+
2833
+ vec3 ndcToRayOrigin( vec2 coord ) {
2834
+
2835
+ vec4 rayOrigin4 = cameraWorldMatrix * invProjectionMatrix * vec4( coord, - 1.0, 1.0 );
2836
+ return rayOrigin4.xyz / rayOrigin4.w;
2837
+ }
2838
+
2839
+ Ray getCameraRay() {
2840
+
2841
+ vec2 ssd = vec2( 1.0 ) / resolution;
2842
+
2843
+ // Jitter the camera ray by finding a uv coordinate at a random sample
2844
+ // around this pixel's UV coordinate for AA
2845
+ vec2 ruv = rand2( 0 );
2846
+ vec2 jitteredUv = vUv + vec2( tentFilter( ruv.x ) * ssd.x, tentFilter( ruv.y ) * ssd.y );
2847
+ Ray ray;
2848
+
2849
+ #if CAMERA_TYPE == 2
2850
+
2851
+ // Equirectangular projection
2852
+ vec4 rayDirection4 = vec4( equirectUvToDirection( jitteredUv ), 0.0 );
2853
+ vec4 rayOrigin4 = vec4( 0.0, 0.0, 0.0, 1.0 );
2854
+
2855
+ rayDirection4 = cameraWorldMatrix * rayDirection4;
2856
+ rayOrigin4 = cameraWorldMatrix * rayOrigin4;
2857
+
2858
+ ray.direction = normalize( rayDirection4.xyz );
2859
+ ray.origin = rayOrigin4.xyz / rayOrigin4.w;
2860
+
2861
+ #else
2862
+
2863
+ // get [- 1, 1] normalized device coordinates
2864
+ vec2 ndc = 2.0 * jitteredUv - vec2( 1.0 );
2865
+ ray.origin = ndcToRayOrigin( ndc );
2866
+
2867
+ #if CAMERA_TYPE == 1
2868
+
2869
+ // Orthographic projection
2870
+ ray.direction = ( cameraWorldMatrix * vec4( 0.0, 0.0, - 1.0, 0.0 ) ).xyz;
2871
+ ray.direction = normalize( ray.direction );
2872
+
2873
+ #else
2874
+
2875
+ // Perspective projection
2876
+ ray.direction = normalize( mat3( cameraWorldMatrix ) * ( invProjectionMatrix * vec4( ndc, 0.0, 1.0 ) ).xyz );
2877
+
2878
+ #endif
2879
+
2880
+ #endif
2881
+
2882
+ #if FEATURE_DOF
2883
+ {
2884
+
2885
+ // depth of field
2886
+ vec3 focalPoint = ray.origin + normalize( ray.direction ) * physicalCamera.focusDistance;
2887
+
2888
+ // get the aperture sample
2889
+ // if blades === 0 then we assume a circle
2890
+ vec3 shapeUVW= rand3( 1 );
2891
+ int blades = physicalCamera.apertureBlades;
2892
+ float anamorphicRatio = physicalCamera.anamorphicRatio;
2893
+ vec2 apertureSample = blades == 0 ? sampleCircle( shapeUVW.xy ) : sampleRegularPolygon( blades, shapeUVW );
2894
+ apertureSample *= physicalCamera.bokehSize * 0.5 * 1e-3;
2895
+
2896
+ // rotate the aperture shape
2897
+ apertureSample =
2898
+ rotateVector( apertureSample, physicalCamera.apertureRotation ) *
2899
+ saturate( vec2( anamorphicRatio, 1.0 / anamorphicRatio ) );
2900
+
2901
+ // create the new ray
2902
+ ray.origin += ( cameraWorldMatrix * vec4( apertureSample, 0.0, 0.0 ) ).xyz;
2903
+ ray.direction = focalPoint - ray.origin;
2904
+
2905
+ }
2906
+ #endif
2907
+
2908
+ ray.direction = normalize( ray.direction );
2909
+
2910
+ return ray;
2911
+
2912
+ }
2913
+
2914
+ `,Mr=`
2915
+
2916
+ vec3 directLightContribution( vec3 worldWo, SurfaceRecord surf, RenderState state, vec3 rayOrigin ) {
2917
+
2918
+ vec3 result = vec3( 0.0 );
2919
+
2920
+ // uniformly pick a light or environment map
2921
+ if( lightsDenom != 0.0 && rand( 5 ) < float( lights.count ) / lightsDenom ) {
2922
+
2923
+ // sample a light or environment
2924
+ LightRecord lightRec = randomLightSample( lights.tex, iesProfiles, lights.count, rayOrigin, rand3( 6 ) );
2925
+
2926
+ bool isSampleBelowSurface = ! surf.volumeParticle && dot( surf.faceNormal, lightRec.direction ) < 0.0;
2927
+ if ( isSampleBelowSurface ) {
2928
+
2929
+ lightRec.pdf = 0.0;
2930
+
2931
+ }
2932
+
2933
+ // check if a ray could even reach the light area
2934
+ Ray lightRay;
2935
+ lightRay.origin = rayOrigin;
2936
+ lightRay.direction = lightRec.direction;
2937
+ vec3 attenuatedColor;
2938
+ if (
2939
+ lightRec.pdf > 0.0 &&
2940
+ isDirectionValid( lightRec.direction, surf.normal, surf.faceNormal ) &&
2941
+ ! attenuateHit( state, lightRay, lightRec.dist, attenuatedColor )
2942
+ ) {
2943
+
2944
+ // get the material pdf
2945
+ vec3 sampleColor;
2946
+ float lightMaterialPdf = bsdfResult( worldWo, lightRec.direction, surf, sampleColor );
2947
+ bool isValidSampleColor = all( greaterThanEqual( sampleColor, vec3( 0.0 ) ) );
2948
+ if ( lightMaterialPdf > 0.0 && isValidSampleColor ) {
2949
+
2950
+ // weight the direct light contribution
2951
+ float lightPdf = lightRec.pdf / lightsDenom;
2952
+ float misWeight = lightRec.type == SPOT_LIGHT_TYPE || lightRec.type == DIR_LIGHT_TYPE || lightRec.type == POINT_LIGHT_TYPE ? 1.0 : misHeuristic( lightPdf, lightMaterialPdf );
2953
+ result = attenuatedColor * lightRec.emission * state.throughputColor * sampleColor * misWeight / lightPdf;
2954
+
2955
+ }
2956
+
2957
+ }
2958
+
2959
+ } else if ( envMapInfo.totalSum != 0.0 && environmentIntensity != 0.0 ) {
2960
+
2961
+ // find a sample in the environment map to include in the contribution
2962
+ vec3 envColor, envDirection;
2963
+ float envPdf = sampleEquirectProbability( rand2( 7 ), envColor, envDirection );
2964
+ envDirection = invEnvRotation3x3 * envDirection;
2965
+
2966
+ // this env sampling is not set up for transmissive sampling and yields overly bright
2967
+ // results so we ignore the sample in this case.
2968
+ // TODO: this should be improved but how? The env samples could traverse a few layers?
2969
+ bool isSampleBelowSurface = ! surf.volumeParticle && dot( surf.faceNormal, envDirection ) < 0.0;
2970
+ if ( isSampleBelowSurface ) {
2971
+
2972
+ envPdf = 0.0;
2973
+
2974
+ }
2975
+
2976
+ // check if a ray could even reach the surface
2977
+ Ray envRay;
2978
+ envRay.origin = rayOrigin;
2979
+ envRay.direction = envDirection;
2980
+ vec3 attenuatedColor;
2981
+ if (
2982
+ envPdf > 0.0 &&
2983
+ isDirectionValid( envDirection, surf.normal, surf.faceNormal ) &&
2984
+ ! attenuateHit( state, envRay, INFINITY, attenuatedColor )
2985
+ ) {
2986
+
2987
+ // get the material pdf
2988
+ vec3 sampleColor;
2989
+ float envMaterialPdf = bsdfResult( worldWo, envDirection, surf, sampleColor );
2990
+ bool isValidSampleColor = all( greaterThanEqual( sampleColor, vec3( 0.0 ) ) );
2991
+ if ( envMaterialPdf > 0.0 && isValidSampleColor ) {
2992
+
2993
+ // weight the direct light contribution
2994
+ envPdf /= lightsDenom;
2995
+ float misWeight = misHeuristic( envPdf, envMaterialPdf );
2996
+ result = attenuatedColor * environmentIntensity * envColor * state.throughputColor * sampleColor * misWeight / envPdf;
2997
+
2998
+ }
2999
+
3000
+ }
3001
+
3002
+ }
3003
+
3004
+ // Function changed to have a single return statement to potentially help with crashes on Mac OS.
3005
+ // See issue #470
3006
+ return result;
3007
+
3008
+ }
3009
+
3010
+ `,Cr=`
3011
+
3012
+ #define SKIP_SURFACE 0
3013
+ #define HIT_SURFACE 1
3014
+ int getSurfaceRecord(
3015
+ Material material, SurfaceHit surfaceHit, sampler2DArray attributesArray,
3016
+ float accumulatedRoughness,
3017
+ inout SurfaceRecord surf
3018
+ ) {
3019
+
3020
+ if ( material.fogVolume ) {
3021
+
3022
+ vec3 normal = vec3( 0, 0, 1 );
3023
+
3024
+ SurfaceRecord fogSurface;
3025
+ fogSurface.volumeParticle = true;
3026
+ fogSurface.color = material.color;
3027
+ fogSurface.emission = material.emissiveIntensity * material.emissive;
3028
+ fogSurface.normal = normal;
3029
+ fogSurface.faceNormal = normal;
3030
+ fogSurface.clearcoatNormal = normal;
3031
+
3032
+ surf = fogSurface;
3033
+ return HIT_SURFACE;
3034
+
3035
+ }
3036
+
3037
+ // uv coord for textures
3038
+ vec2 uv = textureSampleBarycoord( attributesArray, ATTR_UV, surfaceHit.barycoord, surfaceHit.faceIndices.xyz ).xy;
3039
+ vec4 vertexColor = textureSampleBarycoord( attributesArray, ATTR_COLOR, surfaceHit.barycoord, surfaceHit.faceIndices.xyz );
3040
+
3041
+ // albedo
3042
+ vec4 albedo = vec4( material.color, material.opacity );
3043
+ if ( material.map != - 1 ) {
3044
+
3045
+ vec3 uvPrime = material.mapTransform * vec3( uv, 1 );
3046
+ albedo *= texture2D( textures, vec3( uvPrime.xy, material.map ) );
3047
+
3048
+ }
3049
+
3050
+ if ( material.vertexColors ) {
3051
+
3052
+ albedo *= vertexColor;
3053
+
3054
+ }
3055
+
3056
+ // alphaMap
3057
+ if ( material.alphaMap != - 1 ) {
3058
+
3059
+ albedo.a *= texture2D( textures, vec3( uv, material.alphaMap ) ).x;
3060
+
3061
+ }
3062
+
3063
+ // possibly skip this sample if it's transparent, alpha test is enabled, or we hit the wrong material side
3064
+ // and it's single sided.
3065
+ // - alpha test is disabled when it === 0
3066
+ // - the material sidedness test is complicated because we want light to pass through the back side but still
3067
+ // be able to see the front side. This boolean checks if the side we hit is the front side on the first ray
3068
+ // and we're rendering the other then we skip it. Do the opposite on subsequent bounces to get incoming light.
3069
+ float alphaTest = material.alphaTest;
3070
+ bool useAlphaTest = alphaTest != 0.0;
3071
+ if (
3072
+ // material sidedness
3073
+ material.side != 0.0 && surfaceHit.side != material.side
3074
+
3075
+ // alpha test
3076
+ || useAlphaTest && albedo.a < alphaTest
3077
+
3078
+ // opacity
3079
+ || material.transparent && ! useAlphaTest && albedo.a < rand( 3 )
3080
+ ) {
3081
+
3082
+ return SKIP_SURFACE;
3083
+
3084
+ }
3085
+
3086
+ // fetch the interpolated smooth normal
3087
+ vec3 normal = normalize( textureSampleBarycoord(
3088
+ attributesArray,
3089
+ ATTR_NORMAL,
3090
+ surfaceHit.barycoord,
3091
+ surfaceHit.faceIndices.xyz
3092
+ ).xyz );
3093
+
3094
+ // roughness
3095
+ float roughness = material.roughness;
3096
+ if ( material.roughnessMap != - 1 ) {
3097
+
3098
+ vec3 uvPrime = material.roughnessMapTransform * vec3( uv, 1 );
3099
+ roughness *= texture2D( textures, vec3( uvPrime.xy, material.roughnessMap ) ).g;
3100
+
3101
+ }
3102
+
3103
+ // metalness
3104
+ float metalness = material.metalness;
3105
+ if ( material.metalnessMap != - 1 ) {
3106
+
3107
+ vec3 uvPrime = material.metalnessMapTransform * vec3( uv, 1 );
3108
+ metalness *= texture2D( textures, vec3( uvPrime.xy, material.metalnessMap ) ).b;
3109
+
3110
+ }
3111
+
3112
+ // emission
3113
+ vec3 emission = material.emissiveIntensity * material.emissive;
3114
+ if ( material.emissiveMap != - 1 ) {
3115
+
3116
+ vec3 uvPrime = material.emissiveMapTransform * vec3( uv, 1 );
3117
+ emission *= texture2D( textures, vec3( uvPrime.xy, material.emissiveMap ) ).xyz;
3118
+
3119
+ }
3120
+
3121
+ // transmission
3122
+ float transmission = material.transmission;
3123
+ if ( material.transmissionMap != - 1 ) {
3124
+
3125
+ vec3 uvPrime = material.transmissionMapTransform * vec3( uv, 1 );
3126
+ transmission *= texture2D( textures, vec3( uvPrime.xy, material.transmissionMap ) ).r;
3127
+
3128
+ }
3129
+
3130
+ // normal
3131
+ if ( material.flatShading ) {
3132
+
3133
+ // if we're rendering a flat shaded object then use the face normals - the face normal
3134
+ // is provided based on the side the ray hits the mesh so flip it to align with the
3135
+ // interpolated vertex normals.
3136
+ normal = surfaceHit.faceNormal * surfaceHit.side;
3137
+
3138
+ }
3139
+
3140
+ vec3 baseNormal = normal;
3141
+ if ( material.normalMap != - 1 ) {
3142
+
3143
+ vec4 tangentSample = textureSampleBarycoord(
3144
+ attributesArray,
3145
+ ATTR_TANGENT,
3146
+ surfaceHit.barycoord,
3147
+ surfaceHit.faceIndices.xyz
3148
+ );
3149
+
3150
+ // some provided tangents can be malformed (0, 0, 0) causing the normal to be degenerate
3151
+ // resulting in NaNs and slow path tracing.
3152
+ if ( length( tangentSample.xyz ) > 0.0 ) {
3153
+
3154
+ vec3 tangent = normalize( tangentSample.xyz );
3155
+ vec3 bitangent = normalize( cross( normal, tangent ) * tangentSample.w );
3156
+ mat3 vTBN = mat3( tangent, bitangent, normal );
3157
+
3158
+ vec3 uvPrime = material.normalMapTransform * vec3( uv, 1 );
3159
+ vec3 texNormal = texture2D( textures, vec3( uvPrime.xy, material.normalMap ) ).xyz * 2.0 - 1.0;
3160
+ texNormal.xy *= material.normalScale;
3161
+ normal = vTBN * texNormal;
3162
+
3163
+ }
3164
+
3165
+ }
3166
+
3167
+ normal *= surfaceHit.side;
3168
+
3169
+ // clearcoat
3170
+ float clearcoat = material.clearcoat;
3171
+ if ( material.clearcoatMap != - 1 ) {
3172
+
3173
+ vec3 uvPrime = material.clearcoatMapTransform * vec3( uv, 1 );
3174
+ clearcoat *= texture2D( textures, vec3( uvPrime.xy, material.clearcoatMap ) ).r;
3175
+
3176
+ }
3177
+
3178
+ // clearcoatRoughness
3179
+ float clearcoatRoughness = material.clearcoatRoughness;
3180
+ if ( material.clearcoatRoughnessMap != - 1 ) {
3181
+
3182
+ vec3 uvPrime = material.clearcoatRoughnessMapTransform * vec3( uv, 1 );
3183
+ clearcoatRoughness *= texture2D( textures, vec3( uvPrime.xy, material.clearcoatRoughnessMap ) ).g;
3184
+
3185
+ }
3186
+
3187
+ // clearcoatNormal
3188
+ vec3 clearcoatNormal = baseNormal;
3189
+ if ( material.clearcoatNormalMap != - 1 ) {
3190
+
3191
+ vec4 tangentSample = textureSampleBarycoord(
3192
+ attributesArray,
3193
+ ATTR_TANGENT,
3194
+ surfaceHit.barycoord,
3195
+ surfaceHit.faceIndices.xyz
3196
+ );
3197
+
3198
+ // some provided tangents can be malformed (0, 0, 0) causing the normal to be degenerate
3199
+ // resulting in NaNs and slow path tracing.
3200
+ if ( length( tangentSample.xyz ) > 0.0 ) {
3201
+
3202
+ vec3 tangent = normalize( tangentSample.xyz );
3203
+ vec3 bitangent = normalize( cross( clearcoatNormal, tangent ) * tangentSample.w );
3204
+ mat3 vTBN = mat3( tangent, bitangent, clearcoatNormal );
3205
+
3206
+ vec3 uvPrime = material.clearcoatNormalMapTransform * vec3( uv, 1 );
3207
+ vec3 texNormal = texture2D( textures, vec3( uvPrime.xy, material.clearcoatNormalMap ) ).xyz * 2.0 - 1.0;
3208
+ texNormal.xy *= material.clearcoatNormalScale;
3209
+ clearcoatNormal = vTBN * texNormal;
3210
+
3211
+ }
3212
+
3213
+ }
3214
+
3215
+ clearcoatNormal *= surfaceHit.side;
3216
+
3217
+ // sheenColor
3218
+ vec3 sheenColor = material.sheenColor;
3219
+ if ( material.sheenColorMap != - 1 ) {
3220
+
3221
+ vec3 uvPrime = material.sheenColorMapTransform * vec3( uv, 1 );
3222
+ sheenColor *= texture2D( textures, vec3( uvPrime.xy, material.sheenColorMap ) ).rgb;
3223
+
3224
+ }
3225
+
3226
+ // sheenRoughness
3227
+ float sheenRoughness = material.sheenRoughness;
3228
+ if ( material.sheenRoughnessMap != - 1 ) {
3229
+
3230
+ vec3 uvPrime = material.sheenRoughnessMapTransform * vec3( uv, 1 );
3231
+ sheenRoughness *= texture2D( textures, vec3( uvPrime.xy, material.sheenRoughnessMap ) ).a;
3232
+
3233
+ }
3234
+
3235
+ // iridescence
3236
+ float iridescence = material.iridescence;
3237
+ if ( material.iridescenceMap != - 1 ) {
3238
+
3239
+ vec3 uvPrime = material.iridescenceMapTransform * vec3( uv, 1 );
3240
+ iridescence *= texture2D( textures, vec3( uvPrime.xy, material.iridescenceMap ) ).r;
3241
+
3242
+ }
3243
+
3244
+ // iridescence thickness
3245
+ float iridescenceThickness = material.iridescenceThicknessMaximum;
3246
+ if ( material.iridescenceThicknessMap != - 1 ) {
3247
+
3248
+ vec3 uvPrime = material.iridescenceThicknessMapTransform * vec3( uv, 1 );
3249
+ float iridescenceThicknessSampled = texture2D( textures, vec3( uvPrime.xy, material.iridescenceThicknessMap ) ).g;
3250
+ iridescenceThickness = mix( material.iridescenceThicknessMinimum, material.iridescenceThicknessMaximum, iridescenceThicknessSampled );
3251
+
3252
+ }
3253
+
3254
+ iridescence = iridescenceThickness == 0.0 ? 0.0 : iridescence;
3255
+
3256
+ // specular color
3257
+ vec3 specularColor = material.specularColor;
3258
+ if ( material.specularColorMap != - 1 ) {
3259
+
3260
+ vec3 uvPrime = material.specularColorMapTransform * vec3( uv, 1 );
3261
+ specularColor *= texture2D( textures, vec3( uvPrime.xy, material.specularColorMap ) ).rgb;
3262
+
3263
+ }
3264
+
3265
+ // specular intensity
3266
+ float specularIntensity = material.specularIntensity;
3267
+ if ( material.specularIntensityMap != - 1 ) {
3268
+
3269
+ vec3 uvPrime = material.specularIntensityMapTransform * vec3( uv, 1 );
3270
+ specularIntensity *= texture2D( textures, vec3( uvPrime.xy, material.specularIntensityMap ) ).a;
3271
+
3272
+ }
3273
+
3274
+ surf.volumeParticle = false;
3275
+
3276
+ surf.faceNormal = surfaceHit.faceNormal;
3277
+ surf.normal = normal;
3278
+
3279
+ surf.metalness = metalness;
3280
+ surf.color = albedo.rgb;
3281
+ surf.emission = emission;
3282
+
3283
+ surf.ior = material.ior;
3284
+ surf.transmission = transmission;
3285
+ surf.thinFilm = material.thinFilm;
3286
+ surf.attenuationColor = material.attenuationColor;
3287
+ surf.attenuationDistance = material.attenuationDistance;
3288
+
3289
+ surf.clearcoatNormal = clearcoatNormal;
3290
+ surf.clearcoat = clearcoat;
3291
+
3292
+ surf.sheen = material.sheen;
3293
+ surf.sheenColor = sheenColor;
3294
+
3295
+ surf.iridescence = iridescence;
3296
+ surf.iridescenceIor = material.iridescenceIor;
3297
+ surf.iridescenceThickness = iridescenceThickness;
3298
+
3299
+ surf.specularColor = specularColor;
3300
+ surf.specularIntensity = specularIntensity;
3301
+
3302
+ // apply perceptual roughness factor from gltf. sheen perceptual roughness is
3303
+ // applied by its brdf function
3304
+ // https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#microfacet-surfaces
3305
+ surf.roughness = roughness * roughness;
3306
+ surf.clearcoatRoughness = clearcoatRoughness * clearcoatRoughness;
3307
+ surf.sheenRoughness = sheenRoughness;
3308
+
3309
+ // frontFace is used to determine transmissive properties and PDF. If no transmission is used
3310
+ // then we can just always assume this is a front face.
3311
+ surf.frontFace = surfaceHit.side == 1.0 || transmission == 0.0;
3312
+ surf.eta = material.thinFilm || surf.frontFace ? 1.0 / material.ior : material.ior;
3313
+ surf.f0 = iorRatioToF0( surf.eta );
3314
+
3315
+ // Compute the filtered roughness value to use during specular reflection computations.
3316
+ // The accumulated roughness value is scaled by a user setting and a "magic value" of 5.0.
3317
+ // If we're exiting something transmissive then scale the factor down significantly so we can retain
3318
+ // sharp internal reflections
3319
+ surf.filteredRoughness = applyFilteredGlossy( surf.roughness, accumulatedRoughness );
3320
+ surf.filteredClearcoatRoughness = applyFilteredGlossy( surf.clearcoatRoughness, accumulatedRoughness );
3321
+
3322
+ // get the normal frames
3323
+ surf.normalBasis = getBasisFromNormal( surf.normal );
3324
+ surf.normalInvBasis = inverse( surf.normalBasis );
3325
+
3326
+ surf.clearcoatBasis = getBasisFromNormal( surf.clearcoatNormal );
3327
+ surf.clearcoatInvBasis = inverse( surf.clearcoatBasis );
3328
+
3329
+ return HIT_SURFACE;
3330
+
3331
+ }
3332
+ `,Dr=`
3333
+
3334
+ struct Ray {
3335
+
3336
+ vec3 origin;
3337
+ vec3 direction;
3338
+
3339
+ };
3340
+
3341
+ struct SurfaceHit {
3342
+
3343
+ uvec4 faceIndices;
3344
+ vec3 barycoord;
3345
+ vec3 faceNormal;
3346
+ float side;
3347
+ float dist;
3348
+
3349
+ };
3350
+
3351
+ struct RenderState {
3352
+
3353
+ bool firstRay;
3354
+ bool transmissiveRay;
3355
+ bool isShadowRay;
3356
+ float accumulatedRoughness;
3357
+ int transmissiveTraversals;
3358
+ int traversals;
3359
+ uint depth;
3360
+ vec3 throughputColor;
3361
+ Material fogMaterial;
3362
+
3363
+ };
3364
+
3365
+ RenderState initRenderState() {
3366
+
3367
+ RenderState result;
3368
+ result.firstRay = true;
3369
+ result.transmissiveRay = true;
3370
+ result.isShadowRay = false;
3371
+ result.accumulatedRoughness = 0.0;
3372
+ result.transmissiveTraversals = 0;
3373
+ result.traversals = 0;
3374
+ result.throughputColor = vec3( 1.0 );
3375
+ result.depth = 0u;
3376
+ result.fogMaterial.fogVolume = false;
3377
+ return result;
3378
+
3379
+ }
3380
+
3381
+ `,Pr=`
3382
+
3383
+ #define NO_HIT 0
3384
+ #define SURFACE_HIT 1
3385
+ #define LIGHT_HIT 2
3386
+ #define FOG_HIT 3
3387
+
3388
+ // Passing the global variable 'lights' into this function caused shader program errors.
3389
+ // So global variables like 'lights' and 'bvh' were moved out of the function parameters.
3390
+ // For more information, refer to: https://github.com/gkjohnson/three-gpu-pathtracer/pull/457
3391
+ int traceScene(
3392
+ Ray ray, Material fogMaterial, inout SurfaceHit surfaceHit
3393
+ ) {
3394
+
3395
+ int result = NO_HIT;
3396
+ bool hit = bvhIntersectFirstHit( bvh, ray.origin, ray.direction, surfaceHit.faceIndices, surfaceHit.faceNormal, surfaceHit.barycoord, surfaceHit.side, surfaceHit.dist );
3397
+
3398
+ #if FEATURE_FOG
3399
+
3400
+ if ( fogMaterial.fogVolume ) {
3401
+
3402
+ // offset the distance so we don't run into issues with particles on the same surface
3403
+ // as other objects
3404
+ float particleDist = intersectFogVolume( fogMaterial, rand( 1 ) );
3405
+ if ( particleDist + RAY_OFFSET < surfaceHit.dist ) {
3406
+
3407
+ surfaceHit.side = 1.0;
3408
+ surfaceHit.faceNormal = normalize( - ray.direction );
3409
+ surfaceHit.dist = particleDist;
3410
+ return FOG_HIT;
3411
+
3412
+ }
3413
+
3414
+ }
3415
+
3416
+ #endif
3417
+
3418
+ if ( hit ) {
3419
+
3420
+ result = SURFACE_HIT;
3421
+
3422
+ }
3423
+
3424
+ return result;
3425
+
3426
+ }
3427
+
3428
+ `;class Er extends oe{onBeforeRender(){this.setDefine("FEATURE_DOF",this.physicalCamera.bokehSize===0?0:1),this.setDefine("FEATURE_BACKGROUND_MAP",this.backgroundMap?1:0),this.setDefine("FEATURE_FOG",this.materials.features.isUsed("FOG")?1:0)}constructor(e){super({transparent:!0,depthWrite:!1,defines:{FEATURE_MIS:1,FEATURE_RUSSIAN_ROULETTE:1,FEATURE_DOF:1,FEATURE_BACKGROUND_MAP:0,FEATURE_FOG:1,RANDOM_TYPE:2,CAMERA_TYPE:0,DEBUG_MODE:0,ATTR_NORMAL:0,ATTR_TANGENT:1,ATTR_UV:2,ATTR_COLOR:3},uniforms:{resolution:{value:new l.Vector2},opacity:{value:1},bounces:{value:10},transmissiveBounces:{value:10},filterGlossyFactor:{value:0},physicalCamera:{value:new Mt},cameraWorldMatrix:{value:new l.Matrix4},invProjectionMatrix:{value:new l.Matrix4},bvh:{value:new Xe},attributesArray:{value:new Lt},materialIndexAttribute:{value:new Be},materials:{value:new jt},textures:{value:new Fe().texture},lights:{value:new Ht},iesProfiles:{value:new Fe(360,180,{type:l.HalfFloatType,wrapS:l.ClampToEdgeWrapping,wrapT:l.ClampToEdgeWrapping}).texture},environmentIntensity:{value:1},environmentRotation:{value:new l.Matrix4},envMapInfo:{value:new Pt},backgroundBlur:{value:0},backgroundMap:{value:null},backgroundAlpha:{value:1},backgroundIntensity:{value:1},backgroundRotation:{value:new l.Matrix4},seed:{value:0},sobolTexture:{value:null},stratifiedTexture:{value:new tr},stratifiedOffsetTexture:{value:new nr(64,1)}},vertexShader:`
3429
+
3430
+ varying vec2 vUv;
3431
+ void main() {
3432
+
3433
+ vec4 mvPosition = vec4( position, 1.0 );
3434
+ mvPosition = modelViewMatrix * mvPosition;
3435
+ gl_Position = projectionMatrix * mvPosition;
3436
+
3437
+ vUv = uv;
3438
+
3439
+ }
3440
+
3441
+ `,fragmentShader:`
3442
+ #define RAY_OFFSET 1e-4
3443
+ #define INFINITY 1e20
3444
+
3445
+ precision highp isampler2D;
3446
+ precision highp usampler2D;
3447
+ precision highp sampler2DArray;
3448
+ vec4 envMapTexelToLinear( vec4 a ) { return a; }
3449
+ #include <common>
3450
+
3451
+ // bvh intersection
3452
+ ${Ze}
3453
+ ${et}
3454
+ ${Je}
3455
+
3456
+ // uniform structs
3457
+ ${lr}
3458
+ ${ur}
3459
+ ${cr}
3460
+ ${fr}
3461
+ ${hr}
3462
+
3463
+ // random
3464
+ #if RANDOM_TYPE == 2 // Stratified List
3465
+
3466
+ ${br}
3467
+
3468
+ #elif RANDOM_TYPE == 1 // Sobol
3469
+
3470
+ ${Me}
3471
+ ${Le}
3472
+ ${St}
3473
+
3474
+ #define rand(v) sobol(v)
3475
+ #define rand2(v) sobol2(v)
3476
+ #define rand3(v) sobol3(v)
3477
+ #define rand4(v) sobol4(v)
3478
+
3479
+ #else // PCG
3480
+
3481
+ ${Me}
3482
+
3483
+ // Using the sobol functions seems to break the the compiler on MacOS
3484
+ // - specifically the "sobolReverseBits" function.
3485
+ uint sobolPixelIndex = 0u;
3486
+ uint sobolPathIndex = 0u;
3487
+ uint sobolBounceIndex = 0u;
3488
+
3489
+ #define rand(v) pcgRand()
3490
+ #define rand2(v) pcgRand2()
3491
+ #define rand3(v) pcgRand3()
3492
+ #define rand4(v) pcgRand4()
3493
+
3494
+ #endif
3495
+
3496
+ // common
3497
+ ${yr}
3498
+ ${gr}
3499
+ ${Ge}
3500
+ ${vr}
3501
+ ${xr}
3502
+
3503
+ // environment
3504
+ uniform EquirectHdrInfo envMapInfo;
3505
+ uniform mat4 environmentRotation;
3506
+ uniform float environmentIntensity;
3507
+
3508
+ // lighting
3509
+ uniform sampler2DArray iesProfiles;
3510
+ uniform LightsInfo lights;
3511
+
3512
+ // background
3513
+ uniform float backgroundBlur;
3514
+ uniform float backgroundAlpha;
3515
+ #if FEATURE_BACKGROUND_MAP
3516
+
3517
+ uniform sampler2D backgroundMap;
3518
+ uniform mat4 backgroundRotation;
3519
+ uniform float backgroundIntensity;
3520
+
3521
+ #endif
3522
+
3523
+ // camera
3524
+ uniform mat4 cameraWorldMatrix;
3525
+ uniform mat4 invProjectionMatrix;
3526
+ #if FEATURE_DOF
3527
+
3528
+ uniform PhysicalCamera physicalCamera;
3529
+
3530
+ #endif
3531
+
3532
+ // geometry
3533
+ uniform sampler2DArray attributesArray;
3534
+ uniform usampler2D materialIndexAttribute;
3535
+ uniform sampler2D materials;
3536
+ uniform sampler2DArray textures;
3537
+ uniform BVH bvh;
3538
+
3539
+ // path tracer
3540
+ uniform int bounces;
3541
+ uniform int transmissiveBounces;
3542
+ uniform float filterGlossyFactor;
3543
+ uniform int seed;
3544
+
3545
+ // image
3546
+ uniform vec2 resolution;
3547
+ uniform float opacity;
3548
+
3549
+ varying vec2 vUv;
3550
+
3551
+ // globals
3552
+ mat3 envRotation3x3;
3553
+ mat3 invEnvRotation3x3;
3554
+ float lightsDenom;
3555
+
3556
+ // sampling
3557
+ ${pr}
3558
+ ${dr}
3559
+ ${mr}
3560
+
3561
+ ${_r}
3562
+ ${Rr}
3563
+ ${Sr}
3564
+ ${Ir}
3565
+ ${wr}
3566
+ ${Tr}
3567
+
3568
+ float applyFilteredGlossy( float roughness, float accumulatedRoughness ) {
3569
+
3570
+ return clamp(
3571
+ max(
3572
+ roughness,
3573
+ accumulatedRoughness * filterGlossyFactor * 5.0 ),
3574
+ 0.0,
3575
+ 1.0
3576
+ );
3577
+
3578
+ }
3579
+
3580
+ vec3 sampleBackground( vec3 direction, vec2 uv ) {
3581
+
3582
+ vec3 sampleDir = sampleHemisphere( direction, uv ) * 0.5 * backgroundBlur;
3583
+
3584
+ #if FEATURE_BACKGROUND_MAP
3585
+
3586
+ sampleDir = normalize( mat3( backgroundRotation ) * direction + sampleDir );
3587
+ return backgroundIntensity * sampleEquirectColor( backgroundMap, sampleDir );
3588
+
3589
+ #else
3590
+
3591
+ sampleDir = normalize( envRotation3x3 * direction + sampleDir );
3592
+ return environmentIntensity * sampleEquirectColor( envMapInfo.map, sampleDir );
3593
+
3594
+ #endif
3595
+
3596
+ }
3597
+
3598
+ ${Dr}
3599
+ ${Ar}
3600
+ ${Pr}
3601
+ ${Fr}
3602
+ ${Mr}
3603
+ ${Cr}
3604
+
3605
+ void main() {
3606
+
3607
+ // init
3608
+ rng_initialize( gl_FragCoord.xy, seed );
3609
+ sobolPixelIndex = ( uint( gl_FragCoord.x ) << 16 ) | uint( gl_FragCoord.y );
3610
+ sobolPathIndex = uint( seed );
3611
+
3612
+ // get camera ray
3613
+ Ray ray = getCameraRay();
3614
+
3615
+ // inverse environment rotation
3616
+ envRotation3x3 = mat3( environmentRotation );
3617
+ invEnvRotation3x3 = inverse( envRotation3x3 );
3618
+ lightsDenom =
3619
+ ( environmentIntensity == 0.0 || envMapInfo.totalSum == 0.0 ) && lights.count != 0u ?
3620
+ float( lights.count ) :
3621
+ float( lights.count + 1u );
3622
+
3623
+ // final color
3624
+ gl_FragColor = vec4( 0, 0, 0, 1 );
3625
+
3626
+ // surface results
3627
+ SurfaceHit surfaceHit;
3628
+ ScatterRecord scatterRec;
3629
+
3630
+ // path tracing state
3631
+ RenderState state = initRenderState();
3632
+ state.transmissiveTraversals = transmissiveBounces;
3633
+ #if FEATURE_FOG
3634
+
3635
+ state.fogMaterial.fogVolume = bvhIntersectFogVolumeHit(
3636
+ ray.origin, - ray.direction,
3637
+ materialIndexAttribute, materials,
3638
+ state.fogMaterial
3639
+ );
3640
+
3641
+ #endif
3642
+
3643
+ for ( int i = 0; i < bounces; i ++ ) {
3644
+
3645
+ sobolBounceIndex ++;
3646
+
3647
+ state.depth ++;
3648
+ state.traversals = bounces - i;
3649
+ state.firstRay = i == 0 && state.transmissiveTraversals == transmissiveBounces;
3650
+
3651
+ int hitType = traceScene( ray, state.fogMaterial, surfaceHit );
3652
+
3653
+ // check if we intersect any lights and accumulate the light contribution
3654
+ // TODO: we can add support for light surface rendering in the else condition if we
3655
+ // add the ability to toggle visibility of the the light
3656
+ if ( ! state.firstRay && ! state.transmissiveRay ) {
3657
+
3658
+ LightRecord lightRec;
3659
+ float lightDist = hitType == NO_HIT ? INFINITY : surfaceHit.dist;
3660
+ for ( uint i = 0u; i < lights.count; i ++ ) {
3661
+
3662
+ if (
3663
+ intersectLightAtIndex( lights.tex, ray.origin, ray.direction, i, lightRec ) &&
3664
+ lightRec.dist < lightDist
3665
+ ) {
3666
+
3667
+ #if FEATURE_MIS
3668
+
3669
+ // weight the contribution
3670
+ // NOTE: Only area lights are supported for forward sampling and can be hit
3671
+ float misWeight = misHeuristic( scatterRec.pdf, lightRec.pdf / lightsDenom );
3672
+ gl_FragColor.rgb += lightRec.emission * state.throughputColor * misWeight;
3673
+
3674
+ #else
3675
+
3676
+ gl_FragColor.rgb += lightRec.emission * state.throughputColor;
3677
+
3678
+ #endif
3679
+
3680
+ }
3681
+
3682
+ }
3683
+
3684
+ }
3685
+
3686
+ if ( hitType == NO_HIT ) {
3687
+
3688
+ if ( state.firstRay || state.transmissiveRay ) {
3689
+
3690
+ gl_FragColor.rgb += sampleBackground( ray.direction, rand2( 2 ) ) * state.throughputColor;
3691
+ gl_FragColor.a = backgroundAlpha;
3692
+
3693
+ } else {
3694
+
3695
+ #if FEATURE_MIS
3696
+
3697
+ // get the PDF of the hit envmap point
3698
+ vec3 envColor;
3699
+ float envPdf = sampleEquirect( envRotation3x3 * ray.direction, envColor );
3700
+ envPdf /= lightsDenom;
3701
+
3702
+ // and weight the contribution
3703
+ float misWeight = misHeuristic( scatterRec.pdf, envPdf );
3704
+ gl_FragColor.rgb += environmentIntensity * envColor * state.throughputColor * misWeight;
3705
+
3706
+ #else
3707
+
3708
+ gl_FragColor.rgb +=
3709
+ environmentIntensity *
3710
+ sampleEquirectColor( envMapInfo.map, envRotation3x3 * ray.direction ) *
3711
+ state.throughputColor;
3712
+
3713
+ #endif
3714
+
3715
+ }
3716
+ break;
3717
+
3718
+ }
3719
+
3720
+ uint materialIndex = uTexelFetch1D( materialIndexAttribute, surfaceHit.faceIndices.x ).r;
3721
+ Material material = readMaterialInfo( materials, materialIndex );
3722
+
3723
+ #if FEATURE_FOG
3724
+
3725
+ if ( hitType == FOG_HIT ) {
3726
+
3727
+ material = state.fogMaterial;
3728
+ state.accumulatedRoughness += 0.2;
3729
+
3730
+ } else if ( material.fogVolume ) {
3731
+
3732
+ state.fogMaterial = material;
3733
+ state.fogMaterial.fogVolume = surfaceHit.side == 1.0;
3734
+
3735
+ ray.origin = stepRayOrigin( ray.origin, ray.direction, - surfaceHit.faceNormal, surfaceHit.dist );
3736
+
3737
+ i -= sign( state.transmissiveTraversals );
3738
+ state.transmissiveTraversals -= sign( state.transmissiveTraversals );
3739
+ continue;
3740
+
3741
+ }
3742
+
3743
+ #endif
3744
+
3745
+ // early out if this is a matte material
3746
+ if ( material.matte && state.firstRay ) {
3747
+
3748
+ gl_FragColor = vec4( 0.0 );
3749
+ break;
3750
+
3751
+ }
3752
+
3753
+ // if we've determined that this is a shadow ray and we've hit an item with no shadow casting
3754
+ // then skip it
3755
+ if ( ! material.castShadow && state.isShadowRay ) {
3756
+
3757
+ ray.origin = stepRayOrigin( ray.origin, ray.direction, - surfaceHit.faceNormal, surfaceHit.dist );
3758
+ continue;
3759
+
3760
+ }
3761
+
3762
+ SurfaceRecord surf;
3763
+ if (
3764
+ getSurfaceRecord(
3765
+ material, surfaceHit, attributesArray, state.accumulatedRoughness,
3766
+ surf
3767
+ ) == SKIP_SURFACE
3768
+ ) {
3769
+
3770
+ // only allow a limited number of transparency discards otherwise we could
3771
+ // crash the context with too long a loop.
3772
+ i -= sign( state.transmissiveTraversals );
3773
+ state.transmissiveTraversals -= sign( state.transmissiveTraversals );
3774
+
3775
+ ray.origin = stepRayOrigin( ray.origin, ray.direction, - surfaceHit.faceNormal, surfaceHit.dist );
3776
+ continue;
3777
+
3778
+ }
3779
+
3780
+ scatterRec = bsdfSample( - ray.direction, surf );
3781
+ state.isShadowRay = scatterRec.specularPdf < rand( 4 );
3782
+
3783
+ bool isBelowSurface = ! surf.volumeParticle && dot( scatterRec.direction, surf.faceNormal ) < 0.0;
3784
+ vec3 hitPoint = stepRayOrigin( ray.origin, ray.direction, isBelowSurface ? - surf.faceNormal : surf.faceNormal, surfaceHit.dist );
3785
+
3786
+ // next event estimation
3787
+ #if FEATURE_MIS
3788
+
3789
+ gl_FragColor.rgb += directLightContribution( - ray.direction, surf, state, hitPoint );
3790
+
3791
+ #endif
3792
+
3793
+ // accumulate a roughness value to offset diffuse, specular, diffuse rays that have high contribution
3794
+ // to a single pixel resulting in fireflies
3795
+ // TODO: handle transmissive surfaces
3796
+ if ( ! surf.volumeParticle && ! isBelowSurface ) {
3797
+
3798
+ // determine if this is a rough normal or not by checking how far off straight up it is
3799
+ vec3 halfVector = normalize( - ray.direction + scatterRec.direction );
3800
+ state.accumulatedRoughness += max(
3801
+ sin( acosApprox( dot( halfVector, surf.normal ) ) ),
3802
+ sin( acosApprox( dot( halfVector, surf.clearcoatNormal ) ) )
3803
+ );
3804
+
3805
+ state.transmissiveRay = false;
3806
+
3807
+ }
3808
+
3809
+ // accumulate emissive color
3810
+ gl_FragColor.rgb += ( surf.emission * state.throughputColor );
3811
+
3812
+ // skip the sample if our PDF or ray is impossible
3813
+ if ( scatterRec.pdf <= 0.0 || ! isDirectionValid( scatterRec.direction, surf.normal, surf.faceNormal ) ) {
3814
+
3815
+ break;
3816
+
3817
+ }
3818
+
3819
+ // if we're bouncing around the inside a transmissive material then decrement
3820
+ // perform this separate from a bounce
3821
+ bool isTransmissiveRay = ! surf.volumeParticle && dot( scatterRec.direction, surf.faceNormal * surfaceHit.side ) < 0.0;
3822
+ if ( ( isTransmissiveRay || isBelowSurface ) && state.transmissiveTraversals > 0 ) {
3823
+
3824
+ state.transmissiveTraversals --;
3825
+ i --;
3826
+
3827
+ }
3828
+
3829
+ //
3830
+
3831
+ // handle throughput color transformation
3832
+ // attenuate the throughput color by the medium color
3833
+ if ( ! surf.frontFace ) {
3834
+
3835
+ state.throughputColor *= transmissionAttenuation( surfaceHit.dist, surf.attenuationColor, surf.attenuationDistance );
3836
+
3837
+ }
3838
+
3839
+ #if FEATURE_RUSSIAN_ROULETTE
3840
+
3841
+ // russian roulette path termination
3842
+ // https://www.arnoldrenderer.com/research/physically_based_shader_design_in_arnold.pdf
3843
+ uint minBounces = 3u;
3844
+ float depthProb = float( state.depth < minBounces );
3845
+
3846
+ float rrProb = luminance( state.throughputColor * scatterRec.color / scatterRec.pdf );
3847
+ rrProb /= luminance( state.throughputColor );
3848
+ rrProb = sqrt( rrProb );
3849
+ rrProb = max( rrProb, depthProb );
3850
+ rrProb = min( rrProb, 1.0 );
3851
+ if ( rand( 8 ) > rrProb ) {
3852
+
3853
+ break;
3854
+
3855
+ }
3856
+
3857
+ // perform sample clamping here to avoid bright pixels
3858
+ state.throughputColor *= min( 1.0 / rrProb, 20.0 );
3859
+
3860
+ #endif
3861
+
3862
+ // adjust the throughput and discard and exit if we find discard the sample if there are any NaNs
3863
+ state.throughputColor *= scatterRec.color / scatterRec.pdf;
3864
+ if ( any( isnan( state.throughputColor ) ) || any( isinf( state.throughputColor ) ) ) {
3865
+
3866
+ break;
3867
+
3868
+ }
3869
+
3870
+ //
3871
+
3872
+ // prepare for next ray
3873
+ ray.direction = scatterRec.direction;
3874
+ ray.origin = hitPoint;
3875
+
3876
+ }
3877
+
3878
+ gl_FragColor.a *= opacity;
3879
+
3880
+ #if DEBUG_MODE == 1
3881
+
3882
+ // output the number of rays checked in the path and number of
3883
+ // transmissive rays encountered.
3884
+ gl_FragColor.rgb = vec3(
3885
+ float( state.depth ),
3886
+ transmissiveBounces - state.transmissiveTraversals,
3887
+ 0.0
3888
+ );
3889
+ gl_FragColor.a = 1.0;
3890
+
3891
+ #endif
3892
+
3893
+ }
3894
+
3895
+ `}),this.setValues(e)}}function*kr(){const{_renderer:s,_fsQuad:e,_blendQuad:t,_primaryTarget:r,_blendTargets:i,_sobolTarget:o,_subframe:a,alpha:c,material:h}=this,d=new l.Vector4,m=new l.Vector4,f=t.material;let[n,x]=i;for(;;){c?(f.opacity=this._opacityFactor/(this.samples+1),h.blending=l.NoBlending,h.opacity=1):(h.opacity=this._opacityFactor/(this.samples+1),h.blending=l.NormalBlending);const[p,v,u,g]=a,y=r.width,b=r.height;h.resolution.set(y*u,b*g),h.sobolTexture=o.texture,h.stratifiedTexture.init(20,h.bounces+h.transmissiveBounces+5),h.stratifiedTexture.next(),h.seed++;const w=this.tiles.x||1,R=this.tiles.y||1,_=w*R,F=Math.ceil(y*u),Y=Math.ceil(b*g),le=Math.floor(p*y),ce=Math.floor(v*b),X=Math.ceil(F/w),Q=Math.ceil(Y/R);for(let W=0;W<R;W++)for(let L=0;L<w;L++){const ue=s.getRenderTarget(),Ve=s.autoClear,qe=s.getScissorTest();s.getScissor(d),s.getViewport(m);let K=L,fe=W;if(!this.stableTiles){const Z=this._currentTile%(w*R);K=Z%w,fe=~~(Z/w),this._currentTile=Z+1}const he=R-fe-1;r.scissor.set(le+K*X,ce+he*Q,Math.min(X,F-K*X),Math.min(Q,Y-he*Q)),r.viewport.set(le,ce,F,Y),s.setRenderTarget(r),s.setScissorTest(!0),s.autoClear=!1,e.render(s),s.setViewport(m),s.setScissor(d),s.setScissorTest(qe),s.setRenderTarget(ue),s.autoClear=Ve,c&&(f.target1=n.texture,f.target2=r.texture,s.setRenderTarget(x),t.render(s),s.setRenderTarget(ue)),this.samples+=1/_,L===w-1&&W===R-1&&(this.samples=Math.round(this.samples)),yield}[n,x]=[x,n]}}const Ce=new l.Color;class De{get material(){return this._fsQuad.material}set material(e){this._fsQuad.material.removeEventListener("recompilation",this._compileFunction),e.addEventListener("recompilation",this._compileFunction),this._fsQuad.material=e}get target(){return this._alpha?this._blendTargets[1]:this._primaryTarget}set alpha(e){this._alpha!==e&&(e||(this._blendTargets[0].dispose(),this._blendTargets[1].dispose()),this._alpha=e,this.reset())}get alpha(){return this._alpha}get isCompiling(){return!!this._compilePromise}constructor(e){this.camera=null,this.tiles=new l.Vector2(3,3),this.stableNoise=!1,this.stableTiles=!0,this.samples=0,this._subframe=new l.Vector4(0,0,1,1),this._opacityFactor=1,this._renderer=e,this._alpha=!1,this._fsQuad=new z(new Er),this._blendQuad=new z(new Rt),this._task=null,this._currentTile=0,this._compilePromise=null,this._sobolTarget=new Ft().generate(e),this._primaryTarget=new l.WebGLRenderTarget(1,1,{format:l.RGBAFormat,type:l.FloatType,magFilter:l.NearestFilter,minFilter:l.NearestFilter}),this._blendTargets=[new l.WebGLRenderTarget(1,1,{format:l.RGBAFormat,type:l.FloatType,magFilter:l.NearestFilter,minFilter:l.NearestFilter}),new l.WebGLRenderTarget(1,1,{format:l.RGBAFormat,type:l.FloatType,magFilter:l.NearestFilter,minFilter:l.NearestFilter})],this._compileFunction=()=>{const t=this.compileMaterial(this._fsQuad._mesh);t.then(()=>{this._compilePromise===t&&(this._compilePromise=null)}),this._compilePromise=t},this.material.addEventListener("recompilation",this._compileFunction)}compileMaterial(){return this._renderer.compileAsync(this._fsQuad._mesh)}setCamera(e){const{material:t}=this;t.cameraWorldMatrix.copy(e.matrixWorld),t.invProjectionMatrix.copy(e.projectionMatrixInverse),t.physicalCamera.updateFrom(e);let r=0;e.projectionMatrix.elements[15]>0&&(r=1),e.isEquirectCamera&&(r=2),t.setDefine("CAMERA_TYPE",r),this.camera=e}setSize(e,t){e=Math.ceil(e),t=Math.ceil(t),!(this._primaryTarget.width===e&&this._primaryTarget.height===t)&&(this._primaryTarget.setSize(e,t),this._blendTargets[0].setSize(e,t),this._blendTargets[1].setSize(e,t),this.reset())}getSize(e){e.x=this._primaryTarget.width,e.y=this._primaryTarget.height}dispose(){this._primaryTarget.dispose(),this._blendTargets[0].dispose(),this._blendTargets[1].dispose(),this._sobolTarget.dispose(),this._fsQuad.dispose(),this._blendQuad.dispose(),this._task=null}reset(){const{_renderer:e,_primaryTarget:t,_blendTargets:r}=this,i=e.getRenderTarget(),o=e.getClearAlpha();e.getClearColor(Ce),e.setRenderTarget(t),e.setClearColor(0,0),e.clearColor(),e.setRenderTarget(r[0]),e.setClearColor(0,0),e.clearColor(),e.setRenderTarget(r[1]),e.setClearColor(0,0),e.clearColor(),e.setClearColor(Ce,o),e.setRenderTarget(i),this.samples=0,this._task=null,this.material.stratifiedTexture.stableNoise=this.stableNoise,this.stableNoise&&(this.material.seed=0,this.material.stratifiedTexture.reset())}update(){this.material.onBeforeRender(),!this.isCompiling&&(this._task||(this._task=kr.call(this)),this._task.next())}}const P=new l.Vector2,Pe=new l.Vector2,$=new l.Spherical,j=new l.Color;class Or extends l.DataTexture{constructor(e=512,t=512){super(new Float32Array(e*t*4),e,t,l.RGBAFormat,l.FloatType,l.EquirectangularReflectionMapping,l.RepeatWrapping,l.ClampToEdgeWrapping,l.LinearFilter,l.LinearFilter),this.generationCallback=null}update(){this.dispose(),this.needsUpdate=!0;const{data:e,width:t,height:r}=this.image;for(let i=0;i<t;i++)for(let o=0;o<r;o++){Pe.set(t,r),P.set(i/t,o/r),P.x-=.5,P.y=1-P.y,$.theta=P.x*2*Math.PI,$.phi=P.y*Math.PI,$.radius=1,this.generationCallback($,P,Pe,j);const c=4*(o*t+i);e[c+0]=j.r,e[c+1]=j.g,e[c+2]=j.b,e[c+3]=1}}copy(e){return super.copy(e),this.generationCallback=e.generationCallback,this}}const Ee=new l.Vector3;class Br extends Or{constructor(e=512){super(e,e),this.topColor=new l.Color().set(16777215),this.bottomColor=new l.Color().set(0),this.exponent=2,this.generationCallback=(t,r,i,o)=>{Ee.setFromSpherical(t);const a=Ee.y*.5+.5;o.lerpColors(this.bottomColor,this.topColor,a**this.exponent)}}copy(e){return super.copy(e),this.topColor.copy(e.topColor),this.bottomColor.copy(e.bottomColor),this}}class Nr extends l.ShaderMaterial{get map(){return this.uniforms.map.value}set map(e){this.uniforms.map.value=e}get opacity(){return this.uniforms.opacity.value}set opacity(e){this.uniforms&&(this.uniforms.opacity.value=e)}constructor(e){super({uniforms:{map:{value:null},opacity:{value:1}},vertexShader:`
3896
+ varying vec2 vUv;
3897
+ void main() {
3898
+
3899
+ vUv = uv;
3900
+ gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
3901
+
3902
+ }
3903
+ `,fragmentShader:`
3904
+ uniform sampler2D map;
3905
+ uniform float opacity;
3906
+ varying vec2 vUv;
3907
+
3908
+ vec4 clampedTexelFatch( sampler2D map, ivec2 px, int lod ) {
3909
+
3910
+ vec4 res = texelFetch( map, ivec2( px.x, px.y ), 0 );
3911
+
3912
+ #if defined( TONE_MAPPING )
3913
+
3914
+ res.xyz = toneMapping( res.xyz );
3915
+
3916
+ #endif
3917
+
3918
+ return linearToOutputTexel( res );
3919
+
3920
+ }
3921
+
3922
+ void main() {
3923
+
3924
+ vec2 size = vec2( textureSize( map, 0 ) );
3925
+ vec2 pxUv = vUv * size;
3926
+ vec2 pxCurr = floor( pxUv );
3927
+ vec2 pxFrac = fract( pxUv ) - 0.5;
3928
+ vec2 pxOffset;
3929
+ pxOffset.x = pxFrac.x > 0.0 ? 1.0 : - 1.0;
3930
+ pxOffset.y = pxFrac.y > 0.0 ? 1.0 : - 1.0;
3931
+
3932
+ vec2 pxNext = clamp( pxOffset + pxCurr, vec2( 0.0 ), size - 1.0 );
3933
+ vec2 alpha = abs( pxFrac );
3934
+
3935
+ vec4 p1 = mix(
3936
+ clampedTexelFatch( map, ivec2( pxCurr.x, pxCurr.y ), 0 ),
3937
+ clampedTexelFatch( map, ivec2( pxNext.x, pxCurr.y ), 0 ),
3938
+ alpha.x
3939
+ );
3940
+
3941
+ vec4 p2 = mix(
3942
+ clampedTexelFatch( map, ivec2( pxCurr.x, pxNext.y ), 0 ),
3943
+ clampedTexelFatch( map, ivec2( pxNext.x, pxNext.y ), 0 ),
3944
+ alpha.x
3945
+ );
3946
+
3947
+ gl_FragColor = mix( p1, p2, alpha.y );
3948
+ gl_FragColor.a *= opacity;
3949
+ #include <premultiplied_alpha_fragment>
3950
+
3951
+ }
3952
+ `}),this.setValues(e)}}class zr extends l.ShaderMaterial{constructor(){super({uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:`
3953
+ varying vec2 vUv;
3954
+ void main() {
3955
+
3956
+ vUv = uv;
3957
+ gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
3958
+
3959
+ }`,fragmentShader:`
3960
+ #define ENVMAP_TYPE_CUBE_UV
3961
+
3962
+ uniform samplerCube envMap;
3963
+ uniform float flipEnvMap;
3964
+ varying vec2 vUv;
3965
+
3966
+ #include <common>
3967
+ #include <cube_uv_reflection_fragment>
3968
+
3969
+ ${Ge}
3970
+
3971
+ void main() {
3972
+
3973
+ vec3 rayDirection = equirectUvToDirection( vUv );
3974
+ rayDirection.x *= flipEnvMap;
3975
+ gl_FragColor = textureCube( envMap, rayDirection );
3976
+
3977
+ }`}),this.depthWrite=!1,this.depthTest=!1}}class ke{constructor(e){this._renderer=e,this._quad=new z(new zr)}generate(e,t=null,r=null){if(!e.isCubeTexture)throw new Error("CubeToEquirectMaterial: Source can only be cube textures.");const i=e.images[0],o=this._renderer,a=this._quad;t===null&&(t=4*i.height),r===null&&(r=2*i.height);const c=new l.WebGLRenderTarget(t,r,{type:l.FloatType,colorSpace:i.colorSpace}),h=i.height,d=Math.log2(h)-2,m=1/h,f=1/(3*Math.max(Math.pow(2,d),112));a.material.defines.CUBEUV_MAX_MIP=`${d}.0`,a.material.defines.CUBEUV_TEXEL_WIDTH=f,a.material.defines.CUBEUV_TEXEL_HEIGHT=m,a.material.uniforms.envMap.value=e,a.material.uniforms.flipEnvMap.value=e.isRenderTargetTexture?1:-1,a.material.needsUpdate=!0;const n=o.getRenderTarget(),x=o.autoClear;o.autoClear=!0,o.setRenderTarget(c),a.render(o),o.setRenderTarget(n),o.autoClear=x;const p=new Uint16Array(t*r*4),v=new Float32Array(t*r*4);o.readRenderTargetPixels(c,0,0,t,r,v),c.dispose();for(let g=0,y=v.length;g<y;g++)p[g]=l.DataUtils.toHalfFloat(v[g]);const u=new l.DataTexture(p,t,r,l.RGBAFormat,l.HalfFloatType);return u.minFilter=l.LinearMipMapLinearFilter,u.magFilter=l.LinearFilter,u.wrapS=l.RepeatWrapping,u.wrapT=l.RepeatWrapping,u.mapping=l.EquirectangularReflectionMapping,u.needsUpdate=!0,u}dispose(){this._quad.dispose()}}function Hr(s){return s.extensions.get("EXT_float_blend")}const O=new l.Vector2;class Wr{get multipleImportanceSampling(){return!!this._pathTracer.material.defines.FEATURE_MIS}set multipleImportanceSampling(e){this._pathTracer.material.setDefine("FEATURE_MIS",e?1:0)}get transmissiveBounces(){return this._pathTracer.material.transmissiveBounces}set transmissiveBounces(e){this._pathTracer.material.transmissiveBounces=e}get bounces(){return this._pathTracer.material.bounces}set bounces(e){this._pathTracer.material.bounces=e}get filterGlossyFactor(){return this._pathTracer.material.filterGlossyFactor}set filterGlossyFactor(e){this._pathTracer.material.filterGlossyFactor=e}get samples(){return this._pathTracer.samples}get target(){return this._pathTracer.target}get tiles(){return this._pathTracer.tiles}get stableNoise(){return this._pathTracer.stableNoise}set stableNoise(e){this._pathTracer.stableNoise=e}get isCompiling(){return!!this._pathTracer.isCompiling}constructor(e){this._renderer=e,this._generator=new yt,this._pathTracer=new De(e),this._queueReset=!1,this._clock=new l.Clock,this._compilePromise=null,this._lowResPathTracer=new De(e),this._lowResPathTracer.tiles.set(1,1),this._quad=new z(new Nr({map:null,transparent:!0,blending:l.NoBlending,premultipliedAlpha:e.getContextAttributes().premultipliedAlpha})),this._materials=null,this._previousEnvironment=null,this._previousBackground=null,this._internalBackground=null,this.renderDelay=100,this.minSamples=5,this.fadeDuration=500,this.enablePathTracing=!0,this.pausePathTracing=!1,this.dynamicLowRes=!1,this.lowResScale=.25,this.renderScale=1,this.synchronizeRenderSize=!0,this.rasterizeScene=!0,this.renderToCanvas=!0,this.textureSize=new l.Vector2(1024,1024),this.rasterizeSceneCallback=(t,r)=>{this._renderer.render(t,r)},this.renderToCanvasCallback=(t,r,i)=>{const o=r.autoClear;r.autoClear=!1,i.render(r),r.autoClear=o},this.setScene(new l.Scene,new l.PerspectiveCamera)}setBVHWorker(e){this._generator.setBVHWorker(e)}setScene(e,t,r={}){e.updateMatrixWorld(!0),t.updateMatrixWorld();const i=this._generator;if(i.setObjects(e),this._buildAsync)return i.generateAsync(r.onProgress).then(o=>this._updateFromResults(e,t,o));{const o=i.generate();return this._updateFromResults(e,t,o)}}setSceneAsync(...e){this._buildAsync=!0;const t=this.setScene(...e);return this._buildAsync=!1,t}setCamera(e){this.camera=e,this.updateCamera()}updateCamera(){const e=this.camera;e.updateMatrixWorld(),this._pathTracer.setCamera(e),this._lowResPathTracer.setCamera(e),this.reset()}updateMaterials(){const e=this._pathTracer.material,t=this._renderer,r=this._materials,i=this.textureSize,o=Vt(r);e.textures.setTextures(t,o,i.x,i.y),e.materials.updateFrom(r,o),this.reset()}updateLights(){const e=this.scene,t=this._renderer,r=this._pathTracer.material,i=qt(e),o=Gt(i);r.lights.updateFrom(i,o),r.iesProfiles.setTextures(t,o),this.reset()}updateEnvironment(){const e=this.scene,t=this._pathTracer.material;if(this._internalBackground&&(this._internalBackground.dispose(),this._internalBackground=null),t.backgroundBlur=e.backgroundBlurriness,t.backgroundIntensity=e.backgroundIntensity??1,t.backgroundRotation.makeRotationFromEuler(e.backgroundRotation).invert(),e.background===null)t.backgroundMap=null,t.backgroundAlpha=0;else if(e.background.isColor){this._colorBackground=this._colorBackground||new Br(16);const r=this._colorBackground;r.topColor.equals(e.background)||(r.topColor.set(e.background),r.bottomColor.set(e.background),r.update()),t.backgroundMap=r,t.backgroundAlpha=1}else if(e.background.isCubeTexture){if(e.background!==this._previousBackground){const r=new ke(this._renderer).generate(e.background);this._internalBackground=r,t.backgroundMap=r,t.backgroundAlpha=1}}else t.backgroundMap=e.background,t.backgroundAlpha=1;if(t.environmentIntensity=e.environmentIntensity??1,t.environmentRotation.makeRotationFromEuler(e.environmentRotation).invert(),this._previousEnvironment!==e.environment)if(e.environment!==null)if(e.environment.isCubeTexture){const r=new ke(this._renderer).generate(e.environment);t.envMapInfo.updateFrom(r)}else t.envMapInfo.updateFrom(e.environment);else t.environmentIntensity=0;this._previousEnvironment=e.environment,this._previousBackground=e.background,this.reset()}_updateFromResults(e,t,r){const{materials:i,geometry:o,bvh:a,bvhChanged:c}=r;this._materials=i;const d=this._pathTracer.material;return c&&(d.bvh.updateFrom(a),d.attributesArray.updateFrom(o.attributes.normal,o.attributes.tangent,o.attributes.uv,o.attributes.color),d.materialIndexAttribute.updateFrom(o.attributes.materialIndex)),this._previousScene=e,this.scene=e,this.camera=t,this.updateCamera(),this.updateMaterials(),this.updateEnvironment(),this.updateLights(),r}renderSample(){const e=this._lowResPathTracer,t=this._pathTracer,r=this._renderer,i=this._clock,o=this._quad;this._updateScale(),this._queueReset&&(t.reset(),e.reset(),this._queueReset=!1,o.material.opacity=0,i.start());const a=i.getDelta()*1e3,c=i.getElapsedTime()*1e3;if(!this.pausePathTracing&&this.enablePathTracing&&this.renderDelay<=c&&!this.isCompiling&&t.update(),t.alpha=t.material.backgroundAlpha!==1||!Hr(r),e.alpha=t.alpha,this.renderToCanvas){const h=this._renderer,d=this.minSamples;if(c>=this.renderDelay&&this.samples>=this.minSamples&&(this.fadeDuration!==0?o.material.opacity=Math.min(o.material.opacity+a/this.fadeDuration,1):o.material.opacity=1),!this.enablePathTracing||this.samples<d||o.material.opacity<1){if(this.dynamicLowRes&&!this.isCompiling){e.samples<1&&(e.material=t.material,e.update());const m=o.material.opacity;o.material.opacity=1-o.material.opacity,o.material.map=e.target.texture,o.render(h),o.material.opacity=m}(!this.dynamicLowRes&&this.rasterizeScene||this.dynamicLowRes&&this.isCompiling)&&this.rasterizeSceneCallback(this.scene,this.camera)}this.enablePathTracing&&o.material.opacity>0&&(o.material.opacity<1&&(o.material.blending=this.dynamicLowRes?l.AdditiveBlending:l.NormalBlending),o.material.map=t.target.texture,this.renderToCanvasCallback(t.target,h,o),o.material.blending=l.NoBlending)}}reset(){this._queueReset=!0,this._pathTracer.samples=0}dispose(){this._renderQuad.dispose(),this._renderQuad.material.dispose(),this._pathTracer.dispose()}_updateScale(){if(this.synchronizeRenderSize){this._renderer.getDrawingBufferSize(O);const e=Math.floor(this.renderScale*O.x),t=Math.floor(this.renderScale*O.y);if(this._pathTracer.getSize(O),O.x!==e||O.y!==t){const r=this.lowResScale;this._pathTracer.setSize(e,t),this._lowResPathTracer.setSize(Math.floor(e*r),Math.floor(t*r))}}}}function B(s){return s!==null&&typeof s=="object"&&"getInternalRenderer"in s&&typeof s.getInternalRenderer=="function"}class Lr{constructor(){this.pathTracer=null,this.enabled=!1,this.renderer=null,this.sampleCount=0,this.createAttempts=0,this.maxCreateAttempts=10,this.sceneInitialized=!1,this.environmentWaitFrames=0,this.maxEnvironmentWaitFrames=300,this.disposed=!1,this.disposeTimer=null,this.convertedEnvTexture=null,this.lastResetTime=0,this.events=new T.TypedEventEmitter,this.settings={samples:T.DEFAULT_PATH_TRACING_SAMPLES,bounces:4,transmissiveBounces:2,renderScale:.5,lowResScale:.5,dynamicLowRes:!0,enablePathTracing:!0}}convertToDataTexture(e){if(!e.image||!(e.image instanceof HTMLImageElement))return null;const t=e.image,r=document.createElement("canvas");r.width=t.width,r.height=t.height;const i=r.getContext("2d");if(!i)return null;i.drawImage(t,0,0);const o=i.getImageData(0,0,r.width,r.height),a=new Float32Array(o.data.length);for(let h=0;h<o.data.length;h++)a[h]=o.data[h]/255;const c=new A.DataTexture(a,r.width,r.height,A.RGBAFormat,A.FloatType);return c.mapping=e.mapping,c.wrapS=e.wrapS,c.wrapT=e.wrapT,c.magFilter=e.magFilter,c.minFilter=e.minFilter,c.anisotropy=e.anisotropy,c.needsUpdate=!0,c}async initialize(e){try{return this.renderer=e.renderer,this.enabled=e.enabled,this.isSupported()?T.Result.ok(void 0):T.Result.err(new T.ThreeViewerError("Path tracing is not supported in this environment",T.ErrorCode.PATH_TRACING_INIT_FAILED,{reason:"WebGL2 or required extensions not available"}))}catch(t){return T.Result.err(new T.ThreeViewerError("Failed to initialize path tracing",T.ErrorCode.PATH_TRACING_INIT_FAILED,{originalError:t}))}}createPathTracer(){if(this.disposed)return T.Result.err(new T.ThreeViewerError("Instance is disposed",T.ErrorCode.INVALID_STATE));try{const e=B(this.renderer)?this.renderer.getInternalRenderer():null;return e?(this.pathTracer=new Wr(e),this.pathTracer.tiles&&"set"in this.pathTracer.tiles&&this.pathTracer.tiles.set(1,1),this.pathTracer.bounces=this.settings.bounces,this.settings.transmissiveBounces!==void 0&&(this.pathTracer.transmissiveBounces=this.settings.transmissiveBounces),this.pathTracer.renderScale=this.settings.renderScale,this.pathTracer.dynamicLowRes=this.settings.dynamicLowRes,this.pathTracer.lowResScale=this.settings.lowResScale,this.pathTracer.environmentIntensity!==void 0&&(this.pathTracer.environmentIntensity=2),e.toneMapping!==A.ACESFilmicToneMapping&&(e.toneMapping=A.ACESFilmicToneMapping,e.toneMappingExposure=1.5),e.autoClear=!1,e.setRenderTarget(null),T.Result.ok(void 0)):T.Result.err(new T.ThreeViewerError("Renderer not ready, will retry",T.ErrorCode.RENDERER_NOT_INITIALIZED))}catch(e){return T.Result.err(new T.ThreeViewerError("Failed to create path tracer",T.ErrorCode.PATH_TRACING_INIT_FAILED,{originalError:e}))}}setEnabled(e){if(this.enabled!==e&&(this.enabled=e,!e)){this.reset(),this.sceneInitialized=!1;const t=B(this.renderer)?this.renderer.getInternalRenderer():null;t&&(t.autoClear=!0)}}disableAfterSelfPause(e){this.enabled=!1,this.events.emit("pathtracing:paused",{samples:this.sampleCount,reason:e})}updateSettings(e){this.settings={...this.settings,...e},e.enablePathTracing!==void 0&&this.setEnabled(e.enablePathTracing),this.pathTracer&&(e.bounces!==void 0&&(this.pathTracer.bounces=e.bounces),e.transmissiveBounces!==void 0&&(this.pathTracer.transmissiveBounces=e.transmissiveBounces),e.renderScale!==void 0&&(this.pathTracer.renderScale=e.renderScale),e.lowResScale!==void 0&&(this.pathTracer.lowResScale=e.lowResScale),e.dynamicLowRes!==void 0&&(this.pathTracer.dynamicLowRes=e.dynamicLowRes))}async render(e,t){if(this.disposed)return T.Result.ok(void 0);const r=this.renderer;if(!r)return T.Result.ok(void 0);if(!this.enabled)return this.renderWhileDisabled(e,t);if(!this.pathTracer){const i=this.ensurePathTracerCreated(r,e,t);if(i)return i}try{const i=this.extractThreeObjects(e,t);if(!i)return T.Result.err(new T.ThreeViewerError("Could not extract Three.js scene or camera",T.ErrorCode.INVALID_PARAMETER));const{threeScene:o,threeCamera:a}=i;if(!this.sceneInitialized){const c=await this.initializeSceneForPathTracing(r,e,t,o,a);if(c)return c}return this.sceneInitialized?this.accumulateSample(r,e,t):r.render(e,t)}catch(i){return T.Result.err(new T.ThreeViewerError("Failed to render with path tracing",T.ErrorCode.RENDER_FAILED,{originalError:i}))}}ensurePathTracerCreated(e,t,r){var o;this.createAttempts++;const i=this.createPathTracer();return i.ok?(this.createAttempts=0,null):(this.createAttempts<this.maxCreateAttempts&&((o=i.error)==null?void 0:o.message)==="Renderer not ready, will retry"||(this.disableAfterSelfPause("gave-up"),this.createAttempts=0),e.render(t,r))}extractThreeObjects(e,t){let r=null,i=null;return T.hasInternalRenderer(e)&&(r=e.getInternalRenderer()),T.hasInternalRenderer(t)&&(i=t.getInternalRenderer()),!r||!i?null:{threeScene:r,threeCamera:i}}async initializeSceneForPathTracing(e,t,r,i,o){var a,c,h;try{const d=i.__originalEnvironmentTexture;if(!i.environment&&!d)return this.environmentWaitFrames++,this.environmentWaitFrames>=this.maxEnvironmentWaitFrames&&(this.disableAfterSelfPause("gave-up"),this.environmentWaitFrames=0),e.render(t,r);if(this.environmentWaitFrames=0,d&&d.mapping===A.EquirectangularReflectionMapping){let m=d;if(d.image instanceof HTMLImageElement)if(this.convertedEnvTexture)m=this.convertedEnvTexture;else{const n=this.convertToDataTexture(d);if(!n)throw new Error("Failed to convert environment texture to DataTexture");this.convertedEnvTexture=n,m=n}const f=i.environment;i.environment=m;try{const n=d.image;n&&!("data"in n&&n.data)&&n instanceof HTMLImageElement&&!n.complete&&await new Promise(x=>{n.onload=()=>{d.needsUpdate=!0,x()},n.onerror=()=>{x()},n.complete&&x()}),(a=this.pathTracer)==null||a.setScene(i,o),this.sceneInitialized=!0,i.environment=f}catch(n){throw i.environment=f,n}}else if(((c=i.environment)==null?void 0:c.mapping)===A.EquirectangularReflectionMapping)(h=this.pathTracer)==null||h.setScene(i,o),this.sceneInitialized=!0;else return this.disableAfterSelfPause("gave-up"),e.render(t,r)}catch(d){return console.warn("Scene initialization error:",d),e.render(t,r)}return null}accumulateSample(e,t,r){var o;if(this.sampleCount===0)try{(o=this.pathTracer)==null||o.updateLights()}catch(a){console.warn("Failed to update lights for path tracing:",a)}const i=e.render(t,r);return i.ok?(this.accumulateOneSample(),this.sampleCount++,this.sampleCount===this.settings.samples?this.captureCompletedFrame():T.Result.ok(void 0)):i}renderWhileDisabled(e,t){return this.renderer?this.sampleCount>=this.settings.samples&&this.sampleCount>0?(this.pathTracer&&B(this.renderer)&&this.renderer.getInternalRenderer().setRenderTarget(null),T.Result.ok(void 0)):this.renderer.render(e,t):T.Result.ok(void 0)}accumulateOneSample(){const e=B(this.renderer)?this.renderer.getInternalRenderer():null;if(!e)throw new Error("Three.js renderer not available");const t=e.autoClear,r=e.getRenderTarget();e.autoClear=!1,this.pathTracer&&this.pathTracer.renderSample(),e.autoClear=t,e.setRenderTarget(r)}captureCompletedFrame(){const e=B(this.renderer)?this.renderer.getInternalRenderer():null;if(e&&this.pathTracer)try{const t=e.autoClear;e.autoClear=!0,e.setRenderTarget(null),e.clear(!0,!0,!0);const r=this.pathTracer.copyQuad;r&&typeof r.render=="function"?r.render(e):(e.autoClear=!1,this.pathTracer.renderSample()),e.autoClear=t}catch(t){console.warn("Failed to present path traced result:",t)}return this.disableAfterSelfPause("completed"),this.disposeTimer=setTimeout(()=>{this.disposeTimer=null,!this.disposed&&this.disposePathTracingResources()},100),T.Result.ok(void 0)}getSampleCount(){return this.sampleCount}isEnabled(){return this.enabled}isPathTracerDisposed(){return this.disposed}reset(){const e=performance.now();e-this.lastResetTime<50||(this.lastResetTime=e,this.sampleCount=0,this.pathTracer&&(this.pathTracer.reset(),this.sceneInitialized=!1))}disposePathTracingResources(){if(this.pathTracer){try{this.pathTracer.dispose()}catch(e){console.warn("Failed to dispose path tracer:",e)}this.pathTracer=null}if(this.convertedEnvTexture&&(this.convertedEnvTexture.dispose(),this.convertedEnvTexture=null),this.renderer){const e=B(this.renderer)?this.renderer.getInternalRenderer():null;e&&(e.autoClear=!0)}this.sceneInitialized=!1,this.createAttempts=0}dispose(){if(this.disposed=!0,this.events.removeAllListeners(),this.disposeTimer!==null&&(clearTimeout(this.disposeTimer),this.disposeTimer=null),this.pathTracer){try{this.pathTracer.dispose()}catch(e){console.warn("Failed to dispose path tracer during service disposal:",e)}this.pathTracer=null}this.convertedEnvTexture&&(this.convertedEnvTexture.dispose(),this.convertedEnvTexture=null),this.sampleCount=0,this.sceneInitialized=!1,this.createAttempts=0,this.renderer=null}isSupported(){return document.createElement("canvas").getContext("webgl2")!==null}}exports.ThreePathTracingService=Lr;