var LifeSubdivision=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var t=1e3,n=1001,r=1002,i=1003,a=1004,o=1005,s=1006,c=1007,l=1008,u=1009,d=1010,f=1011,p=1012,m=1013,h=1014,g=1015,_=1016,v=1017,y=1018,b=1020,x=35902,S=35899,C=1021,w=1022,T=1023,E=1026,D=1027,O=1028,k=1029,A=1030,ee=1031,te=1033,j=33776,ne=33777,M=33778,N=33779,P=35840,re=35841,F=35842,ie=35843,ae=36196,oe=37492,se=37496,ce=37488,le=37489,ue=37490,de=37491,I=37808,L=37809,fe=37810,pe=37811,me=37812,he=37813,ge=37814,_e=37815,ve=37816,ye=37817,be=37818,xe=37819,Se=37820,Ce=37821,we=36492,Te=36494,R=36495,Ee=36283,De=36284,Oe=36285,z=36286,ke=2300,B=2301,V=2302,Ae=2303,je=2400,Me=2401,Ne=2402,Pe=3200,Fe=`srgb`,Ie=`srgb-linear`,Le=`linear`,Re=`srgb`,ze=7680,Be=35044,Ve=2e3;function He(e){for(let t=e.length-1;t>=0;--t)if(e[t]>=65535)return!0;return!1}function Ue(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function We(e){return document.createElementNS(`http://www.w3.org/1999/xhtml`,e)}function Ge(){let e=We(`canvas`);return e.style.display=`block`,e}var Ke={},qe=null;function Je(...e){let t=`THREE.`+e.shift();qe?qe(`log`,t,...e):console.log(t,...e)}function Ye(e){let t=e[0];if(typeof t==`string`&&t.startsWith(`TSL:`)){let t=e[1];t&&t.isStackTrace?e[0]+=` `+t.getLocation():e[1]=`Stack trace not available. Enable "THREE.Node.captureStackTrace" to capture stack traces.`}return e}function H(...e){e=Ye(e);let t=`THREE.`+e.shift();if(qe)qe(`warn`,t,...e);else{let n=e[0];n&&n.isStackTrace?console.warn(n.getError(t)):console.warn(t,...e)}}function U(...e){e=Ye(e);let t=`THREE.`+e.shift();if(qe)qe(`error`,t,...e);else{let n=e[0];n&&n.isStackTrace?console.error(n.getError(t)):console.error(t,...e)}}function Xe(...e){let t=e.join(` `);t in Ke||(Ke[t]=!0,H(...e))}function Ze(e,t,n){return new Promise(function(r,i){function a(){switch(e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0)){case e.WAIT_FAILED:i();break;case e.TIMEOUT_EXPIRED:setTimeout(a,n);break;default:r()}}setTimeout(a,n)})}var Qe={0:1,2:6,4:7,3:5,1:0,6:2,7:4,5:3},$e=class{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});let n=this._listeners;n[e]===void 0&&(n[e]=[]),n[e].indexOf(t)===-1&&n[e].push(t)}hasEventListener(e,t){let n=this._listeners;return n===void 0?!1:n[e]!==void 0&&n[e].indexOf(t)!==-1}removeEventListener(e,t){let n=this._listeners;if(n===void 0)return;let r=n[e];if(r!==void 0){let e=r.indexOf(t);e!==-1&&r.splice(e,1)}}dispatchEvent(e){let t=this._listeners;if(t===void 0)return;let n=t[e.type];if(n!==void 0){e.target=this;let t=n.slice(0);for(let n=0,r=t.length;n>8&255]+et[e>>16&255]+et[e>>24&255]+`-`+et[t&255]+et[t>>8&255]+`-`+et[t>>16&15|64]+et[t>>24&255]+`-`+et[n&63|128]+et[n>>8&255]+`-`+et[n>>16&255]+et[n>>24&255]+et[r&255]+et[r>>8&255]+et[r>>16&255]+et[r>>24&255]).toLowerCase()}function W(e,t,n){return Math.max(t,Math.min(n,e))}function it(e,t){return(e%t+t)%t}function at(e,t,n){return(1-n)*e+n*t}function ot(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return e/4294967295;case Uint16Array:return e/65535;case Uint8Array:return e/255;case Int32Array:return Math.max(e/2147483647,-1);case Int16Array:return Math.max(e/32767,-1);case Int8Array:return Math.max(e/127,-1);default:throw Error(`Invalid component type.`)}}function st(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return Math.round(e*4294967295);case Uint16Array:return Math.round(e*65535);case Uint8Array:return Math.round(e*255);case Int32Array:return Math.round(e*2147483647);case Int16Array:return Math.round(e*32767);case Int8Array:return Math.round(e*127);default:throw Error(`Invalid component type.`)}}var G=class e{constructor(t=0,n=0){e.prototype.isVector2=!0,this.x=t,this.y=n}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw Error(`index is out of range: `+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw Error(`index is out of range: `+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){let t=this.x,n=this.y,r=e.elements;return this.x=r[0]*t+r[3]*n+r[6],this.y=r[1]*t+r[4]*n+r[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=W(this.x,e.x,t.x),this.y=W(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=W(this.x,e,t),this.y=W(this.y,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(W(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){let t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;let n=this.dot(e)/t;return Math.acos(W(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let t=this.x-e.x,n=this.y-e.y;return t*t+n*n}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){let n=Math.cos(t),r=Math.sin(t),i=this.x-e.x,a=this.y-e.y;return this.x=i*n-a*r+e.x,this.y=i*r+a*n+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}},ct=class{constructor(e=0,t=0,n=0,r=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=n,this._w=r}static slerpFlat(e,t,n,r,i,a,o){let s=n[r+0],c=n[r+1],l=n[r+2],u=n[r+3],d=i[a+0],f=i[a+1],p=i[a+2],m=i[a+3];if(u!==m||s!==d||c!==f||l!==p){let e=s*d+c*f+l*p+u*m;e<0&&(d=-d,f=-f,p=-p,m=-m,e=-e);let t=1-o;if(e<.9995){let n=Math.acos(e),r=Math.sin(n);t=Math.sin(t*n)/r,o=Math.sin(o*n)/r,s=s*t+d*o,c=c*t+f*o,l=l*t+p*o,u=u*t+m*o}else{s=s*t+d*o,c=c*t+f*o,l=l*t+p*o,u=u*t+m*o;let e=1/Math.sqrt(s*s+c*c+l*l+u*u);s*=e,c*=e,l*=e,u*=e}}e[t]=s,e[t+1]=c,e[t+2]=l,e[t+3]=u}static multiplyQuaternionsFlat(e,t,n,r,i,a){let o=n[r],s=n[r+1],c=n[r+2],l=n[r+3],u=i[a],d=i[a+1],f=i[a+2],p=i[a+3];return e[t]=o*p+l*u+s*f-c*d,e[t+1]=s*p+l*d+c*u-o*f,e[t+2]=c*p+l*f+o*d-s*u,e[t+3]=l*p-o*u-s*d-c*f,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,n,r){return this._x=e,this._y=t,this._z=n,this._w=r,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){let n=e._x,r=e._y,i=e._z,a=e._order,o=Math.cos,s=Math.sin,c=o(n/2),l=o(r/2),u=o(i/2),d=s(n/2),f=s(r/2),p=s(i/2);switch(a){case`XYZ`:this._x=d*l*u+c*f*p,this._y=c*f*u-d*l*p,this._z=c*l*p+d*f*u,this._w=c*l*u-d*f*p;break;case`YXZ`:this._x=d*l*u+c*f*p,this._y=c*f*u-d*l*p,this._z=c*l*p-d*f*u,this._w=c*l*u+d*f*p;break;case`ZXY`:this._x=d*l*u-c*f*p,this._y=c*f*u+d*l*p,this._z=c*l*p+d*f*u,this._w=c*l*u-d*f*p;break;case`ZYX`:this._x=d*l*u-c*f*p,this._y=c*f*u+d*l*p,this._z=c*l*p-d*f*u,this._w=c*l*u+d*f*p;break;case`YZX`:this._x=d*l*u+c*f*p,this._y=c*f*u+d*l*p,this._z=c*l*p-d*f*u,this._w=c*l*u-d*f*p;break;case`XZY`:this._x=d*l*u-c*f*p,this._y=c*f*u-d*l*p,this._z=c*l*p+d*f*u,this._w=c*l*u+d*f*p;break;default:H(`Quaternion: .setFromEuler() encountered an unknown order: `+a)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){let n=t/2,r=Math.sin(n);return this._x=e.x*r,this._y=e.y*r,this._z=e.z*r,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(e){let t=e.elements,n=t[0],r=t[4],i=t[8],a=t[1],o=t[5],s=t[9],c=t[2],l=t[6],u=t[10],d=n+o+u;if(d>0){let e=.5/Math.sqrt(d+1);this._w=.25/e,this._x=(l-s)*e,this._y=(i-c)*e,this._z=(a-r)*e}else if(n>o&&n>u){let e=2*Math.sqrt(1+n-o-u);this._w=(l-s)/e,this._x=.25*e,this._y=(r+a)/e,this._z=(i+c)/e}else if(o>u){let e=2*Math.sqrt(1+o-n-u);this._w=(i-c)/e,this._x=(r+a)/e,this._y=.25*e,this._z=(s+l)/e}else{let e=2*Math.sqrt(1+u-n-o);this._w=(a-r)/e,this._x=(i+c)/e,this._y=(s+l)/e,this._z=.25*e}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let n=e.dot(t)+1;return n<1e-8?(n=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=n):(this._x=0,this._y=-e.z,this._z=e.y,this._w=n)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=n),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(W(this.dot(e),-1,1)))}rotateTowards(e,t){let n=this.angleTo(e);if(n===0)return this;let r=Math.min(1,t/n);return this.slerp(e,r),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x*=e,this._y*=e,this._z*=e,this._w*=e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){let n=e._x,r=e._y,i=e._z,a=e._w,o=t._x,s=t._y,c=t._z,l=t._w;return this._x=n*l+a*o+r*c-i*s,this._y=r*l+a*s+i*o-n*c,this._z=i*l+a*c+n*s-r*o,this._w=a*l-n*o-r*s-i*c,this._onChangeCallback(),this}slerp(e,t){let n=e._x,r=e._y,i=e._z,a=e._w,o=this.dot(e);o<0&&(n=-n,r=-r,i=-i,a=-a,o=-o);let s=1-t;if(o<.9995){let e=Math.acos(o),c=Math.sin(e);s=Math.sin(s*e)/c,t=Math.sin(t*e)/c,this._x=this._x*s+n*t,this._y=this._y*s+r*t,this._z=this._z*s+i*t,this._w=this._w*s+a*t,this._onChangeCallback()}else this._x=this._x*s+n*t,this._y=this._y*s+r*t,this._z=this._z*s+i*t,this._w=this._w*s+a*t,this.normalize();return this}slerpQuaternions(e,t,n){return this.copy(e).slerp(t,n)}random(){let e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),n=Math.random(),r=Math.sqrt(1-n),i=Math.sqrt(n);return this.set(r*Math.sin(e),r*Math.cos(e),i*Math.sin(t),i*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}},K=class e{constructor(t=0,n=0,r=0){e.prototype.isVector3=!0,this.x=t,this.y=n,this.z=r}set(e,t,n){return n===void 0&&(n=this.z),this.x=e,this.y=t,this.z=n,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw Error(`index is out of range: `+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw Error(`index is out of range: `+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(ut.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(ut.setFromAxisAngle(e,t))}applyMatrix3(e){let t=this.x,n=this.y,r=this.z,i=e.elements;return this.x=i[0]*t+i[3]*n+i[6]*r,this.y=i[1]*t+i[4]*n+i[7]*r,this.z=i[2]*t+i[5]*n+i[8]*r,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){let t=this.x,n=this.y,r=this.z,i=e.elements,a=1/(i[3]*t+i[7]*n+i[11]*r+i[15]);return this.x=(i[0]*t+i[4]*n+i[8]*r+i[12])*a,this.y=(i[1]*t+i[5]*n+i[9]*r+i[13])*a,this.z=(i[2]*t+i[6]*n+i[10]*r+i[14])*a,this}applyQuaternion(e){let t=this.x,n=this.y,r=this.z,i=e.x,a=e.y,o=e.z,s=e.w,c=2*(a*r-o*n),l=2*(o*t-i*r),u=2*(i*n-a*t);return this.x=t+s*c+a*u-o*l,this.y=n+s*l+o*c-i*u,this.z=r+s*u+i*l-a*c,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){let t=this.x,n=this.y,r=this.z,i=e.elements;return this.x=i[0]*t+i[4]*n+i[8]*r,this.y=i[1]*t+i[5]*n+i[9]*r,this.z=i[2]*t+i[6]*n+i[10]*r,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=W(this.x,e.x,t.x),this.y=W(this.y,e.y,t.y),this.z=W(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=W(this.x,e,t),this.y=W(this.y,e,t),this.z=W(this.z,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(W(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){let n=e.x,r=e.y,i=e.z,a=t.x,o=t.y,s=t.z;return this.x=r*s-i*o,this.y=i*a-n*s,this.z=n*o-r*a,this}projectOnVector(e){let t=e.lengthSq();if(t===0)return this.set(0,0,0);let n=e.dot(this)/t;return this.copy(e).multiplyScalar(n)}projectOnPlane(e){return lt.copy(this).projectOnVector(e),this.sub(lt)}reflect(e){return this.sub(lt.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){let t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;let n=this.dot(e)/t;return Math.acos(W(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let t=this.x-e.x,n=this.y-e.y,r=this.z-e.z;return t*t+n*n+r*r}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,n){let r=Math.sin(t)*e;return this.x=r*Math.sin(n),this.y=Math.cos(t)*e,this.z=r*Math.cos(n),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,n){return this.x=e*Math.sin(t),this.y=n,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){let t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){let t=this.setFromMatrixColumn(e,0).length(),n=this.setFromMatrixColumn(e,1).length(),r=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=n,this.z=r,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){let e=Math.random()*Math.PI*2,t=Math.random()*2-1,n=Math.sqrt(1-t*t);return this.x=n*Math.cos(e),this.y=t,this.z=n*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}},lt=new K,ut=new ct,q=class e{constructor(t,n,r,i,a,o,s,c,l){e.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],t!==void 0&&this.set(t,n,r,i,a,o,s,c,l)}set(e,t,n,r,i,a,o,s,c){let l=this.elements;return l[0]=e,l[1]=r,l[2]=o,l[3]=t,l[4]=i,l[5]=s,l[6]=n,l[7]=a,l[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){let t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],this}extractBasis(e,t,n){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),n.setFromMatrix3Column(this,2),this}setFromMatrix4(e){let t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){let n=e.elements,r=t.elements,i=this.elements,a=n[0],o=n[3],s=n[6],c=n[1],l=n[4],u=n[7],d=n[2],f=n[5],p=n[8],m=r[0],h=r[3],g=r[6],_=r[1],v=r[4],y=r[7],b=r[2],x=r[5],S=r[8];return i[0]=a*m+o*_+s*b,i[3]=a*h+o*v+s*x,i[6]=a*g+o*y+s*S,i[1]=c*m+l*_+u*b,i[4]=c*h+l*v+u*x,i[7]=c*g+l*y+u*S,i[2]=d*m+f*_+p*b,i[5]=d*h+f*v+p*x,i[8]=d*g+f*y+p*S,this}multiplyScalar(e){let t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){let e=this.elements,t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8];return t*a*l-t*o*c-n*i*l+n*o*s+r*i*c-r*a*s}invert(){let e=this.elements,t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8],u=l*a-o*c,d=o*s-l*i,f=c*i-a*s,p=t*u+n*d+r*f;if(p===0)return this.set(0,0,0,0,0,0,0,0,0);let m=1/p;return e[0]=u*m,e[1]=(r*c-l*n)*m,e[2]=(o*n-r*a)*m,e[3]=d*m,e[4]=(l*t-r*s)*m,e[5]=(r*i-o*t)*m,e[6]=f*m,e[7]=(n*s-c*t)*m,e[8]=(a*t-n*i)*m,this}transpose(){let e,t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){let t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,n,r,i,a,o){let s=Math.cos(i),c=Math.sin(i);return this.set(n*s,n*c,-n*(s*a+c*o)+a+e,-r*c,r*s,-r*(-c*a+s*o)+o+t,0,0,1),this}scale(e,t){return this.premultiply(dt.makeScale(e,t)),this}rotate(e){return this.premultiply(dt.makeRotation(-e)),this}translate(e,t){return this.premultiply(dt.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){let t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,n,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){let t=this.elements,n=e.elements;for(let e=0;e<9;e++)if(t[e]!==n[e])return!1;return!0}fromArray(e,t=0){for(let n=0;n<9;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){let n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e}clone(){return new this.constructor().fromArray(this.elements)}},dt=new q,ft=new q().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),pt=new q().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function mt(){let e={enabled:!0,workingColorSpace:Ie,spaces:{},convert:function(e,t,n){return this.enabled===!1||t===n||!t||!n?e:(this.spaces[t].transfer===`srgb`&&(e.r=ht(e.r),e.g=ht(e.g),e.b=ht(e.b)),this.spaces[t].primaries!==this.spaces[n].primaries&&(e.applyMatrix3(this.spaces[t].toXYZ),e.applyMatrix3(this.spaces[n].fromXYZ)),this.spaces[n].transfer===`srgb`&&(e.r=gt(e.r),e.g=gt(e.g),e.b=gt(e.b)),e)},workingToColorSpace:function(e,t){return this.convert(e,this.workingColorSpace,t)},colorSpaceToWorking:function(e,t){return this.convert(e,t,this.workingColorSpace)},getPrimaries:function(e){return this.spaces[e].primaries},getTransfer:function(e){return e===``?Le:this.spaces[e].transfer},getToneMappingMode:function(e){return this.spaces[e].outputColorSpaceConfig.toneMappingMode||`standard`},getLuminanceCoefficients:function(e,t=this.workingColorSpace){return e.fromArray(this.spaces[t].luminanceCoefficients)},define:function(e){Object.assign(this.spaces,e)},_getMatrix:function(e,t,n){return e.copy(this.spaces[t].toXYZ).multiply(this.spaces[n].fromXYZ)},_getDrawingBufferColorSpace:function(e){return this.spaces[e].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(e=this.workingColorSpace){return this.spaces[e].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(t,n){return Xe(`ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace().`),e.workingToColorSpace(t,n)},toWorkingColorSpace:function(t,n){return Xe(`ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking().`),e.colorSpaceToWorking(t,n)}},t=[.64,.33,.3,.6,.15,.06],n=[.2126,.7152,.0722],r=[.3127,.329];return e.define({[Ie]:{primaries:t,whitePoint:r,transfer:Le,toXYZ:ft,fromXYZ:pt,luminanceCoefficients:n,workingColorSpaceConfig:{unpackColorSpace:Fe},outputColorSpaceConfig:{drawingBufferColorSpace:Fe}},[Fe]:{primaries:t,whitePoint:r,transfer:Re,toXYZ:ft,fromXYZ:pt,luminanceCoefficients:n,outputColorSpaceConfig:{drawingBufferColorSpace:Fe}}}),e}var J=mt();function ht(e){return e<.04045?e*.0773993808:(e*.9478672986+.0521327014)**2.4}function gt(e){return e<.0031308?e*12.92:1.055*e**.41666-.055}var _t,vt=class{static getDataURL(e,t=`image/png`){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>`u`)return e.src;let n;if(e instanceof HTMLCanvasElement)n=e;else{_t===void 0&&(_t=We(`canvas`)),_t.width=e.width,_t.height=e.height;let t=_t.getContext(`2d`);e instanceof ImageData?t.putImageData(e,0,0):t.drawImage(e,0,0,e.width,e.height),n=_t}return n.toDataURL(t)}static sRGBToLinear(e){if(typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof ImageBitmap<`u`&&e instanceof ImageBitmap){let t=We(`canvas`);t.width=e.width,t.height=e.height;let n=t.getContext(`2d`);n.drawImage(e,0,0,e.width,e.height);let r=n.getImageData(0,0,e.width,e.height),i=r.data;for(let e=0;e1),this.pmremVersion=0}get width(){return this.source.getSize(Ct).x}get height(){return this.source.getSize(Ct).y}get depth(){return this.source.getSize(Ct).z}get image(){return this.source.data}set image(e=null){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.renderTarget=e.renderTarget,this.isRenderTargetTexture=e.isRenderTargetTexture,this.isArrayTexture=e.isArrayTexture,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}setValues(e){for(let t in e){let n=e[t];if(n===void 0){H(`Texture.setValues(): parameter '${t}' has value of undefined.`);continue}let r=this[t];if(r===void 0){H(`Texture.setValues(): property '${t}' does not exist.`);continue}r&&n&&r.isVector2&&n.isVector2||r&&n&&r.isVector3&&n.isVector3||r&&n&&r.isMatrix3&&n.isMatrix3?r.copy(n):this[t]=n}}toJSON(e){let t=e===void 0||typeof e==`string`;if(!t&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];let n={metadata:{version:4.7,type:`Texture`,generator:`Texture.toJSON`},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(n.userData=this.userData),t||(e.textures[this.uuid]=n),n}dispose(){this.dispatchEvent({type:`dispose`})}transformUv(e){if(this.mapping!==300)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case t:e.x-=Math.floor(e.x);break;case n:e.x=e.x<0?0:1;break;case r:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x-=Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case t:e.y-=Math.floor(e.y);break;case n:e.y=e.y<0?0:1;break;case r:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y-=Math.floor(e.y);break}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}};wt.DEFAULT_IMAGE=null,wt.DEFAULT_MAPPING=300,wt.DEFAULT_ANISOTROPY=1;var Tt=class e{constructor(t=0,n=0,r=0,i=1){e.prototype.isVector4=!0,this.x=t,this.y=n,this.z=r,this.w=i}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,n,r){return this.x=e,this.y=t,this.z=n,this.w=r,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw Error(`index is out of range: `+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw Error(`index is out of range: `+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w===void 0?1:e.w,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){let t=this.x,n=this.y,r=this.z,i=this.w,a=e.elements;return this.x=a[0]*t+a[4]*n+a[8]*r+a[12]*i,this.y=a[1]*t+a[5]*n+a[9]*r+a[13]*i,this.z=a[2]*t+a[6]*n+a[10]*r+a[14]*i,this.w=a[3]*t+a[7]*n+a[11]*r+a[15]*i,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);let t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,n,r,i,a=.01,o=.1,s=e.elements,c=s[0],l=s[4],u=s[8],d=s[1],f=s[5],p=s[9],m=s[2],h=s[6],g=s[10];if(Math.abs(l-d)s&&e>_?e_?s1);this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return new this.constructor().copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let t=0,n=e.textures.length;t>>0}enable(e){this.mask|=1<1){for(let e=0;e1){for(let e=0;e0&&(r.userData=this.userData),r.layers=this.layers.mask,r.matrix=this.matrix.toArray(),r.up=this.up.toArray(),this.pivot!==null&&(r.pivot=this.pivot.toArray()),this.matrixAutoUpdate===!1&&(r.matrixAutoUpdate=!1),this.morphTargetDictionary!==void 0&&(r.morphTargetDictionary=Object.assign({},this.morphTargetDictionary)),this.morphTargetInfluences!==void 0&&(r.morphTargetInfluences=this.morphTargetInfluences.slice()),this.isInstancedMesh&&(r.type=`InstancedMesh`,r.count=this.count,r.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(r.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(r.type=`BatchedMesh`,r.perObjectFrustumCulled=this.perObjectFrustumCulled,r.sortObjects=this.sortObjects,r.drawRanges=this._drawRanges,r.reservedRanges=this._reservedRanges,r.geometryInfo=this._geometryInfo.map(e=>({...e,boundingBox:e.boundingBox?e.boundingBox.toJSON():void 0,boundingSphere:e.boundingSphere?e.boundingSphere.toJSON():void 0})),r.instanceInfo=this._instanceInfo.map(e=>({...e})),r.availableInstanceIds=this._availableInstanceIds.slice(),r.availableGeometryIds=this._availableGeometryIds.slice(),r.nextIndexStart=this._nextIndexStart,r.nextVertexStart=this._nextVertexStart,r.geometryCount=this._geometryCount,r.maxInstanceCount=this._maxInstanceCount,r.maxVertexCount=this._maxVertexCount,r.maxIndexCount=this._maxIndexCount,r.geometryInitialized=this._geometryInitialized,r.matricesTexture=this._matricesTexture.toJSON(e),r.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(r.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(r.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(r.boundingBox=this.boundingBox.toJSON()));function i(t,n){return t[n.uuid]===void 0&&(t[n.uuid]=n.toJSON(e)),n.uuid}if(this.isScene)this.background&&(this.background.isColor?r.background=this.background.toJSON():this.background.isTexture&&(r.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(r.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){r.geometry=i(e.geometries,this.geometry);let t=this.geometry.parameters;if(t!==void 0&&t.shapes!==void 0){let n=t.shapes;if(Array.isArray(n))for(let t=0,r=n.length;t0){r.children=[];for(let t=0;t0){r.animations=[];for(let t=0;t0&&(n.geometries=t),r.length>0&&(n.materials=r),i.length>0&&(n.textures=i),o.length>0&&(n.images=o),s.length>0&&(n.shapes=s),c.length>0&&(n.skeletons=c),l.length>0&&(n.animations=l),u.length>0&&(n.nodes=u)}return n.object=r,n;function a(e){let t=[];for(let n in e){let r=e[n];delete r.metadata,t.push(r)}return t}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),e.pivot!==null&&(this.pivot=e.pivot.clone()),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.static=e.static,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let t=0;ts+l?(c.inputState.pinching=!1,this.dispatchEvent({type:`pinchend`,handedness:e.handedness,target:this})):!c.inputState.pinching&&o<=s-l&&(c.inputState.pinching=!0,this.dispatchEvent({type:`pinchstart`,handedness:e.handedness,target:this}))}else s!==null&&e.gripSpace&&(i=t.getPose(e.gripSpace,n),i!==null&&(s.matrix.fromArray(i.transform.matrix),s.matrix.decompose(s.position,s.rotation,s.scale),s.matrixWorldNeedsUpdate=!0,i.linearVelocity?(s.hasLinearVelocity=!0,s.linearVelocity.copy(i.linearVelocity)):s.hasLinearVelocity=!1,i.angularVelocity?(s.hasAngularVelocity=!0,s.angularVelocity.copy(i.angularVelocity)):s.hasAngularVelocity=!1));o!==null&&(r=t.getPose(e.targetRaySpace,n),r===null&&i!==null&&(r=i),r!==null&&(o.matrix.fromArray(r.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,r.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(r.linearVelocity)):o.hasLinearVelocity=!1,r.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(r.angularVelocity)):o.hasAngularVelocity=!1,this.dispatchEvent(on)))}return o!==null&&(o.visible=r!==null),s!==null&&(s.visible=i!==null),c!==null&&(c.visible=a!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){let n=new an;n.matrixAutoUpdate=!1,n.visible=!1,e.joints[t.jointName]=n,e.add(n)}return e.joints[t.jointName]}},cn={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},ln={h:0,s:0,l:0},un={h:0,s:0,l:0};function dn(e,t,n){return n<0&&(n+=1),n>1&&--n,n<1/6?e+(t-e)*6*n:n<1/2?t:n<2/3?e+(t-e)*6*(2/3-n):e}var Y=class{constructor(e,t,n){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,n)}set(e,t,n){if(t===void 0&&n===void 0){let t=e;t&&t.isColor?this.copy(t):typeof t==`number`?this.setHex(t):typeof t==`string`&&this.setStyle(t)}else this.setRGB(e,t,n);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=Fe){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,J.colorSpaceToWorking(this,t),this}setRGB(e,t,n,r=J.workingColorSpace){return this.r=e,this.g=t,this.b=n,J.colorSpaceToWorking(this,r),this}setHSL(e,t,n,r=J.workingColorSpace){if(e=it(e,1),t=W(t,0,1),n=W(n,0,1),t===0)this.r=this.g=this.b=n;else{let r=n<=.5?n*(1+t):n+t-n*t,i=2*n-r;this.r=dn(i,r,e+1/3),this.g=dn(i,r,e),this.b=dn(i,r,e-1/3)}return J.colorSpaceToWorking(this,r),this}setStyle(e,t=Fe){function n(t){t!==void 0&&parseFloat(t)<1&&H(`Color: Alpha component of `+e+` will be ignored.`)}let r;if(r=/^(\w+)\(([^\)]*)\)/.exec(e)){let i,a=r[1],o=r[2];switch(a){case`rgb`:case`rgba`:if(i=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(i[4]),this.setRGB(Math.min(255,parseInt(i[1],10))/255,Math.min(255,parseInt(i[2],10))/255,Math.min(255,parseInt(i[3],10))/255,t);if(i=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(i[4]),this.setRGB(Math.min(100,parseInt(i[1],10))/100,Math.min(100,parseInt(i[2],10))/100,Math.min(100,parseInt(i[3],10))/100,t);break;case`hsl`:case`hsla`:if(i=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(i[4]),this.setHSL(parseFloat(i[1])/360,parseFloat(i[2])/100,parseFloat(i[3])/100,t);break;default:H(`Color: Unknown color model `+e)}}else if(r=/^\#([A-Fa-f\d]+)$/.exec(e)){let n=r[1],i=n.length;if(i===3)return this.setRGB(parseInt(n.charAt(0),16)/15,parseInt(n.charAt(1),16)/15,parseInt(n.charAt(2),16)/15,t);if(i===6)return this.setHex(parseInt(n,16),t);H(`Color: Invalid hex color `+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=Fe){let n=cn[e.toLowerCase()];return n===void 0?H(`Color: Unknown color `+e):this.setHex(n,t),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=ht(e.r),this.g=ht(e.g),this.b=ht(e.b),this}copyLinearToSRGB(e){return this.r=gt(e.r),this.g=gt(e.g),this.b=gt(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=Fe){return J.workingToColorSpace(fn.copy(this),e),Math.round(W(fn.r*255,0,255))*65536+Math.round(W(fn.g*255,0,255))*256+Math.round(W(fn.b*255,0,255))}getHexString(e=Fe){return(`000000`+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=J.workingColorSpace){J.workingToColorSpace(fn.copy(this),t);let n=fn.r,r=fn.g,i=fn.b,a=Math.max(n,r,i),o=Math.min(n,r,i),s,c,l=(o+a)/2;if(o===a)s=0,c=0;else{let e=a-o;switch(c=l<=.5?e/(a+o):e/(2-a-o),a){case n:s=(r-i)/e+(r0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}},mn=new K,hn=new K,gn=new K,_n=new K,vn=new K,yn=new K,bn=new K,xn=new K,Sn=new K,Cn=new K,wn=new Tt,Tn=new Tt,En=new Tt,Dn=class e{constructor(e=new K,t=new K,n=new K){this.a=e,this.b=t,this.c=n}static getNormal(e,t,n,r){r.subVectors(n,t),mn.subVectors(e,t),r.cross(mn);let i=r.lengthSq();return i>0?r.multiplyScalar(1/Math.sqrt(i)):r.set(0,0,0)}static getBarycoord(e,t,n,r,i){mn.subVectors(r,t),hn.subVectors(n,t),gn.subVectors(e,t);let a=mn.dot(mn),o=mn.dot(hn),s=mn.dot(gn),c=hn.dot(hn),l=hn.dot(gn),u=a*c-o*o;if(u===0)return i.set(0,0,0),null;let d=1/u,f=(c*s-o*l)*d,p=(a*l-o*s)*d;return i.set(1-f-p,p,f)}static containsPoint(e,t,n,r){return this.getBarycoord(e,t,n,r,_n)===null?!1:_n.x>=0&&_n.y>=0&&_n.x+_n.y<=1}static getInterpolation(e,t,n,r,i,a,o,s){return this.getBarycoord(e,t,n,r,_n)===null?(s.x=0,s.y=0,`z`in s&&(s.z=0),`w`in s&&(s.w=0),null):(s.setScalar(0),s.addScaledVector(i,_n.x),s.addScaledVector(a,_n.y),s.addScaledVector(o,_n.z),s)}static getInterpolatedAttribute(e,t,n,r,i,a){return wn.setScalar(0),Tn.setScalar(0),En.setScalar(0),wn.fromBufferAttribute(e,t),Tn.fromBufferAttribute(e,n),En.fromBufferAttribute(e,r),a.setScalar(0),a.addScaledVector(wn,i.x),a.addScaledVector(Tn,i.y),a.addScaledVector(En,i.z),a}static isFrontFacing(e,t,n,r){return mn.subVectors(n,t),hn.subVectors(e,t),mn.cross(hn).dot(r)<0}set(e,t,n){return this.a.copy(e),this.b.copy(t),this.c.copy(n),this}setFromPointsAndIndices(e,t,n,r){return this.a.copy(e[t]),this.b.copy(e[n]),this.c.copy(e[r]),this}setFromAttributeAndIndices(e,t,n,r){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,n),this.c.fromBufferAttribute(e,r),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return mn.subVectors(this.c,this.b),hn.subVectors(this.a,this.b),mn.cross(hn).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(t){return e.getNormal(this.a,this.b,this.c,t)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(t,n){return e.getBarycoord(t,this.a,this.b,this.c,n)}getInterpolation(t,n,r,i,a){return e.getInterpolation(t,this.a,this.b,this.c,n,r,i,a)}containsPoint(t){return e.containsPoint(t,this.a,this.b,this.c)}isFrontFacing(t){return e.isFrontFacing(this.a,this.b,this.c,t)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){let n=this.a,r=this.b,i=this.c,a,o;vn.subVectors(r,n),yn.subVectors(i,n),xn.subVectors(e,n);let s=vn.dot(xn),c=yn.dot(xn);if(s<=0&&c<=0)return t.copy(n);Sn.subVectors(e,r);let l=vn.dot(Sn),u=yn.dot(Sn);if(l>=0&&u<=l)return t.copy(r);let d=s*u-l*c;if(d<=0&&s>=0&&l<=0)return a=s/(s-l),t.copy(n).addScaledVector(vn,a);Cn.subVectors(e,i);let f=vn.dot(Cn),p=yn.dot(Cn);if(p>=0&&f<=p)return t.copy(i);let m=f*c-s*p;if(m<=0&&c>=0&&p<=0)return o=c/(c-p),t.copy(n).addScaledVector(yn,o);let h=l*p-f*u;if(h<=0&&u-l>=0&&f-p>=0)return bn.subVectors(i,r),o=(u-l)/(u-l+(f-p)),t.copy(r).addScaledVector(bn,o);let g=1/(h+m+d);return a=m*g,o=d*g,t.copy(n).addScaledVector(vn,a).addScaledVector(yn,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}},On=class{constructor(e=new K(1/0,1/0,1/0),t=new K(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,n=e.length;t=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,An),An.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,n;return e.normal.x>0?(t=e.normal.x*this.min.x,n=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,n=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,n+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,n+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,n+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,n+=e.normal.z*this.min.z),t<=-e.constant&&n>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(Rn),zn.subVectors(this.max,Rn),Mn.subVectors(e.a,Rn),Nn.subVectors(e.b,Rn),Pn.subVectors(e.c,Rn),Fn.subVectors(Nn,Mn),In.subVectors(Pn,Nn),Ln.subVectors(Mn,Pn);let t=[0,-Fn.z,Fn.y,0,-In.z,In.y,0,-Ln.z,Ln.y,Fn.z,0,-Fn.x,In.z,0,-In.x,Ln.z,0,-Ln.x,-Fn.y,Fn.x,0,-In.y,In.x,0,-Ln.y,Ln.x,0];return!Hn(t,Mn,Nn,Pn,zn)||(t=[1,0,0,0,1,0,0,0,1],!Hn(t,Mn,Nn,Pn,zn))?!1:(Bn.crossVectors(Fn,In),t=[Bn.x,Bn.y,Bn.z],Hn(t,Mn,Nn,Pn,zn))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,An).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(An).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(kn[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),kn[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),kn[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),kn[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),kn[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),kn[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),kn[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),kn[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(kn),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(e){return this.min.fromArray(e.min),this.max.fromArray(e.max),this}},kn=[new K,new K,new K,new K,new K,new K,new K,new K],An=new K,jn=new On,Mn=new K,Nn=new K,Pn=new K,Fn=new K,In=new K,Ln=new K,Rn=new K,zn=new K,Bn=new K,Vn=new K;function Hn(e,t,n,r,i){for(let a=0,o=e.length-3;a<=o;a+=3){Vn.fromArray(e,a);let o=i.x*Math.abs(Vn.x)+i.y*Math.abs(Vn.y)+i.z*Math.abs(Vn.z),s=t.dot(Vn),c=n.dot(Vn),l=r.dot(Vn);if(Math.max(-Math.max(s,c,l),Math.min(s,c,l))>o)return!1}return!0}var Un=new K,Wn=new G,Gn=0,Kn=class{constructor(e,t,n=!1){if(Array.isArray(e))throw TypeError(`THREE.BufferAttribute: array should be a Typed Array.`);this.isBufferAttribute=!0,Object.defineProperty(this,`id`,{value:Gn++}),this.name=``,this.array=e,this.itemSize=t,this.count=e===void 0?0:e.length/t,this.normalized=n,this.usage=Be,this.updateRanges=[],this.gpuType=g,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,n){e*=this.itemSize,n*=t.itemSize;for(let r=0,i=this.itemSize;rthis.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius*=e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;Zn.subVectors(e,this.center);let t=Zn.lengthSq();if(t>this.radius*this.radius){let e=Math.sqrt(t),n=(e-this.radius)*.5;this.center.addScaledVector(Zn,n/e),this.radius+=n}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(Qn.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Zn.copy(e.center).add(Qn)),this.expandByPoint(Zn.copy(e.center).sub(Qn))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(e){return this.radius=e.radius,this.center.fromArray(e.center),this}},er=0,tr=new At,nr=new rn,rr=new K,ir=new On,ar=new On,or=new K,sr=class e extends $e{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,`id`,{value:er++}),this.uuid=rt(),this.name=``,this.type=`BufferGeometry`,this.index=null,this.indirect=null,this.indirectOffset=0,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={}}getIndex(){return this.index}setIndex(e){return Array.isArray(e)?this.index=new(He(e)?Jn:qn)(e,1):this.index=e,this}setIndirect(e,t=0){return this.indirect=e,this.indirectOffset=t,this}getIndirect(){return this.indirect}getAttribute(e){return this.attributes[e]}setAttribute(e,t){return this.attributes[e]=t,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return this.attributes[e]!==void 0}addGroup(e,t,n=0){this.groups.push({start:e,count:t,materialIndex:n})}clearGroups(){this.groups=[]}setDrawRange(e,t){this.drawRange.start=e,this.drawRange.count=t}applyMatrix4(e){let t=this.attributes.position;t!==void 0&&(t.applyMatrix4(e),t.needsUpdate=!0);let n=this.attributes.normal;if(n!==void 0){let t=new q().getNormalMatrix(e);n.applyNormalMatrix(t),n.needsUpdate=!0}let r=this.attributes.tangent;return r!==void 0&&(r.transformDirection(e),r.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}applyQuaternion(e){return tr.makeRotationFromQuaternion(e),this.applyMatrix4(tr),this}rotateX(e){return tr.makeRotationX(e),this.applyMatrix4(tr),this}rotateY(e){return tr.makeRotationY(e),this.applyMatrix4(tr),this}rotateZ(e){return tr.makeRotationZ(e),this.applyMatrix4(tr),this}translate(e,t,n){return tr.makeTranslation(e,t,n),this.applyMatrix4(tr),this}scale(e,t,n){return tr.makeScale(e,t,n),this.applyMatrix4(tr),this}lookAt(e){return nr.lookAt(e),nr.updateMatrix(),this.applyMatrix4(nr.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(rr).negate(),this.translate(rr.x,rr.y,rr.z),this}setFromPoints(e){let t=this.getAttribute(`position`);if(t===void 0){let t=[];for(let n=0,r=e.length;nt.count&&H(`BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.`),t.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new On);let e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){U(`BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.`,this),this.boundingBox.set(new K(-1/0,-1/0,-1/0),new K(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let e=0,n=t.length;e0&&(e.userData=this.userData),this.parameters!==void 0){let t=this.parameters;for(let n in t)t[n]!==void 0&&(e[n]=t[n]);return e}e.data={attributes:{}};let t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});let n=this.attributes;for(let t in n){let r=n[t];e.data.attributes[t]=r.toJSON(e.data)}let r={},i=!1;for(let t in this.morphAttributes){let n=this.morphAttributes[t],a=[];for(let t=0,r=n.length;t0&&(r[t]=a,i=!0)}i&&(e.data.morphAttributes=r,e.data.morphTargetsRelative=this.morphTargetsRelative);let a=this.groups;a.length>0&&(e.data.groups=JSON.parse(JSON.stringify(a)));let o=this.boundingSphere;return o!==null&&(e.data.boundingSphere=o.toJSON()),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;let t={};this.name=e.name;let n=e.index;n!==null&&this.setIndex(n.clone());let r=e.attributes;for(let e in r){let n=r[e];this.setAttribute(e,n.clone(t))}let i=e.morphAttributes;for(let e in i){let n=[],r=i[e];for(let e=0,i=r.length;e0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(let t in e){let n=e[t];if(n===void 0){H(`Material: parameter '${t}' has value of undefined.`);continue}let r=this[t];if(r===void 0){H(`Material: '${t}' is not a property of THREE.${this.type}.`);continue}r&&r.isColor?r.set(n):r&&r.isVector3&&n&&n.isVector3?r.copy(n):this[t]=n}}toJSON(e){let t=e===void 0||typeof e==`string`;t&&(e={textures:{},images:{}});let n={metadata:{version:4.7,type:`Material`,generator:`Material.toJSON`}};n.uuid=this.uuid,n.type=this.type,this.name!==``&&(n.name=this.name),this.color&&this.color.isColor&&(n.color=this.color.getHex()),this.roughness!==void 0&&(n.roughness=this.roughness),this.metalness!==void 0&&(n.metalness=this.metalness),this.sheen!==void 0&&(n.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(n.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(n.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(n.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(n.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(n.shininess=this.shininess),this.clearcoat!==void 0&&(n.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(n.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(n.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,n.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(n.sheenColorMap=this.sheenColorMap.toJSON(e).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(n.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid),this.dispersion!==void 0&&(n.dispersion=this.dispersion),this.iridescence!==void 0&&(n.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(n.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(n.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(n.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(n.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(n.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(n.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(n.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(n.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(n.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(n.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(n.lightMap=this.lightMap.toJSON(e).uuid,n.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(n.aoMap=this.aoMap.toJSON(e).uuid,n.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(n.bumpMap=this.bumpMap.toJSON(e).uuid,n.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(n.normalMap=this.normalMap.toJSON(e).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(n.displacementMap=this.displacementMap.toJSON(e).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(n.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(n.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(n.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(n.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(n.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(n.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(n.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(n.combine=this.combine)),this.envMapRotation!==void 0&&(n.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(n.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(n.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(n.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(n.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(n.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(n.size=this.size),this.shadowSide!==null&&(n.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(n.sizeAttenuation=this.sizeAttenuation),this.blending!==1&&(n.blending=this.blending),this.side!==0&&(n.side=this.side),this.vertexColors===!0&&(n.vertexColors=!0),this.opacity<1&&(n.opacity=this.opacity),this.transparent===!0&&(n.transparent=!0),this.blendSrc!==204&&(n.blendSrc=this.blendSrc),this.blendDst!==205&&(n.blendDst=this.blendDst),this.blendEquation!==100&&(n.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(n.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(n.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(n.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(n.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(n.blendAlpha=this.blendAlpha),this.depthFunc!==3&&(n.depthFunc=this.depthFunc),this.depthTest===!1&&(n.depthTest=this.depthTest),this.depthWrite===!1&&(n.depthWrite=this.depthWrite),this.colorWrite===!1&&(n.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(n.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==519&&(n.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(n.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(n.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==7680&&(n.stencilFail=this.stencilFail),this.stencilZFail!==7680&&(n.stencilZFail=this.stencilZFail),this.stencilZPass!==7680&&(n.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(n.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(n.rotation=this.rotation),this.polygonOffset===!0&&(n.polygonOffset=!0),this.polygonOffsetFactor!==0&&(n.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(n.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(n.linewidth=this.linewidth),this.dashSize!==void 0&&(n.dashSize=this.dashSize),this.gapSize!==void 0&&(n.gapSize=this.gapSize),this.scale!==void 0&&(n.scale=this.scale),this.dithering===!0&&(n.dithering=!0),this.alphaTest>0&&(n.alphaTest=this.alphaTest),this.alphaHash===!0&&(n.alphaHash=!0),this.alphaToCoverage===!0&&(n.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(n.premultipliedAlpha=!0),this.forceSinglePass===!0&&(n.forceSinglePass=!0),this.allowOverride===!1&&(n.allowOverride=!1),this.wireframe===!0&&(n.wireframe=!0),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!==`round`&&(n.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!==`round`&&(n.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(n.flatShading=!0),this.visible===!1&&(n.visible=!1),this.toneMapped===!1&&(n.toneMapped=!1),this.fog===!1&&(n.fog=!1),Object.keys(this.userData).length>0&&(n.userData=this.userData);function r(e){let t=[];for(let n in e){let r=e[n];delete r.metadata,t.push(r)}return t}if(t){let t=r(e.textures),i=r(e.images);t.length>0&&(n.textures=t),i.length>0&&(n.images=i)}return n}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;let t=e.clippingPlanes,n=null;if(t!==null){let e=t.length;n=Array(e);for(let r=0;r!==e;++r)n[r]=t[r].clone()}return this.clippingPlanes=n,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.allowOverride=e.allowOverride,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:`dispose`})}set needsUpdate(e){e===!0&&this.version++}},ur=new K,dr=new K,fr=new K,pr=new K,mr=new K,hr=new K,gr=new K,_r=class{constructor(e=new K,t=new K(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,ur)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);let n=t.dot(this.direction);return n<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,n)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){let t=ur.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(ur.copy(this.origin).addScaledVector(this.direction,t),ur.distanceToSquared(e))}distanceSqToSegment(e,t,n,r){dr.copy(e).add(t).multiplyScalar(.5),fr.copy(t).sub(e).normalize(),pr.copy(this.origin).sub(dr);let i=e.distanceTo(t)*.5,a=-this.direction.dot(fr),o=pr.dot(this.direction),s=-pr.dot(fr),c=pr.lengthSq(),l=Math.abs(1-a*a),u,d,f,p;if(l>0)if(u=a*s-o,d=a*o-s,p=i*l,u>=0)if(d>=-p)if(d<=p){let e=1/l;u*=e,d*=e,f=u*(u+a*d+2*o)+d*(a*u+d+2*s)+c}else d=i,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*s)+c;else d=-i,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*s)+c;else d<=-p?(u=Math.max(0,-(-a*i+o)),d=u>0?-i:Math.min(Math.max(-i,-s),i),f=-u*u+d*(d+2*s)+c):d<=p?(u=0,d=Math.min(Math.max(-i,-s),i),f=d*(d+2*s)+c):(u=Math.max(0,-(a*i+o)),d=u>0?i:Math.min(Math.max(-i,-s),i),f=-u*u+d*(d+2*s)+c);else d=a>0?-i:i,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*s)+c;return n&&n.copy(this.origin).addScaledVector(this.direction,u),r&&r.copy(dr).addScaledVector(fr,d),f}intersectSphere(e,t){ur.subVectors(e.center,this.origin);let n=ur.dot(this.direction),r=ur.dot(ur)-n*n,i=e.radius*e.radius;if(r>i)return null;let a=Math.sqrt(i-r),o=n-a,s=n+a;return s<0?null:o<0?this.at(s,t):this.at(o,t)}intersectsSphere(e){return e.radius<0?!1:this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){let t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;let n=-(this.origin.dot(e.normal)+e.constant)/t;return n>=0?n:null}intersectPlane(e,t){let n=this.distanceToPlane(e);return n===null?null:this.at(n,t)}intersectsPlane(e){let t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let n,r,i,a,o,s,c=1/this.direction.x,l=1/this.direction.y,u=1/this.direction.z,d=this.origin;return c>=0?(n=(e.min.x-d.x)*c,r=(e.max.x-d.x)*c):(n=(e.max.x-d.x)*c,r=(e.min.x-d.x)*c),l>=0?(i=(e.min.y-d.y)*l,a=(e.max.y-d.y)*l):(i=(e.max.y-d.y)*l,a=(e.min.y-d.y)*l),n>a||i>r||((i>n||isNaN(n))&&(n=i),(a=0?(o=(e.min.z-d.z)*u,s=(e.max.z-d.z)*u):(o=(e.max.z-d.z)*u,s=(e.min.z-d.z)*u),n>s||o>r)||((o>n||n!==n)&&(n=o),(s=0?n:r,t)}intersectsBox(e){return this.intersectBox(e,ur)!==null}intersectTriangle(e,t,n,r,i){mr.subVectors(t,e),hr.subVectors(n,e),gr.crossVectors(mr,hr);let a=this.direction.dot(gr),o;if(a>0){if(r)return null;o=1}else if(a<0)o=-1,a=-a;else return null;pr.subVectors(this.origin,e);let s=o*this.direction.dot(hr.crossVectors(pr,hr));if(s<0)return null;let c=o*this.direction.dot(mr.cross(pr));if(c<0||s+c>a)return null;let l=-o*pr.dot(gr);return l<0?null:this.at(l/a,i)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}},vr=class extends lr{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type=`MeshBasicMaterial`,this.color=new Y(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Bt,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap=`round`,this.wireframeLinejoin=`round`,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}},yr=new At,br=new _r,xr=new $n,Sr=new K,Cr=new K,wr=new K,Tr=new K,Er=new K,Dr=new K,Or=new K,kr=new K,Ar=class extends rn{constructor(e=new sr,t=new vr){super(),this.isMesh=!0,this.type=`Mesh`,this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.count=1,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),e.morphTargetInfluences!==void 0&&(this.morphTargetInfluences=e.morphTargetInfluences.slice()),e.morphTargetDictionary!==void 0&&(this.morphTargetDictionary=Object.assign({},e.morphTargetDictionary)),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}updateMorphTargets(){let e=this.geometry.morphAttributes,t=Object.keys(e);if(t.length>0){let n=e[t[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;e(e.far-e.near)**2))&&(yr.copy(i).invert(),br.copy(e.ray).applyMatrix4(yr),!(n.boundingBox!==null&&br.intersectsBox(n.boundingBox)===!1)&&this._computeIntersections(e,t,br)))}_computeIntersections(e,t,n){let r,i=this.geometry,a=this.material,o=i.index,s=i.attributes.position,c=i.attributes.uv,l=i.attributes.uv1,u=i.attributes.normal,d=i.groups,f=i.drawRange;if(o!==null)if(Array.isArray(a))for(let i=0,s=d.length;in.far?null:{distance:l,point:kr.clone(),object:e}}function Mr(e,t,n,r,i,a,o,s,c,l){e.getVertexPosition(s,Cr),e.getVertexPosition(c,wr),e.getVertexPosition(l,Tr);let u=jr(e,t,n,r,Cr,wr,Tr,Or);if(u){let e=new K;Dn.getBarycoord(Or,Cr,wr,Tr,e),i&&(u.uv=Dn.getInterpolatedAttribute(i,s,c,l,e,new G)),a&&(u.uv1=Dn.getInterpolatedAttribute(a,s,c,l,e,new G)),o&&(u.normal=Dn.getInterpolatedAttribute(o,s,c,l,e,new K),u.normal.dot(r.direction)>0&&u.normal.multiplyScalar(-1));let t={a:s,b:c,c:l,normal:new K,materialIndex:0};Dn.getNormal(Cr,wr,Tr,t.normal),u.face=t,u.barycoord=e}return u}var Nr=class extends wt{constructor(e=null,t=1,n=1,r,a,o,s,c,l=i,u=i,d,f){super(null,o,s,c,l,u,r,a,d,f),this.isDataTexture=!0,this.image={data:e,width:t,height:n},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}},Pr=new K,Fr=new K,Ir=new q,Lr=class{constructor(e=new K(1,0,0),t=0){this.isPlane=!0,this.normal=e,this.constant=t}set(e,t){return this.normal.copy(e),this.constant=t,this}setComponents(e,t,n,r){return this.normal.set(e,t,n),this.constant=r,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,n){let r=Pr.subVectors(n,t).cross(Fr.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(r,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){let e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,t){return t.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,t){let n=e.delta(Pr),r=this.normal.dot(n);if(r===0)return this.distanceToPoint(e.start)===0?t.copy(e.start):null;let i=-(e.start.dot(this.normal)+this.constant)/r;return i<0||i>1?null:t.copy(e.start).addScaledVector(n,i)}intersectsLine(e){let t=this.distanceToPoint(e.start),n=this.distanceToPoint(e.end);return t<0&&n>0||n<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){let n=t||Ir.getNormalMatrix(e),r=this.coplanarPoint(Pr).applyMatrix4(e),i=this.normal.applyMatrix3(n).normalize();return this.constant=-r.dot(i),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}},Rr=new $n,zr=new G(.5,.5),Br=new K,Vr=class{constructor(e=new Lr,t=new Lr,n=new Lr,r=new Lr,i=new Lr,a=new Lr){this.planes=[e,t,n,r,i,a]}set(e,t,n,r,i,a){let o=this.planes;return o[0].copy(e),o[1].copy(t),o[2].copy(n),o[3].copy(r),o[4].copy(i),o[5].copy(a),this}copy(e){let t=this.planes;for(let n=0;n<6;n++)t[n].copy(e.planes[n]);return this}setFromProjectionMatrix(e,t=Ve,n=!1){let r=this.planes,i=e.elements,a=i[0],o=i[1],s=i[2],c=i[3],l=i[4],u=i[5],d=i[6],f=i[7],p=i[8],m=i[9],h=i[10],g=i[11],_=i[12],v=i[13],y=i[14],b=i[15];if(r[0].setComponents(c-a,f-l,g-p,b-_).normalize(),r[1].setComponents(c+a,f+l,g+p,b+_).normalize(),r[2].setComponents(c+o,f+u,g+m,b+v).normalize(),r[3].setComponents(c-o,f-u,g-m,b-v).normalize(),n)r[4].setComponents(s,d,h,y).normalize(),r[5].setComponents(c-s,f-d,g-h,b-y).normalize();else if(r[4].setComponents(c-s,f-d,g-h,b-y).normalize(),t===2e3)r[5].setComponents(c+s,f+d,g+h,b+y).normalize();else if(t===2001)r[5].setComponents(s,d,h,y).normalize();else throw Error(`THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: `+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),Rr.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{let t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),Rr.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(Rr)}intersectsSprite(e){return Rr.center.set(0,0,0),Rr.radius=.7071067811865476+zr.distanceTo(e.center),Rr.applyMatrix4(e.matrixWorld),this.intersectsSphere(Rr)}intersectsSphere(e){let t=this.planes,n=e.center,r=-e.radius;for(let e=0;e<6;e++)if(t[e].distanceToPoint(n)0?e.max.x:e.min.x,Br.y=r.normal.y>0?e.max.y:e.min.y,Br.z=r.normal.z>0?e.max.z:e.min.z,r.distanceToPoint(Br)<0)return!1}return!0}containsPoint(e){let t=this.planes;for(let n=0;n<6;n++)if(t[n].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}},Hr=class extends wt{constructor(e=[],t=301,n,r,i,a,o,s,c,l){super(e,t,n,r,i,a,o,s,c,l),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}},Ur=class extends wt{constructor(e,t,n=h,r,a,o,s=i,c=i,l,u=E,d=1){if(u!==1026&&u!==1027)throw Error(`DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat`);super({width:e,height:t,depth:d},r,a,o,s,c,u,n,l),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new bt(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){let t=super.toJSON(e);return this.compareFunction!==null&&(t.compareFunction=this.compareFunction),t}},Wr=class extends Ur{constructor(e,t=h,n=301,r,a,o=i,s=i,c,l=E){let u={width:e,height:e,depth:1},d=[u,u,u,u,u,u];super(e,e,t,n,r,a,o,s,c,l),this.image=d,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images(e){this.image=e}},Gr=class extends wt{constructor(e=null){super(),this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}},Kr=class e extends sr{constructor(e=1,t=1,n=1,r=1,i=1,a=1){super(),this.type=`BoxGeometry`,this.parameters={width:e,height:t,depth:n,widthSegments:r,heightSegments:i,depthSegments:a};let o=this;r=Math.floor(r),i=Math.floor(i),a=Math.floor(a);let s=[],c=[],l=[],u=[],d=0,f=0;p(`z`,`y`,`x`,-1,-1,n,t,e,a,i,0),p(`z`,`y`,`x`,1,-1,n,t,-e,a,i,1),p(`x`,`z`,`y`,1,1,e,n,t,r,a,2),p(`x`,`z`,`y`,1,-1,e,n,-t,r,a,3),p(`x`,`y`,`z`,1,-1,e,t,n,r,i,4),p(`x`,`y`,`z`,-1,-1,e,t,-n,r,i,5),this.setIndex(s),this.setAttribute(`position`,new Yn(c,3)),this.setAttribute(`normal`,new Yn(l,3)),this.setAttribute(`uv`,new Yn(u,2));function p(e,t,n,r,i,a,p,m,h,g,_){let v=a/h,y=p/g,b=a/2,x=p/2,S=m/2,C=h+1,w=g+1,T=0,E=0,D=new K;for(let a=0;a0?1:-1,l.push(D.x,D.y,D.z),u.push(s/h),u.push(1-a/g),T+=1}for(let e=0;e0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;let n={};for(let e in this.extensions)this.extensions[e]===!0&&(n[e]=!0);return Object.keys(n).length>0&&(t.extensions=n),t}},ni=class extends ti{constructor(e){super(e),this.isRawShaderMaterial=!0,this.type=`RawShaderMaterial`}},ri=class extends lr{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type=`MeshDepthMaterial`,this.depthPacking=Pe,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}},ii=class extends lr{constructor(e){super(),this.isMeshDistanceMaterial=!0,this.type=`MeshDistanceMaterial`,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}};function ai(e,t){return!e||e.constructor===t?e:typeof t.BYTES_PER_ELEMENT==`number`?new t(e):Array.prototype.slice.call(e)}var oi=class{constructor(e,t,n,r){this.parameterPositions=e,this._cachedIndex=0,this.resultBuffer=r===void 0?new t.constructor(n):r,this.sampleValues=t,this.valueSize=n,this.settings=null,this.DefaultSettings_={}}evaluate(e){let t=this.parameterPositions,n=this._cachedIndex,r=t[n],i=t[n-1];validate_interval:{seek:{let a;linear_scan:{forward_scan:if(!(e=i)){let o=t[1];e=i)break seek}a=n,n=0;break linear_scan}break validate_interval}for(;n>>1;et;)--a;if(++a,i!==0||a!==r){i>=a&&(a=Math.max(a,1),i=a-1);let e=this.getValueSize();this.times=n.slice(i,a),this.values=this.values.slice(i*e,a*e)}return this}validate(){let e=!0,t=this.getValueSize();t-Math.floor(t)!==0&&(U(`KeyframeTrack: Invalid value size in track.`,this),e=!1);let n=this.times,r=this.values,i=n.length;i===0&&(U(`KeyframeTrack: Track is empty.`,this),e=!1);let a=null;for(let t=0;t!==i;t++){let r=n[t];if(typeof r==`number`&&isNaN(r)){U(`KeyframeTrack: Time is not a valid number.`,this,t,r),e=!1;break}if(a!==null&&a>r){U(`KeyframeTrack: Out of order keys.`,this,t,r,a),e=!1;break}a=r}if(r!==void 0&&Ue(r))for(let t=0,n=r.length;t!==n;++t){let n=r[t];if(isNaN(n)){U(`KeyframeTrack: Value is not a valid number.`,this,t,n),e=!1;break}}return e}optimize(){let e=this.times.slice(),t=this.values.slice(),n=this.getValueSize(),r=this.getInterpolation()===V,i=e.length-1,a=1;for(let o=1;o0){e[a]=e[i];for(let e=i*n,r=a*n,o=0;o!==n;++o)t[r+o]=t[e+o];++a}return a===e.length?(this.times=e,this.values=t):(this.times=e.slice(0,a),this.values=t.slice(0,a*n)),this}clone(){let e=this.times.slice(),t=this.values.slice(),n=this.constructor,r=new n(this.name,e,t);return r.createInterpolant=this.createInterpolant,r}};di.prototype.ValueTypeName=``,di.prototype.TimeBufferType=Float32Array,di.prototype.ValueBufferType=Float32Array,di.prototype.DefaultInterpolation=B;var fi=class extends di{constructor(e,t,n){super(e,t,n)}};fi.prototype.ValueTypeName=`bool`,fi.prototype.ValueBufferType=Array,fi.prototype.DefaultInterpolation=ke,fi.prototype.InterpolantFactoryMethodLinear=void 0,fi.prototype.InterpolantFactoryMethodSmooth=void 0;var pi=class extends di{constructor(e,t,n,r){super(e,t,n,r)}};pi.prototype.ValueTypeName=`color`;var mi=class extends di{constructor(e,t,n,r){super(e,t,n,r)}};mi.prototype.ValueTypeName=`number`;var hi=class extends oi{constructor(e,t,n,r){super(e,t,n,r)}interpolate_(e,t,n,r){let i=this.resultBuffer,a=this.sampleValues,o=this.valueSize,s=(n-t)/(r-t),c=e*o;for(let e=c+o;c!==e;c+=4)ct.slerpFlat(i,0,a,c-o,a,c,s);return i}},gi=class extends di{constructor(e,t,n,r){super(e,t,n,r)}InterpolantFactoryMethodLinear(e){return new hi(this.times,this.values,this.getValueSize(),e)}};gi.prototype.ValueTypeName=`quaternion`,gi.prototype.InterpolantFactoryMethodSmooth=void 0;var _i=class extends di{constructor(e,t,n){super(e,t,n)}};_i.prototype.ValueTypeName=`string`,_i.prototype.ValueBufferType=Array,_i.prototype.DefaultInterpolation=ke,_i.prototype.InterpolantFactoryMethodLinear=void 0,_i.prototype.InterpolantFactoryMethodSmooth=void 0;var vi=class extends di{constructor(e,t,n,r){super(e,t,n,r)}};vi.prototype.ValueTypeName=`vector`;var yi=new class{constructor(e,t,n){let r=this,i=!1,a=0,o=0,s,c=[];this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=n,this._abortController=null,this.itemStart=function(e){o++,i===!1&&r.onStart!==void 0&&r.onStart(e,a,o),i=!0},this.itemEnd=function(e){a++,r.onProgress!==void 0&&r.onProgress(e,a,o),a===o&&(i=!1,r.onLoad!==void 0&&r.onLoad())},this.itemError=function(e){r.onError!==void 0&&r.onError(e)},this.resolveURL=function(e){return s?s(e):e},this.setURLModifier=function(e){return s=e,this},this.addHandler=function(e,t){return c.push(e,t),this},this.removeHandler=function(e){let t=c.indexOf(e);return t!==-1&&c.splice(t,2),this},this.getHandler=function(e){for(let t=0,n=c.length;te.start-t.start);let t=0;for(let e=1;e 0 vec4 plane; #ifdef ALPHA_TO_COVERAGE float distanceToPlane, distanceGradient; float clipOpacity = 1.0; #pragma unroll_loop_start for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { plane = clippingPlanes[ i ]; distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; distanceGradient = fwidth( distanceToPlane ) / 2.0; clipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); if ( clipOpacity == 0.0 ) discard; } #pragma unroll_loop_end #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES float unionClipOpacity = 1.0; #pragma unroll_loop_start for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { plane = clippingPlanes[ i ]; distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; distanceGradient = fwidth( distanceToPlane ) / 2.0; unionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); } #pragma unroll_loop_end clipOpacity *= 1.0 - unionClipOpacity; #endif diffuseColor.a *= clipOpacity; if ( diffuseColor.a == 0.0 ) discard; #else #pragma unroll_loop_start for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { plane = clippingPlanes[ i ]; if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard; } #pragma unroll_loop_end #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES bool clipped = true; #pragma unroll_loop_start for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { plane = clippingPlanes[ i ]; clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped; } #pragma unroll_loop_end if ( clipped ) discard; #endif #endif #endif`,clipping_planes_pars_fragment:`#if NUM_CLIPPING_PLANES > 0 varying vec3 vClipPosition; uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ]; #endif`,clipping_planes_pars_vertex:`#if NUM_CLIPPING_PLANES > 0 varying vec3 vClipPosition; #endif`,clipping_planes_vertex:`#if NUM_CLIPPING_PLANES > 0 vClipPosition = - mvPosition.xyz; #endif`,color_fragment:`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) diffuseColor *= vColor; #endif`,color_pars_fragment:`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) varying vec4 vColor; #endif`,color_pars_vertex:`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) varying vec4 vColor; #endif`,color_vertex:`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) vColor = vec4( 1.0 ); #endif #ifdef USE_COLOR_ALPHA vColor *= color; #elif defined( USE_COLOR ) vColor.rgb *= color; #endif #ifdef USE_INSTANCING_COLOR vColor.rgb *= instanceColor.rgb; #endif #ifdef USE_BATCHING_COLOR vColor *= getBatchingColor( getIndirectIndex( gl_DrawID ) ); #endif`,common:`#define PI 3.141592653589793 #define PI2 6.283185307179586 #define PI_HALF 1.5707963267948966 #define RECIPROCAL_PI 0.3183098861837907 #define RECIPROCAL_PI2 0.15915494309189535 #define EPSILON 1e-6 #ifndef saturate #define saturate( a ) clamp( a, 0.0, 1.0 ) #endif #define whiteComplement( a ) ( 1.0 - saturate( a ) ) float pow2( const in float x ) { return x*x; } vec3 pow2( const in vec3 x ) { return x*x; } float pow3( const in float x ) { return x*x*x; } float pow4( const in float x ) { float x2 = x*x; return x2*x2; } float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); } float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); } highp float rand( const in vec2 uv ) { const highp float a = 12.9898, b = 78.233, c = 43758.5453; highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI ); return fract( sin( sn ) * c ); } #ifdef HIGH_PRECISION float precisionSafeLength( vec3 v ) { return length( v ); } #else float precisionSafeLength( vec3 v ) { float maxComponent = max3( abs( v ) ); return length( v / maxComponent ) * maxComponent; } #endif struct IncidentLight { vec3 color; vec3 direction; bool visible; }; struct ReflectedLight { vec3 directDiffuse; vec3 directSpecular; vec3 indirectDiffuse; vec3 indirectSpecular; }; #ifdef USE_ALPHAHASH varying vec3 vPosition; #endif vec3 transformDirection( in vec3 dir, in mat4 matrix ) { return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); } vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) { return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz ); } bool isPerspectiveMatrix( mat4 m ) { return m[ 2 ][ 3 ] == - 1.0; } vec2 equirectUv( in vec3 dir ) { float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5; float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5; return vec2( u, v ); } vec3 BRDF_Lambert( const in vec3 diffuseColor ) { return RECIPROCAL_PI * diffuseColor; } vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) { float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); } float F_Schlick( const in float f0, const in float f90, const in float dotVH ) { float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); } // validated`,cube_uv_reflection_fragment:`#ifdef ENVMAP_TYPE_CUBE_UV #define cubeUV_minMipLevel 4.0 #define cubeUV_minTileSize 16.0 float getFace( vec3 direction ) { vec3 absDirection = abs( direction ); float face = - 1.0; if ( absDirection.x > absDirection.z ) { if ( absDirection.x > absDirection.y ) face = direction.x > 0.0 ? 0.0 : 3.0; else face = direction.y > 0.0 ? 1.0 : 4.0; } else { if ( absDirection.z > absDirection.y ) face = direction.z > 0.0 ? 2.0 : 5.0; else face = direction.y > 0.0 ? 1.0 : 4.0; } return face; } vec2 getUV( vec3 direction, float face ) { vec2 uv; if ( face == 0.0 ) { uv = vec2( direction.z, direction.y ) / abs( direction.x ); } else if ( face == 1.0 ) { uv = vec2( - direction.x, - direction.z ) / abs( direction.y ); } else if ( face == 2.0 ) { uv = vec2( - direction.x, direction.y ) / abs( direction.z ); } else if ( face == 3.0 ) { uv = vec2( - direction.z, direction.y ) / abs( direction.x ); } else if ( face == 4.0 ) { uv = vec2( - direction.x, direction.z ) / abs( direction.y ); } else { uv = vec2( direction.x, direction.y ) / abs( direction.z ); } return 0.5 * ( uv + 1.0 ); } vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) { float face = getFace( direction ); float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 ); mipInt = max( mipInt, cubeUV_minMipLevel ); float faceSize = exp2( mipInt ); highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0; if ( face > 2.0 ) { uv.y += faceSize; face -= 3.0; } uv.x += face * faceSize; uv.x += filterInt * 3.0 * cubeUV_minTileSize; uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize ); uv.x *= CUBEUV_TEXEL_WIDTH; uv.y *= CUBEUV_TEXEL_HEIGHT; #ifdef texture2DGradEXT return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb; #else return texture2D( envMap, uv ).rgb; #endif } #define cubeUV_r0 1.0 #define cubeUV_m0 - 2.0 #define cubeUV_r1 0.8 #define cubeUV_m1 - 1.0 #define cubeUV_r4 0.4 #define cubeUV_m4 2.0 #define cubeUV_r5 0.305 #define cubeUV_m5 3.0 #define cubeUV_r6 0.21 #define cubeUV_m6 4.0 float roughnessToMip( float roughness ) { float mip = 0.0; if ( roughness >= cubeUV_r1 ) { mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0; } else if ( roughness >= cubeUV_r4 ) { mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1; } else if ( roughness >= cubeUV_r5 ) { mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4; } else if ( roughness >= cubeUV_r6 ) { mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5; } else { mip = - 2.0 * log2( 1.16 * roughness ); } return mip; } vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) { float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP ); float mipF = fract( mip ); float mipInt = floor( mip ); vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt ); if ( mipF == 0.0 ) { return vec4( color0, 1.0 ); } else { vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 ); return vec4( mix( color0, color1, mipF ), 1.0 ); } } #endif`,defaultnormal_vertex:`vec3 transformedNormal = objectNormal; #ifdef USE_TANGENT vec3 transformedTangent = objectTangent; #endif #ifdef USE_BATCHING mat3 bm = mat3( batchingMatrix ); transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) ); transformedNormal = bm * transformedNormal; #ifdef USE_TANGENT transformedTangent = bm * transformedTangent; #endif #endif #ifdef USE_INSTANCING mat3 im = mat3( instanceMatrix ); transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) ); transformedNormal = im * transformedNormal; #ifdef USE_TANGENT transformedTangent = im * transformedTangent; #endif #endif transformedNormal = normalMatrix * transformedNormal; #ifdef FLIP_SIDED transformedNormal = - transformedNormal; #endif #ifdef USE_TANGENT transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz; #ifdef FLIP_SIDED transformedTangent = - transformedTangent; #endif #endif`,displacementmap_pars_vertex:`#ifdef USE_DISPLACEMENTMAP uniform sampler2D displacementMap; uniform float displacementScale; uniform float displacementBias; #endif`,displacementmap_vertex:`#ifdef USE_DISPLACEMENTMAP transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias ); #endif`,emissivemap_fragment:`#ifdef USE_EMISSIVEMAP vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv ); #ifdef DECODE_VIDEO_TEXTURE_EMISSIVE emissiveColor = sRGBTransferEOTF( emissiveColor ); #endif totalEmissiveRadiance *= emissiveColor.rgb; #endif`,emissivemap_pars_fragment:`#ifdef USE_EMISSIVEMAP uniform sampler2D emissiveMap; #endif`,colorspace_fragment:`gl_FragColor = linearToOutputTexel( gl_FragColor );`,colorspace_pars_fragment:`vec4 LinearTransferOETF( in vec4 value ) { return value; } vec4 sRGBTransferEOTF( in vec4 value ) { return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a ); } vec4 sRGBTransferOETF( in vec4 value ) { return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a ); }`,envmap_fragment:`#ifdef USE_ENVMAP #ifdef ENV_WORLDPOS vec3 cameraToFrag; if ( isOrthographic ) { cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); } else { cameraToFrag = normalize( vWorldPosition - cameraPosition ); } vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); #ifdef ENVMAP_MODE_REFLECTION vec3 reflectVec = reflect( cameraToFrag, worldNormal ); #else vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio ); #endif #else vec3 reflectVec = vReflect; #endif #ifdef ENVMAP_TYPE_CUBE vec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) ); #ifdef ENVMAP_BLENDING_MULTIPLY outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity ); #elif defined( ENVMAP_BLENDING_MIX ) outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity ); #elif defined( ENVMAP_BLENDING_ADD ) outgoingLight += envColor.xyz * specularStrength * reflectivity; #endif #endif #endif`,envmap_common_pars_fragment:`#ifdef USE_ENVMAP uniform float envMapIntensity; uniform float flipEnvMap; uniform mat3 envMapRotation; #ifdef ENVMAP_TYPE_CUBE uniform samplerCube envMap; #else uniform sampler2D envMap; #endif #endif`,envmap_pars_fragment:`#ifdef USE_ENVMAP uniform float reflectivity; #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) #define ENV_WORLDPOS #endif #ifdef ENV_WORLDPOS varying vec3 vWorldPosition; uniform float refractionRatio; #else varying vec3 vReflect; #endif #endif`,envmap_pars_vertex:`#ifdef USE_ENVMAP #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) #define ENV_WORLDPOS #endif #ifdef ENV_WORLDPOS varying vec3 vWorldPosition; #else varying vec3 vReflect; uniform float refractionRatio; #endif #endif`,envmap_physical_pars_fragment:`#ifdef USE_ENVMAP vec3 getIBLIrradiance( const in vec3 normal ) { #ifdef ENVMAP_TYPE_CUBE_UV vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); vec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 ); return PI * envMapColor.rgb * envMapIntensity; #else return vec3( 0.0 ); #endif } vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) { #ifdef ENVMAP_TYPE_CUBE_UV vec3 reflectVec = reflect( - viewDir, normal ); reflectVec = normalize( mix( reflectVec, normal, pow4( roughness ) ) ); reflectVec = inverseTransformDirection( reflectVec, viewMatrix ); vec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness ); return envMapColor.rgb * envMapIntensity; #else return vec3( 0.0 ); #endif } #ifdef USE_ANISOTROPY vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) { #ifdef ENVMAP_TYPE_CUBE_UV vec3 bentNormal = cross( bitangent, viewDir ); bentNormal = normalize( cross( bentNormal, bitangent ) ); bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) ); return getIBLRadiance( viewDir, bentNormal, roughness ); #else return vec3( 0.0 ); #endif } #endif #endif`,envmap_vertex:`#ifdef USE_ENVMAP #ifdef ENV_WORLDPOS vWorldPosition = worldPosition.xyz; #else vec3 cameraToVertex; if ( isOrthographic ) { cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); } else { cameraToVertex = normalize( worldPosition.xyz - cameraPosition ); } vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); #ifdef ENVMAP_MODE_REFLECTION vReflect = reflect( cameraToVertex, worldNormal ); #else vReflect = refract( cameraToVertex, worldNormal, refractionRatio ); #endif #endif #endif`,fog_vertex:`#ifdef USE_FOG vFogDepth = - mvPosition.z; #endif`,fog_pars_vertex:`#ifdef USE_FOG varying float vFogDepth; #endif`,fog_fragment:`#ifdef USE_FOG #ifdef FOG_EXP2 float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth ); #else float fogFactor = smoothstep( fogNear, fogFar, vFogDepth ); #endif gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor ); #endif`,fog_pars_fragment:`#ifdef USE_FOG uniform vec3 fogColor; varying float vFogDepth; #ifdef FOG_EXP2 uniform float fogDensity; #else uniform float fogNear; uniform float fogFar; #endif #endif`,gradientmap_pars_fragment:`#ifdef USE_GRADIENTMAP uniform sampler2D gradientMap; #endif vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) { float dotNL = dot( normal, lightDirection ); vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 ); #ifdef USE_GRADIENTMAP return vec3( texture2D( gradientMap, coord ).r ); #else vec2 fw = fwidth( coord ) * 0.5; return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) ); #endif }`,lightmap_pars_fragment:`#ifdef USE_LIGHTMAP uniform sampler2D lightMap; uniform float lightMapIntensity; #endif`,lights_lambert_fragment:`LambertMaterial material; material.diffuseColor = diffuseColor.rgb; material.specularStrength = specularStrength;`,lights_lambert_pars_fragment:`varying vec3 vViewPosition; struct LambertMaterial { vec3 diffuseColor; float specularStrength; }; void RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); vec3 irradiance = dotNL * directLight.color; reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } void RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } #define RE_Direct RE_Direct_Lambert #define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`,lights_pars_begin:`uniform bool receiveShadow; uniform vec3 ambientLightColor; #if defined( USE_LIGHT_PROBES ) uniform vec3 lightProbe[ 9 ]; #endif vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) { float x = normal.x, y = normal.y, z = normal.z; vec3 result = shCoefficients[ 0 ] * 0.886227; result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y; result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z; result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x; result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y; result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z; result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 ); result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z; result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y ); return result; } vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) { vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe ); return irradiance; } vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) { vec3 irradiance = ambientLightColor; return irradiance; } float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) { float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 ); if ( cutoffDistance > 0.0 ) { distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) ); } return distanceFalloff; } float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) { return smoothstep( coneCosine, penumbraCosine, angleCosine ); } #if NUM_DIR_LIGHTS > 0 struct DirectionalLight { vec3 direction; vec3 color; }; uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ]; void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) { light.color = directionalLight.color; light.direction = directionalLight.direction; light.visible = true; } #endif #if NUM_POINT_LIGHTS > 0 struct PointLight { vec3 position; vec3 color; float distance; float decay; }; uniform PointLight pointLights[ NUM_POINT_LIGHTS ]; void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) { vec3 lVector = pointLight.position - geometryPosition; light.direction = normalize( lVector ); float lightDistance = length( lVector ); light.color = pointLight.color; light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay ); light.visible = ( light.color != vec3( 0.0 ) ); } #endif #if NUM_SPOT_LIGHTS > 0 struct SpotLight { vec3 position; vec3 direction; vec3 color; float distance; float decay; float coneCos; float penumbraCos; }; uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ]; void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) { vec3 lVector = spotLight.position - geometryPosition; light.direction = normalize( lVector ); float angleCos = dot( light.direction, spotLight.direction ); float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos ); if ( spotAttenuation > 0.0 ) { float lightDistance = length( lVector ); light.color = spotLight.color * spotAttenuation; light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay ); light.visible = ( light.color != vec3( 0.0 ) ); } else { light.color = vec3( 0.0 ); light.visible = false; } } #endif #if NUM_RECT_AREA_LIGHTS > 0 struct RectAreaLight { vec3 color; vec3 position; vec3 halfWidth; vec3 halfHeight; }; uniform sampler2D ltc_1; uniform sampler2D ltc_2; uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ]; #endif #if NUM_HEMI_LIGHTS > 0 struct HemisphereLight { vec3 direction; vec3 skyColor; vec3 groundColor; }; uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ]; vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) { float dotNL = dot( normal, hemiLight.direction ); float hemiDiffuseWeight = 0.5 * dotNL + 0.5; vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight ); return irradiance; } #endif`,lights_toon_fragment:`ToonMaterial material; material.diffuseColor = diffuseColor.rgb;`,lights_toon_pars_fragment:`varying vec3 vViewPosition; struct ToonMaterial { vec3 diffuseColor; }; void RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color; reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } #define RE_Direct RE_Direct_Toon #define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`,lights_phong_fragment:`BlinnPhongMaterial material; material.diffuseColor = diffuseColor.rgb; material.specularColor = specular; material.specularShininess = shininess; material.specularStrength = specularStrength;`,lights_phong_pars_fragment:`varying vec3 vViewPosition; struct BlinnPhongMaterial { vec3 diffuseColor; vec3 specularColor; float specularShininess; float specularStrength; }; void RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); vec3 irradiance = dotNL * directLight.color; reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength; } void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } #define RE_Direct RE_Direct_BlinnPhong #define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`,lights_physical_fragment:`PhysicalMaterial material; material.diffuseColor = diffuseColor.rgb; material.diffuseContribution = diffuseColor.rgb * ( 1.0 - metalnessFactor ); material.metalness = metalnessFactor; vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) ); float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z ); material.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness; material.roughness = min( material.roughness, 1.0 ); #ifdef IOR material.ior = ior; #ifdef USE_SPECULAR float specularIntensityFactor = specularIntensity; vec3 specularColorFactor = specularColor; #ifdef USE_SPECULAR_COLORMAP specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb; #endif #ifdef USE_SPECULAR_INTENSITYMAP specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a; #endif material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor ); #else float specularIntensityFactor = 1.0; vec3 specularColorFactor = vec3( 1.0 ); material.specularF90 = 1.0; #endif material.specularColor = min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor; material.specularColorBlended = mix( material.specularColor, diffuseColor.rgb, metalnessFactor ); #else material.specularColor = vec3( 0.04 ); material.specularColorBlended = mix( material.specularColor, diffuseColor.rgb, metalnessFactor ); material.specularF90 = 1.0; #endif #ifdef USE_CLEARCOAT material.clearcoat = clearcoat; material.clearcoatRoughness = clearcoatRoughness; material.clearcoatF0 = vec3( 0.04 ); material.clearcoatF90 = 1.0; #ifdef USE_CLEARCOATMAP material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x; #endif #ifdef USE_CLEARCOAT_ROUGHNESSMAP material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y; #endif material.clearcoat = saturate( material.clearcoat ); material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 ); material.clearcoatRoughness += geometryRoughness; material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 ); #endif #ifdef USE_DISPERSION material.dispersion = dispersion; #endif #ifdef USE_IRIDESCENCE material.iridescence = iridescence; material.iridescenceIOR = iridescenceIOR; #ifdef USE_IRIDESCENCEMAP material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r; #endif #ifdef USE_IRIDESCENCE_THICKNESSMAP material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum; #else material.iridescenceThickness = iridescenceThicknessMaximum; #endif #endif #ifdef USE_SHEEN material.sheenColor = sheenColor; #ifdef USE_SHEEN_COLORMAP material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb; #endif material.sheenRoughness = clamp( sheenRoughness, 0.0001, 1.0 ); #ifdef USE_SHEEN_ROUGHNESSMAP material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a; #endif #endif #ifdef USE_ANISOTROPY #ifdef USE_ANISOTROPYMAP mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x ); vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb; vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b; #else vec2 anisotropyV = anisotropyVector; #endif material.anisotropy = length( anisotropyV ); if( material.anisotropy == 0.0 ) { anisotropyV = vec2( 1.0, 0.0 ); } else { anisotropyV /= material.anisotropy; material.anisotropy = saturate( material.anisotropy ); } material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) ); material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y; material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y; #endif`,lights_physical_pars_fragment:`uniform sampler2D dfgLUT; struct PhysicalMaterial { vec3 diffuseColor; vec3 diffuseContribution; vec3 specularColor; vec3 specularColorBlended; float roughness; float metalness; float specularF90; float dispersion; #ifdef USE_CLEARCOAT float clearcoat; float clearcoatRoughness; vec3 clearcoatF0; float clearcoatF90; #endif #ifdef USE_IRIDESCENCE float iridescence; float iridescenceIOR; float iridescenceThickness; vec3 iridescenceFresnel; vec3 iridescenceF0; vec3 iridescenceFresnelDielectric; vec3 iridescenceFresnelMetallic; #endif #ifdef USE_SHEEN vec3 sheenColor; float sheenRoughness; #endif #ifdef IOR float ior; #endif #ifdef USE_TRANSMISSION float transmission; float transmissionAlpha; float thickness; float attenuationDistance; vec3 attenuationColor; #endif #ifdef USE_ANISOTROPY float anisotropy; float alphaT; vec3 anisotropyT; vec3 anisotropyB; #endif }; vec3 clearcoatSpecularDirect = vec3( 0.0 ); vec3 clearcoatSpecularIndirect = vec3( 0.0 ); vec3 sheenSpecularDirect = vec3( 0.0 ); vec3 sheenSpecularIndirect = vec3(0.0 ); vec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) { float x = clamp( 1.0 - dotVH, 0.0, 1.0 ); float x2 = x * x; float x5 = clamp( x * x2 * x2, 0.0, 0.9999 ); return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 ); } float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) { float a2 = pow2( alpha ); float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) ); float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) ); return 0.5 / max( gv + gl, EPSILON ); } float D_GGX( const in float alpha, const in float dotNH ) { float a2 = pow2( alpha ); float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0; return RECIPROCAL_PI * a2 / pow2( denom ); } #ifdef USE_ANISOTROPY float V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) { float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) ); float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) ); float v = 0.5 / ( gv + gl ); return v; } float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) { float a2 = alphaT * alphaB; highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH ); highp float v2 = dot( v, v ); float w2 = a2 / v2; return RECIPROCAL_PI * a2 * pow2 ( w2 ); } #endif #ifdef USE_CLEARCOAT vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) { vec3 f0 = material.clearcoatF0; float f90 = material.clearcoatF90; float roughness = material.clearcoatRoughness; float alpha = pow2( roughness ); vec3 halfDir = normalize( lightDir + viewDir ); float dotNL = saturate( dot( normal, lightDir ) ); float dotNV = saturate( dot( normal, viewDir ) ); float dotNH = saturate( dot( normal, halfDir ) ); float dotVH = saturate( dot( viewDir, halfDir ) ); vec3 F = F_Schlick( f0, f90, dotVH ); float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); float D = D_GGX( alpha, dotNH ); return F * ( V * D ); } #endif vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) { vec3 f0 = material.specularColorBlended; float f90 = material.specularF90; float roughness = material.roughness; float alpha = pow2( roughness ); vec3 halfDir = normalize( lightDir + viewDir ); float dotNL = saturate( dot( normal, lightDir ) ); float dotNV = saturate( dot( normal, viewDir ) ); float dotNH = saturate( dot( normal, halfDir ) ); float dotVH = saturate( dot( viewDir, halfDir ) ); vec3 F = F_Schlick( f0, f90, dotVH ); #ifdef USE_IRIDESCENCE F = mix( F, material.iridescenceFresnel, material.iridescence ); #endif #ifdef USE_ANISOTROPY float dotTL = dot( material.anisotropyT, lightDir ); float dotTV = dot( material.anisotropyT, viewDir ); float dotTH = dot( material.anisotropyT, halfDir ); float dotBL = dot( material.anisotropyB, lightDir ); float dotBV = dot( material.anisotropyB, viewDir ); float dotBH = dot( material.anisotropyB, halfDir ); float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL ); float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH ); #else float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); float D = D_GGX( alpha, dotNH ); #endif return F * ( V * D ); } vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) { const float LUT_SIZE = 64.0; const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE; const float LUT_BIAS = 0.5 / LUT_SIZE; float dotNV = saturate( dot( N, V ) ); vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) ); uv = uv * LUT_SCALE + LUT_BIAS; return uv; } float LTC_ClippedSphereFormFactor( const in vec3 f ) { float l = length( f ); return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 ); } vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) { float x = dot( v1, v2 ); float y = abs( x ); float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y; float b = 3.4175940 + ( 4.1616724 + y ) * y; float v = a / b; float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v; return cross( v1, v2 ) * theta_sintheta; } vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) { vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ]; vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ]; vec3 lightNormal = cross( v1, v2 ); if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 ); vec3 T1, T2; T1 = normalize( V - N * dot( V, N ) ); T2 = - cross( N, T1 ); mat3 mat = mInv * transpose( mat3( T1, T2, N ) ); vec3 coords[ 4 ]; coords[ 0 ] = mat * ( rectCoords[ 0 ] - P ); coords[ 1 ] = mat * ( rectCoords[ 1 ] - P ); coords[ 2 ] = mat * ( rectCoords[ 2 ] - P ); coords[ 3 ] = mat * ( rectCoords[ 3 ] - P ); coords[ 0 ] = normalize( coords[ 0 ] ); coords[ 1 ] = normalize( coords[ 1 ] ); coords[ 2 ] = normalize( coords[ 2 ] ); coords[ 3 ] = normalize( coords[ 3 ] ); vec3 vectorFormFactor = vec3( 0.0 ); vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] ); vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] ); vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] ); vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] ); float result = LTC_ClippedSphereFormFactor( vectorFormFactor ); return vec3( result ); } #if defined( USE_SHEEN ) float D_Charlie( float roughness, float dotNH ) { float alpha = pow2( roughness ); float invAlpha = 1.0 / alpha; float cos2h = dotNH * dotNH; float sin2h = max( 1.0 - cos2h, 0.0078125 ); return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI ); } float V_Neubelt( float dotNV, float dotNL ) { return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) ); } vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) { vec3 halfDir = normalize( lightDir + viewDir ); float dotNL = saturate( dot( normal, lightDir ) ); float dotNV = saturate( dot( normal, viewDir ) ); float dotNH = saturate( dot( normal, halfDir ) ); float D = D_Charlie( sheenRoughness, dotNH ); float V = V_Neubelt( dotNV, dotNL ); return sheenColor * ( D * V ); } #endif float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { float dotNV = saturate( dot( normal, viewDir ) ); float r2 = roughness * roughness; float rInv = 1.0 / ( roughness + 0.1 ); float a = -1.9362 + 1.0678 * roughness + 0.4573 * r2 - 0.8469 * rInv; float b = -0.6014 + 0.5538 * roughness - 0.4670 * r2 - 0.1255 * rInv; float DG = exp( a * dotNV + b ); return saturate( DG ); } vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) { float dotNV = saturate( dot( normal, viewDir ) ); vec2 fab = texture2D( dfgLUT, vec2( roughness, dotNV ) ).rg; return specularColor * fab.x + specularF90 * fab.y; } #ifdef USE_IRIDESCENCE void computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { #else void computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { #endif float dotNV = saturate( dot( normal, viewDir ) ); vec2 fab = texture2D( dfgLUT, vec2( roughness, dotNV ) ).rg; #ifdef USE_IRIDESCENCE vec3 Fr = mix( specularColor, iridescenceF0, iridescence ); #else vec3 Fr = specularColor; #endif vec3 FssEss = Fr * fab.x + specularF90 * fab.y; float Ess = fab.x + fab.y; float Ems = 1.0 - Ess; vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619; vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg ); singleScatter += FssEss; multiScatter += Fms * Ems; } vec3 BRDF_GGX_Multiscatter( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) { vec3 singleScatter = BRDF_GGX( lightDir, viewDir, normal, material ); float dotNL = saturate( dot( normal, lightDir ) ); float dotNV = saturate( dot( normal, viewDir ) ); vec2 dfgV = texture2D( dfgLUT, vec2( material.roughness, dotNV ) ).rg; vec2 dfgL = texture2D( dfgLUT, vec2( material.roughness, dotNL ) ).rg; vec3 FssEss_V = material.specularColorBlended * dfgV.x + material.specularF90 * dfgV.y; vec3 FssEss_L = material.specularColorBlended * dfgL.x + material.specularF90 * dfgL.y; float Ess_V = dfgV.x + dfgV.y; float Ess_L = dfgL.x + dfgL.y; float Ems_V = 1.0 - Ess_V; float Ems_L = 1.0 - Ess_L; vec3 Favg = material.specularColorBlended + ( 1.0 - material.specularColorBlended ) * 0.047619; vec3 Fms = FssEss_V * FssEss_L * Favg / ( 1.0 - Ems_V * Ems_L * Favg + EPSILON ); float compensationFactor = Ems_V * Ems_L; vec3 multiScatter = Fms * compensationFactor; return singleScatter + multiScatter; } #if NUM_RECT_AREA_LIGHTS > 0 void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { vec3 normal = geometryNormal; vec3 viewDir = geometryViewDir; vec3 position = geometryPosition; vec3 lightPos = rectAreaLight.position; vec3 halfWidth = rectAreaLight.halfWidth; vec3 halfHeight = rectAreaLight.halfHeight; vec3 lightColor = rectAreaLight.color; float roughness = material.roughness; vec3 rectCoords[ 4 ]; rectCoords[ 0 ] = lightPos + halfWidth - halfHeight; rectCoords[ 1 ] = lightPos - halfWidth - halfHeight; rectCoords[ 2 ] = lightPos - halfWidth + halfHeight; rectCoords[ 3 ] = lightPos + halfWidth + halfHeight; vec2 uv = LTC_Uv( normal, viewDir, roughness ); vec4 t1 = texture2D( ltc_1, uv ); vec4 t2 = texture2D( ltc_2, uv ); mat3 mInv = mat3( vec3( t1.x, 0, t1.y ), vec3( 0, 1, 0 ), vec3( t1.z, 0, t1.w ) ); vec3 fresnel = ( material.specularColorBlended * t2.x + ( material.specularF90 - material.specularColorBlended ) * t2.y ); reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords ); reflectedLight.directDiffuse += lightColor * material.diffuseContribution * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords ); #ifdef USE_CLEARCOAT vec3 Ncc = geometryClearcoatNormal; vec2 uvClearcoat = LTC_Uv( Ncc, viewDir, material.clearcoatRoughness ); vec4 t1Clearcoat = texture2D( ltc_1, uvClearcoat ); vec4 t2Clearcoat = texture2D( ltc_2, uvClearcoat ); mat3 mInvClearcoat = mat3( vec3( t1Clearcoat.x, 0, t1Clearcoat.y ), vec3( 0, 1, 0 ), vec3( t1Clearcoat.z, 0, t1Clearcoat.w ) ); vec3 fresnelClearcoat = material.clearcoatF0 * t2Clearcoat.x + ( material.clearcoatF90 - material.clearcoatF0 ) * t2Clearcoat.y; clearcoatSpecularDirect += lightColor * fresnelClearcoat * LTC_Evaluate( Ncc, viewDir, position, mInvClearcoat, rectCoords ); #endif } #endif void RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); vec3 irradiance = dotNL * directLight.color; #ifdef USE_CLEARCOAT float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) ); vec3 ccIrradiance = dotNLcc * directLight.color; clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material ); #endif #ifdef USE_SHEEN sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness ); float sheenAlbedoV = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ); float sheenAlbedoL = IBLSheenBRDF( geometryNormal, directLight.direction, material.sheenRoughness ); float sheenEnergyComp = 1.0 - max3( material.sheenColor ) * max( sheenAlbedoV, sheenAlbedoL ); irradiance *= sheenEnergyComp; #endif reflectedLight.directSpecular += irradiance * BRDF_GGX_Multiscatter( directLight.direction, geometryViewDir, geometryNormal, material ); reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseContribution ); } void RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { vec3 diffuse = irradiance * BRDF_Lambert( material.diffuseContribution ); #ifdef USE_SHEEN float sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ); float sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo; diffuse *= sheenEnergyComp; #endif reflectedLight.indirectDiffuse += diffuse; } void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) { #ifdef USE_CLEARCOAT clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness ); #endif #ifdef USE_SHEEN sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ) * RECIPROCAL_PI; #endif vec3 singleScatteringDielectric = vec3( 0.0 ); vec3 multiScatteringDielectric = vec3( 0.0 ); vec3 singleScatteringMetallic = vec3( 0.0 ); vec3 multiScatteringMetallic = vec3( 0.0 ); #ifdef USE_IRIDESCENCE computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnelDielectric, material.roughness, singleScatteringDielectric, multiScatteringDielectric ); computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.diffuseColor, material.specularF90, material.iridescence, material.iridescenceFresnelMetallic, material.roughness, singleScatteringMetallic, multiScatteringMetallic ); #else computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScatteringDielectric, multiScatteringDielectric ); computeMultiscattering( geometryNormal, geometryViewDir, material.diffuseColor, material.specularF90, material.roughness, singleScatteringMetallic, multiScatteringMetallic ); #endif vec3 singleScattering = mix( singleScatteringDielectric, singleScatteringMetallic, material.metalness ); vec3 multiScattering = mix( multiScatteringDielectric, multiScatteringMetallic, material.metalness ); vec3 totalScatteringDielectric = singleScatteringDielectric + multiScatteringDielectric; vec3 diffuse = material.diffuseContribution * ( 1.0 - totalScatteringDielectric ); vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI; vec3 indirectSpecular = radiance * singleScattering; indirectSpecular += multiScattering * cosineWeightedIrradiance; vec3 indirectDiffuse = diffuse * cosineWeightedIrradiance; #ifdef USE_SHEEN float sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ); float sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo; indirectSpecular *= sheenEnergyComp; indirectDiffuse *= sheenEnergyComp; #endif reflectedLight.indirectSpecular += indirectSpecular; reflectedLight.indirectDiffuse += indirectDiffuse; } #define RE_Direct RE_Direct_Physical #define RE_Direct_RectArea RE_Direct_RectArea_Physical #define RE_IndirectDiffuse RE_IndirectDiffuse_Physical #define RE_IndirectSpecular RE_IndirectSpecular_Physical float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) { return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion ); }`,lights_fragment_begin:` vec3 geometryPosition = - vViewPosition; vec3 geometryNormal = normal; vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition ); vec3 geometryClearcoatNormal = vec3( 0.0 ); #ifdef USE_CLEARCOAT geometryClearcoatNormal = clearcoatNormal; #endif #ifdef USE_IRIDESCENCE float dotNVi = saturate( dot( normal, geometryViewDir ) ); if ( material.iridescenceThickness == 0.0 ) { material.iridescence = 0.0; } else { material.iridescence = saturate( material.iridescence ); } if ( material.iridescence > 0.0 ) { material.iridescenceFresnelDielectric = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor ); material.iridescenceFresnelMetallic = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.diffuseColor ); material.iridescenceFresnel = mix( material.iridescenceFresnelDielectric, material.iridescenceFresnelMetallic, material.metalness ); material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi ); } #endif IncidentLight directLight; #if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct ) PointLight pointLight; #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0 PointLightShadow pointLightShadow; #endif #pragma unroll_loop_start for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { pointLight = pointLights[ i ]; getPointLightInfo( pointLight, geometryPosition, directLight ); #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) ) pointLightShadow = pointLightShadows[ i ]; directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0; #endif RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); } #pragma unroll_loop_end #endif #if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct ) SpotLight spotLight; vec4 spotColor; vec3 spotLightCoord; bool inSpotLightMap; #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0 SpotLightShadow spotLightShadow; #endif #pragma unroll_loop_start for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { spotLight = spotLights[ i ]; getSpotLightInfo( spotLight, geometryPosition, directLight ); #if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) #define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX #elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) #define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS #else #define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) #endif #if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS ) spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w; inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) ); spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy ); directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color; #endif #undef SPOT_LIGHT_MAP_INDEX #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) spotLightShadow = spotLightShadows[ i ]; directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; #endif RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); } #pragma unroll_loop_end #endif #if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) DirectionalLight directionalLight; #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 DirectionalLightShadow directionalLightShadow; #endif #pragma unroll_loop_start for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { directionalLight = directionalLights[ i ]; getDirectionalLightInfo( directionalLight, directLight ); #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) directionalLightShadow = directionalLightShadows[ i ]; directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; #endif RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); } #pragma unroll_loop_end #endif #if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea ) RectAreaLight rectAreaLight; #pragma unroll_loop_start for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) { rectAreaLight = rectAreaLights[ i ]; RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); } #pragma unroll_loop_end #endif #if defined( RE_IndirectDiffuse ) vec3 iblIrradiance = vec3( 0.0 ); vec3 irradiance = getAmbientLightIrradiance( ambientLightColor ); #if defined( USE_LIGHT_PROBES ) irradiance += getLightProbeIrradiance( lightProbe, geometryNormal ); #endif #if ( NUM_HEMI_LIGHTS > 0 ) #pragma unroll_loop_start for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal ); } #pragma unroll_loop_end #endif #endif #if defined( RE_IndirectSpecular ) vec3 radiance = vec3( 0.0 ); vec3 clearcoatRadiance = vec3( 0.0 ); #endif`,lights_fragment_maps:`#if defined( RE_IndirectDiffuse ) #ifdef USE_LIGHTMAP vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity; irradiance += lightMapIrradiance; #endif #if defined( USE_ENVMAP ) && defined( ENVMAP_TYPE_CUBE_UV ) #if defined( STANDARD ) || defined( LAMBERT ) || defined( PHONG ) iblIrradiance += getIBLIrradiance( geometryNormal ); #endif #endif #endif #if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular ) #ifdef USE_ANISOTROPY radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy ); #else radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness ); #endif #ifdef USE_CLEARCOAT clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness ); #endif #endif`,lights_fragment_end:`#if defined( RE_IndirectDiffuse ) #if defined( LAMBERT ) || defined( PHONG ) irradiance += iblIrradiance; #endif RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); #endif #if defined( RE_IndirectSpecular ) RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); #endif`,logdepthbuf_fragment:`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER ) gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5; #endif`,logdepthbuf_pars_fragment:`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER ) uniform float logDepthBufFC; varying float vFragDepth; varying float vIsPerspective; #endif`,logdepthbuf_pars_vertex:`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER varying float vFragDepth; varying float vIsPerspective; #endif`,logdepthbuf_vertex:`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER vFragDepth = 1.0 + gl_Position.w; vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) ); #endif`,map_fragment:`#ifdef USE_MAP vec4 sampledDiffuseColor = texture2D( map, vMapUv ); #ifdef DECODE_VIDEO_TEXTURE sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor ); #endif diffuseColor *= sampledDiffuseColor; #endif`,map_pars_fragment:`#ifdef USE_MAP uniform sampler2D map; #endif`,map_particle_fragment:`#if defined( USE_MAP ) || defined( USE_ALPHAMAP ) #if defined( USE_POINTS_UV ) vec2 uv = vUv; #else vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy; #endif #endif #ifdef USE_MAP diffuseColor *= texture2D( map, uv ); #endif #ifdef USE_ALPHAMAP diffuseColor.a *= texture2D( alphaMap, uv ).g; #endif`,map_particle_pars_fragment:`#if defined( USE_POINTS_UV ) varying vec2 vUv; #else #if defined( USE_MAP ) || defined( USE_ALPHAMAP ) uniform mat3 uvTransform; #endif #endif #ifdef USE_MAP uniform sampler2D map; #endif #ifdef USE_ALPHAMAP uniform sampler2D alphaMap; #endif`,metalnessmap_fragment:`float metalnessFactor = metalness; #ifdef USE_METALNESSMAP vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv ); metalnessFactor *= texelMetalness.b; #endif`,metalnessmap_pars_fragment:`#ifdef USE_METALNESSMAP uniform sampler2D metalnessMap; #endif`,morphinstance_vertex:`#ifdef USE_INSTANCING_MORPH float morphTargetInfluences[ MORPHTARGETS_COUNT ]; float morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r; for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { morphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r; } #endif`,morphcolor_vertex:`#if defined( USE_MORPHCOLORS ) vColor *= morphTargetBaseInfluence; for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { #if defined( USE_COLOR_ALPHA ) if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ]; #elif defined( USE_COLOR ) if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ]; #endif } #endif`,morphnormal_vertex:`#ifdef USE_MORPHNORMALS objectNormal *= morphTargetBaseInfluence; for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ]; } #endif`,morphtarget_pars_vertex:`#ifdef USE_MORPHTARGETS #ifndef USE_INSTANCING_MORPH uniform float morphTargetBaseInfluence; uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ]; #endif uniform sampler2DArray morphTargetsTexture; uniform ivec2 morphTargetsTextureSize; vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) { int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset; int y = texelIndex / morphTargetsTextureSize.x; int x = texelIndex - y * morphTargetsTextureSize.x; ivec3 morphUV = ivec3( x, y, morphTargetIndex ); return texelFetch( morphTargetsTexture, morphUV, 0 ); } #endif`,morphtarget_vertex:`#ifdef USE_MORPHTARGETS transformed *= morphTargetBaseInfluence; for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ]; } #endif`,normal_fragment_begin:`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0; #ifdef FLAT_SHADED vec3 fdx = dFdx( vViewPosition ); vec3 fdy = dFdy( vViewPosition ); vec3 normal = normalize( cross( fdx, fdy ) ); #else vec3 normal = normalize( vNormal ); #ifdef DOUBLE_SIDED normal *= faceDirection; #endif #endif #if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) #ifdef USE_TANGENT mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); #else mat3 tbn = getTangentFrame( - vViewPosition, normal, #if defined( USE_NORMALMAP ) vNormalMapUv #elif defined( USE_CLEARCOAT_NORMALMAP ) vClearcoatNormalMapUv #else vUv #endif ); #endif #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) tbn[0] *= faceDirection; tbn[1] *= faceDirection; #endif #endif #ifdef USE_CLEARCOAT_NORMALMAP #ifdef USE_TANGENT mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); #else mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv ); #endif #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) tbn2[0] *= faceDirection; tbn2[1] *= faceDirection; #endif #endif vec3 nonPerturbedNormal = normal;`,normal_fragment_maps:`#ifdef USE_NORMALMAP_OBJECTSPACE normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; #ifdef FLIP_SIDED normal = - normal; #endif #ifdef DOUBLE_SIDED normal = normal * faceDirection; #endif normal = normalize( normalMatrix * normal ); #elif defined( USE_NORMALMAP_TANGENTSPACE ) vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; mapN.xy *= normalScale; normal = normalize( tbn * mapN ); #elif defined( USE_BUMPMAP ) normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection ); #endif`,normal_pars_fragment:`#ifndef FLAT_SHADED varying vec3 vNormal; #ifdef USE_TANGENT varying vec3 vTangent; varying vec3 vBitangent; #endif #endif`,normal_pars_vertex:`#ifndef FLAT_SHADED varying vec3 vNormal; #ifdef USE_TANGENT varying vec3 vTangent; varying vec3 vBitangent; #endif #endif`,normal_vertex:`#ifndef FLAT_SHADED vNormal = normalize( transformedNormal ); #ifdef USE_TANGENT vTangent = normalize( transformedTangent ); vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w ); #endif #endif`,normalmap_pars_fragment:`#ifdef USE_NORMALMAP uniform sampler2D normalMap; uniform vec2 normalScale; #endif #ifdef USE_NORMALMAP_OBJECTSPACE uniform mat3 normalMatrix; #endif #if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) ) mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) { vec3 q0 = dFdx( eye_pos.xyz ); vec3 q1 = dFdy( eye_pos.xyz ); vec2 st0 = dFdx( uv.st ); vec2 st1 = dFdy( uv.st ); vec3 N = surf_norm; vec3 q1perp = cross( q1, N ); vec3 q0perp = cross( N, q0 ); vec3 T = q1perp * st0.x + q0perp * st1.x; vec3 B = q1perp * st0.y + q0perp * st1.y; float det = max( dot( T, T ), dot( B, B ) ); float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det ); return mat3( T * scale, B * scale, N ); } #endif`,clearcoat_normal_fragment_begin:`#ifdef USE_CLEARCOAT vec3 clearcoatNormal = nonPerturbedNormal; #endif`,clearcoat_normal_fragment_maps:`#ifdef USE_CLEARCOAT_NORMALMAP vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0; clearcoatMapN.xy *= clearcoatNormalScale; clearcoatNormal = normalize( tbn2 * clearcoatMapN ); #endif`,clearcoat_pars_fragment:`#ifdef USE_CLEARCOATMAP uniform sampler2D clearcoatMap; #endif #ifdef USE_CLEARCOAT_NORMALMAP uniform sampler2D clearcoatNormalMap; uniform vec2 clearcoatNormalScale; #endif #ifdef USE_CLEARCOAT_ROUGHNESSMAP uniform sampler2D clearcoatRoughnessMap; #endif`,iridescence_pars_fragment:`#ifdef USE_IRIDESCENCEMAP uniform sampler2D iridescenceMap; #endif #ifdef USE_IRIDESCENCE_THICKNESSMAP uniform sampler2D iridescenceThicknessMap; #endif`,opaque_fragment:`#ifdef OPAQUE diffuseColor.a = 1.0; #endif #ifdef USE_TRANSMISSION diffuseColor.a *= material.transmissionAlpha; #endif gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,packing:`vec3 packNormalToRGB( const in vec3 normal ) { return normalize( normal ) * 0.5 + 0.5; } vec3 unpackRGBToNormal( const in vec3 rgb ) { return 2.0 * rgb.xyz - 1.0; } const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.; const float Inv255 = 1. / 255.; const vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 ); const vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g ); const vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b ); const vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a ); vec4 packDepthToRGBA( const in float v ) { if( v <= 0.0 ) return vec4( 0., 0., 0., 0. ); if( v >= 1.0 ) return vec4( 1., 1., 1., 1. ); float vuf; float af = modf( v * PackFactors.a, vuf ); float bf = modf( vuf * ShiftRight8, vuf ); float gf = modf( vuf * ShiftRight8, vuf ); return vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af ); } vec3 packDepthToRGB( const in float v ) { if( v <= 0.0 ) return vec3( 0., 0., 0. ); if( v >= 1.0 ) return vec3( 1., 1., 1. ); float vuf; float bf = modf( v * PackFactors.b, vuf ); float gf = modf( vuf * ShiftRight8, vuf ); return vec3( vuf * Inv255, gf * PackUpscale, bf ); } vec2 packDepthToRG( const in float v ) { if( v <= 0.0 ) return vec2( 0., 0. ); if( v >= 1.0 ) return vec2( 1., 1. ); float vuf; float gf = modf( v * 256., vuf ); return vec2( vuf * Inv255, gf ); } float unpackRGBAToDepth( const in vec4 v ) { return dot( v, UnpackFactors4 ); } float unpackRGBToDepth( const in vec3 v ) { return dot( v, UnpackFactors3 ); } float unpackRGToDepth( const in vec2 v ) { return v.r * UnpackFactors2.r + v.g * UnpackFactors2.g; } vec4 pack2HalfToRGBA( const in vec2 v ) { vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) ); return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w ); } vec2 unpackRGBATo2Half( const in vec4 v ) { return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) ); } float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) { return ( viewZ + near ) / ( near - far ); } float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) { #ifdef USE_REVERSED_DEPTH_BUFFER return depth * ( far - near ) - far; #else return depth * ( near - far ) - near; #endif } float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) { return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ ); } float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) { #ifdef USE_REVERSED_DEPTH_BUFFER return ( near * far ) / ( ( near - far ) * depth - near ); #else return ( near * far ) / ( ( far - near ) * depth - far ); #endif }`,premultiplied_alpha_fragment:`#ifdef PREMULTIPLIED_ALPHA gl_FragColor.rgb *= gl_FragColor.a; #endif`,project_vertex:`vec4 mvPosition = vec4( transformed, 1.0 ); #ifdef USE_BATCHING mvPosition = batchingMatrix * mvPosition; #endif #ifdef USE_INSTANCING mvPosition = instanceMatrix * mvPosition; #endif mvPosition = modelViewMatrix * mvPosition; gl_Position = projectionMatrix * mvPosition;`,dithering_fragment:`#ifdef DITHERING gl_FragColor.rgb = dithering( gl_FragColor.rgb ); #endif`,dithering_pars_fragment:`#ifdef DITHERING vec3 dithering( vec3 color ) { float grid_position = rand( gl_FragCoord.xy ); vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 ); dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position ); return color + dither_shift_RGB; } #endif`,roughnessmap_fragment:`float roughnessFactor = roughness; #ifdef USE_ROUGHNESSMAP vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv ); roughnessFactor *= texelRoughness.g; #endif`,roughnessmap_pars_fragment:`#ifdef USE_ROUGHNESSMAP uniform sampler2D roughnessMap; #endif`,shadowmap_pars_fragment:`#if NUM_SPOT_LIGHT_COORDS > 0 varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; #endif #if NUM_SPOT_LIGHT_MAPS > 0 uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ]; #endif #ifdef USE_SHADOWMAP #if NUM_DIR_LIGHT_SHADOWS > 0 #if defined( SHADOWMAP_TYPE_PCF ) uniform sampler2DShadow directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ]; #else uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ]; #endif varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; struct DirectionalLightShadow { float shadowIntensity; float shadowBias; float shadowNormalBias; float shadowRadius; vec2 shadowMapSize; }; uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; #endif #if NUM_SPOT_LIGHT_SHADOWS > 0 #if defined( SHADOWMAP_TYPE_PCF ) uniform sampler2DShadow spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ]; #else uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ]; #endif struct SpotLightShadow { float shadowIntensity; float shadowBias; float shadowNormalBias; float shadowRadius; vec2 shadowMapSize; }; uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; #endif #if NUM_POINT_LIGHT_SHADOWS > 0 #if defined( SHADOWMAP_TYPE_PCF ) uniform samplerCubeShadow pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ]; #elif defined( SHADOWMAP_TYPE_BASIC ) uniform samplerCube pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ]; #endif varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; struct PointLightShadow { float shadowIntensity; float shadowBias; float shadowNormalBias; float shadowRadius; vec2 shadowMapSize; float shadowCameraNear; float shadowCameraFar; }; uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; #endif #if defined( SHADOWMAP_TYPE_PCF ) float interleavedGradientNoise( vec2 position ) { return fract( 52.9829189 * fract( dot( position, vec2( 0.06711056, 0.00583715 ) ) ) ); } vec2 vogelDiskSample( int sampleIndex, int samplesCount, float phi ) { const float goldenAngle = 2.399963229728653; float r = sqrt( ( float( sampleIndex ) + 0.5 ) / float( samplesCount ) ); float theta = float( sampleIndex ) * goldenAngle + phi; return vec2( cos( theta ), sin( theta ) ) * r; } #endif #if defined( SHADOWMAP_TYPE_PCF ) float getShadow( sampler2DShadow shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) { float shadow = 1.0; shadowCoord.xyz /= shadowCoord.w; shadowCoord.z += shadowBias; bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0; bool frustumTest = inFrustum && shadowCoord.z <= 1.0; if ( frustumTest ) { vec2 texelSize = vec2( 1.0 ) / shadowMapSize; float radius = shadowRadius * texelSize.x; float phi = interleavedGradientNoise( gl_FragCoord.xy ) * PI2; shadow = ( texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 0, 5, phi ) * radius, shadowCoord.z ) ) + texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 1, 5, phi ) * radius, shadowCoord.z ) ) + texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 2, 5, phi ) * radius, shadowCoord.z ) ) + texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 3, 5, phi ) * radius, shadowCoord.z ) ) + texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 4, 5, phi ) * radius, shadowCoord.z ) ) ) * 0.2; } return mix( 1.0, shadow, shadowIntensity ); } #elif defined( SHADOWMAP_TYPE_VSM ) float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) { float shadow = 1.0; shadowCoord.xyz /= shadowCoord.w; #ifdef USE_REVERSED_DEPTH_BUFFER shadowCoord.z -= shadowBias; #else shadowCoord.z += shadowBias; #endif bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0; bool frustumTest = inFrustum && shadowCoord.z <= 1.0; if ( frustumTest ) { vec2 distribution = texture2D( shadowMap, shadowCoord.xy ).rg; float mean = distribution.x; float variance = distribution.y * distribution.y; #ifdef USE_REVERSED_DEPTH_BUFFER float hard_shadow = step( mean, shadowCoord.z ); #else float hard_shadow = step( shadowCoord.z, mean ); #endif if ( hard_shadow == 1.0 ) { shadow = 1.0; } else { variance = max( variance, 0.0000001 ); float d = shadowCoord.z - mean; float p_max = variance / ( variance + d * d ); p_max = clamp( ( p_max - 0.3 ) / 0.65, 0.0, 1.0 ); shadow = max( hard_shadow, p_max ); } } return mix( 1.0, shadow, shadowIntensity ); } #else float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) { float shadow = 1.0; shadowCoord.xyz /= shadowCoord.w; #ifdef USE_REVERSED_DEPTH_BUFFER shadowCoord.z -= shadowBias; #else shadowCoord.z += shadowBias; #endif bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0; bool frustumTest = inFrustum && shadowCoord.z <= 1.0; if ( frustumTest ) { float depth = texture2D( shadowMap, shadowCoord.xy ).r; #ifdef USE_REVERSED_DEPTH_BUFFER shadow = step( depth, shadowCoord.z ); #else shadow = step( shadowCoord.z, depth ); #endif } return mix( 1.0, shadow, shadowIntensity ); } #endif #if NUM_POINT_LIGHT_SHADOWS > 0 #if defined( SHADOWMAP_TYPE_PCF ) float getPointShadow( samplerCubeShadow shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) { float shadow = 1.0; vec3 lightToPosition = shadowCoord.xyz; vec3 bd3D = normalize( lightToPosition ); vec3 absVec = abs( lightToPosition ); float viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z ); if ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) { #ifdef USE_REVERSED_DEPTH_BUFFER float dp = ( shadowCameraNear * ( shadowCameraFar - viewSpaceZ ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) ); dp -= shadowBias; #else float dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) ); dp += shadowBias; #endif float texelSize = shadowRadius / shadowMapSize.x; vec3 absDir = abs( bd3D ); vec3 tangent = absDir.x > absDir.z ? vec3( 0.0, 1.0, 0.0 ) : vec3( 1.0, 0.0, 0.0 ); tangent = normalize( cross( bd3D, tangent ) ); vec3 bitangent = cross( bd3D, tangent ); float phi = interleavedGradientNoise( gl_FragCoord.xy ) * PI2; vec2 sample0 = vogelDiskSample( 0, 5, phi ); vec2 sample1 = vogelDiskSample( 1, 5, phi ); vec2 sample2 = vogelDiskSample( 2, 5, phi ); vec2 sample3 = vogelDiskSample( 3, 5, phi ); vec2 sample4 = vogelDiskSample( 4, 5, phi ); shadow = ( texture( shadowMap, vec4( bd3D + ( tangent * sample0.x + bitangent * sample0.y ) * texelSize, dp ) ) + texture( shadowMap, vec4( bd3D + ( tangent * sample1.x + bitangent * sample1.y ) * texelSize, dp ) ) + texture( shadowMap, vec4( bd3D + ( tangent * sample2.x + bitangent * sample2.y ) * texelSize, dp ) ) + texture( shadowMap, vec4( bd3D + ( tangent * sample3.x + bitangent * sample3.y ) * texelSize, dp ) ) + texture( shadowMap, vec4( bd3D + ( tangent * sample4.x + bitangent * sample4.y ) * texelSize, dp ) ) ) * 0.2; } return mix( 1.0, shadow, shadowIntensity ); } #elif defined( SHADOWMAP_TYPE_BASIC ) float getPointShadow( samplerCube shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) { float shadow = 1.0; vec3 lightToPosition = shadowCoord.xyz; vec3 absVec = abs( lightToPosition ); float viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z ); if ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) { float dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) ); dp += shadowBias; vec3 bd3D = normalize( lightToPosition ); float depth = textureCube( shadowMap, bd3D ).r; #ifdef USE_REVERSED_DEPTH_BUFFER depth = 1.0 - depth; #endif shadow = step( dp, depth ); } return mix( 1.0, shadow, shadowIntensity ); } #endif #endif #endif`,shadowmap_pars_vertex:`#if NUM_SPOT_LIGHT_COORDS > 0 uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ]; varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; #endif #ifdef USE_SHADOWMAP #if NUM_DIR_LIGHT_SHADOWS > 0 uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ]; varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; struct DirectionalLightShadow { float shadowIntensity; float shadowBias; float shadowNormalBias; float shadowRadius; vec2 shadowMapSize; }; uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; #endif #if NUM_SPOT_LIGHT_SHADOWS > 0 struct SpotLightShadow { float shadowIntensity; float shadowBias; float shadowNormalBias; float shadowRadius; vec2 shadowMapSize; }; uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; #endif #if NUM_POINT_LIGHT_SHADOWS > 0 uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ]; varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; struct PointLightShadow { float shadowIntensity; float shadowBias; float shadowNormalBias; float shadowRadius; vec2 shadowMapSize; float shadowCameraNear; float shadowCameraFar; }; uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; #endif #endif`,shadowmap_vertex:`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 ) vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); vec4 shadowWorldPosition; #endif #if defined( USE_SHADOWMAP ) #if NUM_DIR_LIGHT_SHADOWS > 0 #pragma unroll_loop_start for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 ); vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition; } #pragma unroll_loop_end #endif #if NUM_POINT_LIGHT_SHADOWS > 0 #pragma unroll_loop_start for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 ); vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition; } #pragma unroll_loop_end #endif #endif #if NUM_SPOT_LIGHT_COORDS > 0 #pragma unroll_loop_start for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) { shadowWorldPosition = worldPosition; #if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias; #endif vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition; } #pragma unroll_loop_end #endif`,shadowmask_pars_fragment:`float getShadowMask() { float shadow = 1.0; #ifdef USE_SHADOWMAP #if NUM_DIR_LIGHT_SHADOWS > 0 DirectionalLightShadow directionalLight; #pragma unroll_loop_start for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { directionalLight = directionalLightShadows[ i ]; shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; } #pragma unroll_loop_end #endif #if NUM_SPOT_LIGHT_SHADOWS > 0 SpotLightShadow spotLight; #pragma unroll_loop_start for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) { spotLight = spotLightShadows[ i ]; shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; } #pragma unroll_loop_end #endif #if NUM_POINT_LIGHT_SHADOWS > 0 && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) ) PointLightShadow pointLight; #pragma unroll_loop_start for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { pointLight = pointLightShadows[ i ]; shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0; } #pragma unroll_loop_end #endif #endif return shadow; }`,skinbase_vertex:`#ifdef USE_SKINNING mat4 boneMatX = getBoneMatrix( skinIndex.x ); mat4 boneMatY = getBoneMatrix( skinIndex.y ); mat4 boneMatZ = getBoneMatrix( skinIndex.z ); mat4 boneMatW = getBoneMatrix( skinIndex.w ); #endif`,skinning_pars_vertex:`#ifdef USE_SKINNING uniform mat4 bindMatrix; uniform mat4 bindMatrixInverse; uniform highp sampler2D boneTexture; mat4 getBoneMatrix( const in float i ) { int size = textureSize( boneTexture, 0 ).x; int j = int( i ) * 4; int x = j % size; int y = j / size; vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 ); vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 ); vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 ); vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 ); return mat4( v1, v2, v3, v4 ); } #endif`,skinning_vertex:`#ifdef USE_SKINNING vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); vec4 skinned = vec4( 0.0 ); skinned += boneMatX * skinVertex * skinWeight.x; skinned += boneMatY * skinVertex * skinWeight.y; skinned += boneMatZ * skinVertex * skinWeight.z; skinned += boneMatW * skinVertex * skinWeight.w; transformed = ( bindMatrixInverse * skinned ).xyz; #endif`,skinnormal_vertex:`#ifdef USE_SKINNING mat4 skinMatrix = mat4( 0.0 ); skinMatrix += skinWeight.x * boneMatX; skinMatrix += skinWeight.y * boneMatY; skinMatrix += skinWeight.z * boneMatZ; skinMatrix += skinWeight.w * boneMatW; skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix; objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz; #ifdef USE_TANGENT objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz; #endif #endif`,specularmap_fragment:`float specularStrength; #ifdef USE_SPECULARMAP vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv ); specularStrength = texelSpecular.r; #else specularStrength = 1.0; #endif`,specularmap_pars_fragment:`#ifdef USE_SPECULARMAP uniform sampler2D specularMap; #endif`,tonemapping_fragment:`#if defined( TONE_MAPPING ) gl_FragColor.rgb = toneMapping( gl_FragColor.rgb ); #endif`,tonemapping_pars_fragment:`#ifndef saturate #define saturate( a ) clamp( a, 0.0, 1.0 ) #endif uniform float toneMappingExposure; vec3 LinearToneMapping( vec3 color ) { return saturate( toneMappingExposure * color ); } vec3 ReinhardToneMapping( vec3 color ) { color *= toneMappingExposure; return saturate( color / ( vec3( 1.0 ) + color ) ); } vec3 CineonToneMapping( vec3 color ) { color *= toneMappingExposure; color = max( vec3( 0.0 ), color - 0.004 ); return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) ); } vec3 RRTAndODTFit( vec3 v ) { vec3 a = v * ( v + 0.0245786 ) - 0.000090537; vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081; return a / b; } vec3 ACESFilmicToneMapping( vec3 color ) { const mat3 ACESInputMat = mat3( vec3( 0.59719, 0.07600, 0.02840 ), vec3( 0.35458, 0.90834, 0.13383 ), vec3( 0.04823, 0.01566, 0.83777 ) ); const mat3 ACESOutputMat = mat3( vec3( 1.60475, -0.10208, -0.00327 ), vec3( -0.53108, 1.10813, -0.07276 ), vec3( -0.07367, -0.00605, 1.07602 ) ); color *= toneMappingExposure / 0.6; color = ACESInputMat * color; color = RRTAndODTFit( color ); color = ACESOutputMat * color; return saturate( color ); } const mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3( vec3( 1.6605, - 0.1246, - 0.0182 ), vec3( - 0.5876, 1.1329, - 0.1006 ), vec3( - 0.0728, - 0.0083, 1.1187 ) ); const mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3( vec3( 0.6274, 0.0691, 0.0164 ), vec3( 0.3293, 0.9195, 0.0880 ), vec3( 0.0433, 0.0113, 0.8956 ) ); vec3 agxDefaultContrastApprox( vec3 x ) { vec3 x2 = x * x; vec3 x4 = x2 * x2; return + 15.5 * x4 * x2 - 40.14 * x4 * x + 31.96 * x4 - 6.868 * x2 * x + 0.4298 * x2 + 0.1191 * x - 0.00232; } vec3 AgXToneMapping( vec3 color ) { const mat3 AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) ); const mat3 AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) ); const float AgxMinEv = - 12.47393; const float AgxMaxEv = 4.026069; color *= toneMappingExposure; color = LINEAR_SRGB_TO_LINEAR_REC2020 * color; color = AgXInsetMatrix * color; color = max( color, 1e-10 ); color = log2( color ); color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv ); color = clamp( color, 0.0, 1.0 ); color = agxDefaultContrastApprox( color ); color = AgXOutsetMatrix * color; color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) ); color = LINEAR_REC2020_TO_LINEAR_SRGB * color; color = clamp( color, 0.0, 1.0 ); return color; } vec3 NeutralToneMapping( vec3 color ) { const float StartCompression = 0.8 - 0.04; const float Desaturation = 0.15; color *= toneMappingExposure; float x = min( color.r, min( color.g, color.b ) ); float offset = x < 0.08 ? x - 6.25 * x * x : 0.04; color -= offset; float peak = max( color.r, max( color.g, color.b ) ); if ( peak < StartCompression ) return color; float d = 1. - StartCompression; float newPeak = 1. - d * d / ( peak + d - StartCompression ); color *= newPeak / peak; float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. ); return mix( color, vec3( newPeak ), g ); } vec3 CustomToneMapping( vec3 color ) { return color; }`,transmission_fragment:`#ifdef USE_TRANSMISSION material.transmission = transmission; material.transmissionAlpha = 1.0; material.thickness = thickness; material.attenuationDistance = attenuationDistance; material.attenuationColor = attenuationColor; #ifdef USE_TRANSMISSIONMAP material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r; #endif #ifdef USE_THICKNESSMAP material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g; #endif vec3 pos = vWorldPosition; vec3 v = normalize( cameraPosition - pos ); vec3 n = inverseTransformDirection( normal, viewMatrix ); vec4 transmitted = getIBLVolumeRefraction( n, v, material.roughness, material.diffuseContribution, material.specularColorBlended, material.specularF90, pos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness, material.attenuationColor, material.attenuationDistance ); material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission ); totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission ); #endif`,transmission_pars_fragment:`#ifdef USE_TRANSMISSION uniform float transmission; uniform float thickness; uniform float attenuationDistance; uniform vec3 attenuationColor; #ifdef USE_TRANSMISSIONMAP uniform sampler2D transmissionMap; #endif #ifdef USE_THICKNESSMAP uniform sampler2D thicknessMap; #endif uniform vec2 transmissionSamplerSize; uniform sampler2D transmissionSamplerMap; uniform mat4 modelMatrix; uniform mat4 projectionMatrix; varying vec3 vWorldPosition; float w0( float a ) { return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 ); } float w1( float a ) { return ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 ); } float w2( float a ){ return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 ); } float w3( float a ) { return ( 1.0 / 6.0 ) * ( a * a * a ); } float g0( float a ) { return w0( a ) + w1( a ); } float g1( float a ) { return w2( a ) + w3( a ); } float h0( float a ) { return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) ); } float h1( float a ) { return 1.0 + w3( a ) / ( w2( a ) + w3( a ) ); } vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) { uv = uv * texelSize.zw + 0.5; vec2 iuv = floor( uv ); vec2 fuv = fract( uv ); float g0x = g0( fuv.x ); float g1x = g1( fuv.x ); float h0x = h0( fuv.x ); float h1x = h1( fuv.x ); float h0y = h0( fuv.y ); float h1y = h1( fuv.y ); vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) + g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) ); } vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) { vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) ); vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) ); vec2 fLodSizeInv = 1.0 / fLodSize; vec2 cLodSizeInv = 1.0 / cLodSize; vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) ); vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) ); return mix( fSample, cSample, fract( lod ) ); } vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) { vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior ); vec3 modelScale; modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) ); modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) ); modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) ); return normalize( refractionVector ) * thickness * modelScale; } float applyIorToRoughness( const in float roughness, const in float ior ) { return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 ); } vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) { float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior ); return textureBicubic( transmissionSamplerMap, fragCoord.xy, lod ); } vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) { if ( isinf( attenuationDistance ) ) { return vec3( 1.0 ); } else { vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance; vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); return transmittance; } } vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor, const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix, const in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness, const in vec3 attenuationColor, const in float attenuationDistance ) { vec4 transmittedLight; vec3 transmittance; #ifdef USE_DISPERSION float halfSpread = ( ior - 1.0 ) * 0.025 * dispersion; vec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread ); for ( int i = 0; i < 3; i ++ ) { vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix ); vec3 refractedRayExit = position + transmissionRay; vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); vec2 refractionCoords = ndcPos.xy / ndcPos.w; refractionCoords += 1.0; refractionCoords /= 2.0; vec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] ); transmittedLight[ i ] = transmissionSample[ i ]; transmittedLight.a += transmissionSample.a; transmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ]; } transmittedLight.a /= 3.0; #else vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix ); vec3 refractedRayExit = position + transmissionRay; vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); vec2 refractionCoords = ndcPos.xy / ndcPos.w; refractionCoords += 1.0; refractionCoords /= 2.0; transmittedLight = getTransmissionSample( refractionCoords, roughness, ior ); transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ); #endif vec3 attenuatedColor = transmittance * transmittedLight.rgb; vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness ); float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0; return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor ); } #endif`,uv_pars_fragment:`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) varying vec2 vUv; #endif #ifdef USE_MAP varying vec2 vMapUv; #endif #ifdef USE_ALPHAMAP varying vec2 vAlphaMapUv; #endif #ifdef USE_LIGHTMAP varying vec2 vLightMapUv; #endif #ifdef USE_AOMAP varying vec2 vAoMapUv; #endif #ifdef USE_BUMPMAP varying vec2 vBumpMapUv; #endif #ifdef USE_NORMALMAP varying vec2 vNormalMapUv; #endif #ifdef USE_EMISSIVEMAP varying vec2 vEmissiveMapUv; #endif #ifdef USE_METALNESSMAP varying vec2 vMetalnessMapUv; #endif #ifdef USE_ROUGHNESSMAP varying vec2 vRoughnessMapUv; #endif #ifdef USE_ANISOTROPYMAP varying vec2 vAnisotropyMapUv; #endif #ifdef USE_CLEARCOATMAP varying vec2 vClearcoatMapUv; #endif #ifdef USE_CLEARCOAT_NORMALMAP varying vec2 vClearcoatNormalMapUv; #endif #ifdef USE_CLEARCOAT_ROUGHNESSMAP varying vec2 vClearcoatRoughnessMapUv; #endif #ifdef USE_IRIDESCENCEMAP varying vec2 vIridescenceMapUv; #endif #ifdef USE_IRIDESCENCE_THICKNESSMAP varying vec2 vIridescenceThicknessMapUv; #endif #ifdef USE_SHEEN_COLORMAP varying vec2 vSheenColorMapUv; #endif #ifdef USE_SHEEN_ROUGHNESSMAP varying vec2 vSheenRoughnessMapUv; #endif #ifdef USE_SPECULARMAP varying vec2 vSpecularMapUv; #endif #ifdef USE_SPECULAR_COLORMAP varying vec2 vSpecularColorMapUv; #endif #ifdef USE_SPECULAR_INTENSITYMAP varying vec2 vSpecularIntensityMapUv; #endif #ifdef USE_TRANSMISSIONMAP uniform mat3 transmissionMapTransform; varying vec2 vTransmissionMapUv; #endif #ifdef USE_THICKNESSMAP uniform mat3 thicknessMapTransform; varying vec2 vThicknessMapUv; #endif`,uv_pars_vertex:`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) varying vec2 vUv; #endif #ifdef USE_MAP uniform mat3 mapTransform; varying vec2 vMapUv; #endif #ifdef USE_ALPHAMAP uniform mat3 alphaMapTransform; varying vec2 vAlphaMapUv; #endif #ifdef USE_LIGHTMAP uniform mat3 lightMapTransform; varying vec2 vLightMapUv; #endif #ifdef USE_AOMAP uniform mat3 aoMapTransform; varying vec2 vAoMapUv; #endif #ifdef USE_BUMPMAP uniform mat3 bumpMapTransform; varying vec2 vBumpMapUv; #endif #ifdef USE_NORMALMAP uniform mat3 normalMapTransform; varying vec2 vNormalMapUv; #endif #ifdef USE_DISPLACEMENTMAP uniform mat3 displacementMapTransform; varying vec2 vDisplacementMapUv; #endif #ifdef USE_EMISSIVEMAP uniform mat3 emissiveMapTransform; varying vec2 vEmissiveMapUv; #endif #ifdef USE_METALNESSMAP uniform mat3 metalnessMapTransform; varying vec2 vMetalnessMapUv; #endif #ifdef USE_ROUGHNESSMAP uniform mat3 roughnessMapTransform; varying vec2 vRoughnessMapUv; #endif #ifdef USE_ANISOTROPYMAP uniform mat3 anisotropyMapTransform; varying vec2 vAnisotropyMapUv; #endif #ifdef USE_CLEARCOATMAP uniform mat3 clearcoatMapTransform; varying vec2 vClearcoatMapUv; #endif #ifdef USE_CLEARCOAT_NORMALMAP uniform mat3 clearcoatNormalMapTransform; varying vec2 vClearcoatNormalMapUv; #endif #ifdef USE_CLEARCOAT_ROUGHNESSMAP uniform mat3 clearcoatRoughnessMapTransform; varying vec2 vClearcoatRoughnessMapUv; #endif #ifdef USE_SHEEN_COLORMAP uniform mat3 sheenColorMapTransform; varying vec2 vSheenColorMapUv; #endif #ifdef USE_SHEEN_ROUGHNESSMAP uniform mat3 sheenRoughnessMapTransform; varying vec2 vSheenRoughnessMapUv; #endif #ifdef USE_IRIDESCENCEMAP uniform mat3 iridescenceMapTransform; varying vec2 vIridescenceMapUv; #endif #ifdef USE_IRIDESCENCE_THICKNESSMAP uniform mat3 iridescenceThicknessMapTransform; varying vec2 vIridescenceThicknessMapUv; #endif #ifdef USE_SPECULARMAP uniform mat3 specularMapTransform; varying vec2 vSpecularMapUv; #endif #ifdef USE_SPECULAR_COLORMAP uniform mat3 specularColorMapTransform; varying vec2 vSpecularColorMapUv; #endif #ifdef USE_SPECULAR_INTENSITYMAP uniform mat3 specularIntensityMapTransform; varying vec2 vSpecularIntensityMapUv; #endif #ifdef USE_TRANSMISSIONMAP uniform mat3 transmissionMapTransform; varying vec2 vTransmissionMapUv; #endif #ifdef USE_THICKNESSMAP uniform mat3 thicknessMapTransform; varying vec2 vThicknessMapUv; #endif`,uv_vertex:`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) vUv = vec3( uv, 1 ).xy; #endif #ifdef USE_MAP vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy; #endif #ifdef USE_ALPHAMAP vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy; #endif #ifdef USE_LIGHTMAP vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy; #endif #ifdef USE_AOMAP vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy; #endif #ifdef USE_BUMPMAP vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy; #endif #ifdef USE_NORMALMAP vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy; #endif #ifdef USE_DISPLACEMENTMAP vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy; #endif #ifdef USE_EMISSIVEMAP vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy; #endif #ifdef USE_METALNESSMAP vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy; #endif #ifdef USE_ROUGHNESSMAP vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy; #endif #ifdef USE_ANISOTROPYMAP vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy; #endif #ifdef USE_CLEARCOATMAP vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy; #endif #ifdef USE_CLEARCOAT_NORMALMAP vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy; #endif #ifdef USE_CLEARCOAT_ROUGHNESSMAP vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy; #endif #ifdef USE_IRIDESCENCEMAP vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy; #endif #ifdef USE_IRIDESCENCE_THICKNESSMAP vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy; #endif #ifdef USE_SHEEN_COLORMAP vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy; #endif #ifdef USE_SHEEN_ROUGHNESSMAP vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy; #endif #ifdef USE_SPECULARMAP vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy; #endif #ifdef USE_SPECULAR_COLORMAP vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy; #endif #ifdef USE_SPECULAR_INTENSITYMAP vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy; #endif #ifdef USE_TRANSMISSIONMAP vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy; #endif #ifdef USE_THICKNESSMAP vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy; #endif`,worldpos_vertex:`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0 vec4 worldPosition = vec4( transformed, 1.0 ); #ifdef USE_BATCHING worldPosition = batchingMatrix * worldPosition; #endif #ifdef USE_INSTANCING worldPosition = instanceMatrix * worldPosition; #endif worldPosition = modelMatrix * worldPosition; #endif`,background_vert:`varying vec2 vUv; uniform mat3 uvTransform; void main() { vUv = ( uvTransform * vec3( uv, 1 ) ).xy; gl_Position = vec4( position.xy, 1.0, 1.0 ); }`,background_frag:`uniform sampler2D t2D; uniform float backgroundIntensity; varying vec2 vUv; void main() { vec4 texColor = texture2D( t2D, vUv ); #ifdef DECODE_VIDEO_TEXTURE texColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w ); #endif texColor.rgb *= backgroundIntensity; gl_FragColor = texColor; #include #include }`,backgroundCube_vert:`varying vec3 vWorldDirection; #include void main() { vWorldDirection = transformDirection( position, modelMatrix ); #include #include gl_Position.z = gl_Position.w; }`,backgroundCube_frag:`#ifdef ENVMAP_TYPE_CUBE uniform samplerCube envMap; #elif defined( ENVMAP_TYPE_CUBE_UV ) uniform sampler2D envMap; #endif uniform float flipEnvMap; uniform float backgroundBlurriness; uniform float backgroundIntensity; uniform mat3 backgroundRotation; varying vec3 vWorldDirection; #include void main() { #ifdef ENVMAP_TYPE_CUBE vec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) ); #elif defined( ENVMAP_TYPE_CUBE_UV ) vec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness ); #else vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 ); #endif texColor.rgb *= backgroundIntensity; gl_FragColor = texColor; #include #include }`,cube_vert:`varying vec3 vWorldDirection; #include void main() { vWorldDirection = transformDirection( position, modelMatrix ); #include #include gl_Position.z = gl_Position.w; }`,cube_frag:`uniform samplerCube tCube; uniform float tFlip; uniform float opacity; varying vec3 vWorldDirection; void main() { vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) ); gl_FragColor = texColor; gl_FragColor.a *= opacity; #include #include }`,depth_vert:`#include #include #include #include #include #include #include #include varying vec2 vHighPrecisionZW; void main() { #include #include #include #include #ifdef USE_DISPLACEMENTMAP #include #include #include #endif #include #include #include #include #include #include #include vHighPrecisionZW = gl_Position.zw; }`,depth_frag:`#if DEPTH_PACKING == 3200 uniform float opacity; #endif #include #include #include #include #include #include #include #include #include varying vec2 vHighPrecisionZW; void main() { vec4 diffuseColor = vec4( 1.0 ); #include #if DEPTH_PACKING == 3200 diffuseColor.a = opacity; #endif #include #include #include #include #include #ifdef USE_REVERSED_DEPTH_BUFFER float fragCoordZ = vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ]; #else float fragCoordZ = 0.5 * vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ] + 0.5; #endif #if DEPTH_PACKING == 3200 gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity ); #elif DEPTH_PACKING == 3201 gl_FragColor = packDepthToRGBA( fragCoordZ ); #elif DEPTH_PACKING == 3202 gl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 ); #elif DEPTH_PACKING == 3203 gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 ); #endif }`,distance_vert:`#define DISTANCE varying vec3 vWorldPosition; #include #include #include #include #include #include #include void main() { #include #include #include #include #ifdef USE_DISPLACEMENTMAP #include #include #include #endif #include #include #include #include #include #include #include vWorldPosition = worldPosition.xyz; }`,distance_frag:`#define DISTANCE uniform vec3 referencePosition; uniform float nearDistance; uniform float farDistance; varying vec3 vWorldPosition; #include #include #include #include #include #include #include void main () { vec4 diffuseColor = vec4( 1.0 ); #include #include #include #include #include float dist = length( vWorldPosition - referencePosition ); dist = ( dist - nearDistance ) / ( farDistance - nearDistance ); dist = saturate( dist ); gl_FragColor = vec4( dist, 0.0, 0.0, 1.0 ); }`,equirect_vert:`varying vec3 vWorldDirection; #include void main() { vWorldDirection = transformDirection( position, modelMatrix ); #include #include }`,equirect_frag:`uniform sampler2D tEquirect; varying vec3 vWorldDirection; #include void main() { vec3 direction = normalize( vWorldDirection ); vec2 sampleUV = equirectUv( direction ); gl_FragColor = texture2D( tEquirect, sampleUV ); #include #include }`,linedashed_vert:`uniform float scale; attribute float lineDistance; varying float vLineDistance; #include #include #include #include #include #include #include void main() { vLineDistance = scale * lineDistance; #include #include #include #include #include #include #include #include #include #include }`,linedashed_frag:`uniform vec3 diffuse; uniform float opacity; uniform float dashSize; uniform float totalSize; varying float vLineDistance; #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include if ( mod( vLineDistance, totalSize ) > dashSize ) { discard; } vec3 outgoingLight = vec3( 0.0 ); #include #include #include outgoingLight = diffuseColor.rgb; #include #include #include #include #include }`,meshbasic_vert:`#include #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #if defined ( USE_ENVMAP ) || defined ( USE_SKINNING ) #include #include #include #include #include #endif #include #include #include #include #include #include #include #include #include }`,meshbasic_frag:`uniform vec3 diffuse; uniform float opacity; #ifndef FLAT_SHADED varying vec3 vNormal; #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include #include #include #include #include #include #include #include ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); #ifdef USE_LIGHTMAP vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI; #else reflectedLight.indirectDiffuse += vec3( 1.0 ); #endif #include reflectedLight.indirectDiffuse *= diffuseColor.rgb; vec3 outgoingLight = reflectedLight.indirectDiffuse; #include #include #include #include #include #include #include }`,meshlambert_vert:`#define LAMBERT varying vec3 vViewPosition; #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vViewPosition = - mvPosition.xyz; #include #include #include #include }`,meshlambert_frag:`#define LAMBERT uniform vec3 diffuse; uniform vec3 emissive; uniform float opacity; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); vec3 totalEmissiveRadiance = emissive; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; #include #include #include #include #include #include #include }`,meshmatcap_vert:`#define MATCAP varying vec3 vViewPosition; #include #include #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vViewPosition = - mvPosition.xyz; }`,meshmatcap_frag:`#define MATCAP uniform vec3 diffuse; uniform float opacity; uniform sampler2D matcap; varying vec3 vViewPosition; #include #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include #include #include #include #include #include #include #include #include vec3 viewDir = normalize( vViewPosition ); vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) ); vec3 y = cross( viewDir, x ); vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5; #ifdef USE_MATCAP vec4 matcapColor = texture2D( matcap, uv ); #else vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 ); #endif vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb; #include #include #include #include #include #include }`,meshnormal_vert:`#define NORMAL #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) varying vec3 vViewPosition; #endif #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) vViewPosition = - mvPosition.xyz; #endif }`,meshnormal_frag:`#define NORMAL uniform float opacity; #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) varying vec3 vViewPosition; #endif #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity ); #include #include #include #include gl_FragColor = vec4( normalize( normal ) * 0.5 + 0.5, diffuseColor.a ); #ifdef OPAQUE gl_FragColor.a = 1.0; #endif }`,meshphong_vert:`#define PHONG varying vec3 vViewPosition; #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vViewPosition = - mvPosition.xyz; #include #include #include #include }`,meshphong_frag:`#define PHONG uniform vec3 diffuse; uniform vec3 emissive; uniform vec3 specular; uniform float shininess; uniform float opacity; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); vec3 totalEmissiveRadiance = emissive; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance; #include #include #include #include #include #include #include }`,meshphysical_vert:`#define STANDARD varying vec3 vViewPosition; #ifdef USE_TRANSMISSION varying vec3 vWorldPosition; #endif #include #include #include #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vViewPosition = - mvPosition.xyz; #include #include #include #ifdef USE_TRANSMISSION vWorldPosition = worldPosition.xyz; #endif }`,meshphysical_frag:`#define STANDARD #ifdef PHYSICAL #define IOR #define USE_SPECULAR #endif uniform vec3 diffuse; uniform vec3 emissive; uniform float roughness; uniform float metalness; uniform float opacity; #ifdef IOR uniform float ior; #endif #ifdef USE_SPECULAR uniform float specularIntensity; uniform vec3 specularColor; #ifdef USE_SPECULAR_COLORMAP uniform sampler2D specularColorMap; #endif #ifdef USE_SPECULAR_INTENSITYMAP uniform sampler2D specularIntensityMap; #endif #endif #ifdef USE_CLEARCOAT uniform float clearcoat; uniform float clearcoatRoughness; #endif #ifdef USE_DISPERSION uniform float dispersion; #endif #ifdef USE_IRIDESCENCE uniform float iridescence; uniform float iridescenceIOR; uniform float iridescenceThicknessMinimum; uniform float iridescenceThicknessMaximum; #endif #ifdef USE_SHEEN uniform vec3 sheenColor; uniform float sheenRoughness; #ifdef USE_SHEEN_COLORMAP uniform sampler2D sheenColorMap; #endif #ifdef USE_SHEEN_ROUGHNESSMAP uniform sampler2D sheenRoughnessMap; #endif #endif #ifdef USE_ANISOTROPY uniform vec2 anisotropyVector; #ifdef USE_ANISOTROPYMAP uniform sampler2D anisotropyMap; #endif #endif varying vec3 vViewPosition; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); vec3 totalEmissiveRadiance = emissive; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse; vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular; #include vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance; #ifdef USE_SHEEN outgoingLight = outgoingLight + sheenSpecularDirect + sheenSpecularIndirect; #endif #ifdef USE_CLEARCOAT float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) ); vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc ); outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat; #endif #include #include #include #include #include #include }`,meshtoon_vert:`#define TOON varying vec3 vViewPosition; #include #include #include #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vViewPosition = - mvPosition.xyz; #include #include #include }`,meshtoon_frag:`#define TOON uniform vec3 diffuse; uniform vec3 emissive; uniform float opacity; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); vec3 totalEmissiveRadiance = emissive; #include #include #include #include #include #include #include #include #include #include #include #include #include #include vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; #include #include #include #include #include #include }`,points_vert:`uniform float size; uniform float scale; #include #include #include #include #include #include #ifdef USE_POINTS_UV varying vec2 vUv; uniform mat3 uvTransform; #endif void main() { #ifdef USE_POINTS_UV vUv = ( uvTransform * vec3( uv, 1 ) ).xy; #endif #include #include #include #include #include #include gl_PointSize = size; #ifdef USE_SIZEATTENUATION bool isPerspective = isPerspectiveMatrix( projectionMatrix ); if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z ); #endif #include #include #include #include }`,points_frag:`uniform vec3 diffuse; uniform float opacity; #include #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include vec3 outgoingLight = vec3( 0.0 ); #include #include #include #include #include outgoingLight = diffuseColor.rgb; #include #include #include #include #include }`,shadow_vert:`#include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include }`,shadow_frag:`uniform vec3 color; uniform float opacity; #include #include #include #include #include #include #include void main() { #include gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) ); #include #include #include #include }`,sprite_vert:`uniform float rotation; uniform vec2 center; #include #include #include #include #include void main() { #include vec4 mvPosition = modelViewMatrix[ 3 ]; vec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) ); #ifndef USE_SIZEATTENUATION bool isPerspective = isPerspectiveMatrix( projectionMatrix ); if ( isPerspective ) scale *= - mvPosition.z; #endif vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale; vec2 rotatedPosition; rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y; rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y; mvPosition.xy += rotatedPosition; gl_Position = projectionMatrix * mvPosition; #include #include #include }`,sprite_frag:`uniform vec3 diffuse; uniform float opacity; #include #include #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include vec3 outgoingLight = vec3( 0.0 ); #include #include #include #include #include outgoingLight = diffuseColor.rgb; #include #include #include #include }`},Z={common:{diffuse:{value:new Y(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new q},alphaMap:{value:null},alphaMapTransform:{value:new q},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new q}},envmap:{envMap:{value:null},envMapRotation:{value:new q},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98},dfgLUT:{value:null}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new q}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new q}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new q},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new q},normalScale:{value:new G(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new q},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new q}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new q}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new q}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new Y(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new Y(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new q},alphaTest:{value:0},uvTransform:{value:new q}},sprite:{diffuse:{value:new Y(16777215)},opacity:{value:1},center:{value:new G(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new q},alphaMap:{value:null},alphaMapTransform:{value:new q},alphaTest:{value:0}}},Qi={basic:{uniforms:Yr([Z.common,Z.specularmap,Z.envmap,Z.aomap,Z.lightmap,Z.fog]),vertexShader:X.meshbasic_vert,fragmentShader:X.meshbasic_frag},lambert:{uniforms:Yr([Z.common,Z.specularmap,Z.envmap,Z.aomap,Z.lightmap,Z.emissivemap,Z.bumpmap,Z.normalmap,Z.displacementmap,Z.fog,Z.lights,{emissive:{value:new Y(0)},envMapIntensity:{value:1}}]),vertexShader:X.meshlambert_vert,fragmentShader:X.meshlambert_frag},phong:{uniforms:Yr([Z.common,Z.specularmap,Z.envmap,Z.aomap,Z.lightmap,Z.emissivemap,Z.bumpmap,Z.normalmap,Z.displacementmap,Z.fog,Z.lights,{emissive:{value:new Y(0)},specular:{value:new Y(1118481)},shininess:{value:30},envMapIntensity:{value:1}}]),vertexShader:X.meshphong_vert,fragmentShader:X.meshphong_frag},standard:{uniforms:Yr([Z.common,Z.envmap,Z.aomap,Z.lightmap,Z.emissivemap,Z.bumpmap,Z.normalmap,Z.displacementmap,Z.roughnessmap,Z.metalnessmap,Z.fog,Z.lights,{emissive:{value:new Y(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:X.meshphysical_vert,fragmentShader:X.meshphysical_frag},toon:{uniforms:Yr([Z.common,Z.aomap,Z.lightmap,Z.emissivemap,Z.bumpmap,Z.normalmap,Z.displacementmap,Z.gradientmap,Z.fog,Z.lights,{emissive:{value:new Y(0)}}]),vertexShader:X.meshtoon_vert,fragmentShader:X.meshtoon_frag},matcap:{uniforms:Yr([Z.common,Z.bumpmap,Z.normalmap,Z.displacementmap,Z.fog,{matcap:{value:null}}]),vertexShader:X.meshmatcap_vert,fragmentShader:X.meshmatcap_frag},points:{uniforms:Yr([Z.points,Z.fog]),vertexShader:X.points_vert,fragmentShader:X.points_frag},dashed:{uniforms:Yr([Z.common,Z.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:X.linedashed_vert,fragmentShader:X.linedashed_frag},depth:{uniforms:Yr([Z.common,Z.displacementmap]),vertexShader:X.depth_vert,fragmentShader:X.depth_frag},normal:{uniforms:Yr([Z.common,Z.bumpmap,Z.normalmap,Z.displacementmap,{opacity:{value:1}}]),vertexShader:X.meshnormal_vert,fragmentShader:X.meshnormal_frag},sprite:{uniforms:Yr([Z.sprite,Z.fog]),vertexShader:X.sprite_vert,fragmentShader:X.sprite_frag},background:{uniforms:{uvTransform:{value:new q},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:X.background_vert,fragmentShader:X.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new q}},vertexShader:X.backgroundCube_vert,fragmentShader:X.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:X.cube_vert,fragmentShader:X.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:X.equirect_vert,fragmentShader:X.equirect_frag},distance:{uniforms:Yr([Z.common,Z.displacementmap,{referencePosition:{value:new K},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:X.distance_vert,fragmentShader:X.distance_frag},shadow:{uniforms:Yr([Z.lights,Z.fog,{color:{value:new Y(0)},opacity:{value:1}}]),vertexShader:X.shadow_vert,fragmentShader:X.shadow_frag}};Qi.physical={uniforms:Yr([Qi.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new q},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new q},clearcoatNormalScale:{value:new G(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new q},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new q},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new q},sheen:{value:0},sheenColor:{value:new Y(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new q},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new q},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new q},transmissionSamplerSize:{value:new G},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new q},attenuationDistance:{value:0},attenuationColor:{value:new Y(0)},specularColor:{value:new Y(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new q},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new q},anisotropyVector:{value:new G},anisotropyMap:{value:null},anisotropyMapTransform:{value:new q}}]),vertexShader:X.meshphysical_vert,fragmentShader:X.meshphysical_frag};var $i={r:0,b:0,g:0},ea=new Bt,ta=new At;function na(e,t,n,r,i,a){let o=new Y(0),s=i===!0?0:1,c,l,u=null,d=0,f=null;function p(e){let n=e.isScene===!0?e.background:null;if(n&&n.isTexture){let r=e.backgroundBlurriness>0;n=t.get(n,r)}return n}function m(t){let r=!1,i=p(t);i===null?g(o,s):i&&i.isColor&&(g(i,1),r=!0);let c=e.xr.getEnvironmentBlendMode();c===`additive`?n.buffers.color.setClear(0,0,0,1,a):c===`alpha-blend`&&n.buffers.color.setClear(0,0,0,0,a),(e.autoClear||r)&&(n.buffers.depth.setTest(!0),n.buffers.depth.setMask(!0),n.buffers.color.setMask(!0),e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil))}function h(t,n){let i=p(n);i&&(i.isCubeTexture||i.mapping===306)?(l===void 0&&(l=new Ar(new Kr(1,1,1),new ti({name:`BackgroundCubeMaterial`,uniforms:Jr(Qi.backgroundCube.uniforms),vertexShader:Qi.backgroundCube.vertexShader,fragmentShader:Qi.backgroundCube.fragmentShader,side:1,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),l.geometry.deleteAttribute(`normal`),l.geometry.deleteAttribute(`uv`),l.onBeforeRender=function(e,t,n){this.matrixWorld.copyPosition(n.matrixWorld)},Object.defineProperty(l.material,`envMap`,{get:function(){return this.uniforms.envMap.value}}),r.update(l)),ea.copy(n.backgroundRotation),ea.x*=-1,ea.y*=-1,ea.z*=-1,i.isCubeTexture&&i.isRenderTargetTexture===!1&&(ea.y*=-1,ea.z*=-1),l.material.uniforms.envMap.value=i,l.material.uniforms.flipEnvMap.value=i.isCubeTexture&&i.isRenderTargetTexture===!1?-1:1,l.material.uniforms.backgroundBlurriness.value=n.backgroundBlurriness,l.material.uniforms.backgroundIntensity.value=n.backgroundIntensity,l.material.uniforms.backgroundRotation.value.setFromMatrix4(ta.makeRotationFromEuler(ea)),l.material.toneMapped=J.getTransfer(i.colorSpace)!==Re,(u!==i||d!==i.version||f!==e.toneMapping)&&(l.material.needsUpdate=!0,u=i,d=i.version,f=e.toneMapping),l.layers.enableAll(),t.unshift(l,l.geometry,l.material,0,0,null)):i&&i.isTexture&&(c===void 0&&(c=new Ar(new qr(2,2),new ti({name:`BackgroundMaterial`,uniforms:Jr(Qi.background.uniforms),vertexShader:Qi.background.vertexShader,fragmentShader:Qi.background.fragmentShader,side:0,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),c.geometry.deleteAttribute(`normal`),Object.defineProperty(c.material,`map`,{get:function(){return this.uniforms.t2D.value}}),r.update(c)),c.material.uniforms.t2D.value=i,c.material.uniforms.backgroundIntensity.value=n.backgroundIntensity,c.material.toneMapped=J.getTransfer(i.colorSpace)!==Re,i.matrixAutoUpdate===!0&&i.updateMatrix(),c.material.uniforms.uvTransform.value.copy(i.matrix),(u!==i||d!==i.version||f!==e.toneMapping)&&(c.material.needsUpdate=!0,u=i,d=i.version,f=e.toneMapping),c.layers.enableAll(),t.unshift(c,c.geometry,c.material,0,0,null))}function g(t,r){t.getRGB($i,Zr(e)),n.buffers.color.setClear($i.r,$i.g,$i.b,r,a)}function _(){l!==void 0&&(l.geometry.dispose(),l.material.dispose(),l=void 0),c!==void 0&&(c.geometry.dispose(),c.material.dispose(),c=void 0)}return{getClearColor:function(){return o},setClearColor:function(e,t=1){o.set(e),s=t,g(o,s)},getClearAlpha:function(){return s},setClearAlpha:function(e){s=e,g(o,s)},render:m,addToRenderList:h,dispose:_}}function ra(e,t){let n=e.getParameter(e.MAX_VERTEX_ATTRIBS),r={},i=f(null),a=i,o=!1;function s(n,r,i,s,c){let u=!1,f=d(n,s,i,r);a!==f&&(a=f,l(a.object)),u=p(n,s,i,c),u&&m(n,s,i,c),c!==null&&t.update(c,e.ELEMENT_ARRAY_BUFFER),(u||o)&&(o=!1,b(n,r,i,s),c!==null&&e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,t.get(c).buffer))}function c(){return e.createVertexArray()}function l(t){return e.bindVertexArray(t)}function u(t){return e.deleteVertexArray(t)}function d(e,t,n,i){let a=i.wireframe===!0,o=r[t.id];o===void 0&&(o={},r[t.id]=o);let s=e.isInstancedMesh===!0?e.id:0,l=o[s];l===void 0&&(l={},o[s]=l);let u=l[n.id];u===void 0&&(u={},l[n.id]=u);let d=u[a];return d===void 0&&(d=f(c()),u[a]=d),d}function f(e){let t=[],r=[],i=[];for(let e=0;e=0){let n=i[t],r=o[t];if(r===void 0&&(t===`instanceMatrix`&&e.instanceMatrix&&(r=e.instanceMatrix),t===`instanceColor`&&e.instanceColor&&(r=e.instanceColor)),n===void 0||n.attribute!==r||r&&n.data!==r.data)return!0;s++}return a.attributesNum!==s||a.index!==r}function m(e,t,n,r){let i={},o=t.attributes,s=0,c=n.getAttributes();for(let t in c)if(c[t].location>=0){let n=o[t];n===void 0&&(t===`instanceMatrix`&&e.instanceMatrix&&(n=e.instanceMatrix),t===`instanceColor`&&e.instanceColor&&(n=e.instanceColor));let r={};r.attribute=n,n&&n.data&&(r.data=n.data),i[t]=r,s++}a.attributes=i,a.attributesNum=s,a.index=r}function h(){let e=a.newAttributes;for(let t=0,n=e.length;t=0){let s=o[r];if(s===void 0&&(r===`instanceMatrix`&&n.instanceMatrix&&(s=n.instanceMatrix),r===`instanceColor`&&n.instanceColor&&(s=n.instanceColor)),s!==void 0){let r=s.normalized,o=s.itemSize,c=t.get(s);if(c===void 0)continue;let l=c.buffer,u=c.type,d=c.bytesPerElement,f=u===e.INT||u===e.UNSIGNED_INT||s.gpuType===1013;if(s.isInterleavedBufferAttribute){let t=s.data,c=t.stride,p=s.offset;if(t.isInstancedInterleavedBuffer){for(let e=0;e0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT).precision>0)return`highp`;t=`mediump`}return t===`mediump`&&e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.MEDIUM_FLOAT).precision>0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?`mediump`:`lowp`}let l=n.precision===void 0?`highp`:n.precision,u=c(l);u!==l&&(H(`WebGLRenderer:`,l,`not supported, using`,u,`instead.`),l=u);let d=n.logarithmicDepthBuffer===!0,f=n.reversedDepthBuffer===!0&&t.has(`EXT_clip_control`),p=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),m=e.getParameter(e.MAX_VERTEX_TEXTURE_IMAGE_UNITS),h=e.getParameter(e.MAX_TEXTURE_SIZE),g=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),_=e.getParameter(e.MAX_VERTEX_ATTRIBS),v=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),y=e.getParameter(e.MAX_VARYING_VECTORS),b=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),x=e.getParameter(e.MAX_SAMPLES),S=e.getParameter(e.SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:a,getMaxPrecision:c,textureFormatReadable:o,textureTypeReadable:s,precision:l,logarithmicDepthBuffer:d,reversedDepthBuffer:f,maxTextures:p,maxVertexTextures:m,maxTextureSize:h,maxCubemapSize:g,maxAttributes:_,maxVertexUniforms:v,maxVaryings:y,maxFragmentUniforms:b,maxSamples:x,samples:S}}function oa(e){let t=this,n=null,r=0,i=!1,a=!1,o=new Lr,s=new q,c={value:null,needsUpdate:!1};this.uniform=c,this.numPlanes=0,this.numIntersection=0,this.init=function(e,t){let n=e.length!==0||t||r!==0||i;return i=t,r=e.length,n},this.beginShadows=function(){a=!0,u(null)},this.endShadows=function(){a=!1},this.setGlobalState=function(e,t){n=u(e,t,0)},this.setState=function(t,o,s){let d=t.clippingPlanes,f=t.clipIntersection,p=t.clipShadows,m=e.get(t);if(!i||d===null||d.length===0||a&&!p)a?u(null):l();else{let e=a?0:r,t=e*4,i=m.clippingState||null;c.value=i,i=u(d,o,t,s);for(let e=0;e!==t;++e)i[e]=n[e];m.clippingState=i,this.numIntersection=f?this.numPlanes:0,this.numPlanes+=e}};function l(){c.value!==n&&(c.value=n,c.needsUpdate=r>0),t.numPlanes=r,t.numIntersection=0}function u(e,n,r,i){let a=e===null?0:e.length,l=null;if(a!==0){if(l=c.value,i!==!0||l===null){let t=r+a*4,i=n.matrixWorldInverse;s.getNormalMatrix(i),(l===null||l.length0&&this._blur(s,0,0,t),this._applyPMREM(s),this._cleanup(s),s}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=Ta(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=wa(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose(),this._backgroundBox!==null&&(this._backgroundBox.geometry.dispose(),this._backgroundBox.material.dispose())}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=2**this._lodMax}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._ggxMaterial!==null&&this._ggxMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e2?l:0,l,l),c.setRenderTarget(r),p&&c.render(d,a),c.render(e,a)}c.toneMapping=u,c.autoClear=l,e.background=m}_textureToCubeUV(e,t){let n=this._renderer,r=e.mapping===301||e.mapping===302;r?(this._cubemapMaterial===null&&(this._cubemapMaterial=Ta()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=wa());let i=r?this._cubemapMaterial:this._equirectMaterial,a=this._lodMeshes[0];a.material=i;let o=i.uniforms;o.envMap.value=e;let s=this._cubeSize;xa(t,0,0,3*s,2*s),n.setRenderTarget(t),n.render(a,da)}_applyPMREM(e){let t=this._renderer,n=t.autoClear;t.autoClear=!1;let r=this._lodMeshes.length;for(let t=1;td-sa?n-d+sa:0),m=4*(this._cubeSize-f);s.envMap.value=e.texture,s.roughness.value=u,s.mipInt.value=d-t,xa(i,p,m,3*f,2*f),r.setRenderTarget(i),r.render(o,da),s.envMap.value=i.texture,s.roughness.value=0,s.mipInt.value=d-n,xa(e,p,m,3*f,2*f),r.setRenderTarget(e),r.render(o,da)}_blur(e,t,n,r,i){let a=this._pingPongRenderTarget;this._halfBlur(e,a,t,n,r,`latitudinal`,i),this._halfBlur(a,e,n,n,r,`longitudinal`,i)}_halfBlur(e,t,n,r,i,a,o){let s=this._renderer,c=this._blurMaterial;a!==`latitudinal`&&a!==`longitudinal`&&U(`blur direction must be either latitudinal or longitudinal!`);let l=this._lodMeshes[r];l.material=c;let u=c.uniforms,d=this._sizeLods[n]-1,f=isFinite(i)?Math.PI/(2*d):2*Math.PI/(2*la-1),p=i/f,m=isFinite(i)?1+Math.floor(3*p):la;m>la&&H(`sigmaRadians, ${i}, is too large and will clip, as it requested ${m} samples when the maximum is set to ${la}`);let h=[],g=0;for(let e=0;e_-sa?r-_+sa:0),4*(this._cubeSize-v),3*v,2*v),s.setRenderTarget(t),s.render(l,da)}};function ya(e){let t=[],n=[],r=[],i=e,a=e-sa+1+ca.length;for(let o=0;oe-sa?s=ca[o-e+sa-1]:o===0&&(s=0),n.push(s);let c=1/(a-2),l=-c,u=1+c,d=[l,l,u,l,u,u,l,l,u,u,l,u],f=new Float32Array(108),p=new Float32Array(72),m=new Float32Array(36);for(let e=0;e<6;e++){let t=e%3*2/3-1,n=e>2?0:-1,r=[t,n,0,t+2/3,n,0,t+2/3,n+1,0,t,n,0,t+2/3,n+1,0,t,n+1,0];f.set(r,18*e),p.set(d,12*e);let i=[e,e,e,e,e,e];m.set(i,6*e)}let h=new sr;h.setAttribute(`position`,new Kn(f,3)),h.setAttribute(`uv`,new Kn(p,2)),h.setAttribute(`faceIndex`,new Kn(m,1)),r.push(new Ar(h,null)),i>sa&&i--}return{lodMeshes:r,sizeLods:t,sigmas:n}}function ba(e,t,n){let r=new Dt(e,t,n);return r.texture.mapping=306,r.texture.name=`PMREM.cubeUv`,r.scissorTest=!0,r}function xa(e,t,n,r,i){e.viewport.set(t,n,r,i),e.scissor.set(t,n,r,i)}function Sa(e,t,n){return new ti({name:`PMREMGGXConvolution`,defines:{GGX_SAMPLES:ua,CUBEUV_TEXEL_WIDTH:1/t,CUBEUV_TEXEL_HEIGHT:1/n,CUBEUV_MAX_MIP:`${e}.0`},uniforms:{envMap:{value:null},roughness:{value:0},mipInt:{value:0}},vertexShader:Ea(),fragmentShader:` precision highp float; precision highp int; varying vec3 vOutputDirection; uniform sampler2D envMap; uniform float roughness; uniform float mipInt; #define ENVMAP_TYPE_CUBE_UV #include #define PI 3.14159265359 // Van der Corput radical inverse float radicalInverse_VdC(uint bits) { bits = (bits << 16u) | (bits >> 16u); bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u); bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u); bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u); bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u); return float(bits) * 2.3283064365386963e-10; // / 0x100000000 } // Hammersley sequence vec2 hammersley(uint i, uint N) { return vec2(float(i) / float(N), radicalInverse_VdC(i)); } // GGX VNDF importance sampling (Eric Heitz 2018) // "Sampling the GGX Distribution of Visible Normals" // https://jcgt.org/published/0007/04/01/ vec3 importanceSampleGGX_VNDF(vec2 Xi, vec3 V, float roughness) { float alpha = roughness * roughness; // Section 4.1: Orthonormal basis vec3 T1 = vec3(1.0, 0.0, 0.0); vec3 T2 = cross(V, T1); // Section 4.2: Parameterization of projected area float r = sqrt(Xi.x); float phi = 2.0 * PI * Xi.y; float t1 = r * cos(phi); float t2 = r * sin(phi); float s = 0.5 * (1.0 + V.z); t2 = (1.0 - s) * sqrt(1.0 - t1 * t1) + s * t2; // Section 4.3: Reprojection onto hemisphere vec3 Nh = t1 * T1 + t2 * T2 + sqrt(max(0.0, 1.0 - t1 * t1 - t2 * t2)) * V; // Section 3.4: Transform back to ellipsoid configuration return normalize(vec3(alpha * Nh.x, alpha * Nh.y, max(0.0, Nh.z))); } void main() { vec3 N = normalize(vOutputDirection); vec3 V = N; // Assume view direction equals normal for pre-filtering vec3 prefilteredColor = vec3(0.0); float totalWeight = 0.0; // For very low roughness, just sample the environment directly if (roughness < 0.001) { gl_FragColor = vec4(bilinearCubeUV(envMap, N, mipInt), 1.0); return; } // Tangent space basis for VNDF sampling vec3 up = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0); vec3 tangent = normalize(cross(up, N)); vec3 bitangent = cross(N, tangent); for(uint i = 0u; i < uint(GGX_SAMPLES); i++) { vec2 Xi = hammersley(i, uint(GGX_SAMPLES)); // For PMREM, V = N, so in tangent space V is always (0, 0, 1) vec3 H_tangent = importanceSampleGGX_VNDF(Xi, vec3(0.0, 0.0, 1.0), roughness); // Transform H back to world space vec3 H = normalize(tangent * H_tangent.x + bitangent * H_tangent.y + N * H_tangent.z); vec3 L = normalize(2.0 * dot(V, H) * H - V); float NdotL = max(dot(N, L), 0.0); if(NdotL > 0.0) { // Sample environment at fixed mip level // VNDF importance sampling handles the distribution filtering vec3 sampleColor = bilinearCubeUV(envMap, L, mipInt); // Weight by NdotL for the split-sum approximation // VNDF PDF naturally accounts for the visible microfacet distribution prefilteredColor += sampleColor * NdotL; totalWeight += NdotL; } } if (totalWeight > 0.0) { prefilteredColor = prefilteredColor / totalWeight; } gl_FragColor = vec4(prefilteredColor, 1.0); } `,blending:0,depthTest:!1,depthWrite:!1})}function Ca(e,t,n){let r=new Float32Array(la),i=new K(0,1,0);return new ti({name:`SphericalGaussianBlur`,defines:{n:la,CUBEUV_TEXEL_WIDTH:1/t,CUBEUV_TEXEL_HEIGHT:1/n,CUBEUV_MAX_MIP:`${e}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:r},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:i}},vertexShader:Ea(),fragmentShader:` precision mediump float; precision mediump int; varying vec3 vOutputDirection; uniform sampler2D envMap; uniform int samples; uniform float weights[ n ]; uniform bool latitudinal; uniform float dTheta; uniform float mipInt; uniform vec3 poleAxis; #define ENVMAP_TYPE_CUBE_UV #include vec3 getSample( float theta, vec3 axis ) { float cosTheta = cos( theta ); // Rodrigues' axis-angle rotation vec3 sampleDirection = vOutputDirection * cosTheta + cross( axis, vOutputDirection ) * sin( theta ) + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta ); return bilinearCubeUV( envMap, sampleDirection, mipInt ); } void main() { vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection ); if ( all( equal( axis, vec3( 0.0 ) ) ) ) { axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x ); } axis = normalize( axis ); gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis ); for ( int i = 1; i < n; i++ ) { if ( i >= samples ) { break; } float theta = dTheta * float( i ); gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis ); gl_FragColor.rgb += weights[ i ] * getSample( theta, axis ); } } `,blending:0,depthTest:!1,depthWrite:!1})}function wa(){return new ti({name:`EquirectangularToCubeUV`,uniforms:{envMap:{value:null}},vertexShader:Ea(),fragmentShader:` precision mediump float; precision mediump int; varying vec3 vOutputDirection; uniform sampler2D envMap; #include void main() { vec3 outputDirection = normalize( vOutputDirection ); vec2 uv = equirectUv( outputDirection ); gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 ); } `,blending:0,depthTest:!1,depthWrite:!1})}function Ta(){return new ti({name:`CubemapToCubeUV`,uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:Ea(),fragmentShader:` precision mediump float; precision mediump int; uniform float flipEnvMap; varying vec3 vOutputDirection; uniform samplerCube envMap; void main() { gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) ); } `,blending:0,depthTest:!1,depthWrite:!1})}function Ea(){return` precision mediump float; precision mediump int; attribute float faceIndex; varying vec3 vOutputDirection; // RH coordinate system; PMREM face-indexing convention vec3 getDirection( vec2 uv, float face ) { uv = 2.0 * uv - 1.0; vec3 direction = vec3( uv, 1.0 ); if ( face == 0.0 ) { direction = direction.zyx; // ( 1, v, u ) pos x } else if ( face == 1.0 ) { direction = direction.xzy; direction.xz *= -1.0; // ( -u, 1, -v ) pos y } else if ( face == 2.0 ) { direction.x *= -1.0; // ( -u, v, 1 ) pos z } else if ( face == 3.0 ) { direction = direction.zyx; direction.xz *= -1.0; // ( -1, v, -u ) neg x } else if ( face == 4.0 ) { direction = direction.xzy; direction.xy *= -1.0; // ( -u, -1, v ) neg y } else if ( face == 5.0 ) { direction.z *= -1.0; // ( u, v, -1 ) neg z } return direction; } void main() { vOutputDirection = getDirection( uv, faceIndex ); gl_Position = vec4( position, 1.0 ); } `}var Da=class extends Dt{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;let n={width:e,height:e,depth:1};this.texture=new Hr([n,n,n,n,n,n]),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;let n={uniforms:{tEquirect:{value:null}},vertexShader:` varying vec3 vWorldDirection; vec3 transformDirection( in vec3 dir, in mat4 matrix ) { return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); } void main() { vWorldDirection = transformDirection( position, modelMatrix ); #include #include } `,fragmentShader:` uniform sampler2D tEquirect; varying vec3 vWorldDirection; #include void main() { vec3 direction = normalize( vWorldDirection ); vec2 sampleUV = equirectUv( direction ); gl_FragColor = texture2D( tEquirect, sampleUV ); } `},r=new Kr(5,5,5),i=new ti({name:`CubemapFromEquirect`,uniforms:Jr(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:1,blending:0});i.uniforms.tEquirect.value=t;let a=new Ar(r,i),o=t.minFilter;return t.minFilter===1008&&(t.minFilter=s),new Mi(1,10,this).update(e,a),t.minFilter=o,a.geometry.dispose(),a.material.dispose(),this}clear(e,t=!0,n=!0,r=!0){let i=e.getRenderTarget();for(let i=0;i<6;i++)e.setRenderTarget(this,i),e.clear(t,n,r);e.setRenderTarget(i)}};function Oa(e){let t=new WeakMap,n=new WeakMap,r=null;function i(e,t=!1){return e==null?null:t?o(e):a(e)}function a(n){if(n&&n.isTexture){let r=n.mapping;if(r===303||r===304)if(t.has(n)){let e=t.get(n).texture;return s(e,n.mapping)}else{let r=n.image;if(r&&r.height>0){let i=new Da(r.height);return i.fromEquirectangularTexture(e,n),t.set(n,i),n.addEventListener(`dispose`,l),s(i.texture,n.mapping)}else return null}}return n}function o(t){if(t&&t.isTexture){let i=t.mapping,a=i===303||i===304,o=i===301||i===302;if(a||o){let i=n.get(t),s=i===void 0?0:i.texture.pmremVersion;if(t.isRenderTargetTexture&&t.pmremVersion!==s)return r===null&&(r=new va(e)),i=a?r.fromEquirectangular(t,i):r.fromCubemap(t,i),i.texture.pmremVersion=t.pmremVersion,n.set(t,i),i.texture;if(i!==void 0)return i.texture;{let s=t.image;return a&&s&&s.height>0||o&&s&&c(s)?(r===null&&(r=new va(e)),i=a?r.fromEquirectangular(t):r.fromCubemap(t),i.texture.pmremVersion=t.pmremVersion,n.set(t,i),t.addEventListener(`dispose`,u),i.texture):null}}}return t}function s(e,t){return t===303?e.mapping=301:t===304&&(e.mapping=302),e}function c(e){let t=0;for(let n=0;n<6;n++)e[n]!==void 0&&t++;return t===6}function l(e){let n=e.target;n.removeEventListener(`dispose`,l);let r=t.get(n);r!==void 0&&(t.delete(n),r.dispose())}function u(e){let t=e.target;t.removeEventListener(`dispose`,u);let r=n.get(t);r!==void 0&&(n.delete(t),r.dispose())}function d(){t=new WeakMap,n=new WeakMap,r!==null&&(r.dispose(),r=null)}return{get:i,dispose:d}}function ka(e){let t={};function n(n){if(t[n]!==void 0)return t[n];let r=e.getExtension(n);return t[n]=r,r}return{has:function(e){return n(e)!==null},init:function(){n(`EXT_color_buffer_float`),n(`WEBGL_clip_cull_distance`),n(`OES_texture_float_linear`),n(`EXT_color_buffer_half_float`),n(`WEBGL_multisampled_render_to_texture`),n(`WEBGL_render_shared_exponent`)},get:function(e){let t=n(e);return t===null&&Xe(`WebGLRenderer: `+e+` extension not supported.`),t}}}function Aa(e,t,n,r){let i={},a=new WeakMap;function o(e){let s=e.target;s.index!==null&&t.remove(s.index);for(let e in s.attributes)t.remove(s.attributes[e]);s.removeEventListener(`dispose`,o),delete i[s.id];let c=a.get(s);c&&(t.remove(c),a.delete(s)),r.releaseStatesOfGeometry(s),s.isInstancedBufferGeometry===!0&&delete s._maxInstanceCount,n.memory.geometries--}function s(e,t){return i[t.id]===!0?t:(t.addEventListener(`dispose`,o),i[t.id]=!0,n.memory.geometries++,t)}function c(n){let r=n.attributes;for(let n in r)t.update(r[n],e.ARRAY_BUFFER)}function l(e){let n=[],r=e.index,i=e.attributes.position,o=0;if(i===void 0)return;if(r!==null){let e=r.array;o=r.version;for(let t=0,r=e.length;t=65535?Jn:qn)(n,1);s.version=o;let c=a.get(e);c&&t.remove(c),a.set(e,s)}function u(e){let t=a.get(e);if(t){let n=e.index;n!==null&&t.versiont.maxTextureSize&&(m=Math.ceil(p/t.maxTextureSize),p=t.maxTextureSize);let h=new Float32Array(p*m*4*u),_=new Ot(h,p,m,u);_.type=g,_.needsUpdate=!0;let v=f*4;for(let t=0;t #include void main() { gl_FragColor = texture2D( tDiffuse, vUv ); #ifdef LINEAR_TONE_MAPPING gl_FragColor.rgb = LinearToneMapping( gl_FragColor.rgb ); #elif defined( REINHARD_TONE_MAPPING ) gl_FragColor.rgb = ReinhardToneMapping( gl_FragColor.rgb ); #elif defined( CINEON_TONE_MAPPING ) gl_FragColor.rgb = CineonToneMapping( gl_FragColor.rgb ); #elif defined( ACES_FILMIC_TONE_MAPPING ) gl_FragColor.rgb = ACESFilmicToneMapping( gl_FragColor.rgb ); #elif defined( AGX_TONE_MAPPING ) gl_FragColor.rgb = AgXToneMapping( gl_FragColor.rgb ); #elif defined( NEUTRAL_TONE_MAPPING ) gl_FragColor.rgb = NeutralToneMapping( gl_FragColor.rgb ); #elif defined( CUSTOM_TONE_MAPPING ) gl_FragColor.rgb = CustomToneMapping( gl_FragColor.rgb ); #endif #ifdef SRGB_TRANSFER gl_FragColor = sRGBTransferOETF( gl_FragColor ); #endif }`,depthTest:!1,depthWrite:!1}),l=new Ar(s,c),u=new ki(-1,1,1,-1,0,1),d=null,f=null,p=!1,m,h=null,g=[],v=!1;this.setSize=function(e,t){a.setSize(e,t),o.setSize(e,t);for(let n=0;n0&&g[0].isRenderPass===!0;let t=a.width,n=a.height;for(let e=0;e0)return e;let i=t*n,a=Ha[i];if(a===void 0&&(a=new Float32Array(i),Ha[i]=a),t!==0){r.toArray(a,0);for(let r=1,i=0;r!==t;++r)i+=n,e[r].toArray(a,i)}return a}function Ja(e,t){if(e.length!==t.length)return!1;for(let n=0,r=e.length;n0&&(this.seq=r.concat(i))}setValue(e,t,n,r){let i=this.map[t];i!==void 0&&i.setValue(e,n,r)}setOptional(e,t,n){let r=t[n];r!==void 0&&this.setValue(e,n,r)}static upload(e,t,n,r){for(let i=0,a=t.length;i!==a;++i){let a=t[i],o=n[a.id];o.needsUpdate!==!1&&a.setValue(e,o.value,r)}}static seqWithValue(e,t){let n=[];for(let r=0,i=e.length;r!==i;++r){let i=e[r];i.id in t&&n.push(i)}return n}};function Go(e,t,n){let r=e.createShader(t);return e.shaderSource(r,n),e.compileShader(r),r}var Ko=37297,qo=0;function Jo(e,t){let n=e.split(` `),r=[],i=Math.max(t-6,0),a=Math.min(t+6,n.length);for(let e=i;e`:` `} ${i}: ${n[e]}`)}return r.join(` `)}var Yo=new q;function Xo(e){J._getMatrix(Yo,J.workingColorSpace,e);let t=`mat3( ${Yo.elements.map(e=>e.toFixed(4))} )`;switch(J.getTransfer(e)){case Le:return[t,`LinearTransferOETF`];case Re:return[t,`sRGBTransferOETF`];default:return H(`WebGLProgram: Unsupported color space: `,e),[t,`LinearTransferOETF`]}}function Zo(e,t,n){let r=e.getShaderParameter(t,e.COMPILE_STATUS),i=(e.getShaderInfoLog(t)||``).trim();if(r&&i===``)return``;let a=/ERROR: 0:(\d+)/.exec(i);if(a){let r=parseInt(a[1]);return n.toUpperCase()+` `+i+` `+Jo(e.getShaderSource(t),r)}else return i}function Qo(e,t){let n=Xo(t);return[`vec4 ${e}( vec4 value ) {`,` return ${n[1]}( vec4( value.rgb * ${n[0]}, value.a ) );`,`}`].join(` `)}var $o={1:`Linear`,2:`Reinhard`,3:`Cineon`,4:`ACESFilmic`,6:`AgX`,7:`Neutral`,5:`Custom`};function es(e,t){let n=$o[t];return n===void 0?(H(`WebGLProgram: Unsupported toneMapping:`,t),`vec3 `+e+`( vec3 color ) { return LinearToneMapping( color ); }`):`vec3 `+e+`( vec3 color ) { return `+n+`ToneMapping( color ); }`}var ts=new K;function ns(){return J.getLuminanceCoefficients(ts),[`float luminance( const in vec3 rgb ) {`,` const vec3 weights = vec3( ${ts.x.toFixed(4)}, ${ts.y.toFixed(4)}, ${ts.z.toFixed(4)} );`,` return dot( weights, rgb );`,`}`].join(` `)}function rs(e){return[e.extensionClipCullDistance?`#extension GL_ANGLE_clip_cull_distance : require`:``,e.extensionMultiDraw?`#extension GL_ANGLE_multi_draw : require`:``].filter(os).join(` `)}function is(e){let t=[];for(let n in e){let r=e[n];r!==!1&&t.push(`#define `+n+` `+r)}return t.join(` `)}function as(e,t){let n={},r=e.getProgramParameter(t,e.ACTIVE_ATTRIBUTES);for(let i=0;i/gm;function us(e){return e.replace(ls,fs)}var ds=new Map;function fs(e,t){let n=X[t];if(n===void 0){let e=ds.get(t);if(e!==void 0)n=X[e],H(`WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.`,t,e);else throw Error(`Can not resolve #include <`+t+`>`)}return us(n)}var ps=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function ms(e){return e.replace(ps,hs)}function hs(e,t,n,r){let i=``;for(let e=parseInt(t);e0&&(g+=` `),_=[`#define SHADER_TYPE `+n.shaderType,`#define SHADER_NAME `+n.shaderName,m].filter(os).join(` `),_.length>0&&(_+=` `)):(g=[gs(n),`#define SHADER_TYPE `+n.shaderType,`#define SHADER_NAME `+n.shaderName,m,n.extensionClipCullDistance?`#define USE_CLIP_DISTANCE`:``,n.batching?`#define USE_BATCHING`:``,n.batchingColor?`#define USE_BATCHING_COLOR`:``,n.instancing?`#define USE_INSTANCING`:``,n.instancingColor?`#define USE_INSTANCING_COLOR`:``,n.instancingMorph?`#define USE_INSTANCING_MORPH`:``,n.useFog&&n.fog?`#define USE_FOG`:``,n.useFog&&n.fogExp2?`#define FOG_EXP2`:``,n.map?`#define USE_MAP`:``,n.envMap?`#define USE_ENVMAP`:``,n.envMap?`#define `+u:``,n.lightMap?`#define USE_LIGHTMAP`:``,n.aoMap?`#define USE_AOMAP`:``,n.bumpMap?`#define USE_BUMPMAP`:``,n.normalMap?`#define USE_NORMALMAP`:``,n.normalMapObjectSpace?`#define USE_NORMALMAP_OBJECTSPACE`:``,n.normalMapTangentSpace?`#define USE_NORMALMAP_TANGENTSPACE`:``,n.displacementMap?`#define USE_DISPLACEMENTMAP`:``,n.emissiveMap?`#define USE_EMISSIVEMAP`:``,n.anisotropy?`#define USE_ANISOTROPY`:``,n.anisotropyMap?`#define USE_ANISOTROPYMAP`:``,n.clearcoatMap?`#define USE_CLEARCOATMAP`:``,n.clearcoatRoughnessMap?`#define USE_CLEARCOAT_ROUGHNESSMAP`:``,n.clearcoatNormalMap?`#define USE_CLEARCOAT_NORMALMAP`:``,n.iridescenceMap?`#define USE_IRIDESCENCEMAP`:``,n.iridescenceThicknessMap?`#define USE_IRIDESCENCE_THICKNESSMAP`:``,n.specularMap?`#define USE_SPECULARMAP`:``,n.specularColorMap?`#define USE_SPECULAR_COLORMAP`:``,n.specularIntensityMap?`#define USE_SPECULAR_INTENSITYMAP`:``,n.roughnessMap?`#define USE_ROUGHNESSMAP`:``,n.metalnessMap?`#define USE_METALNESSMAP`:``,n.alphaMap?`#define USE_ALPHAMAP`:``,n.alphaHash?`#define USE_ALPHAHASH`:``,n.transmission?`#define USE_TRANSMISSION`:``,n.transmissionMap?`#define USE_TRANSMISSIONMAP`:``,n.thicknessMap?`#define USE_THICKNESSMAP`:``,n.sheenColorMap?`#define USE_SHEEN_COLORMAP`:``,n.sheenRoughnessMap?`#define USE_SHEEN_ROUGHNESSMAP`:``,n.mapUv?`#define MAP_UV `+n.mapUv:``,n.alphaMapUv?`#define ALPHAMAP_UV `+n.alphaMapUv:``,n.lightMapUv?`#define LIGHTMAP_UV `+n.lightMapUv:``,n.aoMapUv?`#define AOMAP_UV `+n.aoMapUv:``,n.emissiveMapUv?`#define EMISSIVEMAP_UV `+n.emissiveMapUv:``,n.bumpMapUv?`#define BUMPMAP_UV `+n.bumpMapUv:``,n.normalMapUv?`#define NORMALMAP_UV `+n.normalMapUv:``,n.displacementMapUv?`#define DISPLACEMENTMAP_UV `+n.displacementMapUv:``,n.metalnessMapUv?`#define METALNESSMAP_UV `+n.metalnessMapUv:``,n.roughnessMapUv?`#define ROUGHNESSMAP_UV `+n.roughnessMapUv:``,n.anisotropyMapUv?`#define ANISOTROPYMAP_UV `+n.anisotropyMapUv:``,n.clearcoatMapUv?`#define CLEARCOATMAP_UV `+n.clearcoatMapUv:``,n.clearcoatNormalMapUv?`#define CLEARCOAT_NORMALMAP_UV `+n.clearcoatNormalMapUv:``,n.clearcoatRoughnessMapUv?`#define CLEARCOAT_ROUGHNESSMAP_UV `+n.clearcoatRoughnessMapUv:``,n.iridescenceMapUv?`#define IRIDESCENCEMAP_UV `+n.iridescenceMapUv:``,n.iridescenceThicknessMapUv?`#define IRIDESCENCE_THICKNESSMAP_UV `+n.iridescenceThicknessMapUv:``,n.sheenColorMapUv?`#define SHEEN_COLORMAP_UV `+n.sheenColorMapUv:``,n.sheenRoughnessMapUv?`#define SHEEN_ROUGHNESSMAP_UV `+n.sheenRoughnessMapUv:``,n.specularMapUv?`#define SPECULARMAP_UV `+n.specularMapUv:``,n.specularColorMapUv?`#define SPECULAR_COLORMAP_UV `+n.specularColorMapUv:``,n.specularIntensityMapUv?`#define SPECULAR_INTENSITYMAP_UV `+n.specularIntensityMapUv:``,n.transmissionMapUv?`#define TRANSMISSIONMAP_UV `+n.transmissionMapUv:``,n.thicknessMapUv?`#define THICKNESSMAP_UV `+n.thicknessMapUv:``,n.vertexTangents&&n.flatShading===!1?`#define USE_TANGENT`:``,n.vertexColors?`#define USE_COLOR`:``,n.vertexAlphas?`#define USE_COLOR_ALPHA`:``,n.vertexUv1s?`#define USE_UV1`:``,n.vertexUv2s?`#define USE_UV2`:``,n.vertexUv3s?`#define USE_UV3`:``,n.pointsUvs?`#define USE_POINTS_UV`:``,n.flatShading?`#define FLAT_SHADED`:``,n.skinning?`#define USE_SKINNING`:``,n.morphTargets?`#define USE_MORPHTARGETS`:``,n.morphNormals&&n.flatShading===!1?`#define USE_MORPHNORMALS`:``,n.morphColors?`#define USE_MORPHCOLORS`:``,n.morphTargetsCount>0?`#define MORPHTARGETS_TEXTURE_STRIDE `+n.morphTextureStride:``,n.morphTargetsCount>0?`#define MORPHTARGETS_COUNT `+n.morphTargetsCount:``,n.doubleSided?`#define DOUBLE_SIDED`:``,n.flipSided?`#define FLIP_SIDED`:``,n.shadowMapEnabled?`#define USE_SHADOWMAP`:``,n.shadowMapEnabled?`#define `+c:``,n.sizeAttenuation?`#define USE_SIZEATTENUATION`:``,n.numLightProbes>0?`#define USE_LIGHT_PROBES`:``,n.logarithmicDepthBuffer?`#define USE_LOGARITHMIC_DEPTH_BUFFER`:``,n.reversedDepthBuffer?`#define USE_REVERSED_DEPTH_BUFFER`:``,`uniform mat4 modelMatrix;`,`uniform mat4 modelViewMatrix;`,`uniform mat4 projectionMatrix;`,`uniform mat4 viewMatrix;`,`uniform mat3 normalMatrix;`,`uniform vec3 cameraPosition;`,`uniform bool isOrthographic;`,`#ifdef USE_INSTANCING`,` attribute mat4 instanceMatrix;`,`#endif`,`#ifdef USE_INSTANCING_COLOR`,` attribute vec3 instanceColor;`,`#endif`,`#ifdef USE_INSTANCING_MORPH`,` uniform sampler2D morphTexture;`,`#endif`,`attribute vec3 position;`,`attribute vec3 normal;`,`attribute vec2 uv;`,`#ifdef USE_UV1`,` attribute vec2 uv1;`,`#endif`,`#ifdef USE_UV2`,` attribute vec2 uv2;`,`#endif`,`#ifdef USE_UV3`,` attribute vec2 uv3;`,`#endif`,`#ifdef USE_TANGENT`,` attribute vec4 tangent;`,`#endif`,`#if defined( USE_COLOR_ALPHA )`,` attribute vec4 color;`,`#elif defined( USE_COLOR )`,` attribute vec3 color;`,`#endif`,`#ifdef USE_SKINNING`,` attribute vec4 skinIndex;`,` attribute vec4 skinWeight;`,`#endif`,` `].filter(os).join(` `),_=[gs(n),`#define SHADER_TYPE `+n.shaderType,`#define SHADER_NAME `+n.shaderName,m,n.useFog&&n.fog?`#define USE_FOG`:``,n.useFog&&n.fogExp2?`#define FOG_EXP2`:``,n.alphaToCoverage?`#define ALPHA_TO_COVERAGE`:``,n.map?`#define USE_MAP`:``,n.matcap?`#define USE_MATCAP`:``,n.envMap?`#define USE_ENVMAP`:``,n.envMap?`#define `+l:``,n.envMap?`#define `+u:``,n.envMap?`#define `+d:``,f?`#define CUBEUV_TEXEL_WIDTH `+f.texelWidth:``,f?`#define CUBEUV_TEXEL_HEIGHT `+f.texelHeight:``,f?`#define CUBEUV_MAX_MIP `+f.maxMip+`.0`:``,n.lightMap?`#define USE_LIGHTMAP`:``,n.aoMap?`#define USE_AOMAP`:``,n.bumpMap?`#define USE_BUMPMAP`:``,n.normalMap?`#define USE_NORMALMAP`:``,n.normalMapObjectSpace?`#define USE_NORMALMAP_OBJECTSPACE`:``,n.normalMapTangentSpace?`#define USE_NORMALMAP_TANGENTSPACE`:``,n.emissiveMap?`#define USE_EMISSIVEMAP`:``,n.anisotropy?`#define USE_ANISOTROPY`:``,n.anisotropyMap?`#define USE_ANISOTROPYMAP`:``,n.clearcoat?`#define USE_CLEARCOAT`:``,n.clearcoatMap?`#define USE_CLEARCOATMAP`:``,n.clearcoatRoughnessMap?`#define USE_CLEARCOAT_ROUGHNESSMAP`:``,n.clearcoatNormalMap?`#define USE_CLEARCOAT_NORMALMAP`:``,n.dispersion?`#define USE_DISPERSION`:``,n.iridescence?`#define USE_IRIDESCENCE`:``,n.iridescenceMap?`#define USE_IRIDESCENCEMAP`:``,n.iridescenceThicknessMap?`#define USE_IRIDESCENCE_THICKNESSMAP`:``,n.specularMap?`#define USE_SPECULARMAP`:``,n.specularColorMap?`#define USE_SPECULAR_COLORMAP`:``,n.specularIntensityMap?`#define USE_SPECULAR_INTENSITYMAP`:``,n.roughnessMap?`#define USE_ROUGHNESSMAP`:``,n.metalnessMap?`#define USE_METALNESSMAP`:``,n.alphaMap?`#define USE_ALPHAMAP`:``,n.alphaTest?`#define USE_ALPHATEST`:``,n.alphaHash?`#define USE_ALPHAHASH`:``,n.sheen?`#define USE_SHEEN`:``,n.sheenColorMap?`#define USE_SHEEN_COLORMAP`:``,n.sheenRoughnessMap?`#define USE_SHEEN_ROUGHNESSMAP`:``,n.transmission?`#define USE_TRANSMISSION`:``,n.transmissionMap?`#define USE_TRANSMISSIONMAP`:``,n.thicknessMap?`#define USE_THICKNESSMAP`:``,n.vertexTangents&&n.flatShading===!1?`#define USE_TANGENT`:``,n.vertexColors||n.instancingColor?`#define USE_COLOR`:``,n.vertexAlphas||n.batchingColor?`#define USE_COLOR_ALPHA`:``,n.vertexUv1s?`#define USE_UV1`:``,n.vertexUv2s?`#define USE_UV2`:``,n.vertexUv3s?`#define USE_UV3`:``,n.pointsUvs?`#define USE_POINTS_UV`:``,n.gradientMap?`#define USE_GRADIENTMAP`:``,n.flatShading?`#define FLAT_SHADED`:``,n.doubleSided?`#define DOUBLE_SIDED`:``,n.flipSided?`#define FLIP_SIDED`:``,n.shadowMapEnabled?`#define USE_SHADOWMAP`:``,n.shadowMapEnabled?`#define `+c:``,n.premultipliedAlpha?`#define PREMULTIPLIED_ALPHA`:``,n.numLightProbes>0?`#define USE_LIGHT_PROBES`:``,n.decodeVideoTexture?`#define DECODE_VIDEO_TEXTURE`:``,n.decodeVideoTextureEmissive?`#define DECODE_VIDEO_TEXTURE_EMISSIVE`:``,n.logarithmicDepthBuffer?`#define USE_LOGARITHMIC_DEPTH_BUFFER`:``,n.reversedDepthBuffer?`#define USE_REVERSED_DEPTH_BUFFER`:``,`uniform mat4 viewMatrix;`,`uniform vec3 cameraPosition;`,`uniform bool isOrthographic;`,n.toneMapping===0?``:`#define TONE_MAPPING`,n.toneMapping===0?``:X.tonemapping_pars_fragment,n.toneMapping===0?``:es(`toneMapping`,n.toneMapping),n.dithering?`#define DITHERING`:``,n.opaque?`#define OPAQUE`:``,X.colorspace_pars_fragment,Qo(`linearToOutputTexel`,n.outputColorSpace),ns(),n.useDepthPacking?`#define DEPTH_PACKING `+n.depthPacking:``,` `].filter(os).join(` `)),o=us(o),o=ss(o,n),o=cs(o,n),s=us(s),s=ss(s,n),s=cs(s,n),o=ms(o),s=ms(s),n.isRawShaderMaterial!==!0&&(v=`#version 300 es `,g=[p,`#define attribute in`,`#define varying out`,`#define texture2D texture`].join(` `)+` `+g,_=[`#define varying in`,n.glslVersion===`300 es`?``:`layout(location = 0) out highp vec4 pc_fragColor;`,n.glslVersion===`300 es`?``:`#define gl_FragColor pc_fragColor`,`#define gl_FragDepthEXT gl_FragDepth`,`#define texture2D texture`,`#define textureCube texture`,`#define texture2DProj textureProj`,`#define texture2DLodEXT textureLod`,`#define texture2DProjLodEXT textureProjLod`,`#define textureCubeLodEXT textureLod`,`#define texture2DGradEXT textureGrad`,`#define texture2DProjGradEXT textureProjGrad`,`#define textureCubeGradEXT textureGrad`].join(` `)+` `+_);let y=v+g+o,b=v+_+s,x=Go(i,i.VERTEX_SHADER,y),S=Go(i,i.FRAGMENT_SHADER,b);i.attachShader(h,x),i.attachShader(h,S),n.index0AttributeName===void 0?n.morphTargets===!0&&i.bindAttribLocation(h,0,`position`):i.bindAttribLocation(h,0,n.index0AttributeName),i.linkProgram(h);function C(t){if(e.debug.checkShaderErrors){let n=i.getProgramInfoLog(h)||``,r=i.getShaderInfoLog(x)||``,a=i.getShaderInfoLog(S)||``,o=n.trim(),s=r.trim(),c=a.trim(),l=!0,u=!0;if(i.getProgramParameter(h,i.LINK_STATUS)===!1)if(l=!1,typeof e.debug.onShaderError==`function`)e.debug.onShaderError(i,h,x,S);else{let e=Zo(i,x,`vertex`),n=Zo(i,S,`fragment`);U(`THREE.WebGLProgram: Shader Error `+i.getError()+` - VALIDATE_STATUS `+i.getProgramParameter(h,i.VALIDATE_STATUS)+` Material Name: `+t.name+` Material Type: `+t.type+` Program Info Log: `+o+` `+e+` `+n)}else o===``?(s===``||c===``)&&(u=!1):H(`WebGLProgram: Program Info Log:`,o);u&&(t.diagnostics={runnable:l,programLog:o,vertexShader:{log:s,prefix:g},fragmentShader:{log:c,prefix:_}})}i.deleteShader(x),i.deleteShader(S),w=new Wo(i,h),T=as(i,h)}let w;this.getUniforms=function(){return w===void 0&&C(this),w};let T;this.getAttributes=function(){return T===void 0&&C(this),T};let E=n.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return E===!1&&(E=i.getProgramParameter(h,Ko)),E},this.destroy=function(){r.releaseStatesOfProgram(this),i.deleteProgram(h),this.program=void 0},this.type=n.shaderType,this.name=n.shaderName,this.id=qo++,this.cacheKey=t,this.usedTimes=1,this.program=h,this.vertexShader=x,this.fragmentShader=S,this}var Ds=0,Os=class{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){let t=e.vertexShader,n=e.fragmentShader,r=this._getShaderStage(t),i=this._getShaderStage(n),a=this._getShaderCacheForMaterial(e);return a.has(r)===!1&&(a.add(r),r.usedTimes++),a.has(i)===!1&&(a.add(i),i.usedTimes++),this}remove(e){let t=this.materialCache.get(e);for(let e of t)e.usedTimes--,e.usedTimes===0&&this.shaderCache.delete(e.code);return this.materialCache.delete(e),this}getVertexShaderID(e){return this._getShaderStage(e.vertexShader).id}getFragmentShaderID(e){return this._getShaderStage(e.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){let t=this.materialCache,n=t.get(e);return n===void 0&&(n=new Set,t.set(e,n)),n}_getShaderStage(e){let t=this.shaderCache,n=t.get(e);return n===void 0&&(n=new ks(e),t.set(e,n)),n}},ks=class{constructor(e){this.id=Ds++,this.code=e,this.usedTimes=0}};function As(e,t,n,r,i,a){let o=new Vt,s=new Os,c=new Set,l=[],u=new Map,d=r.logarithmicDepthBuffer,f=r.precision,p={MeshDepthMaterial:`depth`,MeshDistanceMaterial:`distance`,MeshNormalMaterial:`normal`,MeshBasicMaterial:`basic`,MeshLambertMaterial:`lambert`,MeshPhongMaterial:`phong`,MeshToonMaterial:`toon`,MeshStandardMaterial:`physical`,MeshPhysicalMaterial:`physical`,MeshMatcapMaterial:`matcap`,LineBasicMaterial:`basic`,LineDashedMaterial:`dashed`,PointsMaterial:`points`,ShadowMaterial:`shadow`,SpriteMaterial:`sprite`};function m(e){return c.add(e),e===0?`uv`:`uv${e}`}function h(i,o,l,u,h){let g=u.fog,_=h.geometry,v=i.isMeshStandardMaterial||i.isMeshLambertMaterial||i.isMeshPhongMaterial?u.environment:null,y=i.isMeshStandardMaterial||i.isMeshLambertMaterial&&!i.envMap||i.isMeshPhongMaterial&&!i.envMap,b=t.get(i.envMap||v,y),x=b&&b.mapping===306?b.image.height:null,S=p[i.type];i.precision!==null&&(f=r.getMaxPrecision(i.precision),f!==i.precision&&H(`WebGLProgram.getParameters:`,i.precision,`not supported, using`,f,`instead.`));let C=_.morphAttributes.position||_.morphAttributes.normal||_.morphAttributes.color,w=C===void 0?0:C.length,T=0;_.morphAttributes.position!==void 0&&(T=1),_.morphAttributes.normal!==void 0&&(T=2),_.morphAttributes.color!==void 0&&(T=3);let E,D,O,k;if(S){let e=Qi[S];E=e.vertexShader,D=e.fragmentShader}else E=i.vertexShader,D=i.fragmentShader,s.update(i),O=s.getVertexShaderID(i),k=s.getFragmentShaderID(i);let A=e.getRenderTarget(),ee=e.state.buffers.depth.getReversed(),te=h.isInstancedMesh===!0,j=h.isBatchedMesh===!0,ne=!!i.map,M=!!i.matcap,N=!!b,P=!!i.aoMap,re=!!i.lightMap,F=!!i.bumpMap,ie=!!i.normalMap,ae=!!i.displacementMap,oe=!!i.emissiveMap,se=!!i.metalnessMap,ce=!!i.roughnessMap,le=i.anisotropy>0,ue=i.clearcoat>0,de=i.dispersion>0,I=i.iridescence>0,L=i.sheen>0,fe=i.transmission>0,pe=le&&!!i.anisotropyMap,me=ue&&!!i.clearcoatMap,he=ue&&!!i.clearcoatNormalMap,ge=ue&&!!i.clearcoatRoughnessMap,_e=I&&!!i.iridescenceMap,ve=I&&!!i.iridescenceThicknessMap,ye=L&&!!i.sheenColorMap,be=L&&!!i.sheenRoughnessMap,xe=!!i.specularMap,Se=!!i.specularColorMap,Ce=!!i.specularIntensityMap,we=fe&&!!i.transmissionMap,Te=fe&&!!i.thicknessMap,R=!!i.gradientMap,Ee=!!i.alphaMap,De=i.alphaTest>0,Oe=!!i.alphaHash,z=!!i.extensions,ke=0;i.toneMapped&&(A===null||A.isXRRenderTarget===!0)&&(ke=e.toneMapping);let B={shaderID:S,shaderType:i.type,shaderName:i.name,vertexShader:E,fragmentShader:D,defines:i.defines,customVertexShaderID:O,customFragmentShaderID:k,isRawShaderMaterial:i.isRawShaderMaterial===!0,glslVersion:i.glslVersion,precision:f,batching:j,batchingColor:j&&h._colorsTexture!==null,instancing:te,instancingColor:te&&h.instanceColor!==null,instancingMorph:te&&h.morphTexture!==null,outputColorSpace:A===null?e.outputColorSpace:A.isXRRenderTarget===!0?A.texture.colorSpace:Ie,alphaToCoverage:!!i.alphaToCoverage,map:ne,matcap:M,envMap:N,envMapMode:N&&b.mapping,envMapCubeUVHeight:x,aoMap:P,lightMap:re,bumpMap:F,normalMap:ie,displacementMap:ae,emissiveMap:oe,normalMapObjectSpace:ie&&i.normalMapType===1,normalMapTangentSpace:ie&&i.normalMapType===0,metalnessMap:se,roughnessMap:ce,anisotropy:le,anisotropyMap:pe,clearcoat:ue,clearcoatMap:me,clearcoatNormalMap:he,clearcoatRoughnessMap:ge,dispersion:de,iridescence:I,iridescenceMap:_e,iridescenceThicknessMap:ve,sheen:L,sheenColorMap:ye,sheenRoughnessMap:be,specularMap:xe,specularColorMap:Se,specularIntensityMap:Ce,transmission:fe,transmissionMap:we,thicknessMap:Te,gradientMap:R,opaque:i.transparent===!1&&i.blending===1&&i.alphaToCoverage===!1,alphaMap:Ee,alphaTest:De,alphaHash:Oe,combine:i.combine,mapUv:ne&&m(i.map.channel),aoMapUv:P&&m(i.aoMap.channel),lightMapUv:re&&m(i.lightMap.channel),bumpMapUv:F&&m(i.bumpMap.channel),normalMapUv:ie&&m(i.normalMap.channel),displacementMapUv:ae&&m(i.displacementMap.channel),emissiveMapUv:oe&&m(i.emissiveMap.channel),metalnessMapUv:se&&m(i.metalnessMap.channel),roughnessMapUv:ce&&m(i.roughnessMap.channel),anisotropyMapUv:pe&&m(i.anisotropyMap.channel),clearcoatMapUv:me&&m(i.clearcoatMap.channel),clearcoatNormalMapUv:he&&m(i.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:ge&&m(i.clearcoatRoughnessMap.channel),iridescenceMapUv:_e&&m(i.iridescenceMap.channel),iridescenceThicknessMapUv:ve&&m(i.iridescenceThicknessMap.channel),sheenColorMapUv:ye&&m(i.sheenColorMap.channel),sheenRoughnessMapUv:be&&m(i.sheenRoughnessMap.channel),specularMapUv:xe&&m(i.specularMap.channel),specularColorMapUv:Se&&m(i.specularColorMap.channel),specularIntensityMapUv:Ce&&m(i.specularIntensityMap.channel),transmissionMapUv:we&&m(i.transmissionMap.channel),thicknessMapUv:Te&&m(i.thicknessMap.channel),alphaMapUv:Ee&&m(i.alphaMap.channel),vertexTangents:!!_.attributes.tangent&&(ie||le),vertexColors:i.vertexColors,vertexAlphas:i.vertexColors===!0&&!!_.attributes.color&&_.attributes.color.itemSize===4,pointsUvs:h.isPoints===!0&&!!_.attributes.uv&&(ne||Ee),fog:!!g,useFog:i.fog===!0,fogExp2:!!g&&g.isFogExp2,flatShading:i.wireframe===!1&&(i.flatShading===!0||_.attributes.normal===void 0&&ie===!1&&(i.isMeshLambertMaterial||i.isMeshPhongMaterial||i.isMeshStandardMaterial||i.isMeshPhysicalMaterial)),sizeAttenuation:i.sizeAttenuation===!0,logarithmicDepthBuffer:d,reversedDepthBuffer:ee,skinning:h.isSkinnedMesh===!0,morphTargets:_.morphAttributes.position!==void 0,morphNormals:_.morphAttributes.normal!==void 0,morphColors:_.morphAttributes.color!==void 0,morphTargetsCount:w,morphTextureStride:T,numDirLights:o.directional.length,numPointLights:o.point.length,numSpotLights:o.spot.length,numSpotLightMaps:o.spotLightMap.length,numRectAreaLights:o.rectArea.length,numHemiLights:o.hemi.length,numDirLightShadows:o.directionalShadowMap.length,numPointLightShadows:o.pointShadowMap.length,numSpotLightShadows:o.spotShadowMap.length,numSpotLightShadowsWithMaps:o.numSpotLightShadowsWithMaps,numLightProbes:o.numLightProbes,numClippingPlanes:a.numPlanes,numClipIntersection:a.numIntersection,dithering:i.dithering,shadowMapEnabled:e.shadowMap.enabled&&l.length>0,shadowMapType:e.shadowMap.type,toneMapping:ke,decodeVideoTexture:ne&&i.map.isVideoTexture===!0&&J.getTransfer(i.map.colorSpace)===`srgb`,decodeVideoTextureEmissive:oe&&i.emissiveMap.isVideoTexture===!0&&J.getTransfer(i.emissiveMap.colorSpace)===`srgb`,premultipliedAlpha:i.premultipliedAlpha,doubleSided:i.side===2,flipSided:i.side===1,useDepthPacking:i.depthPacking>=0,depthPacking:i.depthPacking||0,index0AttributeName:i.index0AttributeName,extensionClipCullDistance:z&&i.extensions.clipCullDistance===!0&&n.has(`WEBGL_clip_cull_distance`),extensionMultiDraw:(z&&i.extensions.multiDraw===!0||j)&&n.has(`WEBGL_multi_draw`),rendererExtensionParallelShaderCompile:n.has(`KHR_parallel_shader_compile`),customProgramCacheKey:i.customProgramCacheKey()};return B.vertexUv1s=c.has(1),B.vertexUv2s=c.has(2),B.vertexUv3s=c.has(3),c.clear(),B}function g(t){let n=[];if(t.shaderID?n.push(t.shaderID):(n.push(t.customVertexShaderID),n.push(t.customFragmentShaderID)),t.defines!==void 0)for(let e in t.defines)n.push(e),n.push(t.defines[e]);return t.isRawShaderMaterial===!1&&(_(n,t),v(n,t),n.push(e.outputColorSpace)),n.push(t.customProgramCacheKey),n.join()}function _(e,t){e.push(t.precision),e.push(t.outputColorSpace),e.push(t.envMapMode),e.push(t.envMapCubeUVHeight),e.push(t.mapUv),e.push(t.alphaMapUv),e.push(t.lightMapUv),e.push(t.aoMapUv),e.push(t.bumpMapUv),e.push(t.normalMapUv),e.push(t.displacementMapUv),e.push(t.emissiveMapUv),e.push(t.metalnessMapUv),e.push(t.roughnessMapUv),e.push(t.anisotropyMapUv),e.push(t.clearcoatMapUv),e.push(t.clearcoatNormalMapUv),e.push(t.clearcoatRoughnessMapUv),e.push(t.iridescenceMapUv),e.push(t.iridescenceThicknessMapUv),e.push(t.sheenColorMapUv),e.push(t.sheenRoughnessMapUv),e.push(t.specularMapUv),e.push(t.specularColorMapUv),e.push(t.specularIntensityMapUv),e.push(t.transmissionMapUv),e.push(t.thicknessMapUv),e.push(t.combine),e.push(t.fogExp2),e.push(t.sizeAttenuation),e.push(t.morphTargetsCount),e.push(t.morphAttributeCount),e.push(t.numDirLights),e.push(t.numPointLights),e.push(t.numSpotLights),e.push(t.numSpotLightMaps),e.push(t.numHemiLights),e.push(t.numRectAreaLights),e.push(t.numDirLightShadows),e.push(t.numPointLightShadows),e.push(t.numSpotLightShadows),e.push(t.numSpotLightShadowsWithMaps),e.push(t.numLightProbes),e.push(t.shadowMapType),e.push(t.toneMapping),e.push(t.numClippingPlanes),e.push(t.numClipIntersection),e.push(t.depthPacking)}function v(e,t){o.disableAll(),t.instancing&&o.enable(0),t.instancingColor&&o.enable(1),t.instancingMorph&&o.enable(2),t.matcap&&o.enable(3),t.envMap&&o.enable(4),t.normalMapObjectSpace&&o.enable(5),t.normalMapTangentSpace&&o.enable(6),t.clearcoat&&o.enable(7),t.iridescence&&o.enable(8),t.alphaTest&&o.enable(9),t.vertexColors&&o.enable(10),t.vertexAlphas&&o.enable(11),t.vertexUv1s&&o.enable(12),t.vertexUv2s&&o.enable(13),t.vertexUv3s&&o.enable(14),t.vertexTangents&&o.enable(15),t.anisotropy&&o.enable(16),t.alphaHash&&o.enable(17),t.batching&&o.enable(18),t.dispersion&&o.enable(19),t.batchingColor&&o.enable(20),t.gradientMap&&o.enable(21),e.push(o.mask),o.disableAll(),t.fog&&o.enable(0),t.useFog&&o.enable(1),t.flatShading&&o.enable(2),t.logarithmicDepthBuffer&&o.enable(3),t.reversedDepthBuffer&&o.enable(4),t.skinning&&o.enable(5),t.morphTargets&&o.enable(6),t.morphNormals&&o.enable(7),t.morphColors&&o.enable(8),t.premultipliedAlpha&&o.enable(9),t.shadowMapEnabled&&o.enable(10),t.doubleSided&&o.enable(11),t.flipSided&&o.enable(12),t.useDepthPacking&&o.enable(13),t.dithering&&o.enable(14),t.transmission&&o.enable(15),t.sheen&&o.enable(16),t.opaque&&o.enable(17),t.pointsUvs&&o.enable(18),t.decodeVideoTexture&&o.enable(19),t.decodeVideoTextureEmissive&&o.enable(20),t.alphaToCoverage&&o.enable(21),e.push(o.mask)}function y(e){let t=p[e.type],n;if(t){let e=Qi[t];n=Qr.clone(e.uniforms)}else n=e.uniforms;return n}function b(t,n){let r=u.get(n);return r===void 0?(r=new Es(e,n,t,i),l.push(r),u.set(n,r)):++r.usedTimes,r}function x(e){if(--e.usedTimes===0){let t=l.indexOf(e);l[t]=l[l.length-1],l.pop(),u.delete(e.cacheKey),e.destroy()}}function S(e){s.remove(e)}function C(){s.dispose()}return{getParameters:h,getProgramCacheKey:g,getUniforms:y,acquireProgram:b,releaseProgram:x,releaseShaderCache:S,programs:l,dispose:C}}function js(){let e=new WeakMap;function t(t){return e.has(t)}function n(t){let n=e.get(t);return n===void 0&&(n={},e.set(t,n)),n}function r(t){e.delete(t)}function i(t,n,r){e.get(t)[n]=r}function a(){e=new WeakMap}return{has:t,get:n,remove:r,update:i,dispose:a}}function Ms(e,t){return e.groupOrder===t.groupOrder?e.renderOrder===t.renderOrder?e.material.id===t.material.id?e.materialVariant===t.materialVariant?e.z===t.z?e.id-t.id:e.z-t.z:e.materialVariant-t.materialVariant:e.material.id-t.material.id:e.renderOrder-t.renderOrder:e.groupOrder-t.groupOrder}function Ns(e,t){return e.groupOrder===t.groupOrder?e.renderOrder===t.renderOrder?e.z===t.z?e.id-t.id:t.z-e.z:e.renderOrder-t.renderOrder:e.groupOrder-t.groupOrder}function Ps(){let e=[],t=0,n=[],r=[],i=[];function a(){t=0,n.length=0,r.length=0,i.length=0}function o(e){let t=0;return e.isInstancedMesh&&(t+=2),e.isSkinnedMesh&&(t+=1),t}function s(n,r,i,a,s,c){let l=e[t];return l===void 0?(l={id:n.id,object:n,geometry:r,material:i,materialVariant:o(n),groupOrder:a,renderOrder:n.renderOrder,z:s,group:c},e[t]=l):(l.id=n.id,l.object=n,l.geometry=r,l.material=i,l.materialVariant=o(n),l.groupOrder=a,l.renderOrder=n.renderOrder,l.z=s,l.group=c),t++,l}function c(e,t,a,o,c,l){let u=s(e,t,a,o,c,l);a.transmission>0?r.push(u):a.transparent===!0?i.push(u):n.push(u)}function l(e,t,a,o,c,l){let u=s(e,t,a,o,c,l);a.transmission>0?r.unshift(u):a.transparent===!0?i.unshift(u):n.unshift(u)}function u(e,t){n.length>1&&n.sort(e||Ms),r.length>1&&r.sort(t||Ns),i.length>1&&i.sort(t||Ns)}function d(){for(let n=t,r=e.length;n=r.length?(i=new Ps,r.push(i)):i=r[n],i}function n(){e=new WeakMap}return{get:t,dispose:n}}function Is(){let e={};return{get:function(t){if(e[t.id]!==void 0)return e[t.id];let n;switch(t.type){case`DirectionalLight`:n={direction:new K,color:new Y};break;case`SpotLight`:n={position:new K,direction:new K,color:new Y,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case`PointLight`:n={position:new K,color:new Y,distance:0,decay:0};break;case`HemisphereLight`:n={direction:new K,skyColor:new Y,groundColor:new Y};break;case`RectAreaLight`:n={color:new Y,position:new K,halfWidth:new K,halfHeight:new K};break}return e[t.id]=n,n}}}function Ls(){let e={};return{get:function(t){if(e[t.id]!==void 0)return e[t.id];let n;switch(t.type){case`DirectionalLight`:n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new G};break;case`SpotLight`:n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new G};break;case`PointLight`:n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new G,shadowCameraNear:1,shadowCameraFar:1e3};break}return e[t.id]=n,n}}}var Rs=0;function zs(e,t){return(t.castShadow?2:0)-(e.castShadow?2:0)+(t.map?1:0)-(e.map?1:0)}function Bs(e){let t=new Is,n=Ls(),r={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let e=0;e<9;e++)r.probe.push(new K);let i=new K,a=new At,o=new At;function s(i){let a=0,o=0,s=0;for(let e=0;e<9;e++)r.probe[e].set(0,0,0);let c=0,l=0,u=0,d=0,f=0,p=0,m=0,h=0,g=0,_=0,v=0;i.sort(zs);for(let e=0,y=i.length;e0&&(e.has(`OES_texture_float_linear`)===!0?(r.rectAreaLTC1=Z.LTC_FLOAT_1,r.rectAreaLTC2=Z.LTC_FLOAT_2):(r.rectAreaLTC1=Z.LTC_HALF_1,r.rectAreaLTC2=Z.LTC_HALF_2)),r.ambient[0]=a,r.ambient[1]=o,r.ambient[2]=s;let y=r.hash;(y.directionalLength!==c||y.pointLength!==l||y.spotLength!==u||y.rectAreaLength!==d||y.hemiLength!==f||y.numDirectionalShadows!==p||y.numPointShadows!==m||y.numSpotShadows!==h||y.numSpotMaps!==g||y.numLightProbes!==v)&&(r.directional.length=c,r.spot.length=u,r.rectArea.length=d,r.point.length=l,r.hemi.length=f,r.directionalShadow.length=p,r.directionalShadowMap.length=p,r.pointShadow.length=m,r.pointShadowMap.length=m,r.spotShadow.length=h,r.spotShadowMap.length=h,r.directionalShadowMatrix.length=p,r.pointShadowMatrix.length=m,r.spotLightMatrix.length=h+g-_,r.spotLightMap.length=g,r.numSpotLightShadowsWithMaps=_,r.numLightProbes=v,y.directionalLength=c,y.pointLength=l,y.spotLength=u,y.rectAreaLength=d,y.hemiLength=f,y.numDirectionalShadows=p,y.numPointShadows=m,y.numSpotShadows=h,y.numSpotMaps=g,y.numLightProbes=v,r.version=Rs++)}function c(e,t){let n=0,s=0,c=0,l=0,u=0,d=t.matrixWorldInverse;for(let t=0,f=e.length;t=i.length?(a=new Vs(e),i.push(a)):a=i[r],a}function r(){t=new WeakMap}return{get:n,dispose:r}}var Us=`void main() { gl_Position = vec4( position, 1.0 ); }`,Ws=`uniform sampler2D shadow_pass; uniform vec2 resolution; uniform float radius; void main() { const float samples = float( VSM_SAMPLES ); float mean = 0.0; float squared_mean = 0.0; float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 ); float uvStart = samples <= 1.0 ? 0.0 : - 1.0; for ( float i = 0.0; i < samples; i ++ ) { float uvOffset = uvStart + i * uvStride; #ifdef HORIZONTAL_PASS vec2 distribution = texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ).rg; mean += distribution.x; squared_mean += distribution.y * distribution.y + distribution.x * distribution.x; #else float depth = texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ).r; mean += depth; squared_mean += depth * depth; #endif } mean = mean / samples; squared_mean = squared_mean / samples; float std_dev = sqrt( max( 0.0, squared_mean - mean * mean ) ); gl_FragColor = vec4( mean, std_dev, 0.0, 1.0 ); }`,Gs=[new K(1,0,0),new K(-1,0,0),new K(0,1,0),new K(0,-1,0),new K(0,0,1),new K(0,0,-1)],Ks=[new K(0,-1,0),new K(0,-1,0),new K(0,0,1),new K(0,0,-1),new K(0,-1,0),new K(0,-1,0)],qs=new At,Js=new K,Ys=new K;function Xs(e,t,n){let r=new Vr,a=new G,o=new G,c=new Tt,l=new ri,u=new ii,d={},f=n.maxTextureSize,p={0:1,1:0,2:2},m=new ti({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new G},radius:{value:4}},vertexShader:Us,fragmentShader:Ws}),v=m.clone();v.defines.HORIZONTAL_PASS=1;let y=new sr;y.setAttribute(`position`,new Kn(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));let b=new Ar(y,m),x=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=1;let S=this.type;this.render=function(t,n,l){if(x.enabled===!1||x.autoUpdate===!1&&x.needsUpdate===!1||t.length===0)return;this.type===2&&(H(`WebGLShadowMap: PCFSoftShadowMap has been deprecated. Using PCFShadowMap instead.`),this.type=1);let u=e.getRenderTarget(),d=e.getActiveCubeFace(),p=e.getActiveMipmapLevel(),m=e.state;m.setBlending(0),m.buffers.depth.getReversed()===!0?m.buffers.color.setClear(0,0,0,0):m.buffers.color.setClear(1,1,1,1),m.buffers.depth.setTest(!0),m.setScissorTest(!1);let v=S!==this.type;v&&n.traverse(function(e){e.material&&(Array.isArray(e.material)?e.material.forEach(e=>e.needsUpdate=!0):e.material.needsUpdate=!0)});for(let u=0,d=t.length;uf||a.y>f)&&(a.x>f&&(o.x=Math.floor(f/y.x),a.x=o.x*y.x,p.mapSize.x=o.x),a.y>f&&(o.y=Math.floor(f/y.y),a.y=o.y*y.y,p.mapSize.y=o.y));let b=e.state.buffers.depth.getReversed();if(p.camera._reversedDepth=b,p.map===null||v===!0){if(p.map!==null&&(p.map.depthTexture!==null&&(p.map.depthTexture.dispose(),p.map.depthTexture=null),p.map.dispose()),this.type===3){if(d.isPointLight){H(`WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.`);continue}p.map=new Dt(a.x,a.y,{format:A,type:_,minFilter:s,magFilter:s,generateMipmaps:!1}),p.map.texture.name=d.name+`.shadowMap`,p.map.depthTexture=new Ur(a.x,a.y,g),p.map.depthTexture.name=d.name+`.shadowMapDepth`,p.map.depthTexture.format=E,p.map.depthTexture.compareFunction=null,p.map.depthTexture.minFilter=i,p.map.depthTexture.magFilter=i}else d.isPointLight?(p.map=new Da(a.x),p.map.depthTexture=new Wr(a.x,h)):(p.map=new Dt(a.x,a.y),p.map.depthTexture=new Ur(a.x,a.y,h)),p.map.depthTexture.name=d.name+`.shadowMap`,p.map.depthTexture.format=E,this.type===1?(p.map.depthTexture.compareFunction=b?518:515,p.map.depthTexture.minFilter=s,p.map.depthTexture.magFilter=s):(p.map.depthTexture.compareFunction=null,p.map.depthTexture.minFilter=i,p.map.depthTexture.magFilter=i);p.camera.updateProjectionMatrix()}let x=p.map.isWebGLCubeRenderTarget?6:1;for(let t=0;t0||n.map&&n.alphaTest>0||n.alphaToCoverage===!0){let e=a.uuid,t=n.uuid,r=d[e];r===void 0&&(r={},d[e]=r);let i=r[t];i===void 0&&(i=a.clone(),r[t]=i,n.addEventListener(`dispose`,D)),a=i}if(a.visible=n.visible,a.wireframe=n.wireframe,i===3?a.side=n.shadowSide===null?n.side:n.shadowSide:a.side=n.shadowSide===null?p[n.side]:n.shadowSide,a.alphaMap=n.alphaMap,a.alphaTest=n.alphaToCoverage===!0?.5:n.alphaTest,a.map=n.map,a.clipShadows=n.clipShadows,a.clippingPlanes=n.clippingPlanes,a.clipIntersection=n.clipIntersection,a.displacementMap=n.displacementMap,a.displacementScale=n.displacementScale,a.displacementBias=n.displacementBias,a.wireframeLinewidth=n.wireframeLinewidth,a.linewidth=n.linewidth,r.isPointLight===!0&&a.isMeshDistanceMaterial===!0){let t=e.properties.get(a);t.light=r}return a}function T(n,i,a,o,s){if(n.visible===!1)return;if(n.layers.test(i.layers)&&(n.isMesh||n.isLine||n.isPoints)&&(n.castShadow||n.receiveShadow&&s===3)&&(!n.frustumCulled||r.intersectsObject(n))){n.modelViewMatrix.multiplyMatrices(a.matrixWorldInverse,n.matrixWorld);let r=t.update(n),c=n.material;if(Array.isArray(c)){let t=r.groups;for(let l=0,u=t.length;l=2):(j=parseFloat(/^WebGL (\d)/.exec(ne)[1]),te=j>=1);let M=null,N={},P=e.getParameter(e.SCISSOR_BOX),re=e.getParameter(e.VIEWPORT),F=new Tt().fromArray(P),ie=new Tt().fromArray(re);function ae(t,n,r,i){let a=new Uint8Array(4),o=e.createTexture();e.bindTexture(t,o),e.texParameteri(t,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(t,e.TEXTURE_MAG_FILTER,e.NEAREST);for(let o=0;o`u`?!1:/OculusBrowser/g.test(navigator.userAgent),v=new G,y=new WeakMap,b,x=new WeakMap,S=!1;try{S=typeof OffscreenCanvas<`u`&&new OffscreenCanvas(1,1).getContext(`2d`)!==null}catch{}function C(e,t){return S?new OffscreenCanvas(e,t):We(`canvas`)}function w(e,t,n){let r=1,i=z(e);if((i.width>n||i.height>n)&&(r=n/Math.max(i.width,i.height)),r<1)if(typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof ImageBitmap<`u`&&e instanceof ImageBitmap||typeof VideoFrame<`u`&&e instanceof VideoFrame){let n=Math.floor(r*i.width),a=Math.floor(r*i.height);b===void 0&&(b=C(n,a));let o=t?C(n,a):b;return o.width=n,o.height=a,o.getContext(`2d`).drawImage(e,0,0,n,a),H(`WebGLRenderer: Texture has been resized from (`+i.width+`x`+i.height+`) to (`+n+`x`+a+`).`),o}else return`data`in e&&H(`WebGLRenderer: Image in DataTexture is too big (`+i.width+`x`+i.height+`).`),e;return e}function T(e){return e.generateMipmaps}function E(t){e.generateMipmap(t)}function O(t){return t.isWebGLCubeRenderTarget?e.TEXTURE_CUBE_MAP:t.isWebGL3DRenderTarget?e.TEXTURE_3D:t.isWebGLArrayRenderTarget||t.isCompressedArrayTexture?e.TEXTURE_2D_ARRAY:e.TEXTURE_2D}function k(t,n,r,i,a=!1){if(t!==null){if(e[t]!==void 0)return e[t];H(`WebGLRenderer: Attempt to use non-existing WebGL internal format '`+t+`'`)}let o=n;if(n===e.RED&&(r===e.FLOAT&&(o=e.R32F),r===e.HALF_FLOAT&&(o=e.R16F),r===e.UNSIGNED_BYTE&&(o=e.R8)),n===e.RED_INTEGER&&(r===e.UNSIGNED_BYTE&&(o=e.R8UI),r===e.UNSIGNED_SHORT&&(o=e.R16UI),r===e.UNSIGNED_INT&&(o=e.R32UI),r===e.BYTE&&(o=e.R8I),r===e.SHORT&&(o=e.R16I),r===e.INT&&(o=e.R32I)),n===e.RG&&(r===e.FLOAT&&(o=e.RG32F),r===e.HALF_FLOAT&&(o=e.RG16F),r===e.UNSIGNED_BYTE&&(o=e.RG8)),n===e.RG_INTEGER&&(r===e.UNSIGNED_BYTE&&(o=e.RG8UI),r===e.UNSIGNED_SHORT&&(o=e.RG16UI),r===e.UNSIGNED_INT&&(o=e.RG32UI),r===e.BYTE&&(o=e.RG8I),r===e.SHORT&&(o=e.RG16I),r===e.INT&&(o=e.RG32I)),n===e.RGB_INTEGER&&(r===e.UNSIGNED_BYTE&&(o=e.RGB8UI),r===e.UNSIGNED_SHORT&&(o=e.RGB16UI),r===e.UNSIGNED_INT&&(o=e.RGB32UI),r===e.BYTE&&(o=e.RGB8I),r===e.SHORT&&(o=e.RGB16I),r===e.INT&&(o=e.RGB32I)),n===e.RGBA_INTEGER&&(r===e.UNSIGNED_BYTE&&(o=e.RGBA8UI),r===e.UNSIGNED_SHORT&&(o=e.RGBA16UI),r===e.UNSIGNED_INT&&(o=e.RGBA32UI),r===e.BYTE&&(o=e.RGBA8I),r===e.SHORT&&(o=e.RGBA16I),r===e.INT&&(o=e.RGBA32I)),n===e.RGB&&(r===e.UNSIGNED_INT_5_9_9_9_REV&&(o=e.RGB9_E5),r===e.UNSIGNED_INT_10F_11F_11F_REV&&(o=e.R11F_G11F_B10F)),n===e.RGBA){let t=a?Le:J.getTransfer(i);r===e.FLOAT&&(o=e.RGBA32F),r===e.HALF_FLOAT&&(o=e.RGBA16F),r===e.UNSIGNED_BYTE&&(o=t===`srgb`?e.SRGB8_ALPHA8:e.RGBA8),r===e.UNSIGNED_SHORT_4_4_4_4&&(o=e.RGBA4),r===e.UNSIGNED_SHORT_5_5_5_1&&(o=e.RGB5_A1)}return(o===e.R16F||o===e.R32F||o===e.RG16F||o===e.RG32F||o===e.RGBA16F||o===e.RGBA32F)&&u.get(`EXT_color_buffer_float`),o}function A(t,n){let r;return t?n===null||n===1014||n===1020?r=e.DEPTH24_STENCIL8:n===1015?r=e.DEPTH32F_STENCIL8:n===1012&&(r=e.DEPTH24_STENCIL8,H(`DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.`)):n===null||n===1014||n===1020?r=e.DEPTH_COMPONENT24:n===1015?r=e.DEPTH_COMPONENT32F:n===1012&&(r=e.DEPTH_COMPONENT16),r}function ee(e,t){return T(e)===!0||e.isFramebufferTexture&&e.minFilter!==1003&&e.minFilter!==1006?Math.log2(Math.max(t.width,t.height))+1:e.mipmaps!==void 0&&e.mipmaps.length>0?e.mipmaps.length:e.isCompressedTexture&&Array.isArray(e.image)?t.mipmaps.length:1}function te(e){let t=e.target;t.removeEventListener(`dispose`,te),ne(t),t.isVideoTexture&&y.delete(t)}function j(e){let t=e.target;t.removeEventListener(`dispose`,j),N(t)}function ne(e){let t=f.get(e);if(t.__webglInit===void 0)return;let n=e.source,r=x.get(n);if(r){let i=r[t.__cacheKey];i.usedTimes--,i.usedTimes===0&&M(e),Object.keys(r).length===0&&x.delete(n)}f.remove(e)}function M(t){let n=f.get(t);e.deleteTexture(n.__webglTexture);let r=t.source,i=x.get(r);delete i[n.__cacheKey],h.memory.textures--}function N(t){let n=f.get(t);if(t.depthTexture&&(t.depthTexture.dispose(),f.remove(t.depthTexture)),t.isWebGLCubeRenderTarget)for(let t=0;t<6;t++){if(Array.isArray(n.__webglFramebuffer[t]))for(let r=0;r=p.maxTextures&&H(`WebGLTextures: Trying to use `+e+` texture units while this GPU supports only `+p.maxTextures),P+=1,e}function ie(e){let t=[];return t.push(e.wrapS),t.push(e.wrapT),t.push(e.wrapR||0),t.push(e.magFilter),t.push(e.minFilter),t.push(e.anisotropy),t.push(e.internalFormat),t.push(e.format),t.push(e.type),t.push(e.generateMipmaps),t.push(e.premultiplyAlpha),t.push(e.flipY),t.push(e.unpackAlignment),t.push(e.colorSpace),t.join()}function ae(t,n){let r=f.get(t);if(t.isVideoTexture&&De(t),t.isRenderTargetTexture===!1&&t.isExternalTexture!==!0&&t.version>0&&r.__version!==t.version){let e=t.image;if(e===null)H(`WebGLRenderer: Texture marked for update but no image data found.`);else if(e.complete===!1)H(`WebGLRenderer: Texture marked for update but image is incomplete`);else{me(r,t,n);return}}else t.isExternalTexture&&(r.__webglTexture=t.sourceTexture?t.sourceTexture:null);d.bindTexture(e.TEXTURE_2D,r.__webglTexture,e.TEXTURE0+n)}function oe(t,n){let r=f.get(t);if(t.isRenderTargetTexture===!1&&t.version>0&&r.__version!==t.version){me(r,t,n);return}else t.isExternalTexture&&(r.__webglTexture=t.sourceTexture?t.sourceTexture:null);d.bindTexture(e.TEXTURE_2D_ARRAY,r.__webglTexture,e.TEXTURE0+n)}function se(t,n){let r=f.get(t);if(t.isRenderTargetTexture===!1&&t.version>0&&r.__version!==t.version){me(r,t,n);return}d.bindTexture(e.TEXTURE_3D,r.__webglTexture,e.TEXTURE0+n)}function ce(t,n){let r=f.get(t);if(t.isCubeDepthTexture!==!0&&t.version>0&&r.__version!==t.version){he(r,t,n);return}d.bindTexture(e.TEXTURE_CUBE_MAP,r.__webglTexture,e.TEXTURE0+n)}let le={[t]:e.REPEAT,[n]:e.CLAMP_TO_EDGE,[r]:e.MIRRORED_REPEAT},ue={[i]:e.NEAREST,[a]:e.NEAREST_MIPMAP_NEAREST,[o]:e.NEAREST_MIPMAP_LINEAR,[s]:e.LINEAR,[c]:e.LINEAR_MIPMAP_NEAREST,[l]:e.LINEAR_MIPMAP_LINEAR},de={512:e.NEVER,519:e.ALWAYS,513:e.LESS,515:e.LEQUAL,514:e.EQUAL,518:e.GEQUAL,516:e.GREATER,517:e.NOTEQUAL};function I(t,n){if(n.type===1015&&u.has(`OES_texture_float_linear`)===!1&&(n.magFilter===1006||n.magFilter===1007||n.magFilter===1005||n.magFilter===1008||n.minFilter===1006||n.minFilter===1007||n.minFilter===1005||n.minFilter===1008)&&H(`WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device.`),e.texParameteri(t,e.TEXTURE_WRAP_S,le[n.wrapS]),e.texParameteri(t,e.TEXTURE_WRAP_T,le[n.wrapT]),(t===e.TEXTURE_3D||t===e.TEXTURE_2D_ARRAY)&&e.texParameteri(t,e.TEXTURE_WRAP_R,le[n.wrapR]),e.texParameteri(t,e.TEXTURE_MAG_FILTER,ue[n.magFilter]),e.texParameteri(t,e.TEXTURE_MIN_FILTER,ue[n.minFilter]),n.compareFunction&&(e.texParameteri(t,e.TEXTURE_COMPARE_MODE,e.COMPARE_REF_TO_TEXTURE),e.texParameteri(t,e.TEXTURE_COMPARE_FUNC,de[n.compareFunction])),u.has(`EXT_texture_filter_anisotropic`)===!0){if(n.magFilter===1003||n.minFilter!==1005&&n.minFilter!==1008||n.type===1015&&u.has(`OES_texture_float_linear`)===!1)return;if(n.anisotropy>1||f.get(n).__currentAnisotropy){let r=u.get(`EXT_texture_filter_anisotropic`);e.texParameterf(t,r.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(n.anisotropy,p.getMaxAnisotropy())),f.get(n).__currentAnisotropy=n.anisotropy}}}function L(t,n){let r=!1;t.__webglInit===void 0&&(t.__webglInit=!0,n.addEventListener(`dispose`,te));let i=n.source,a=x.get(i);a===void 0&&(a={},x.set(i,a));let o=ie(n);if(o!==t.__cacheKey){a[o]===void 0&&(a[o]={texture:e.createTexture(),usedTimes:0},h.memory.textures++,r=!0),a[o].usedTimes++;let i=a[t.__cacheKey];i!==void 0&&(a[t.__cacheKey].usedTimes--,i.usedTimes===0&&M(n)),t.__cacheKey=o,t.__webglTexture=a[o].texture}return r}function fe(e,t,n){return Math.floor(Math.floor(e/n)/t)}function pe(t,n,r,i){let a=t.updateRanges;if(a.length===0)d.texSubImage2D(e.TEXTURE_2D,0,0,0,n.width,n.height,r,i,n.data);else{a.sort((e,t)=>e.start-t.start);let o=0;for(let e=1;e0){y&&b&&d.texStorage2D(e.TEXTURE_2D,S,g,v[0].width,v[0].height);for(let t=0,n=v.length;t0){let r=Ji(_.width,_.height,n.format,n.type);for(let i of n.layerUpdates){let n=_.data.subarray(i*r/_.data.BYTES_PER_ELEMENT,(i+1)*r/_.data.BYTES_PER_ELEMENT);d.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,t,0,0,i,_.width,_.height,1,f,n)}n.clearLayerUpdates()}else d.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,t,0,0,0,_.width,_.height,u.depth,f,_.data)}else d.compressedTexImage3D(e.TEXTURE_2D_ARRAY,t,g,_.width,_.height,u.depth,0,_.data,0,0);else H(`WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()`);else y?x&&d.texSubImage3D(e.TEXTURE_2D_ARRAY,t,0,0,0,_.width,_.height,u.depth,f,h,_.data):d.texImage3D(e.TEXTURE_2D_ARRAY,t,g,_.width,_.height,u.depth,0,f,h,_.data)}else{y&&b&&d.texStorage2D(e.TEXTURE_2D,S,g,v[0].width,v[0].height);for(let t=0,r=v.length;t0){let t=Ji(u.width,u.height,n.format,n.type);for(let r of n.layerUpdates){let n=u.data.subarray(r*t/u.data.BYTES_PER_ELEMENT,(r+1)*t/u.data.BYTES_PER_ELEMENT);d.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,r,u.width,u.height,1,f,h,n)}n.clearLayerUpdates()}else d.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,0,u.width,u.height,u.depth,f,h,u.data)}else d.texImage3D(e.TEXTURE_2D_ARRAY,0,g,u.width,u.height,u.depth,0,f,h,u.data);else if(n.isData3DTexture)y?(b&&d.texStorage3D(e.TEXTURE_3D,S,g,u.width,u.height,u.depth),x&&d.texSubImage3D(e.TEXTURE_3D,0,0,0,0,u.width,u.height,u.depth,f,h,u.data)):d.texImage3D(e.TEXTURE_3D,0,g,u.width,u.height,u.depth,0,f,h,u.data);else if(n.isFramebufferTexture){if(b)if(y)d.texStorage2D(e.TEXTURE_2D,S,g,u.width,u.height);else{let t=u.width,n=u.height;for(let r=0;r>=1,n>>=1}}else if(v.length>0){if(y&&b){let t=z(v[0]);d.texStorage2D(e.TEXTURE_2D,S,g,t.width,t.height)}for(let t=0,n=v.length;t0&&S++;let t=z(f[0]);d.texStorage2D(e.TEXTURE_CUBE_MAP,S,v,t.width,t.height)}for(let t=0;t<6;t++)if(u){y?x&&d.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,0,0,f[t].width,f[t].height,g,_,f[t].data):d.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,v,f[t].width,f[t].height,0,g,_,f[t].data);for(let n=0;n>o),r=Math.max(1,n.height>>o);a===e.TEXTURE_3D||a===e.TEXTURE_2D_ARRAY?d.texImage3D(a,o,l,t,r,n.depth,0,s,c,null):d.texImage2D(a,o,l,t,r,0,s,c,null)}d.bindFramebuffer(e.FRAMEBUFFER,t),Ee(n)?g.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,i,a,p.__webglTexture,0,R(n)):(a===e.TEXTURE_2D||a>=e.TEXTURE_CUBE_MAP_POSITIVE_X&&a<=e.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&e.framebufferTexture2D(e.FRAMEBUFFER,i,a,p.__webglTexture,o),d.bindFramebuffer(e.FRAMEBUFFER,null)}function _e(t,n,r){if(e.bindRenderbuffer(e.RENDERBUFFER,t),n.depthBuffer){let i=n.depthTexture,a=i&&i.isDepthTexture?i.type:null,o=A(n.stencilBuffer,a),s=n.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;Ee(n)?g.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,R(n),o,n.width,n.height):r?e.renderbufferStorageMultisample(e.RENDERBUFFER,R(n),o,n.width,n.height):e.renderbufferStorage(e.RENDERBUFFER,o,n.width,n.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,s,e.RENDERBUFFER,t)}else{let t=n.textures;for(let i=0;i{delete n.__boundDepthTexture,delete n.__depthDisposeCallback,e.removeEventListener(`dispose`,t)};e.addEventListener(`dispose`,t),n.__depthDisposeCallback=t}n.__boundDepthTexture=e}if(t.depthTexture&&!n.__autoAllocateDepthBuffer)if(r)for(let e=0;e<6;e++)ve(n.__webglFramebuffer[e],t,e);else{let e=t.texture.mipmaps;e&&e.length>0?ve(n.__webglFramebuffer[0],t,0):ve(n.__webglFramebuffer,t,0)}else if(r){n.__webglDepthbuffer=[];for(let r=0;r<6;r++)if(d.bindFramebuffer(e.FRAMEBUFFER,n.__webglFramebuffer[r]),n.__webglDepthbuffer[r]===void 0)n.__webglDepthbuffer[r]=e.createRenderbuffer(),_e(n.__webglDepthbuffer[r],t,!1);else{let i=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,a=n.__webglDepthbuffer[r];e.bindRenderbuffer(e.RENDERBUFFER,a),e.framebufferRenderbuffer(e.FRAMEBUFFER,i,e.RENDERBUFFER,a)}}else{let r=t.texture.mipmaps;if(r&&r.length>0?d.bindFramebuffer(e.FRAMEBUFFER,n.__webglFramebuffer[0]):d.bindFramebuffer(e.FRAMEBUFFER,n.__webglFramebuffer),n.__webglDepthbuffer===void 0)n.__webglDepthbuffer=e.createRenderbuffer(),_e(n.__webglDepthbuffer,t,!1);else{let r=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,i=n.__webglDepthbuffer;e.bindRenderbuffer(e.RENDERBUFFER,i),e.framebufferRenderbuffer(e.FRAMEBUFFER,r,e.RENDERBUFFER,i)}}d.bindFramebuffer(e.FRAMEBUFFER,null)}function be(t,n,r){let i=f.get(t);n!==void 0&&ge(i.__webglFramebuffer,t,t.texture,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,0),r!==void 0&&ye(t)}function xe(t){let n=t.texture,r=f.get(t),i=f.get(n);t.addEventListener(`dispose`,j);let a=t.textures,o=t.isWebGLCubeRenderTarget===!0,s=a.length>1;if(s||(i.__webglTexture===void 0&&(i.__webglTexture=e.createTexture()),i.__version=n.version,h.memory.textures++),o){r.__webglFramebuffer=[];for(let t=0;t<6;t++)if(n.mipmaps&&n.mipmaps.length>0){r.__webglFramebuffer[t]=[];for(let i=0;i0){r.__webglFramebuffer=[];for(let t=0;t0&&Ee(t)===!1){r.__webglMultisampledFramebuffer=e.createFramebuffer(),r.__webglColorRenderbuffer=[],d.bindFramebuffer(e.FRAMEBUFFER,r.__webglMultisampledFramebuffer);for(let n=0;n0)for(let a=0;a0)for(let i=0;i0){if(Ee(t)===!1){let n=t.textures,r=t.width,i=t.height,a=e.COLOR_BUFFER_BIT,o=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,s=f.get(t),c=n.length>1;if(c)for(let t=0;t0?d.bindFramebuffer(e.DRAW_FRAMEBUFFER,s.__webglFramebuffer[0]):d.bindFramebuffer(e.DRAW_FRAMEBUFFER,s.__webglFramebuffer);for(let l=0;l0&&u.has(`WEBGL_multisampled_render_to_texture`)===!0&&t.__useRenderToTexture!==!1}function De(e){let t=h.render.frame;y.get(e)!==t&&(y.set(e,t),e.update())}function Oe(e,t){let n=e.colorSpace,r=e.format,i=e.type;return e.isCompressedTexture===!0||e.isVideoTexture===!0||n!==`srgb-linear`&&n!==``&&(J.getTransfer(n)===`srgb`?(r!==1023||i!==1009)&&H(`WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.`):U(`WebGLTextures: Unsupported texture color space:`,n)),t}function z(e){return typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement?(v.width=e.naturalWidth||e.width,v.height=e.naturalHeight||e.height):typeof VideoFrame<`u`&&e instanceof VideoFrame?(v.width=e.displayWidth,v.height=e.displayHeight):(v.width=e.width,v.height=e.height),v}this.allocateTextureUnit=F,this.resetTextureUnits=re,this.setTexture2D=ae,this.setTexture2DArray=oe,this.setTexture3D=se,this.setTextureCube=ce,this.rebindTextures=be,this.setupRenderTarget=xe,this.updateRenderTargetMipmap=Se,this.updateMultisampleRenderTarget=Te,this.setupDepthRenderbuffer=ye,this.setupFrameBufferTexture=ge,this.useMultisampledRTT=Ee,this.isReversedDepthBuffer=function(){return d.buffers.depth.getReversed()}}function $s(e,t){function n(n,r=``){let i,a=J.getTransfer(r);if(n===1009)return e.UNSIGNED_BYTE;if(n===1017)return e.UNSIGNED_SHORT_4_4_4_4;if(n===1018)return e.UNSIGNED_SHORT_5_5_5_1;if(n===35902)return e.UNSIGNED_INT_5_9_9_9_REV;if(n===35899)return e.UNSIGNED_INT_10F_11F_11F_REV;if(n===1010)return e.BYTE;if(n===1011)return e.SHORT;if(n===1012)return e.UNSIGNED_SHORT;if(n===1013)return e.INT;if(n===1014)return e.UNSIGNED_INT;if(n===1015)return e.FLOAT;if(n===1016)return e.HALF_FLOAT;if(n===1021)return e.ALPHA;if(n===1022)return e.RGB;if(n===1023)return e.RGBA;if(n===1026)return e.DEPTH_COMPONENT;if(n===1027)return e.DEPTH_STENCIL;if(n===1028)return e.RED;if(n===1029)return e.RED_INTEGER;if(n===1030)return e.RG;if(n===1031)return e.RG_INTEGER;if(n===1033)return e.RGBA_INTEGER;if(n===33776||n===33777||n===33778||n===33779)if(a===`srgb`)if(i=t.get(`WEBGL_compressed_texture_s3tc_srgb`),i!==null){if(n===33776)return i.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(n===33777)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(n===33778)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(n===33779)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(i=t.get(`WEBGL_compressed_texture_s3tc`),i!==null){if(n===33776)return i.COMPRESSED_RGB_S3TC_DXT1_EXT;if(n===33777)return i.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(n===33778)return i.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(n===33779)return i.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(n===35840||n===35841||n===35842||n===35843)if(i=t.get(`WEBGL_compressed_texture_pvrtc`),i!==null){if(n===35840)return i.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(n===35841)return i.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(n===35842)return i.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(n===35843)return i.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(n===36196||n===37492||n===37496||n===37488||n===37489||n===37490||n===37491)if(i=t.get(`WEBGL_compressed_texture_etc`),i!==null){if(n===36196||n===37492)return a===`srgb`?i.COMPRESSED_SRGB8_ETC2:i.COMPRESSED_RGB8_ETC2;if(n===37496)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:i.COMPRESSED_RGBA8_ETC2_EAC;if(n===37488)return i.COMPRESSED_R11_EAC;if(n===37489)return i.COMPRESSED_SIGNED_R11_EAC;if(n===37490)return i.COMPRESSED_RG11_EAC;if(n===37491)return i.COMPRESSED_SIGNED_RG11_EAC}else return null;if(n===37808||n===37809||n===37810||n===37811||n===37812||n===37813||n===37814||n===37815||n===37816||n===37817||n===37818||n===37819||n===37820||n===37821)if(i=t.get(`WEBGL_compressed_texture_astc`),i!==null){if(n===37808)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:i.COMPRESSED_RGBA_ASTC_4x4_KHR;if(n===37809)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:i.COMPRESSED_RGBA_ASTC_5x4_KHR;if(n===37810)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:i.COMPRESSED_RGBA_ASTC_5x5_KHR;if(n===37811)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:i.COMPRESSED_RGBA_ASTC_6x5_KHR;if(n===37812)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:i.COMPRESSED_RGBA_ASTC_6x6_KHR;if(n===37813)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:i.COMPRESSED_RGBA_ASTC_8x5_KHR;if(n===37814)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:i.COMPRESSED_RGBA_ASTC_8x6_KHR;if(n===37815)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:i.COMPRESSED_RGBA_ASTC_8x8_KHR;if(n===37816)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:i.COMPRESSED_RGBA_ASTC_10x5_KHR;if(n===37817)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:i.COMPRESSED_RGBA_ASTC_10x6_KHR;if(n===37818)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:i.COMPRESSED_RGBA_ASTC_10x8_KHR;if(n===37819)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:i.COMPRESSED_RGBA_ASTC_10x10_KHR;if(n===37820)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:i.COMPRESSED_RGBA_ASTC_12x10_KHR;if(n===37821)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:i.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(n===36492||n===36494||n===36495)if(i=t.get(`EXT_texture_compression_bptc`),i!==null){if(n===36492)return a===`srgb`?i.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:i.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(n===36494)return i.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(n===36495)return i.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(n===36283||n===36284||n===36285||n===36286)if(i=t.get(`EXT_texture_compression_rgtc`),i!==null){if(n===36283)return i.COMPRESSED_RED_RGTC1_EXT;if(n===36284)return i.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(n===36285)return i.COMPRESSED_RED_GREEN_RGTC2_EXT;if(n===36286)return i.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return n===1020?e.UNSIGNED_INT_24_8:e[n]===void 0?null:e[n]}return{convert:n}}var ec=` void main() { gl_Position = vec4( position, 1.0 ); }`,tc=` uniform sampler2DArray depthColor; uniform float depthWidth; uniform float depthHeight; void main() { vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight ); if ( coord.x >= 1.0 ) { gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r; } else { gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r; } }`,nc=class{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t){if(this.texture===null){let n=new Gr(e.texture);(e.depthNear!==t.depthNear||e.depthFar!==t.depthFar)&&(this.depthNear=e.depthNear,this.depthFar=e.depthFar),this.texture=n}}getMesh(e){if(this.texture!==null&&this.mesh===null){let t=e.cameras[0].viewport,n=new ti({vertexShader:ec,fragmentShader:tc,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new Ar(new qr(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}},rc=class extends $e{constructor(e,t){super();let n=this,r=null,i=1,a=null,o=`local-floor`,s=1,c=null,l=null,d=null,f=null,p=null,m=null,g=typeof XRWebGLBinding<`u`,_=new nc,v={},y=t.getContextAttributes(),x=null,S=null,C=[],w=[],O=new G,k=null,A=new Oi;A.viewport=new Tt;let ee=new Oi;ee.viewport=new Tt;let te=[A,ee],j=new Ni,ne=null,M=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(e){let t=C[e];return t===void 0&&(t=new sn,C[e]=t),t.getTargetRaySpace()},this.getControllerGrip=function(e){let t=C[e];return t===void 0&&(t=new sn,C[e]=t),t.getGripSpace()},this.getHand=function(e){let t=C[e];return t===void 0&&(t=new sn,C[e]=t),t.getHandSpace()};function N(e){let t=w.indexOf(e.inputSource);if(t===-1)return;let n=C[t];n!==void 0&&(n.update(e.inputSource,e.frame,c||a),n.dispatchEvent({type:e.type,data:e.inputSource}))}function P(){r.removeEventListener(`select`,N),r.removeEventListener(`selectstart`,N),r.removeEventListener(`selectend`,N),r.removeEventListener(`squeeze`,N),r.removeEventListener(`squeezestart`,N),r.removeEventListener(`squeezeend`,N),r.removeEventListener(`end`,P),r.removeEventListener(`inputsourceschange`,re);for(let e=0;e=0&&(w[r]=null,C[r].disconnect(n))}for(let t=0;t=w.length){w.push(n),r=e;break}else if(w[e]===null){w[e]=n,r=e;break}if(r===-1)break}let i=C[r];i&&i.connect(n)}}let F=new K,ie=new K;function ae(e,t,n){F.setFromMatrixPosition(t.matrixWorld),ie.setFromMatrixPosition(n.matrixWorld);let r=F.distanceTo(ie),i=t.projectionMatrix.elements,a=n.projectionMatrix.elements,o=i[14]/(i[10]-1),s=i[14]/(i[10]+1),c=(i[9]+1)/i[5],l=(i[9]-1)/i[5],u=(i[8]-1)/i[0],d=(a[8]+1)/a[0],f=o*u,p=o*d,m=r/(-u+d),h=m*-u;if(t.matrixWorld.decompose(e.position,e.quaternion,e.scale),e.translateX(h),e.translateZ(m),e.matrixWorld.compose(e.position,e.quaternion,e.scale),e.matrixWorldInverse.copy(e.matrixWorld).invert(),i[10]===-1)e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse);else{let t=o+m,n=s+m,i=f-h,a=p+(r-h),u=c*s/n*t,d=l*s/n*t;e.projectionMatrix.makePerspective(i,a,u,d,t,n),e.projectionMatrixInverse.copy(e.projectionMatrix).invert()}}function oe(e,t){t===null?e.matrixWorld.copy(e.matrix):e.matrixWorld.multiplyMatrices(t.matrixWorld,e.matrix),e.matrixWorldInverse.copy(e.matrixWorld).invert()}this.updateCamera=function(e){if(r===null)return;let t=e.near,n=e.far;_.texture!==null&&(_.depthNear>0&&(t=_.depthNear),_.depthFar>0&&(n=_.depthFar)),j.near=ee.near=A.near=t,j.far=ee.far=A.far=n,(ne!==j.near||M!==j.far)&&(r.updateRenderState({depthNear:j.near,depthFar:j.far}),ne=j.near,M=j.far),j.layers.mask=e.layers.mask|6,A.layers.mask=j.layers.mask&-5,ee.layers.mask=j.layers.mask&-3;let i=e.parent,a=j.cameras;oe(j,i);for(let e=0;e0&&(e.alphaTest.value=r.alphaTest);let i=t.get(r),a=i.envMap,o=i.envMapRotation;a&&(e.envMap.value=a,ic.copy(o),ic.x*=-1,ic.y*=-1,ic.z*=-1,a.isCubeTexture&&a.isRenderTargetTexture===!1&&(ic.y*=-1,ic.z*=-1),e.envMapRotation.value.setFromMatrix4(ac.makeRotationFromEuler(ic)),e.flipEnvMap.value=a.isCubeTexture&&a.isRenderTargetTexture===!1?-1:1,e.reflectivity.value=r.reflectivity,e.ior.value=r.ior,e.refractionRatio.value=r.refractionRatio),r.lightMap&&(e.lightMap.value=r.lightMap,e.lightMapIntensity.value=r.lightMapIntensity,n(r.lightMap,e.lightMapTransform)),r.aoMap&&(e.aoMap.value=r.aoMap,e.aoMapIntensity.value=r.aoMapIntensity,n(r.aoMap,e.aoMapTransform))}function o(e,t){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,t.map&&(e.map.value=t.map,n(t.map,e.mapTransform))}function s(e,t){e.dashSize.value=t.dashSize,e.totalSize.value=t.dashSize+t.gapSize,e.scale.value=t.scale}function c(e,t,r,i){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.size.value=t.size*r,e.scale.value=i*.5,t.map&&(e.map.value=t.map,n(t.map,e.uvTransform)),t.alphaMap&&(e.alphaMap.value=t.alphaMap,n(t.alphaMap,e.alphaMapTransform)),t.alphaTest>0&&(e.alphaTest.value=t.alphaTest)}function l(e,t){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.rotation.value=t.rotation,t.map&&(e.map.value=t.map,n(t.map,e.mapTransform)),t.alphaMap&&(e.alphaMap.value=t.alphaMap,n(t.alphaMap,e.alphaMapTransform)),t.alphaTest>0&&(e.alphaTest.value=t.alphaTest)}function u(e,t){e.specular.value.copy(t.specular),e.shininess.value=Math.max(t.shininess,1e-4)}function d(e,t){t.gradientMap&&(e.gradientMap.value=t.gradientMap)}function f(e,t){e.metalness.value=t.metalness,t.metalnessMap&&(e.metalnessMap.value=t.metalnessMap,n(t.metalnessMap,e.metalnessMapTransform)),e.roughness.value=t.roughness,t.roughnessMap&&(e.roughnessMap.value=t.roughnessMap,n(t.roughnessMap,e.roughnessMapTransform)),t.envMap&&(e.envMapIntensity.value=t.envMapIntensity)}function p(e,t,r){e.ior.value=t.ior,t.sheen>0&&(e.sheenColor.value.copy(t.sheenColor).multiplyScalar(t.sheen),e.sheenRoughness.value=t.sheenRoughness,t.sheenColorMap&&(e.sheenColorMap.value=t.sheenColorMap,n(t.sheenColorMap,e.sheenColorMapTransform)),t.sheenRoughnessMap&&(e.sheenRoughnessMap.value=t.sheenRoughnessMap,n(t.sheenRoughnessMap,e.sheenRoughnessMapTransform))),t.clearcoat>0&&(e.clearcoat.value=t.clearcoat,e.clearcoatRoughness.value=t.clearcoatRoughness,t.clearcoatMap&&(e.clearcoatMap.value=t.clearcoatMap,n(t.clearcoatMap,e.clearcoatMapTransform)),t.clearcoatRoughnessMap&&(e.clearcoatRoughnessMap.value=t.clearcoatRoughnessMap,n(t.clearcoatRoughnessMap,e.clearcoatRoughnessMapTransform)),t.clearcoatNormalMap&&(e.clearcoatNormalMap.value=t.clearcoatNormalMap,n(t.clearcoatNormalMap,e.clearcoatNormalMapTransform),e.clearcoatNormalScale.value.copy(t.clearcoatNormalScale),t.side===1&&e.clearcoatNormalScale.value.negate())),t.dispersion>0&&(e.dispersion.value=t.dispersion),t.iridescence>0&&(e.iridescence.value=t.iridescence,e.iridescenceIOR.value=t.iridescenceIOR,e.iridescenceThicknessMinimum.value=t.iridescenceThicknessRange[0],e.iridescenceThicknessMaximum.value=t.iridescenceThicknessRange[1],t.iridescenceMap&&(e.iridescenceMap.value=t.iridescenceMap,n(t.iridescenceMap,e.iridescenceMapTransform)),t.iridescenceThicknessMap&&(e.iridescenceThicknessMap.value=t.iridescenceThicknessMap,n(t.iridescenceThicknessMap,e.iridescenceThicknessMapTransform))),t.transmission>0&&(e.transmission.value=t.transmission,e.transmissionSamplerMap.value=r.texture,e.transmissionSamplerSize.value.set(r.width,r.height),t.transmissionMap&&(e.transmissionMap.value=t.transmissionMap,n(t.transmissionMap,e.transmissionMapTransform)),e.thickness.value=t.thickness,t.thicknessMap&&(e.thicknessMap.value=t.thicknessMap,n(t.thicknessMap,e.thicknessMapTransform)),e.attenuationDistance.value=t.attenuationDistance,e.attenuationColor.value.copy(t.attenuationColor)),t.anisotropy>0&&(e.anisotropyVector.value.set(t.anisotropy*Math.cos(t.anisotropyRotation),t.anisotropy*Math.sin(t.anisotropyRotation)),t.anisotropyMap&&(e.anisotropyMap.value=t.anisotropyMap,n(t.anisotropyMap,e.anisotropyMapTransform))),e.specularIntensity.value=t.specularIntensity,e.specularColor.value.copy(t.specularColor),t.specularColorMap&&(e.specularColorMap.value=t.specularColorMap,n(t.specularColorMap,e.specularColorMapTransform)),t.specularIntensityMap&&(e.specularIntensityMap.value=t.specularIntensityMap,n(t.specularIntensityMap,e.specularIntensityMapTransform))}function m(e,t){t.matcap&&(e.matcap.value=t.matcap)}function h(e,n){let r=t.get(n).light;e.referencePosition.value.setFromMatrixPosition(r.matrixWorld),e.nearDistance.value=r.shadow.camera.near,e.farDistance.value=r.shadow.camera.far}return{refreshFogUniforms:r,refreshMaterialUniforms:i}}function sc(e,t,n,r){let i={},a={},o=[],s=e.getParameter(e.MAX_UNIFORM_BUFFER_BINDINGS);function c(e,t){let n=t.program;r.uniformBlockBinding(e,n)}function l(e,n){let o=i[e.id];o===void 0&&(m(e),o=u(e),i[e.id]=o,e.addEventListener(`dispose`,g));let s=n.program;r.updateUBOMapping(e,s);let c=t.render.frame;a[e.id]!==c&&(f(e),a[e.id]=c)}function u(t){let n=d();t.__bindingPointIndex=n;let r=e.createBuffer(),i=t.__size,a=t.usage;return e.bindBuffer(e.UNIFORM_BUFFER,r),e.bufferData(e.UNIFORM_BUFFER,i,a),e.bindBuffer(e.UNIFORM_BUFFER,null),e.bindBufferBase(e.UNIFORM_BUFFER,n,r),r}function d(){for(let e=0;e0&&(n+=16-r),e.__size=n,e.__cache={},this}function h(e){let t={boundary:0,storage:0};return typeof e==`number`||typeof e==`boolean`?(t.boundary=4,t.storage=4):e.isVector2?(t.boundary=8,t.storage=8):e.isVector3||e.isColor?(t.boundary=16,t.storage=12):e.isVector4?(t.boundary=16,t.storage=16):e.isMatrix3?(t.boundary=48,t.storage=48):e.isMatrix4?(t.boundary=64,t.storage=64):e.isTexture?H(`WebGLRenderer: Texture samplers can not be part of an uniforms group.`):H(`WebGLRenderer: Unsupported uniform value type.`,e),t}function g(t){let n=t.target;n.removeEventListener(`dispose`,g);let r=o.indexOf(n.__bindingPointIndex);o.splice(r,1),e.deleteBuffer(i[n.id]),delete i[n.id],delete a[n.id]}function _(){for(let t in i)e.deleteBuffer(i[t]);o=[],i={},a={}}return{bind:c,update:l,dispose:_}}var cc=new Uint16Array([12469,15057,12620,14925,13266,14620,13807,14376,14323,13990,14545,13625,14713,13328,14840,12882,14931,12528,14996,12233,15039,11829,15066,11525,15080,11295,15085,10976,15082,10705,15073,10495,13880,14564,13898,14542,13977,14430,14158,14124,14393,13732,14556,13410,14702,12996,14814,12596,14891,12291,14937,11834,14957,11489,14958,11194,14943,10803,14921,10506,14893,10278,14858,9960,14484,14039,14487,14025,14499,13941,14524,13740,14574,13468,14654,13106,14743,12678,14818,12344,14867,11893,14889,11509,14893,11180,14881,10751,14852,10428,14812,10128,14765,9754,14712,9466,14764,13480,14764,13475,14766,13440,14766,13347,14769,13070,14786,12713,14816,12387,14844,11957,14860,11549,14868,11215,14855,10751,14825,10403,14782,10044,14729,9651,14666,9352,14599,9029,14967,12835,14966,12831,14963,12804,14954,12723,14936,12564,14917,12347,14900,11958,14886,11569,14878,11247,14859,10765,14828,10401,14784,10011,14727,9600,14660,9289,14586,8893,14508,8533,15111,12234,15110,12234,15104,12216,15092,12156,15067,12010,15028,11776,14981,11500,14942,11205,14902,10752,14861,10393,14812,9991,14752,9570,14682,9252,14603,8808,14519,8445,14431,8145,15209,11449,15208,11451,15202,11451,15190,11438,15163,11384,15117,11274,15055,10979,14994,10648,14932,10343,14871,9936,14803,9532,14729,9218,14645,8742,14556,8381,14461,8020,14365,7603,15273,10603,15272,10607,15267,10619,15256,10631,15231,10614,15182,10535,15118,10389,15042,10167,14963,9787,14883,9447,14800,9115,14710,8665,14615,8318,14514,7911,14411,7507,14279,7198,15314,9675,15313,9683,15309,9712,15298,9759,15277,9797,15229,9773,15166,9668,15084,9487,14995,9274,14898,8910,14800,8539,14697,8234,14590,7790,14479,7409,14367,7067,14178,6621,15337,8619,15337,8631,15333,8677,15325,8769,15305,8871,15264,8940,15202,8909,15119,8775,15022,8565,14916,8328,14804,8009,14688,7614,14569,7287,14448,6888,14321,6483,14088,6171,15350,7402,15350,7419,15347,7480,15340,7613,15322,7804,15287,7973,15229,8057,15148,8012,15046,7846,14933,7611,14810,7357,14682,7069,14552,6656,14421,6316,14251,5948,14007,5528,15356,5942,15356,5977,15353,6119,15348,6294,15332,6551,15302,6824,15249,7044,15171,7122,15070,7050,14949,6861,14818,6611,14679,6349,14538,6067,14398,5651,14189,5311,13935,4958,15359,4123,15359,4153,15356,4296,15353,4646,15338,5160,15311,5508,15263,5829,15188,6042,15088,6094,14966,6001,14826,5796,14678,5543,14527,5287,14377,4985,14133,4586,13869,4257,15360,1563,15360,1642,15358,2076,15354,2636,15341,3350,15317,4019,15273,4429,15203,4732,15105,4911,14981,4932,14836,4818,14679,4621,14517,4386,14359,4156,14083,3795,13808,3437,15360,122,15360,137,15358,285,15355,636,15344,1274,15322,2177,15281,2765,15215,3223,15120,3451,14995,3569,14846,3567,14681,3466,14511,3305,14344,3121,14037,2800,13753,2467,15360,0,15360,1,15359,21,15355,89,15346,253,15325,479,15287,796,15225,1148,15133,1492,15008,1749,14856,1882,14685,1886,14506,1783,14324,1608,13996,1398,13702,1183]),lc=null;function uc(){return lc===null&&(lc=new Nr(cc,16,16,A,_),lc.name=`DFG_LUT`,lc.minFilter=s,lc.magFilter=s,lc.wrapS=n,lc.wrapT=n,lc.generateMipmaps=!1,lc.needsUpdate=!0),lc}var dc=class{constructor(e={}){let{canvas:t=Ge(),context:n=null,depth:r=!0,stencil:i=!1,alpha:a=!1,antialias:o=!1,premultipliedAlpha:s=!0,preserveDrawingBuffer:c=!1,powerPreference:d=`default`,failIfMajorPerformanceCaveat:f=!1,reversedDepthBuffer:m=!1,outputBufferType:g=u}=e;this.isWebGLRenderer=!0;let x;if(n!==null){if(typeof WebGLRenderingContext<`u`&&n instanceof WebGLRenderingContext)throw Error(`THREE.WebGLRenderer: WebGL 1 is not supported since r163.`);x=n.getContextAttributes().alpha}else x=a;let S=g,C=new Set([te,ee,k]),w=new Set([u,h,p,b,v,y]),T=new Uint32Array(4),E=new Int32Array(4),D=null,O=null,A=[],j=[],ne=null;this.domElement=t,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=0,this.toneMappingExposure=1,this.transmissionResolutionScale=1;let M=this,N=!1;this._outputColorSpace=Fe;let P=0,re=0,F=null,ie=-1,ae=null,oe=new Tt,se=new Tt,ce=null,le=new Y(0),ue=0,de=t.width,I=t.height,L=1,fe=null,pe=null,me=new Tt(0,0,de,I),he=new Tt(0,0,de,I),ge=!1,_e=new Vr,ve=!1,ye=!1,be=new At,xe=new K,Se=new Tt,Ce={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0},we=!1;function Te(){return F===null?L:1}let R=n;function Ee(e,n){return t.getContext(e,n)}try{let e={alpha:!0,depth:r,stencil:i,antialias:o,premultipliedAlpha:s,preserveDrawingBuffer:c,powerPreference:d,failIfMajorPerformanceCaveat:f};if(`setAttribute`in t&&t.setAttribute(`data-engine`,`three.js r183`),t.addEventListener(`webglcontextlost`,nt,!1),t.addEventListener(`webglcontextrestored`,rt,!1),t.addEventListener(`webglcontextcreationerror`,W,!1),R===null){let t=`webgl2`;if(R=Ee(t,e),R===null)throw Ee(t)?Error(`Error creating WebGL context with your selected attributes.`):Error(`Error creating WebGL context.`)}}catch(e){throw U(`WebGLRenderer: `+e.message),e}let De,Oe,z,ke,B,V,Ae,je,Me,Ne,Pe,Le,Re,ze,Be,He,Ue,We,Ke,qe,Ye,Qe,$e;function et(){De=new ka(R),De.init(),Ye=new $s(R,De),Oe=new aa(R,De,e,Ye),z=new Zs(R,De),Oe.reversedDepthBuffer&&m&&z.buffers.depth.setReversed(!0),ke=new Ma(R),B=new js,V=new Qs(R,De,z,B,Oe,Ye,ke),Ae=new Oa(M),je=new Zi(R),Qe=new ra(R,je),Me=new Aa(R,je,ke,Qe),Ne=new Pa(R,Me,je,Qe,ke),We=new Na(R,Oe,V),Be=new oa(B),Pe=new As(M,Ae,De,Oe,Qe,Be),Le=new oc(M,B),Re=new Fs,ze=new Hs(De),Ue=new na(M,Ae,z,Ne,x,s),He=new Xs(M,Ne,Oe),$e=new sc(R,ke,Oe,z),Ke=new ia(R,De,ke),qe=new ja(R,De,ke),ke.programs=Pe.programs,M.capabilities=Oe,M.extensions=De,M.properties=B,M.renderLists=Re,M.shadowMap=He,M.state=z,M.info=ke}et(),S!==1009&&(ne=new Ia(S,t.width,t.height,r,i));let tt=new rc(M,R);this.xr=tt,this.getContext=function(){return R},this.getContextAttributes=function(){return R.getContextAttributes()},this.forceContextLoss=function(){let e=De.get(`WEBGL_lose_context`);e&&e.loseContext()},this.forceContextRestore=function(){let e=De.get(`WEBGL_lose_context`);e&&e.restoreContext()},this.getPixelRatio=function(){return L},this.setPixelRatio=function(e){e!==void 0&&(L=e,this.setSize(de,I,!1))},this.getSize=function(e){return e.set(de,I)},this.setSize=function(e,n,r=!0){if(tt.isPresenting){H(`WebGLRenderer: Can't change size while VR device is presenting.`);return}de=e,I=n,t.width=Math.floor(e*L),t.height=Math.floor(n*L),r===!0&&(t.style.width=e+`px`,t.style.height=n+`px`),ne!==null&&ne.setSize(t.width,t.height),this.setViewport(0,0,e,n)},this.getDrawingBufferSize=function(e){return e.set(de*L,I*L).floor()},this.setDrawingBufferSize=function(e,n,r){de=e,I=n,L=r,t.width=Math.floor(e*r),t.height=Math.floor(n*r),this.setViewport(0,0,e,n)},this.setEffects=function(e){if(S===1009){console.error(`THREE.WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.`);return}if(e){for(let t=0;t{function n(){if(r.forEach(function(e){B.get(e).currentProgram.isReady()&&r.delete(e)}),r.size===0){t(e);return}setTimeout(n,10)}De.get(`KHR_parallel_shader_compile`)===null?setTimeout(n,10):n()})};let G=null;function ct(e){G&&G(e)}function lt(){q.stop()}function ut(){q.start()}let q=new Xi;q.setAnimationLoop(ct),typeof self<`u`&&q.setContext(self),this.setAnimationLoop=function(e){G=e,tt.setAnimationLoop(e),e===null?q.stop():q.start()},tt.addEventListener(`sessionstart`,lt),tt.addEventListener(`sessionend`,ut),this.render=function(e,t){if(t!==void 0&&t.isCamera!==!0){U(`WebGLRenderer.render: camera is not an instance of THREE.Camera.`);return}if(N===!0)return;let n=tt.enabled===!0&&tt.isPresenting===!0,r=ne!==null&&(F===null||n)&&ne.begin(M,F);if(e.matrixWorldAutoUpdate===!0&&e.updateMatrixWorld(),t.parent===null&&t.matrixWorldAutoUpdate===!0&&t.updateMatrixWorld(),tt.enabled===!0&&tt.isPresenting===!0&&(ne===null||ne.isCompositing()===!1)&&(tt.cameraAutoUpdate===!0&&tt.updateCamera(t),t=tt.getCamera()),e.isScene===!0&&e.onBeforeRender(M,e,t,F),O=ze.get(e,j.length),O.init(t),j.push(O),be.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),_e.setFromProjectionMatrix(be,Ve,t.reversedDepth),ye=this.localClippingEnabled,ve=Be.init(this.clippingPlanes,ye),D=Re.get(e,A.length),D.init(),A.push(D),tt.enabled===!0&&tt.isPresenting===!0){let e=M.xr.getDepthSensingMesh();e!==null&&dt(e,t,-1/0,M.sortObjects)}dt(e,t,0,M.sortObjects),D.finish(),M.sortObjects===!0&&D.sort(fe,pe),we=tt.enabled===!1||tt.isPresenting===!1||tt.hasDepthSensing()===!1,we&&Ue.addToRenderList(D,e),this.info.render.frame++,ve===!0&&Be.beginShadows();let i=O.state.shadowsArray;if(He.render(i,e,t),ve===!0&&Be.endShadows(),this.info.autoReset===!0&&this.info.reset(),(r&&ne.hasRenderPass())===!1){let n=D.opaque,r=D.transmissive;if(O.setupLights(),t.isArrayCamera){let i=t.cameras;if(r.length>0)for(let t=0,a=i.length;t0&&pt(n,r,e,t),we&&Ue.render(e),ft(D,e,t)}F!==null&&re===0&&(V.updateMultisampleRenderTarget(F),V.updateRenderTargetMipmap(F)),r&&ne.end(M),e.isScene===!0&&e.onAfterRender(M,e,t),Qe.resetDefaultState(),ie=-1,ae=null,j.pop(),j.length>0?(O=j[j.length-1],ve===!0&&Be.setGlobalState(M.clippingPlanes,O.state.camera)):O=null,A.pop(),D=A.length>0?A[A.length-1]:null};function dt(e,t,n,r){if(e.visible===!1)return;if(e.layers.test(t.layers)){if(e.isGroup)n=e.renderOrder;else if(e.isLOD)e.autoUpdate===!0&&e.update(t);else if(e.isLight)O.pushLight(e),e.castShadow&&O.pushShadow(e);else if(e.isSprite){if(!e.frustumCulled||_e.intersectsSprite(e)){r&&Se.setFromMatrixPosition(e.matrixWorld).applyMatrix4(be);let t=Ne.update(e),i=e.material;i.visible&&D.push(e,t,i,n,Se.z,null)}}else if((e.isMesh||e.isLine||e.isPoints)&&(!e.frustumCulled||_e.intersectsObject(e))){let t=Ne.update(e),i=e.material;if(r&&(e.boundingSphere===void 0?(t.boundingSphere===null&&t.computeBoundingSphere(),Se.copy(t.boundingSphere.center)):(e.boundingSphere===null&&e.computeBoundingSphere(),Se.copy(e.boundingSphere.center)),Se.applyMatrix4(e.matrixWorld).applyMatrix4(be)),Array.isArray(i)){let r=t.groups;for(let a=0,o=r.length;a0&&mt(i,t,n),a.length>0&&mt(a,t,n),o.length>0&&mt(o,t,n),z.buffers.depth.setTest(!0),z.buffers.depth.setMask(!0),z.buffers.color.setMask(!0),z.setPolygonOffset(!1)}function pt(e,t,n,r){if((n.isScene===!0?n.overrideMaterial:null)!==null)return;if(O.state.transmissionRenderTarget[r.id]===void 0){let e=De.has(`EXT_color_buffer_half_float`)||De.has(`EXT_color_buffer_float`);O.state.transmissionRenderTarget[r.id]=new Dt(1,1,{generateMipmaps:!0,type:e?_:u,minFilter:l,samples:Math.max(4,Oe.samples),stencilBuffer:i,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:J.workingColorSpace})}let a=O.state.transmissionRenderTarget[r.id],o=r.viewport||oe;a.setSize(o.z*M.transmissionResolutionScale,o.w*M.transmissionResolutionScale);let s=M.getRenderTarget(),c=M.getActiveCubeFace(),d=M.getActiveMipmapLevel();M.setRenderTarget(a),M.getClearColor(le),ue=M.getClearAlpha(),ue<1&&M.setClearColor(16777215,.5),M.clear(),we&&Ue.render(n);let f=M.toneMapping;M.toneMapping=0;let p=r.viewport;if(r.viewport!==void 0&&(r.viewport=void 0),O.setupLightsView(r),ve===!0&&Be.setGlobalState(M.clippingPlanes,r),mt(e,n,r),V.updateMultisampleRenderTarget(a),V.updateRenderTargetMipmap(a),De.has(`WEBGL_multisampled_render_to_texture`)===!1){let e=!1;for(let i=0,a=t.length;i0),f=!!n.morphAttributes.position,p=!!n.morphAttributes.normal,m=!!n.morphAttributes.color,h=0;r.toneMapped&&(F===null||F.isXRRenderTarget===!0)&&(h=M.toneMapping);let g=n.morphAttributes.position||n.morphAttributes.normal||n.morphAttributes.color,_=g===void 0?0:g.length,v=B.get(r),y=O.state.lights;if(ve===!0&&(ye===!0||e!==ae)){let t=e===ae&&r.id===ie;Be.setState(r,e,t)}let b=!1;r.version===v.__version?v.needsLights&&v.lightsStateVersion!==y.state.version?b=!0:v.outputColorSpace===s?i.isBatchedMesh&&v.batching===!1||!i.isBatchedMesh&&v.batching===!0||i.isBatchedMesh&&v.batchingColor===!0&&i.colorTexture===null||i.isBatchedMesh&&v.batchingColor===!1&&i.colorTexture!==null||i.isInstancedMesh&&v.instancing===!1||!i.isInstancedMesh&&v.instancing===!0||i.isSkinnedMesh&&v.skinning===!1||!i.isSkinnedMesh&&v.skinning===!0||i.isInstancedMesh&&v.instancingColor===!0&&i.instanceColor===null||i.isInstancedMesh&&v.instancingColor===!1&&i.instanceColor!==null||i.isInstancedMesh&&v.instancingMorph===!0&&i.morphTexture===null||i.isInstancedMesh&&v.instancingMorph===!1&&i.morphTexture!==null?b=!0:v.envMap===l?r.fog===!0&&v.fog!==a||v.numClippingPlanes!==void 0&&(v.numClippingPlanes!==Be.numPlanes||v.numIntersection!==Be.numIntersection)?b=!0:v.vertexAlphas===u&&v.vertexTangents===d&&v.morphTargets===f&&v.morphNormals===p&&v.morphColors===m&&v.toneMapping===h?v.morphTargetsCount!==_&&(b=!0):b=!0:b=!0:b=!0:(b=!0,v.__version=r.version);let x=v.currentProgram;b===!0&&(x=gt(r,t,i));let S=!1,C=!1,w=!1,T=x.getUniforms(),E=v.uniforms;if(z.useProgram(x.program)&&(S=!0,C=!0,w=!0),r.id!==ie&&(ie=r.id,C=!0),S||ae!==e){z.buffers.depth.getReversed()&&e.reversedDepth!==!0&&(e._reversedDepth=!0,e.updateProjectionMatrix()),T.setValue(R,`projectionMatrix`,e.projectionMatrix),T.setValue(R,`viewMatrix`,e.matrixWorldInverse);let t=T.map.cameraPosition;t!==void 0&&t.setValue(R,xe.setFromMatrixPosition(e.matrixWorld)),Oe.logarithmicDepthBuffer&&T.setValue(R,`logDepthBufFC`,2/(Math.log(e.far+1)/Math.LN2)),(r.isMeshPhongMaterial||r.isMeshToonMaterial||r.isMeshLambertMaterial||r.isMeshBasicMaterial||r.isMeshStandardMaterial||r.isShaderMaterial)&&T.setValue(R,`isOrthographic`,e.isOrthographicCamera===!0),ae!==e&&(ae=e,C=!0,w=!0)}if(v.needsLights&&(y.state.directionalShadowMap.length>0&&T.setValue(R,`directionalShadowMap`,y.state.directionalShadowMap,V),y.state.spotShadowMap.length>0&&T.setValue(R,`spotShadowMap`,y.state.spotShadowMap,V),y.state.pointShadowMap.length>0&&T.setValue(R,`pointShadowMap`,y.state.pointShadowMap,V)),i.isSkinnedMesh){T.setOptional(R,i,`bindMatrix`),T.setOptional(R,i,`bindMatrixInverse`);let e=i.skeleton;e&&(e.boneTexture===null&&e.computeBoneTexture(),T.setValue(R,`boneTexture`,e.boneTexture,V))}i.isBatchedMesh&&(T.setOptional(R,i,`batchingTexture`),T.setValue(R,`batchingTexture`,i._matricesTexture,V),T.setOptional(R,i,`batchingIdTexture`),T.setValue(R,`batchingIdTexture`,i._indirectTexture,V),T.setOptional(R,i,`batchingColorTexture`),i._colorsTexture!==null&&T.setValue(R,`batchingColorTexture`,i._colorsTexture,V));let D=n.morphAttributes;if((D.position!==void 0||D.normal!==void 0||D.color!==void 0)&&We.update(i,n,x),(C||v.receiveShadow!==i.receiveShadow)&&(v.receiveShadow=i.receiveShadow,T.setValue(R,`receiveShadow`,i.receiveShadow)),(r.isMeshStandardMaterial||r.isMeshLambertMaterial||r.isMeshPhongMaterial)&&r.envMap===null&&t.environment!==null&&(E.envMapIntensity.value=t.environmentIntensity),E.dfgLUT!==void 0&&(E.dfgLUT.value=uc()),C&&(T.setValue(R,`toneMappingExposure`,M.toneMappingExposure),v.needsLights&&bt(E,w),a&&r.fog===!0&&Le.refreshFogUniforms(E,a),Le.refreshMaterialUniforms(E,r,L,I,O.state.transmissionRenderTarget[e.id]),Wo.upload(R,_t(v),E,V)),r.isShaderMaterial&&r.uniformsNeedUpdate===!0&&(Wo.upload(R,_t(v),E,V),r.uniformsNeedUpdate=!1),r.isSpriteMaterial&&T.setValue(R,`center`,i.center),T.setValue(R,`modelViewMatrix`,i.modelViewMatrix),T.setValue(R,`normalMatrix`,i.normalMatrix),T.setValue(R,`modelMatrix`,i.matrixWorld),r.isShaderMaterial||r.isRawShaderMaterial){let e=r.uniformsGroups;for(let t=0,n=e.length;t0&&V.useMultisampledRTT(e)===!1?B.get(e).__webglMultisampledFramebuffer:Array.isArray(c)?c[n]:c,oe.copy(e.viewport),se.copy(e.scissor),ce=e.scissorTest}else oe.copy(me).multiplyScalar(L).floor(),se.copy(he).multiplyScalar(L).floor(),ce=ge;if(n!==0&&(r=St),z.bindFramebuffer(R.FRAMEBUFFER,r)&&z.drawBuffers(e,r),z.viewport(oe),z.scissor(se),z.setScissorTest(ce),i){let r=B.get(e.texture);R.framebufferTexture2D(R.FRAMEBUFFER,R.COLOR_ATTACHMENT0,R.TEXTURE_CUBE_MAP_POSITIVE_X+t,r.__webglTexture,n)}else if(a){let r=t;for(let t=0;t1&&R.readBuffer(R.COLOR_ATTACHMENT0+s),!Oe.textureFormatReadable(c)){U(`WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.`);return}if(!Oe.textureTypeReadable(l)){U(`WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.`);return}t>=0&&t<=e.width-r&&n>=0&&n<=e.height-i&&R.readPixels(t,n,r,i,Ye.convert(c),Ye.convert(l),a)}finally{let e=F===null?null:B.get(F).__webglFramebuffer;z.bindFramebuffer(R.FRAMEBUFFER,e)}}},this.readRenderTargetPixelsAsync=async function(e,t,n,r,i,a,o,s=0){if(!(e&&e.isWebGLRenderTarget))throw Error(`THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.`);let c=B.get(e).__webglFramebuffer;if(e.isWebGLCubeRenderTarget&&o!==void 0&&(c=c[o]),c)if(t>=0&&t<=e.width-r&&n>=0&&n<=e.height-i){z.bindFramebuffer(R.FRAMEBUFFER,c);let o=e.textures[s],l=o.format,u=o.type;if(e.textures.length>1&&R.readBuffer(R.COLOR_ATTACHMENT0+s),!Oe.textureFormatReadable(l))throw Error(`THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.`);if(!Oe.textureTypeReadable(u))throw Error(`THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.`);let d=R.createBuffer();R.bindBuffer(R.PIXEL_PACK_BUFFER,d),R.bufferData(R.PIXEL_PACK_BUFFER,a.byteLength,R.STREAM_READ),R.readPixels(t,n,r,i,Ye.convert(l),Ye.convert(u),0);let f=F===null?null:B.get(F).__webglFramebuffer;z.bindFramebuffer(R.FRAMEBUFFER,f);let p=R.fenceSync(R.SYNC_GPU_COMMANDS_COMPLETE,0);return R.flush(),await Ze(R,p,4),R.bindBuffer(R.PIXEL_PACK_BUFFER,d),R.getBufferSubData(R.PIXEL_PACK_BUFFER,0,a),R.deleteBuffer(d),R.deleteSync(p),a}else throw Error(`THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.`)},this.copyFramebufferToTexture=function(e,t=null,n=0){let r=2**-n,i=Math.floor(e.image.width*r),a=Math.floor(e.image.height*r),o=t===null?0:t.x,s=t===null?0:t.y;V.setTexture2D(e,0),R.copyTexSubImage2D(R.TEXTURE_2D,n,0,0,o,s,i,a),z.unbindTexture()};let Ct=R.createFramebuffer(),wt=R.createFramebuffer();this.copyTextureToTexture=function(e,t,n=null,r=null,i=0,a=0){let o,s,c,l,u,d,f,p,m,h=e.isCompressedTexture?e.mipmaps[a]:e.image;if(n!==null)o=n.max.x-n.min.x,s=n.max.y-n.min.y,c=n.isBox3?n.max.z-n.min.z:1,l=n.min.x,u=n.min.y,d=n.isBox3?n.min.z:0;else{let t=2**-i;o=Math.floor(h.width*t),s=Math.floor(h.height*t),c=e.isDataArrayTexture?h.depth:e.isData3DTexture?Math.floor(h.depth*t):1,l=0,u=0,d=0}r===null?(f=0,p=0,m=0):(f=r.x,p=r.y,m=r.z);let g=Ye.convert(t.format),_=Ye.convert(t.type),v;t.isData3DTexture?(V.setTexture3D(t,0),v=R.TEXTURE_3D):t.isDataArrayTexture||t.isCompressedArrayTexture?(V.setTexture2DArray(t,0),v=R.TEXTURE_2D_ARRAY):(V.setTexture2D(t,0),v=R.TEXTURE_2D),R.pixelStorei(R.UNPACK_FLIP_Y_WEBGL,t.flipY),R.pixelStorei(R.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),R.pixelStorei(R.UNPACK_ALIGNMENT,t.unpackAlignment);let y=R.getParameter(R.UNPACK_ROW_LENGTH),b=R.getParameter(R.UNPACK_IMAGE_HEIGHT),x=R.getParameter(R.UNPACK_SKIP_PIXELS),S=R.getParameter(R.UNPACK_SKIP_ROWS),C=R.getParameter(R.UNPACK_SKIP_IMAGES);R.pixelStorei(R.UNPACK_ROW_LENGTH,h.width),R.pixelStorei(R.UNPACK_IMAGE_HEIGHT,h.height),R.pixelStorei(R.UNPACK_SKIP_PIXELS,l),R.pixelStorei(R.UNPACK_SKIP_ROWS,u),R.pixelStorei(R.UNPACK_SKIP_IMAGES,d);let w=e.isDataArrayTexture||e.isData3DTexture,T=t.isDataArrayTexture||t.isData3DTexture;if(e.isDepthTexture){let n=B.get(e),r=B.get(t),h=B.get(n.__renderTarget),g=B.get(r.__renderTarget);z.bindFramebuffer(R.READ_FRAMEBUFFER,h.__webglFramebuffer),z.bindFramebuffer(R.DRAW_FRAMEBUFFER,g.__webglFramebuffer);for(let n=0;n{let i=e[r],a=t[r];return hc(i)&&hc(a)?Object.assign(Object.assign({},n),{[r]:_c(i,a)}):Object.assign(Object.assign({},n),{[r]:r in t?a:i})},{})}function vc(e){return mc(e)?`target`in e:!1}var yc={alreadydisposed:()=>`View has been already disposed`,invalidparams:e=>`Invalid parameters for '${e.name}'`,nomatchingcontroller:e=>`No matching controller for '${e.key}'`,nomatchingview:e=>`No matching view for '${JSON.stringify(e.params)}'`,notbindable:()=>`Value is not bindable`,notcompatible:e=>`Not compatible with plugin '${e.id}'`,propertynotfound:e=>`Property '${e.name}' not found`,shouldneverhappen:()=>`This error should never happen`},bc=class e{static alreadyDisposed(){return new e({type:`alreadydisposed`})}static notBindable(){return new e({type:`notbindable`})}static notCompatible(t,n){return new e({type:`notcompatible`,context:{id:`${t}.${n}`}})}static propertyNotFound(t){return new e({type:`propertynotfound`,context:{name:t}})}static shouldNeverHappen(){return new e({type:`shouldneverhappen`})}constructor(e){this.message=yc[e.type](fc(e.context))??`Unexpected error`,this.name=this.constructor.name,this.stack=Error(this.message).stack,this.type=e.type}toString(){return this.message}},xc=class e{constructor(e,t){this.obj_=e,this.key=t}static isBindable(e){return!(e===null||typeof e!=`object`&&typeof e!=`function`)}read(){return this.obj_[this.key]}write(e){this.obj_[this.key]=e}writeProperty(t,n){let r=this.read();if(!e.isBindable(r))throw bc.notBindable();if(!(t in r))throw bc.propertyNotFound(t);r[t]=n}},Sc=class{constructor(){this.observers_={}}on(e,t,n){let r=this.observers_[e];return r||=this.observers_[e]=[],r.push({handler:t,key:n?.key??t}),this}off(e,t){let n=this.observers_[e];return n&&(this.observers_[e]=n.filter(e=>e.key!==t)),this}emit(e,t){let n=this.observers_[e];n&&n.forEach(e=>{e.handler(t)})}},Cc=class{constructor(e,t){this.constraint_=t?.constraint,this.equals_=t?.equals??((e,t)=>e===t),this.emitter=new Sc,this.rawValue_=e}get constraint(){return this.constraint_}get rawValue(){return this.rawValue_}set rawValue(e){this.setRawValue(e,{forceEmit:!1,last:!0})}setRawValue(e,t){let n=t??{forceEmit:!1,last:!0},r=this.constraint_?this.constraint_.constrain(e):e,i=this.rawValue_;this.equals_(i,r)&&!n.forceEmit||(this.emitter.emit(`beforechange`,{sender:this}),this.rawValue_=r,this.emitter.emit(`change`,{options:n,previousRawValue:i,rawValue:r,sender:this}))}},wc=class{constructor(e){this.emitter=new Sc,this.value_=e}get rawValue(){return this.value_}set rawValue(e){this.setRawValue(e,{forceEmit:!1,last:!0})}setRawValue(e,t){let n=t??{forceEmit:!1,last:!0},r=this.value_;r===e&&!n.forceEmit||(this.emitter.emit(`beforechange`,{sender:this}),this.value_=e,this.emitter.emit(`change`,{options:n,previousRawValue:r,rawValue:this.value_,sender:this}))}},Tc=class{constructor(e){this.emitter=new Sc,this.onValueBeforeChange_=this.onValueBeforeChange_.bind(this),this.onValueChange_=this.onValueChange_.bind(this),this.value_=e,this.value_.emitter.on(`beforechange`,this.onValueBeforeChange_),this.value_.emitter.on(`change`,this.onValueChange_)}get rawValue(){return this.value_.rawValue}onValueBeforeChange_(e){this.emitter.emit(`beforechange`,Object.assign(Object.assign({},e),{sender:this}))}onValueChange_(e){this.emitter.emit(`change`,Object.assign(Object.assign({},e),{sender:this}))}};function Ec(e,t){let n=t?.constraint,r=t?.equals;return!n&&!r?new wc(e):new Cc(e,t)}function Dc(e){return[new Tc(e),(t,n)=>{e.setRawValue(t,n)}]}var Q=class e{constructor(e){this.emitter=new Sc,this.valMap_=e;for(let e in this.valMap_)this.valMap_[e].emitter.on(`change`,()=>{this.emitter.emit(`change`,{key:e,sender:this})})}static createCore(e){return Object.keys(e).reduce((t,n)=>Object.assign(t,{[n]:Ec(e[n])}),{})}static fromObject(t){return new e(this.createCore(t))}get(e){return this.valMap_[e].rawValue}set(e,t){this.valMap_[e].rawValue=t}value(e){return this.valMap_[e]}},Oc=class{constructor(e){this.values=Q.fromObject({max:e.max,min:e.min})}constrain(e){let t=this.values.get(`max`),n=this.values.get(`min`);return Math.min(Math.max(e,n),t)}},kc=class{constructor(e){this.values=Q.fromObject({max:e.max,min:e.min})}constrain(e){let t=this.values.get(`max`),n=this.values.get(`min`),r=e;return pc(n)||(r=Math.max(r,n)),pc(t)||(r=Math.min(r,t)),r}},Ac=class{constructor(e,t=0){this.step=e,this.origin=t}constrain(e){let t=this.origin%this.step;return t+Math.round((e-t)/this.step)*this.step}},jc=class{constructor(e){this.text=e}evaluate(){return Number(this.text)}toString(){return this.text}},Mc={"**":(e,t)=>e**+t,"*":(e,t)=>e*t,"/":(e,t)=>e/t,"%":(e,t)=>e%t,"+":(e,t)=>e+t,"-":(e,t)=>e-t,"<<":(e,t)=>e<>":(e,t)=>e>>t,">>>":(e,t)=>e>>>t,"&":(e,t)=>e&t,"^":(e,t)=>e^t,"|":(e,t)=>e|t},Nc=class{constructor(e,t,n){this.left=t,this.operator=e,this.right=n}evaluate(){let e=Mc[this.operator];if(!e)throw Error(`unexpected binary operator: '${this.operator}`);return e(this.left.evaluate(),this.right.evaluate())}toString(){return[`b(`,this.left.toString(),this.operator,this.right.toString(),`)`].join(` `)}},Pc={"+":e=>e,"-":e=>-e,"~":e=>~e},Fc=class{constructor(e,t){this.operator=e,this.expression=t}evaluate(){let e=Pc[this.operator];if(!e)throw Error(`unexpected unary operator: '${this.operator}`);return e(this.expression.evaluate())}toString(){return[`u(`,this.operator,this.expression.toString(),`)`].join(` `)}};function Ic(e){return(t,n)=>{for(let r=0;rt.startsWith(e,n))[0];return r?(n+=r.length,n+=Lc(t,n).length,{cursor:n,operator:r}):null}function al(e,t){return(n,r)=>{let i=e(n,r);if(!i)return null;r=i.cursor;let a=i.evaluable;for(;;){let i=il(t,n,r);if(!i)break;r=i.cursor;let o=e(n,r);if(!o)return null;r=o.cursor,a=new Nc(i.operator,a,o.evaluable)}return a?{cursor:r,evaluable:a}:null}}var ol=[[`**`],[`*`,`/`,`%`],[`+`,`-`],[`<<`,`>>>`,`>>`],[`&`],[`^`],[`|`]].reduce((e,t)=>al(e,t),rl);function sl(e,t){return t+=Lc(e,t).length,ol(e,t)}function cl(e){let t=sl(e,0);return!t||t.cursor+Lc(e,t.cursor).length!==e.length?null:t.evaluable}function ll(e){return cl(e)?.evaluate()??null}function ul(e){if(typeof e==`number`)return e;if(typeof e==`string`){let t=ll(e);if(!pc(t))return t}return 0}function dl(e){return String(e)}function fl(e){return t=>t.toFixed(Math.max(Math.min(e,20),0))}function pl(e,t,n,r,i){return r+(e-t)/(n-t)*(i-r)}function ml(e){return String(e.toFixed(10)).split(`.`)[1].replace(/0+$/,``).length}function hl(e,t,n){return Math.min(Math.max(e,t),n)}function gl(e,t){return(e%t+t)%t}function _l(e,t){return pc(e.step)?Math.max(ml(t),2):ml(e.step)}function vl(e){return e.step??1}function yl(e,t){let n=Math.abs(e.step??t);return n===0?.1:10**(Math.floor(Math.log10(n))-1)}function bl(e,t){return pc(e.step)?null:new Ac(e.step,t)}function xl(e){return!pc(e.max)&&!pc(e.min)?new Oc({max:e.max,min:e.min}):!pc(e.max)||!pc(e.min)?new kc({max:e.max,min:e.min}):null}function Sl(e,t){return{formatter:e.format??fl(_l(e,t)),keyScale:e.keyScale??vl(e),pointerScale:e.pointerScale??yl(e,t)}}function Cl(e){return{format:e.optional.function,keyScale:e.optional.number,max:e.optional.number,min:e.optional.number,pointerScale:e.optional.number,step:e.optional.number}}function wl(e){return{constraint:e.constraint,textProps:Q.fromObject(Sl(e.params,e.initialValue))}}var Tl=class{constructor(e){this.controller=e}get element(){return this.controller.view.element}get disabled(){return this.controller.viewProps.get(`disabled`)}set disabled(e){this.controller.viewProps.set(`disabled`,e)}get hidden(){return this.controller.viewProps.get(`hidden`)}set hidden(e){this.controller.viewProps.set(`hidden`,e)}dispose(){this.controller.viewProps.set(`disposed`,!0)}importState(e){return this.controller.importState(e)}exportState(){return this.controller.exportState()}},El=class{constructor(e){this.target=e}},Dl=class extends El{constructor(e,t,n){super(e),this.value=t,this.last=n??!0}},Ol=class extends El{constructor(e,t){super(e),this.expanded=t}},kl=class extends El{constructor(e,t){super(e),this.index=t}},Al=class extends El{constructor(e,t){super(e),this.native=t}},jl=class extends Tl{constructor(e){super(e),this.onValueChange_=this.onValueChange_.bind(this),this.emitter_=new Sc,this.controller.value.emitter.on(`change`,this.onValueChange_)}get label(){return this.controller.labelController.props.get(`label`)}set label(e){this.controller.labelController.props.set(`label`,e)}get key(){return this.controller.value.binding.target.key}get tag(){return this.controller.tag}set tag(e){this.controller.tag=e}on(e,t){let n=t.bind(this);return this.emitter_.on(e,e=>{n(e)},{key:t}),this}off(e,t){return this.emitter_.off(e,t),this}refresh(){this.controller.value.fetch()}onValueChange_(e){let t=this.controller.value;this.emitter_.emit(`change`,new Dl(this,fc(t.binding.target.read()),e.options.last))}},Ml=class{constructor(e,t){this.onValueBeforeChange_=this.onValueBeforeChange_.bind(this),this.onValueChange_=this.onValueChange_.bind(this),this.binding=t,this.value_=e,this.value_.emitter.on(`beforechange`,this.onValueBeforeChange_),this.value_.emitter.on(`change`,this.onValueChange_),this.emitter=new Sc}get rawValue(){return this.value_.rawValue}set rawValue(e){this.value_.rawValue=e}setRawValue(e,t){this.value_.setRawValue(e,t)}fetch(){this.value_.rawValue=this.binding.read()}push(){this.binding.write(this.value_.rawValue)}onValueBeforeChange_(e){this.emitter.emit(`beforechange`,Object.assign(Object.assign({},e),{sender:this}))}onValueChange_(e){this.push(),this.emitter.emit(`change`,Object.assign(Object.assign({},e),{sender:this}))}};function Nl(e){if(!(`binding`in e))return!1;let t=e.binding;return vc(t)&&`read`in t&&`write`in t}function Pl(e,t){return fc(Object.keys(t).reduce((n,r)=>{if(n===void 0)return;let i=t[r],a=i(e[r]);return a.succeeded?Object.assign(Object.assign({},n),{[r]:a.value}):void 0},{}))}function Fl(e,t){return e.reduce((e,n)=>{if(e===void 0)return;let r=t(n);if(!(!r.succeeded||r.value===void 0))return[...e,r.value]},[])}function Il(e){return e===null?!1:typeof e==`object`}function Ll(e){return t=>n=>{if(!t&&n===void 0)return{succeeded:!1,value:void 0};if(t&&n===void 0)return{succeeded:!0,value:void 0};let r=e(n);return r===void 0?{succeeded:!1,value:void 0}:{succeeded:!0,value:r}}}function Rl(e){return{custom:t=>Ll(t)(e),boolean:Ll(e=>typeof e==`boolean`?e:void 0)(e),number:Ll(e=>typeof e==`number`?e:void 0)(e),string:Ll(e=>typeof e==`string`?e:void 0)(e),function:Ll(e=>typeof e==`function`?e:void 0)(e),constant:t=>Ll(e=>e===t?t:void 0)(e),raw:Ll(e=>e)(e),object:t=>Ll(e=>{if(Il(e))return Pl(e,t)})(e),array:t=>Ll(e=>{if(Array.isArray(e))return Fl(e,t)})(e)}}var zl={optional:Rl(!0),required:Rl(!1)};function Bl(e,t){let n=t(zl),r=zl.required.object(n)(e);return r.succeeded?r.value:void 0}function Vl(e,t,n,r){if(t&&!t(e))return!1;let i=Bl(e,n);return i?r(i):!1}function Hl(e,t){return _c(e?.()??{},t)}function Ul(e){return`value`in e}function Wl(e){if(!mc(e)||!(`binding`in e))return!1;let t=e.binding;return vc(t)}var Gl=`http://www.w3.org/2000/svg`;function Kl(e){e.offsetHeight}function ql(e,t){let n=e.style.transition;e.style.transition=`none`,t(),e.style.transition=n}function Jl(e){return e.ontouchstart!==void 0}function Yl(){return globalThis}function Xl(){return fc(Yl()).document}function Zl(e){let t=e.ownerDocument.defaultView;return t&&`document`in t?e.getContext(`2d`,{willReadFrequently:!0}):null}var Ql={check:``,dropdown:``,p2dpad:``};function $l(e,t){let n=e.createElementNS(Gl,`svg`);return n.innerHTML=Ql[t],n}function eu(e,t,n){e.insertBefore(t,e.children[n])}function tu(e){e.parentElement&&e.parentElement.removeChild(e)}function nu(e){for(;e.children.length>0;)e.removeChild(e.children[0])}function ru(e){for(;e.childNodes.length>0;)e.removeChild(e.childNodes[0])}function iu(e){return e.relatedTarget?fc(e.relatedTarget):`explicitOriginalTarget`in e?e.explicitOriginalTarget:null}function au(e,t){e.emitter.on(`change`,e=>{t(e.rawValue)}),t(e.rawValue)}function ou(e,t,n){au(e.value(t),n)}var su=`tp`;function $(e){return(t,n)=>[su,`-`,e,`v`,t?`_${t}`:``,n?`-${n}`:``].join(``)}var cu=$(`lbl`);function lu(e,t){let n=e.createDocumentFragment();return t.split(` `).map(t=>e.createTextNode(t)).forEach((t,r)=>{r>0&&n.appendChild(e.createElement(`br`)),n.appendChild(t)}),n}var uu=class{constructor(e,t){this.element=e.createElement(`div`),this.element.classList.add(cu()),t.viewProps.bindClassModifiers(this.element);let n=e.createElement(`div`);n.classList.add(cu(`l`)),ou(t.props,`label`,t=>{pc(t)?this.element.classList.add(cu(void 0,`nol`)):(this.element.classList.remove(cu(void 0,`nol`)),ru(n),n.appendChild(lu(e,t)))}),this.element.appendChild(n),this.labelElement=n;let r=e.createElement(`div`);r.classList.add(cu(`v`)),this.element.appendChild(r),this.valueElement=r}},du=class{constructor(e,t){this.props=t.props,this.valueController=t.valueController,this.viewProps=t.valueController.viewProps,this.view=new uu(e,{props:t.props,viewProps:this.viewProps}),this.view.valueElement.appendChild(this.valueController.view.element)}importProps(e){return Vl(e,null,e=>({label:e.optional.string}),e=>(this.props.set(`label`,e.label),!0))}exportProps(){return Hl(null,{label:this.props.get(`label`)})}};function fu(){return[`veryfirst`,`first`,`last`,`verylast`]}var pu=$(``),mu={veryfirst:`vfst`,first:`fst`,last:`lst`,verylast:`vlst`},hu=class{constructor(e){this.parent_=null,this.blade=e.blade,this.view=e.view,this.viewProps=e.viewProps;let t=this.view.element;this.blade.value(`positions`).emitter.on(`change`,()=>{fu().forEach(e=>{t.classList.remove(pu(void 0,mu[e]))}),this.blade.get(`positions`).forEach(e=>{t.classList.add(pu(void 0,mu[e]))})}),this.viewProps.handleDispose(()=>{tu(t)})}get parent(){return this.parent_}set parent(e){this.parent_=e,this.viewProps.set(`parent`,this.parent_?this.parent_.viewProps:null)}importState(e){return Vl(e,null,e=>({disabled:e.required.boolean,hidden:e.required.boolean}),e=>(this.viewProps.importState(e),!0))}exportState(){return Hl(null,Object.assign({},this.viewProps.exportState()))}},gu=class extends hu{constructor(e,t){if(t.value!==t.valueController.value)throw bc.shouldNeverHappen();let n=t.valueController.viewProps,r=new du(e,{blade:t.blade,props:t.props,valueController:t.valueController});super(Object.assign(Object.assign({},t),{view:new uu(e,{props:t.props,viewProps:n}),viewProps:n})),this.labelController=r,this.value=t.value,this.valueController=t.valueController,this.view.valueElement.appendChild(this.valueController.view.element)}importState(e){return Vl(e,t=>{var n;return super.importState(t)&&this.labelController.importProps(t)&&((n=this.valueController).importProps?.call(n,e)??!0)},e=>({value:e.optional.raw}),e=>(e.value&&(this.value.rawValue=e.value),!0))}exportState(){var e;return Hl(()=>super.exportState(),Object.assign(Object.assign({value:this.value.rawValue},this.labelController.exportProps()),(e=this.valueController).exportProps?.call(e)??{}))}};function _u(e){let t=Object.assign({},e);return delete t.value,t}var vu=class extends gu{constructor(e,t){super(e,t),this.tag=t.tag}importState(e){return Vl(e,t=>super.importState(_u(e)),e=>({tag:e.optional.string}),e=>(this.tag=e.tag,!0))}exportState(){return Hl(()=>_u(super.exportState()),{binding:{key:this.value.binding.target.key,value:this.value.binding.target.read()},tag:this.tag})}};function yu(e){return Ul(e)&&Wl(e.value)}var bu=class extends vu{importState(e){return Vl(e,e=>super.importState(e),e=>({binding:e.required.object({value:e.required.raw})}),e=>(this.value.binding.inject(e.binding.value),this.value.fetch(),!0))}};function xu(e){return Ul(e)&&Nl(e.value)}function Su(e,t){for(;e.lengthe.length?n.splice(0,n.length-e.length):Su(n,e.length),n}var Eu=class{constructor(e){this.emitter=new Sc,this.onTick_=this.onTick_.bind(this),this.onValueBeforeChange_=this.onValueBeforeChange_.bind(this),this.onValueChange_=this.onValueChange_.bind(this),this.binding=e.binding,this.value_=Ec(Cu(e.bufferSize)),this.value_.emitter.on(`beforechange`,this.onValueBeforeChange_),this.value_.emitter.on(`change`,this.onValueChange_),this.ticker=e.ticker,this.ticker.emitter.on(`tick`,this.onTick_),this.fetch()}get rawValue(){return this.value_.rawValue}set rawValue(e){this.value_.rawValue=e}setRawValue(e,t){this.value_.setRawValue(e,t)}fetch(){this.value_.rawValue=Tu(this.value_.rawValue,this.binding.read())}onTick_(){this.fetch()}onValueBeforeChange_(e){this.emitter.emit(`beforechange`,Object.assign(Object.assign({},e),{sender:this}))}onValueChange_(e){this.emitter.emit(`change`,Object.assign(Object.assign({},e),{sender:this}))}};function Du(e){if(!(`binding`in e))return!1;let t=e.binding;return vc(t)&&`read`in t&&!(`write`in t)}var Ou=class extends vu{exportState(){return Hl(()=>super.exportState(),{binding:{readonly:!0}})}};function ku(e){return Ul(e)&&Du(e.value)}var Au=class extends Tl{get label(){return this.controller.labelController.props.get(`label`)}set label(e){this.controller.labelController.props.set(`label`,e)}get title(){return this.controller.buttonController.props.get(`title`)??``}set title(e){this.controller.buttonController.props.set(`title`,e)}on(e,t){let n=t.bind(this);return this.controller.buttonController.emitter.on(e,e=>{n(new Al(this,e.nativeEvent))}),this}off(e,t){return this.controller.buttonController.emitter.off(e,t),this}};function ju(e,t,n){n?e.classList.add(t):e.classList.remove(t)}function Mu(e,t){return n=>{ju(e,t,n)}}function Nu(e,t){au(e,e=>{t.textContent=e??``})}var Pu=$(`btn`),Fu=class{constructor(e,t){this.element=e.createElement(`div`),this.element.classList.add(Pu()),t.viewProps.bindClassModifiers(this.element);let n=e.createElement(`button`);n.classList.add(Pu(`b`)),t.viewProps.bindDisabled(n),this.element.appendChild(n),this.buttonElement=n;let r=e.createElement(`div`);r.classList.add(Pu(`t`)),Nu(t.props.value(`title`),r),this.buttonElement.appendChild(r)}},Iu=class{constructor(e,t){this.emitter=new Sc,this.onClick_=this.onClick_.bind(this),this.props=t.props,this.viewProps=t.viewProps,this.view=new Fu(e,{props:this.props,viewProps:this.viewProps}),this.view.buttonElement.addEventListener(`click`,this.onClick_)}importProps(e){return Vl(e,null,e=>({title:e.optional.string}),e=>(this.props.set(`title`,e.title),!0))}exportProps(){return Hl(null,{title:this.props.get(`title`)})}onClick_(e){this.emitter.emit(`click`,{nativeEvent:e,sender:this})}},Lu=class extends hu{constructor(e,t){let n=new Iu(e,{props:t.buttonProps,viewProps:t.viewProps}),r=new du(e,{blade:t.blade,props:t.labelProps,valueController:n});super({blade:t.blade,view:r.view,viewProps:t.viewProps}),this.buttonController=n,this.labelController=r}importState(e){return Vl(e,e=>super.importState(e)&&this.buttonController.importProps(e)&&this.labelController.importProps(e),()=>({}),()=>!0)}exportState(){return Hl(()=>super.exportState(),Object.assign(Object.assign({},this.buttonController.exportProps()),this.labelController.exportProps()))}},Ru=class{constructor(e){let[t,n]=e.split(`-`),r=t.split(`.`);this.major=parseInt(r[0],10),this.minor=parseInt(r[1],10),this.patch=parseInt(r[2],10),this.prerelease=n??null}toString(){let e=[this.major,this.minor,this.patch].join(`.`);return this.prerelease===null?e:[e,this.prerelease].join(`-`)}},zu=new Ru(`2.0.5`);function Bu(e){return Object.assign({core:zu},e)}var Vu=Bu({id:`button`,type:`blade`,accept(e){let t=Bl(e,e=>({title:e.required.string,view:e.required.constant(`button`),label:e.optional.string}));return t?{params:t}:null},controller(e){return new Lu(e.document,{blade:e.blade,buttonProps:Q.fromObject({title:e.params.title}),labelProps:Q.fromObject({label:e.params.label}),viewProps:e.viewProps})},api(e){return e.controller instanceof Lu?new Au(e.controller):null}});function Hu(e,t){return e.addBlade(Object.assign(Object.assign({},t),{view:`button`}))}function Uu(e,t){return e.addBlade(Object.assign(Object.assign({},t),{view:`folder`}))}function Wu(e,t){return e.addBlade(Object.assign(Object.assign({},t),{view:`tab`}))}function Gu(e){return mc(e)?`refresh`in e&&typeof e.refresh==`function`:!1}function Ku(e,t){if(!xc.isBindable(e))throw bc.notBindable();return new xc(e,t)}var qu=class{constructor(e,t){this.onRackValueChange_=this.onRackValueChange_.bind(this),this.controller_=e,this.emitter_=new Sc,this.pool_=t,this.controller_.rack.emitter.on(`valuechange`,this.onRackValueChange_)}get children(){return this.controller_.rack.children.map(e=>this.pool_.createApi(e))}addBinding(e,t,n){let r=n??{},i=this.controller_.element.ownerDocument,a=this.pool_.createBinding(i,Ku(e,t),r),o=this.pool_.createBindingApi(a);return this.add(o,r.index)}addFolder(e){return Uu(this,e)}addButton(e){return Hu(this,e)}addTab(e){return Wu(this,e)}add(e,t){let n=e.controller;return this.controller_.rack.add(n,t),e}remove(e){this.controller_.rack.remove(e.controller)}addBlade(e){let t=this.controller_.element.ownerDocument,n=this.pool_.createBlade(t,e),r=this.pool_.createApi(n);return this.add(r,e.index)}on(e,t){let n=t.bind(this);return this.emitter_.on(e,e=>{n(e)},{key:t}),this}off(e,t){return this.emitter_.off(e,t),this}refresh(){this.children.forEach(e=>{Gu(e)&&e.refresh()})}onRackValueChange_(e){let t=e.bladeController,n=this.pool_.createApi(t),r=Wl(t.value)?t.value.binding:null;this.emitter_.emit(`change`,new Dl(n,r?r.target.read():t.value.rawValue,e.options.last))}},Ju=class extends Tl{constructor(e,t){super(e),this.rackApi_=new qu(e.rackController,t)}refresh(){this.rackApi_.refresh()}},Yu=class extends hu{constructor(e){super({blade:e.blade,view:e.view,viewProps:e.rackController.viewProps}),this.rackController=e.rackController}importState(e){return Vl(e,e=>super.importState(e),e=>({children:e.required.array(e.required.raw)}),e=>this.rackController.rack.children.every((t,n)=>t.importState(e.children[n])))}exportState(){return Hl(()=>super.exportState(),{children:this.rackController.rack.children.map(e=>e.exportState())})}};function Xu(e){return`rackController`in e}var Zu=class{constructor(e){this.emitter=new Sc,this.items_=[],this.cache_=new Set,this.onSubListAdd_=this.onSubListAdd_.bind(this),this.onSubListRemove_=this.onSubListRemove_.bind(this),this.extract_=e}get items(){return this.items_}allItems(){return Array.from(this.cache_)}find(e){for(let t of this.allItems())if(e(t))return t;return null}includes(e){return this.cache_.has(e)}add(e,t){if(this.includes(e))throw bc.shouldNeverHappen();let n=t===void 0?this.items_.length:t;this.items_.splice(n,0,e),this.cache_.add(e);let r=this.extract_(e);r&&(r.emitter.on(`add`,this.onSubListAdd_),r.emitter.on(`remove`,this.onSubListRemove_),r.allItems().forEach(e=>{this.cache_.add(e)})),this.emitter.emit(`add`,{index:n,item:e,root:this,target:this})}remove(e){let t=this.items_.indexOf(e);if(t<0)return;this.items_.splice(t,1),this.cache_.delete(e);let n=this.extract_(e);n&&(n.allItems().forEach(e=>{this.cache_.delete(e)}),n.emitter.off(`add`,this.onSubListAdd_),n.emitter.off(`remove`,this.onSubListRemove_)),this.emitter.emit(`remove`,{index:t,item:e,root:this,target:this})}onSubListAdd_(e){this.cache_.add(e.item),this.emitter.emit(`add`,{index:e.index,item:e.item,root:this,target:e.target})}onSubListRemove_(e){this.cache_.delete(e.item),this.emitter.emit(`remove`,{index:e.index,item:e.item,root:this,target:e.target})}};function Qu(e,t){for(let n=0;n!e.viewProps.get(`hidden`)),t=e[0],n=e[e.length-1];this.bcSet_.items.forEach(e=>{let r=[];e===t&&(r.push(`first`),(!this.blade_||this.blade_.get(`positions`).includes(`veryfirst`))&&r.push(`veryfirst`)),e===n&&(r.push(`last`),(!this.blade_||this.blade_.get(`positions`).includes(`verylast`))&&r.push(`verylast`)),e.blade.set(`positions`,r)})}onChildPositionsChange_(){this.updatePositions_(),this.emitter.emit(`layout`,{sender:this})}onChildViewPropsChange_(e){this.updatePositions_(),this.emitter.emit(`layout`,{sender:this})}onChildDispose_(){this.bcSet_.items.filter(e=>e.viewProps.get(`disposed`)).forEach(e=>{this.bcSet_.remove(e)})}onChildValueChange_(e){let t=Qu(this.find(Ul),e.sender);if(!t)throw bc.alreadyDisposed();this.emitter.emit(`valuechange`,{bladeController:t,options:e.options,sender:this})}onRackLayout_(e){this.updatePositions_(),this.emitter.emit(`layout`,{sender:this})}onRackValueChange_(e){this.emitter.emit(`valuechange`,{bladeController:e.bladeController,options:e.options,sender:this})}onBladePositionsChange_(){this.updatePositions_()}},td=class{constructor(e){this.onRackAdd_=this.onRackAdd_.bind(this),this.onRackRemove_=this.onRackRemove_.bind(this),this.element=e.element,this.viewProps=e.viewProps;let t=new ed({blade:e.root?void 0:e.blade,viewProps:e.viewProps});t.emitter.on(`add`,this.onRackAdd_),t.emitter.on(`remove`,this.onRackRemove_),this.rack=t,this.viewProps.handleDispose(()=>{for(let e=this.rack.children.length-1;e>=0;e--)this.rack.children[e].viewProps.set(`disposed`,!0)})}onRackAdd_(e){e.root&&eu(this.element,e.bladeController.view.element,e.index)}onRackRemove_(e){e.root&&tu(e.bladeController.view.element)}};function nd(){return new Q({positions:Ec([],{equals:gc})})}var rd=class e extends Q{constructor(e){super(e)}static create(t){let n={completed:!0,expanded:t,expandedHeight:null,shouldFixHeight:!1,temporaryExpanded:null};return new e(Q.createCore(n))}get styleExpanded(){return this.get(`temporaryExpanded`)??this.get(`expanded`)}get styleHeight(){if(!this.styleExpanded)return`0`;let e=this.get(`expandedHeight`);return this.get(`shouldFixHeight`)&&!pc(e)?`${e}px`:`auto`}bindExpandedClass(e,t){let n=()=>{this.styleExpanded?e.classList.add(t):e.classList.remove(t)};ou(this,`expanded`,n),ou(this,`temporaryExpanded`,n)}cleanUpTransition(){this.set(`shouldFixHeight`,!1),this.set(`expandedHeight`,null),this.set(`completed`,!0)}};function id(e,t){let n=0;return ql(t,()=>{e.set(`expandedHeight`,null),e.set(`temporaryExpanded`,!0),Kl(t),n=t.clientHeight,e.set(`temporaryExpanded`,null),Kl(t)}),n}function ad(e,t){t.style.height=e.styleHeight}function od(e,t){e.value(`expanded`).emitter.on(`beforechange`,()=>{if(e.set(`completed`,!1),pc(e.get(`expandedHeight`))){let n=id(e,t);n>0&&e.set(`expandedHeight`,n)}e.set(`shouldFixHeight`,!0),Kl(t)}),e.emitter.on(`change`,()=>{ad(e,t)}),ad(e,t),t.addEventListener(`transitionend`,t=>{t.propertyName===`height`&&e.cleanUpTransition()})}var sd=class extends Ju{constructor(e,t){super(e,t),this.emitter_=new Sc,this.controller.foldable.value(`expanded`).emitter.on(`change`,e=>{this.emitter_.emit(`fold`,new Ol(this,e.sender.rawValue))}),this.rackApi_.on(`change`,e=>{this.emitter_.emit(`change`,e)})}get expanded(){return this.controller.foldable.get(`expanded`)}set expanded(e){this.controller.foldable.set(`expanded`,e)}get title(){return this.controller.props.get(`title`)}set title(e){this.controller.props.set(`title`,e)}get children(){return this.rackApi_.children}addBinding(e,t,n){return this.rackApi_.addBinding(e,t,n)}addFolder(e){return this.rackApi_.addFolder(e)}addButton(e){return this.rackApi_.addButton(e)}addTab(e){return this.rackApi_.addTab(e)}add(e,t){return this.rackApi_.add(e,t)}remove(e){this.rackApi_.remove(e)}addBlade(e){return this.rackApi_.addBlade(e)}on(e,t){let n=t.bind(this);return this.emitter_.on(e,e=>{n(e)},{key:t}),this}off(e,t){return this.emitter_.off(e,t),this}},cd=$(`cnt`),ld=class{constructor(e,t){this.className_=$(t.viewName??`fld`),this.element=e.createElement(`div`),this.element.classList.add(this.className_(),cd()),t.viewProps.bindClassModifiers(this.element),this.foldable_=t.foldable,this.foldable_.bindExpandedClass(this.element,this.className_(void 0,`expanded`)),ou(this.foldable_,`completed`,Mu(this.element,this.className_(void 0,`cpl`)));let n=e.createElement(`button`);n.classList.add(this.className_(`b`)),ou(t.props,`title`,e=>{pc(e)?this.element.classList.add(this.className_(void 0,`not`)):this.element.classList.remove(this.className_(void 0,`not`))}),t.viewProps.bindDisabled(n),this.element.appendChild(n),this.buttonElement=n;let r=e.createElement(`div`);r.classList.add(this.className_(`i`)),this.element.appendChild(r);let i=e.createElement(`div`);i.classList.add(this.className_(`t`)),Nu(t.props.value(`title`),i),this.buttonElement.appendChild(i),this.titleElement=i;let a=e.createElement(`div`);a.classList.add(this.className_(`m`)),this.buttonElement.appendChild(a);let o=e.createElement(`div`);o.classList.add(this.className_(`c`)),this.element.appendChild(o),this.containerElement=o}},ud=class extends Yu{constructor(e,t){let n=rd.create(t.expanded??!0),r=new ld(e,{foldable:n,props:t.props,viewName:t.root?`rot`:void 0,viewProps:t.viewProps});super(Object.assign(Object.assign({},t),{rackController:new td({blade:t.blade,element:r.containerElement,root:t.root,viewProps:t.viewProps}),view:r})),this.onTitleClick_=this.onTitleClick_.bind(this),this.props=t.props,this.foldable=n,od(this.foldable,this.view.containerElement),this.rackController.rack.emitter.on(`add`,()=>{this.foldable.cleanUpTransition()}),this.rackController.rack.emitter.on(`remove`,()=>{this.foldable.cleanUpTransition()}),this.view.buttonElement.addEventListener(`click`,this.onTitleClick_)}get document(){return this.view.element.ownerDocument}importState(e){return Vl(e,e=>super.importState(e),e=>({expanded:e.required.boolean,title:e.optional.string}),e=>(this.foldable.set(`expanded`,e.expanded),this.props.set(`title`,e.title),!0))}exportState(){return Hl(()=>super.exportState(),{expanded:this.foldable.get(`expanded`),title:this.props.get(`title`)})}onTitleClick_(){this.foldable.set(`expanded`,!this.foldable.get(`expanded`))}},dd=Bu({id:`folder`,type:`blade`,accept(e){let t=Bl(e,e=>({title:e.required.string,view:e.required.constant(`folder`),expanded:e.optional.boolean}));return t?{params:t}:null},controller(e){return new ud(e.document,{blade:e.blade,expanded:e.params.expanded,props:Q.fromObject({title:e.params.title}),viewProps:e.viewProps})},api(e){return e.controller instanceof ud?new sd(e.controller,e.pool):null}}),fd=$(``);function pd(e,t){return Mu(e,fd(void 0,t))}var md=class e extends Q{constructor(e){var t;super(e),this.onDisabledChange_=this.onDisabledChange_.bind(this),this.onParentChange_=this.onParentChange_.bind(this),this.onParentGlobalDisabledChange_=this.onParentGlobalDisabledChange_.bind(this),[this.globalDisabled_,this.setGlobalDisabled_]=Dc(Ec(this.getGlobalDisabled_())),this.value(`disabled`).emitter.on(`change`,this.onDisabledChange_),this.value(`parent`).emitter.on(`change`,this.onParentChange_),(t=this.get(`parent`))==null||t.globalDisabled.emitter.on(`change`,this.onParentGlobalDisabledChange_)}static create(t){let n=t??{};return new e(Q.createCore({disabled:n.disabled??!1,disposed:!1,hidden:n.hidden??!1,parent:n.parent??null}))}get globalDisabled(){return this.globalDisabled_}bindClassModifiers(e){au(this.globalDisabled_,pd(e,`disabled`)),ou(this,`hidden`,pd(e,`hidden`))}bindDisabled(e){au(this.globalDisabled_,t=>{e.disabled=t})}bindTabIndex(e){au(this.globalDisabled_,t=>{e.tabIndex=t?-1:0})}handleDispose(e){this.value(`disposed`).emitter.on(`change`,t=>{t&&e()})}importState(e){this.set(`disabled`,e.disabled),this.set(`hidden`,e.hidden)}exportState(){return{disabled:this.get(`disabled`),hidden:this.get(`hidden`)}}getGlobalDisabled_(){let e=this.get(`parent`);return(e?e.globalDisabled.rawValue:!1)||this.get(`disabled`)}updateGlobalDisabled_(){this.setGlobalDisabled_(this.getGlobalDisabled_())}onDisabledChange_(){this.updateGlobalDisabled_()}onParentGlobalDisabledChange_(){this.updateGlobalDisabled_()}onParentChange_(e){var t;e.previousRawValue?.globalDisabled.emitter.off(`change`,this.onParentGlobalDisabledChange_),(t=this.get(`parent`))==null||t.globalDisabled.emitter.on(`change`,this.onParentGlobalDisabledChange_),this.updateGlobalDisabled_()}},hd=$(`tbp`),gd=class{constructor(e,t){this.element=e.createElement(`div`),this.element.classList.add(hd()),t.viewProps.bindClassModifiers(this.element);let n=e.createElement(`div`);n.classList.add(hd(`c`)),this.element.appendChild(n),this.containerElement=n}},_d=$(`tbi`),vd=class{constructor(e,t){this.element=e.createElement(`div`),this.element.classList.add(_d()),t.viewProps.bindClassModifiers(this.element),ou(t.props,`selected`,e=>{e?this.element.classList.add(_d(void 0,`sel`)):this.element.classList.remove(_d(void 0,`sel`))});let n=e.createElement(`button`);n.classList.add(_d(`b`)),t.viewProps.bindDisabled(n),this.element.appendChild(n),this.buttonElement=n;let r=e.createElement(`div`);r.classList.add(_d(`t`)),Nu(t.props.value(`title`),r),this.buttonElement.appendChild(r),this.titleElement=r}},yd=class{constructor(e,t){this.emitter=new Sc,this.onClick_=this.onClick_.bind(this),this.props=t.props,this.viewProps=t.viewProps,this.view=new vd(e,{props:t.props,viewProps:t.viewProps}),this.view.buttonElement.addEventListener(`click`,this.onClick_)}onClick_(){this.emitter.emit(`click`,{sender:this})}},bd=class extends Yu{constructor(e,t){let n=new gd(e,{viewProps:t.viewProps});super(Object.assign(Object.assign({},t),{rackController:new td({blade:t.blade,element:n.containerElement,viewProps:t.viewProps}),view:n})),this.onItemClick_=this.onItemClick_.bind(this),this.ic_=new yd(e,{props:t.itemProps,viewProps:md.create()}),this.ic_.emitter.on(`click`,this.onItemClick_),this.props=t.props,ou(this.props,`selected`,e=>{this.itemController.props.set(`selected`,e),this.viewProps.set(`hidden`,!e)})}get itemController(){return this.ic_}importState(e){return Vl(e,e=>super.importState(e),e=>({selected:e.required.boolean,title:e.required.string}),e=>(this.ic_.props.set(`selected`,e.selected),this.ic_.props.set(`title`,e.title),!0))}exportState(){return Hl(()=>super.exportState(),{selected:this.ic_.props.get(`selected`),title:this.ic_.props.get(`title`)})}onItemClick_(){this.props.set(`selected`,!0)}},xd=class extends Ju{constructor(e,t){super(e,t),this.emitter_=new Sc,this.onSelect_=this.onSelect_.bind(this),this.pool_=t,this.rackApi_.on(`change`,e=>{this.emitter_.emit(`change`,e)}),this.controller.tab.selectedIndex.emitter.on(`change`,this.onSelect_)}get pages(){return this.rackApi_.children}addPage(e){let t=this.controller.view.element.ownerDocument,n=new bd(t,{blade:nd(),itemProps:Q.fromObject({selected:!1,title:e.title}),props:Q.fromObject({selected:!1}),viewProps:md.create()}),r=this.pool_.createApi(n);return this.rackApi_.add(r,e.index)}removePage(e){this.rackApi_.remove(this.rackApi_.children[e])}on(e,t){let n=t.bind(this);return this.emitter_.on(e,e=>{n(e)},{key:t}),this}off(e,t){return this.emitter_.off(e,t),this}onSelect_(e){this.emitter_.emit(`select`,new kl(this,e.rawValue))}},Sd=class extends Ju{get title(){return this.controller.itemController.props.get(`title`)??``}set title(e){this.controller.itemController.props.set(`title`,e)}get selected(){return this.controller.props.get(`selected`)}set selected(e){this.controller.props.set(`selected`,e)}get children(){return this.rackApi_.children}addButton(e){return this.rackApi_.addButton(e)}addFolder(e){return this.rackApi_.addFolder(e)}addTab(e){return this.rackApi_.addTab(e)}add(e,t){this.rackApi_.add(e,t)}remove(e){this.rackApi_.remove(e)}addBinding(e,t,n){return this.rackApi_.addBinding(e,t,n)}addBlade(e){return this.rackApi_.addBlade(e)}},Cd=-1,wd=class{constructor(){this.onItemSelectedChange_=this.onItemSelectedChange_.bind(this),this.empty=Ec(!0),this.selectedIndex=Ec(Cd),this.items_=[]}add(e,t){let n=t??this.items_.length;this.items_.splice(n,0,e),e.emitter.on(`change`,this.onItemSelectedChange_),this.keepSelection_()}remove(e){let t=this.items_.indexOf(e);t<0||(this.items_.splice(t,1),e.emitter.off(`change`,this.onItemSelectedChange_),this.keepSelection_())}keepSelection_(){if(this.items_.length===0){this.selectedIndex.rawValue=Cd,this.empty.rawValue=!0;return}let e=this.items_.findIndex(e=>e.rawValue);e<0?(this.items_.forEach((e,t)=>{e.rawValue=t===0}),this.selectedIndex.rawValue=0):(this.items_.forEach((t,n)=>{t.rawValue=n===e}),this.selectedIndex.rawValue=e),this.empty.rawValue=!1}onItemSelectedChange_(e){if(e.rawValue){let t=this.items_.findIndex(t=>t===e.sender);this.items_.forEach((e,n)=>{e.rawValue=n===t}),this.selectedIndex.rawValue=t}else this.keepSelection_()}},Td=$(`tab`),Ed=class{constructor(e,t){this.element=e.createElement(`div`),this.element.classList.add(Td(),cd()),t.viewProps.bindClassModifiers(this.element),au(t.empty,Mu(this.element,Td(void 0,`nop`)));let n=e.createElement(`div`);n.classList.add(Td(`t`)),this.element.appendChild(n),this.itemsElement=n;let r=e.createElement(`div`);r.classList.add(Td(`i`)),this.element.appendChild(r);let i=e.createElement(`div`);i.classList.add(Td(`c`)),this.element.appendChild(i),this.contentsElement=i}},Dd=class extends Yu{constructor(e,t){let n=new wd,r=new Ed(e,{empty:n.empty,viewProps:t.viewProps});super({blade:t.blade,rackController:new td({blade:t.blade,element:r.contentsElement,viewProps:t.viewProps}),view:r}),this.onRackAdd_=this.onRackAdd_.bind(this),this.onRackRemove_=this.onRackRemove_.bind(this);let i=this.rackController.rack;i.emitter.on(`add`,this.onRackAdd_),i.emitter.on(`remove`,this.onRackRemove_),this.tab=n}add(e,t){this.rackController.rack.add(e,t)}remove(e){this.rackController.rack.remove(this.rackController.rack.children[e])}onRackAdd_(e){if(!e.root)return;let t=e.bladeController;eu(this.view.itemsElement,t.itemController.view.element,e.index),t.itemController.viewProps.set(`parent`,this.viewProps),this.tab.add(t.props.value(`selected`))}onRackRemove_(e){if(!e.root)return;let t=e.bladeController;tu(t.itemController.view.element),t.itemController.viewProps.set(`parent`,null),this.tab.remove(t.props.value(`selected`))}},Od=Bu({id:`tab`,type:`blade`,accept(e){let t=Bl(e,e=>({pages:e.required.array(e.required.object({title:e.required.string})),view:e.required.constant(`tab`)}));return!t||t.pages.length===0?null:{params:t}},controller(e){let t=new Dd(e.document,{blade:e.blade,viewProps:e.viewProps});return e.params.pages.forEach(n=>{let r=new bd(e.document,{blade:nd(),itemProps:Q.fromObject({selected:!1,title:n.title}),props:Q.fromObject({selected:!1}),viewProps:md.create()});t.add(r)}),t},api(e){return e.controller instanceof Dd?new xd(e.controller,e.pool):e.controller instanceof bd?new Sd(e.controller,e.pool):null}});function kd(e,t){let n=e.accept(t.params);if(!n)return null;let r=Bl(t.params,e=>({disabled:e.optional.boolean,hidden:e.optional.boolean}));return e.controller({blade:nd(),document:t.document,params:fc(Object.assign(Object.assign({},n.params),{disabled:r?.disabled,hidden:r?.hidden})),viewProps:md.create({disabled:r?.disabled,hidden:r?.hidden})})}var Ad=class extends jl{get options(){return this.controller.valueController.props.get(`options`)}set options(e){this.controller.valueController.props.set(`options`,e)}},jd=class{constructor(){this.disabled=!1,this.emitter=new Sc}dispose(){}tick(){this.disabled||this.emitter.emit(`tick`,{sender:this})}},Md=class{constructor(e,t){this.disabled_=!1,this.timerId_=null,this.onTick_=this.onTick_.bind(this),this.doc_=e,this.emitter=new Sc,this.interval_=t,this.setTimer_()}get disabled(){return this.disabled_}set disabled(e){this.disabled_=e,this.disabled_?this.clearTimer_():this.setTimer_()}dispose(){this.clearTimer_()}clearTimer_(){if(this.timerId_===null)return;let e=this.doc_.defaultView;e&&e.clearInterval(this.timerId_),this.timerId_=null}setTimer_(){if(this.clearTimer_(),this.interval_<=0)return;let e=this.doc_.defaultView;e&&(this.timerId_=e.setInterval(this.onTick_,this.interval_))}onTick_(){this.disabled_||this.emitter.emit(`tick`,{sender:this})}},Nd=class{constructor(e){this.constraints=e}constrain(e){return this.constraints.reduce((e,t)=>t.constrain(e),e)}};function Pd(e,t){if(e instanceof t)return e;if(e instanceof Nd){let n=e.constraints.reduce((e,n)=>e||(n instanceof t?n:null),null);if(n)return n}return null}var Fd=class{constructor(e){this.values=Q.fromObject({options:e})}constrain(e){let t=this.values.get(`options`);return t.length===0||t.filter(t=>t.value===e).length>0?e:t[0].value}};function Id(e){let t=zl;if(Array.isArray(e))return Bl({items:e},e=>({items:e.required.array(e.required.object({text:e.required.string,value:e.required.raw}))}))?.items;if(typeof e==`object`)return t.required.raw(e).value}function Ld(e){if(Array.isArray(e))return e;let t=[];return Object.keys(e).forEach(n=>{t.push({text:n,value:e[n]})}),t}function Rd(e){return pc(e)?null:new Fd(Ld(fc(e)))}var zd=$(`lst`),Bd=class{constructor(e,t){this.onValueChange_=this.onValueChange_.bind(this),this.props_=t.props,this.element=e.createElement(`div`),this.element.classList.add(zd()),t.viewProps.bindClassModifiers(this.element);let n=e.createElement(`select`);n.classList.add(zd(`s`)),t.viewProps.bindDisabled(n),this.element.appendChild(n),this.selectElement=n;let r=e.createElement(`div`);r.classList.add(zd(`m`)),r.appendChild($l(e,`dropdown`)),this.element.appendChild(r),t.value.emitter.on(`change`,this.onValueChange_),this.value_=t.value,ou(this.props_,`options`,t=>{nu(this.selectElement),t.forEach(t=>{let n=e.createElement(`option`);n.textContent=t.text,this.selectElement.appendChild(n)}),this.update_()})}update_(){let e=this.props_.get(`options`).map(e=>e.value);this.selectElement.selectedIndex=e.indexOf(this.value_.rawValue)}onValueChange_(){this.update_()}},Vd=class{constructor(e,t){this.onSelectChange_=this.onSelectChange_.bind(this),this.props=t.props,this.value=t.value,this.viewProps=t.viewProps,this.view=new Bd(e,{props:this.props,value:this.value,viewProps:this.viewProps}),this.view.selectElement.addEventListener(`change`,this.onSelectChange_)}onSelectChange_(e){let t=fc(e.currentTarget);this.value.rawValue=this.props.get(`options`)[t.selectedIndex].value}importProps(e){return Vl(e,null,e=>({options:e.required.custom(Id)}),e=>(this.props.set(`options`,Ld(e.options)),!0))}exportProps(){return Hl(null,{options:this.props.get(`options`)})}},Hd=$(`pop`),Ud=class{constructor(e,t){this.element=e.createElement(`div`),this.element.classList.add(Hd()),t.viewProps.bindClassModifiers(this.element),au(t.shows,Mu(this.element,Hd(void 0,`v`)))}},Wd=class{constructor(e,t){this.shows=Ec(!1),this.viewProps=t.viewProps,this.view=new Ud(e,{shows:this.shows,viewProps:this.viewProps})}},Gd=$(`txt`),Kd=class{constructor(e,t){this.onChange_=this.onChange_.bind(this),this.element=e.createElement(`div`),this.element.classList.add(Gd()),t.viewProps.bindClassModifiers(this.element),this.props_=t.props,this.props_.emitter.on(`change`,this.onChange_);let n=e.createElement(`input`);n.classList.add(Gd(`i`)),n.type=`text`,t.viewProps.bindDisabled(n),this.element.appendChild(n),this.inputElement=n,t.value.emitter.on(`change`,this.onChange_),this.value_=t.value,this.refresh()}refresh(){let e=this.props_.get(`formatter`);this.inputElement.value=e(this.value_.rawValue)}onChange_(){this.refresh()}},qd=class{constructor(e,t){this.onInputChange_=this.onInputChange_.bind(this),this.parser_=t.parser,this.props=t.props,this.value=t.value,this.viewProps=t.viewProps,this.view=new Kd(e,{props:t.props,value:this.value,viewProps:this.viewProps}),this.view.inputElement.addEventListener(`change`,this.onInputChange_)}onInputChange_(e){let t=fc(e.currentTarget).value,n=this.parser_(t);pc(n)||(this.value.rawValue=n),this.view.refresh()}};function Jd(e){return String(e)}function Yd(e){return e===`false`?!1:!!e}function Xd(e){return Jd(e)}function Zd(e){return t=>e.reduce((e,n)=>e===null?n(t):e,null)}var Qd=fl(0);function $d(e){return Qd(e)+`%`}function ef(e){return String(e)}function tf(e){return e}function nf({primary:e,secondary:t,forward:n,backward:r}){let i=!1;function a(e){i||=(i=!0,e(),!1)}e.emitter.on(`change`,r=>{a(()=>{t.setRawValue(n(e.rawValue,t.rawValue),r.options)})}),t.emitter.on(`change`,i=>{a(()=>{e.setRawValue(r(e.rawValue,t.rawValue),i.options)}),a(()=>{t.setRawValue(n(e.rawValue,t.rawValue),i.options)})}),a(()=>{t.setRawValue(n(e.rawValue,t.rawValue),{forceEmit:!1,last:!0})})}function rf(e,t){let n=e*(t.altKey?.1:1)*(t.shiftKey?10:1);return t.upKey?+n:t.downKey?-n:0}function af(e){return{altKey:e.altKey,downKey:e.key===`ArrowDown`,shiftKey:e.shiftKey,upKey:e.key===`ArrowUp`}}function of(e){return{altKey:e.altKey,downKey:e.key===`ArrowLeft`,shiftKey:e.shiftKey,upKey:e.key===`ArrowRight`}}function sf(e){return e===`ArrowUp`||e===`ArrowDown`}function cf(e){return sf(e)||e===`ArrowLeft`||e===`ArrowRight`}function lf(e,t){let n=t.ownerDocument.defaultView,r=t.getBoundingClientRect();return{x:e.pageX-(((n&&n.scrollX)??0)+r.left),y:e.pageY-(((n&&n.scrollY)??0)+r.top)}}var uf=class{constructor(e){this.lastTouch_=null,this.onDocumentMouseMove_=this.onDocumentMouseMove_.bind(this),this.onDocumentMouseUp_=this.onDocumentMouseUp_.bind(this),this.onMouseDown_=this.onMouseDown_.bind(this),this.onTouchEnd_=this.onTouchEnd_.bind(this),this.onTouchMove_=this.onTouchMove_.bind(this),this.onTouchStart_=this.onTouchStart_.bind(this),this.elem_=e,this.emitter=new Sc,e.addEventListener(`touchstart`,this.onTouchStart_,{passive:!1}),e.addEventListener(`touchmove`,this.onTouchMove_,{passive:!0}),e.addEventListener(`touchend`,this.onTouchEnd_),e.addEventListener(`mousedown`,this.onMouseDown_)}computePosition_(e){let t=this.elem_.getBoundingClientRect();return{bounds:{width:t.width,height:t.height},point:e?{x:e.x,y:e.y}:null}}onMouseDown_(e){var t;e.preventDefault(),(t=e.currentTarget)==null||t.focus();let n=this.elem_.ownerDocument;n.addEventListener(`mousemove`,this.onDocumentMouseMove_),n.addEventListener(`mouseup`,this.onDocumentMouseUp_),this.emitter.emit(`down`,{altKey:e.altKey,data:this.computePosition_(lf(e,this.elem_)),sender:this,shiftKey:e.shiftKey})}onDocumentMouseMove_(e){this.emitter.emit(`move`,{altKey:e.altKey,data:this.computePosition_(lf(e,this.elem_)),sender:this,shiftKey:e.shiftKey})}onDocumentMouseUp_(e){let t=this.elem_.ownerDocument;t.removeEventListener(`mousemove`,this.onDocumentMouseMove_),t.removeEventListener(`mouseup`,this.onDocumentMouseUp_),this.emitter.emit(`up`,{altKey:e.altKey,data:this.computePosition_(lf(e,this.elem_)),sender:this,shiftKey:e.shiftKey})}onTouchStart_(e){e.preventDefault();let t=e.targetTouches.item(0),n=this.elem_.getBoundingClientRect();this.emitter.emit(`down`,{altKey:e.altKey,data:this.computePosition_(t?{x:t.clientX-n.left,y:t.clientY-n.top}:void 0),sender:this,shiftKey:e.shiftKey}),this.lastTouch_=t}onTouchMove_(e){let t=e.targetTouches.item(0),n=this.elem_.getBoundingClientRect();this.emitter.emit(`move`,{altKey:e.altKey,data:this.computePosition_(t?{x:t.clientX-n.left,y:t.clientY-n.top}:void 0),sender:this,shiftKey:e.shiftKey}),this.lastTouch_=t}onTouchEnd_(e){let t=e.targetTouches.item(0)??this.lastTouch_,n=this.elem_.getBoundingClientRect();this.emitter.emit(`up`,{altKey:e.altKey,data:this.computePosition_(t?{x:t.clientX-n.left,y:t.clientY-n.top}:void 0),sender:this,shiftKey:e.shiftKey})}},df=$(`txt`),ff=class{constructor(e,t){this.onChange_=this.onChange_.bind(this),this.props_=t.props,this.props_.emitter.on(`change`,this.onChange_),this.element=e.createElement(`div`),this.element.classList.add(df(),df(void 0,`num`)),t.arrayPosition&&this.element.classList.add(df(void 0,t.arrayPosition)),t.viewProps.bindClassModifiers(this.element);let n=e.createElement(`input`);n.classList.add(df(`i`)),n.type=`text`,t.viewProps.bindDisabled(n),this.element.appendChild(n),this.inputElement=n,this.onDraggingChange_=this.onDraggingChange_.bind(this),this.dragging_=t.dragging,this.dragging_.emitter.on(`change`,this.onDraggingChange_),this.element.classList.add(df()),this.inputElement.classList.add(df(`i`));let r=e.createElement(`div`);r.classList.add(df(`k`)),this.element.appendChild(r),this.knobElement=r;let i=e.createElementNS(Gl,`svg`);i.classList.add(df(`g`)),this.knobElement.appendChild(i);let a=e.createElementNS(Gl,`path`);a.classList.add(df(`gb`)),i.appendChild(a),this.guideBodyElem_=a;let o=e.createElementNS(Gl,`path`);o.classList.add(df(`gh`)),i.appendChild(o),this.guideHeadElem_=o;let s=e.createElement(`div`);s.classList.add($(`tt`)()),this.knobElement.appendChild(s),this.tooltipElem_=s,t.value.emitter.on(`change`,this.onChange_),this.value=t.value,this.refresh()}onDraggingChange_(e){if(e.rawValue===null){this.element.classList.remove(df(void 0,`drg`));return}this.element.classList.add(df(void 0,`drg`));let t=e.rawValue/this.props_.get(`pointerScale`),n=t+(t>0?-1:t<0?1:0),r=hl(-n,-4,4);this.guideHeadElem_.setAttributeNS(null,`d`,[`M ${n+r},0 L${n},4 L${n+r},8`,`M ${t},-1 L${t},9`].join(` `)),this.guideBodyElem_.setAttributeNS(null,`d`,`M 0,4 L${t},4`);let i=this.props_.get(`formatter`);this.tooltipElem_.textContent=i(this.value.rawValue),this.tooltipElem_.style.left=`${t}px`}refresh(){let e=this.props_.get(`formatter`);this.inputElement.value=e(this.value.rawValue)}onChange_(){this.refresh()}},pf=class{constructor(e,t){this.originRawValue_=0,this.onInputChange_=this.onInputChange_.bind(this),this.onInputKeyDown_=this.onInputKeyDown_.bind(this),this.onInputKeyUp_=this.onInputKeyUp_.bind(this),this.onPointerDown_=this.onPointerDown_.bind(this),this.onPointerMove_=this.onPointerMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.parser_=t.parser,this.props=t.props,this.sliderProps_=t.sliderProps??null,this.value=t.value,this.viewProps=t.viewProps,this.dragging_=Ec(null),this.view=new ff(e,{arrayPosition:t.arrayPosition,dragging:this.dragging_,props:this.props,value:this.value,viewProps:this.viewProps}),this.view.inputElement.addEventListener(`change`,this.onInputChange_),this.view.inputElement.addEventListener(`keydown`,this.onInputKeyDown_),this.view.inputElement.addEventListener(`keyup`,this.onInputKeyUp_);let n=new uf(this.view.knobElement);n.emitter.on(`down`,this.onPointerDown_),n.emitter.on(`move`,this.onPointerMove_),n.emitter.on(`up`,this.onPointerUp_)}constrainValue_(e){let t=this.sliderProps_?.get(`min`),n=this.sliderProps_?.get(`max`),r=e;return t!==void 0&&(r=Math.max(r,t)),n!==void 0&&(r=Math.min(r,n)),r}onInputChange_(e){let t=fc(e.currentTarget).value,n=this.parser_(t);pc(n)||(this.value.rawValue=this.constrainValue_(n)),this.view.refresh()}onInputKeyDown_(e){let t=rf(this.props.get(`keyScale`),af(e));t!==0&&this.value.setRawValue(this.constrainValue_(this.value.rawValue+t),{forceEmit:!1,last:!1})}onInputKeyUp_(e){rf(this.props.get(`keyScale`),af(e))!==0&&this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}onPointerDown_(){this.originRawValue_=this.value.rawValue,this.dragging_.rawValue=0}computeDraggingValue_(e){if(!e.point)return null;let t=e.point.x-e.bounds.width/2;return this.constrainValue_(this.originRawValue_+t*this.props.get(`pointerScale`))}onPointerMove_(e){let t=this.computeDraggingValue_(e.data);t!==null&&(this.value.setRawValue(t,{forceEmit:!1,last:!1}),this.dragging_.rawValue=this.value.rawValue-this.originRawValue_)}onPointerUp_(e){let t=this.computeDraggingValue_(e.data);t!==null&&(this.value.setRawValue(t,{forceEmit:!0,last:!0}),this.dragging_.rawValue=null)}},mf=$(`sld`),hf=class{constructor(e,t){this.onChange_=this.onChange_.bind(this),this.props_=t.props,this.props_.emitter.on(`change`,this.onChange_),this.element=e.createElement(`div`),this.element.classList.add(mf()),t.viewProps.bindClassModifiers(this.element);let n=e.createElement(`div`);n.classList.add(mf(`t`)),t.viewProps.bindTabIndex(n),this.element.appendChild(n),this.trackElement=n;let r=e.createElement(`div`);r.classList.add(mf(`k`)),this.trackElement.appendChild(r),this.knobElement=r,t.value.emitter.on(`change`,this.onChange_),this.value=t.value,this.update_()}update_(){let e=hl(pl(this.value.rawValue,this.props_.get(`min`),this.props_.get(`max`),0,100),0,100);this.knobElement.style.width=`${e}%`}onChange_(){this.update_()}},gf=class{constructor(e,t){this.onKeyDown_=this.onKeyDown_.bind(this),this.onKeyUp_=this.onKeyUp_.bind(this),this.onPointerDownOrMove_=this.onPointerDownOrMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.value=t.value,this.viewProps=t.viewProps,this.props=t.props,this.view=new hf(e,{props:this.props,value:this.value,viewProps:this.viewProps}),this.ptHandler_=new uf(this.view.trackElement),this.ptHandler_.emitter.on(`down`,this.onPointerDownOrMove_),this.ptHandler_.emitter.on(`move`,this.onPointerDownOrMove_),this.ptHandler_.emitter.on(`up`,this.onPointerUp_),this.view.trackElement.addEventListener(`keydown`,this.onKeyDown_),this.view.trackElement.addEventListener(`keyup`,this.onKeyUp_)}handlePointerEvent_(e,t){e.point&&this.value.setRawValue(pl(hl(e.point.x,0,e.bounds.width),0,e.bounds.width,this.props.get(`min`),this.props.get(`max`)),t)}onPointerDownOrMove_(e){this.handlePointerEvent_(e.data,{forceEmit:!1,last:!1})}onPointerUp_(e){this.handlePointerEvent_(e.data,{forceEmit:!0,last:!0})}onKeyDown_(e){let t=rf(this.props.get(`keyScale`),of(e));t!==0&&this.value.setRawValue(this.value.rawValue+t,{forceEmit:!1,last:!1})}onKeyUp_(e){rf(this.props.get(`keyScale`),of(e))!==0&&this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}},_f=$(`sldtxt`),vf=class{constructor(e,t){this.element=e.createElement(`div`),this.element.classList.add(_f());let n=e.createElement(`div`);n.classList.add(_f(`s`)),this.sliderView_=t.sliderView,n.appendChild(this.sliderView_.element),this.element.appendChild(n);let r=e.createElement(`div`);r.classList.add(_f(`t`)),this.textView_=t.textView,r.appendChild(this.textView_.element),this.element.appendChild(r)}},yf=class{constructor(e,t){this.value=t.value,this.viewProps=t.viewProps,this.sliderC_=new gf(e,{props:t.sliderProps,value:t.value,viewProps:this.viewProps}),this.textC_=new pf(e,{parser:t.parser,props:t.textProps,sliderProps:t.sliderProps,value:t.value,viewProps:t.viewProps}),this.view=new vf(e,{sliderView:this.sliderC_.view,textView:this.textC_.view})}get sliderController(){return this.sliderC_}get textController(){return this.textC_}importProps(e){return Vl(e,null,e=>({max:e.required.number,min:e.required.number}),e=>{let t=this.sliderC_.props;return t.set(`max`,e.max),t.set(`min`,e.min),!0})}exportProps(){let e=this.sliderC_.props;return Hl(null,{max:e.get(`max`),min:e.get(`min`)})}};function bf(e){return{sliderProps:new Q({keyScale:e.keyScale,max:e.max,min:e.min}),textProps:new Q({formatter:Ec(e.formatter),keyScale:e.keyScale,pointerScale:Ec(e.pointerScale)})}}var xf={containerUnitSize:`cnt-usz`};function Sf(e){return`--${xf[e]}`}function Cf(e){return Cl(e)}function wf(e){if(hc(e))return Bl(e,Cf)}function Tf(e,t){if(!e)return;let n=[],r=bl(e,t);r&&n.push(r);let i=xl(e);return i&&n.push(i),new Nd(n)}function Ef(e){return e?e.major===zu.major:!1}function Df(e){if(e===`inline`||e===`popup`)return e}function Of(e,t){e.write(t)}var kf=$(`ckb`),Af=class{constructor(e,t){this.onValueChange_=this.onValueChange_.bind(this),this.element=e.createElement(`div`),this.element.classList.add(kf()),t.viewProps.bindClassModifiers(this.element);let n=e.createElement(`label`);n.classList.add(kf(`l`)),this.element.appendChild(n),this.labelElement=n;let r=e.createElement(`input`);r.classList.add(kf(`i`)),r.type=`checkbox`,this.labelElement.appendChild(r),this.inputElement=r,t.viewProps.bindDisabled(this.inputElement);let i=e.createElement(`div`);i.classList.add(kf(`w`)),this.labelElement.appendChild(i);let a=$l(e,`check`);i.appendChild(a),t.value.emitter.on(`change`,this.onValueChange_),this.value=t.value,this.update_()}update_(){this.inputElement.checked=this.value.rawValue}onValueChange_(){this.update_()}},jf=class{constructor(e,t){this.onInputChange_=this.onInputChange_.bind(this),this.onLabelMouseDown_=this.onLabelMouseDown_.bind(this),this.value=t.value,this.viewProps=t.viewProps,this.view=new Af(e,{value:this.value,viewProps:this.viewProps}),this.view.inputElement.addEventListener(`change`,this.onInputChange_),this.view.labelElement.addEventListener(`mousedown`,this.onLabelMouseDown_)}onInputChange_(e){let t=fc(e.currentTarget);this.value.rawValue=t.checked,e.preventDefault(),e.stopPropagation()}onLabelMouseDown_(e){e.preventDefault()}};function Mf(e){let t=[],n=Rd(e.options);return n&&t.push(n),new Nd(t)}var Nf=Bu({id:`input-bool`,type:`input`,accept:(e,t)=>{if(typeof e!=`boolean`)return null;let n=Bl(t,e=>({options:e.optional.custom(Id),readonly:e.optional.constant(!1)}));return n?{initialValue:e,params:n}:null},binding:{reader:e=>Yd,constraint:e=>Mf(e.params),writer:e=>Of},controller:e=>{let t=e.document,n=e.value,r=e.constraint,i=r&&Pd(r,Fd);return i?new Vd(t,{props:new Q({options:i.values.value(`options`)}),value:n,viewProps:e.viewProps}):new jf(t,{value:n,viewProps:e.viewProps})},api(e){return typeof e.controller.value.rawValue==`boolean`&&e.controller.valueController instanceof Vd?new Ad(e.controller):null}}),Pf=$(`col`),Ff=class{constructor(e,t){this.element=e.createElement(`div`),this.element.classList.add(Pf()),t.foldable.bindExpandedClass(this.element,Pf(void 0,`expanded`)),ou(t.foldable,`completed`,Mu(this.element,Pf(void 0,`cpl`)));let n=e.createElement(`div`);n.classList.add(Pf(`h`)),this.element.appendChild(n);let r=e.createElement(`div`);r.classList.add(Pf(`s`)),n.appendChild(r),this.swatchElement=r;let i=e.createElement(`div`);if(i.classList.add(Pf(`t`)),n.appendChild(i),this.textElement=i,t.pickerLayout===`inline`){let t=e.createElement(`div`);t.classList.add(Pf(`p`)),this.element.appendChild(t),this.pickerElement=t}else this.pickerElement=null}};function If(e,t,n){let r=hl(e/255,0,1),i=hl(t/255,0,1),a=hl(n/255,0,1),o=Math.max(r,i,a),s=Math.min(r,i,a),c=o-s,l=0,u=0,d=(s+o)/2;return c!==0&&(u=c/(1-Math.abs(o+s-1)),l=r===o?(i-a)/c:i===o?2+(a-r)/c:4+(r-i)/c,l=l/6+(l<0?1:0)),[l*360,u*100,d*100]}function Lf(e,t,n){let r=(e%360+360)%360,i=hl(t/100,0,1),a=hl(n/100,0,1),o=(1-Math.abs(2*a-1))*i,s=o*(1-Math.abs(r/60%2-1)),c=a-o/2,l,u,d;return r>=0&&r<60?[l,u,d]=[o,s,0]:r>=60&&r<120?[l,u,d]=[s,o,0]:r>=120&&r<180?[l,u,d]=[0,o,s]:r>=180&&r<240?[l,u,d]=[0,s,o]:r>=240&&r<300?[l,u,d]=[s,0,o]:[l,u,d]=[o,0,s],[(l+c)*255,(u+c)*255,(d+c)*255]}function Rf(e,t,n){let r=hl(e/255,0,1),i=hl(t/255,0,1),a=hl(n/255,0,1),o=Math.max(r,i,a),s=o-Math.min(r,i,a),c;c=s===0?0:o===r?60*(((i-a)/s%6+6)%6):o===i?60*((a-r)/s+2):60*((r-i)/s+4);let l=o===0?0:s/o,u=o;return[c,l*100,u*100]}function zf(e,t,n){let r=gl(e,360),i=hl(t/100,0,1),a=hl(n/100,0,1),o=a*i,s=o*(1-Math.abs(r/60%2-1)),c=a-o,l,u,d;return r>=0&&r<60?[l,u,d]=[o,s,0]:r>=60&&r<120?[l,u,d]=[s,o,0]:r>=120&&r<180?[l,u,d]=[0,o,s]:r>=180&&r<240?[l,u,d]=[0,s,o]:r>=240&&r<300?[l,u,d]=[s,0,o]:[l,u,d]=[o,0,s],[(l+c)*255,(u+c)*255,(d+c)*255]}function Bf(e,t,n){let r=n+t*(100-Math.abs(2*n-100))/200;return[e,r===0?0:t*(100-Math.abs(2*n-100))/r,n+t*(100-Math.abs(2*n-100))/200]}function Vf(e,t,n){let r=100-Math.abs(n*(200-t)/100-100);return[e,r===0?0:t*n/r,n*(200-t)/200]}function Hf(e){return[e[0],e[1],e[2]]}function Uf(e,t){return[e[0],e[1],e[2],t]}var Wf={hsl:{hsl:(e,t,n)=>[e,t,n],hsv:Bf,rgb:Lf},hsv:{hsl:Vf,hsv:(e,t,n)=>[e,t,n],rgb:zf},rgb:{hsl:If,hsv:Rf,rgb:(e,t,n)=>[e,t,n]}};function Gf(e,t){return[t===`float`?1:e===`rgb`?255:360,t===`float`?1:e===`rgb`?255:100,t===`float`?1:e===`rgb`?255:100]}function Kf(e,t){return e===t?t:gl(e,t)}function qf(e,t,n){let r=Gf(t,n);return[t===`rgb`?hl(e[0],0,r[0]):Kf(e[0],r[0]),hl(e[1],0,r[1]),hl(e[2],0,r[2]),hl(e[3]??1,0,1)]}function Jf(e,t,n,r){let i=Gf(t,n),a=Gf(t,r);return e.map((e,t)=>e/i[t]*a[t])}function Yf(e,t,n){let r=Jf(e,t.mode,t.type,`int`);return Jf(Wf[t.mode][n.mode](...r),n.mode,`int`,n.type)}var Xf=class e{static black(){return new e([0,0,0],`rgb`)}constructor(e,t){this.type=`int`,this.mode=t,this.comps_=qf(e,t,this.type)}getComponents(e){return Uf(Yf(Hf(this.comps_),{mode:this.mode,type:this.type},{mode:e??this.mode,type:this.type}),this.comps_[3])}toRgbaObject(){let e=this.getComponents(`rgb`);return{r:e[0],g:e[1],b:e[2],a:e[3]}}},Zf=$(`colp`),Qf=class{constructor(e,t){this.alphaViews_=null,this.element=e.createElement(`div`),this.element.classList.add(Zf()),t.viewProps.bindClassModifiers(this.element);let n=e.createElement(`div`);n.classList.add(Zf(`hsv`));let r=e.createElement(`div`);r.classList.add(Zf(`sv`)),this.svPaletteView_=t.svPaletteView,r.appendChild(this.svPaletteView_.element),n.appendChild(r);let i=e.createElement(`div`);i.classList.add(Zf(`h`)),this.hPaletteView_=t.hPaletteView,i.appendChild(this.hPaletteView_.element),n.appendChild(i),this.element.appendChild(n);let a=e.createElement(`div`);if(a.classList.add(Zf(`rgb`)),this.textsView_=t.textsView,a.appendChild(this.textsView_.element),this.element.appendChild(a),t.alphaViews){this.alphaViews_={palette:t.alphaViews.palette,text:t.alphaViews.text};let n=e.createElement(`div`);n.classList.add(Zf(`a`));let r=e.createElement(`div`);r.classList.add(Zf(`ap`)),r.appendChild(this.alphaViews_.palette.element),n.appendChild(r);let i=e.createElement(`div`);i.classList.add(Zf(`at`)),i.appendChild(this.alphaViews_.text.element),n.appendChild(i),this.element.appendChild(n)}}get allFocusableElements(){let e=[this.svPaletteView_.element,this.hPaletteView_.element,this.textsView_.modeSelectElement,...this.textsView_.inputViews.map(e=>e.inputElement)];return this.alphaViews_&&e.push(this.alphaViews_.palette.element,this.alphaViews_.text.inputElement),e}};function $f(e){return e===`int`?`int`:e===`float`?`float`:void 0}function ep(e){return Bl(e,e=>({color:e.optional.object({alpha:e.optional.boolean,type:e.optional.custom($f)}),expanded:e.optional.boolean,picker:e.optional.custom(Df),readonly:e.optional.constant(!1)}))}function tp(e){return e?.1:1}function np(e){return e.color?.type}var rp=class{constructor(e,t){this.type=`float`,this.mode=t,this.comps_=qf(e,t,this.type)}getComponents(e){return Uf(Yf(Hf(this.comps_),{mode:this.mode,type:this.type},{mode:e??this.mode,type:this.type}),this.comps_[3])}toRgbaObject(){let e=this.getComponents(`rgb`);return{r:e[0],g:e[1],b:e[2],a:e[3]}}},ip={int:(e,t)=>new Xf(e,t),float:(e,t)=>new rp(e,t)};function ap(e,t,n){return ip[n](e,t)}function op(e){return e.type===`float`}function sp(e){return e.type===`int`}function cp(e){let t=e.getComponents(),n=Gf(e.mode,`int`);return new Xf([Math.round(pl(t[0],0,1,0,n[0])),Math.round(pl(t[1],0,1,0,n[1])),Math.round(pl(t[2],0,1,0,n[2])),t[3]],e.mode)}function lp(e){let t=e.getComponents(),n=Gf(e.mode,`int`);return new rp([pl(t[0],0,n[0],0,1),pl(t[1],0,n[1],0,1),pl(t[2],0,n[2],0,1),t[3]],e.mode)}function up(e,t){if(e.type===t)return e;if(sp(e)&&t===`float`)return lp(e);if(op(e)&&t===`int`)return cp(e);throw bc.shouldNeverHappen()}function dp(e,t){return e.alpha===t.alpha&&e.mode===t.mode&&e.notation===t.notation&&e.type===t.type}function fp(e,t){let n=e.match(/^(.+)%$/);return n?Math.min(parseFloat(n[1])*.01*t,t):Math.min(parseFloat(e),t)}var pp={deg:e=>e,grad:e=>e*360/400,rad:e=>e*360/(2*Math.PI),turn:e=>e*360};function mp(e){let t=e.match(/^([0-9.]+?)(deg|grad|rad|turn)$/);if(!t)return parseFloat(e);let n=parseFloat(t[1]);return pp[t[2]](n)}function hp(e){let t=e.match(/^rgb\(\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*\)$/);if(!t)return null;let n=[fp(t[1],255),fp(t[2],255),fp(t[3],255)];return isNaN(n[0])||isNaN(n[1])||isNaN(n[2])?null:n}function gp(e){let t=hp(e);return t?new Xf(t,`rgb`):null}function _p(e){let t=e.match(/^rgba\(\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*\)$/);if(!t)return null;let n=[fp(t[1],255),fp(t[2],255),fp(t[3],255),fp(t[4],1)];return isNaN(n[0])||isNaN(n[1])||isNaN(n[2])||isNaN(n[3])?null:n}function vp(e){let t=_p(e);return t?new Xf(t,`rgb`):null}function yp(e){let t=e.match(/^hsl\(\s*([0-9A-Fa-f.]+(?:deg|grad|rad|turn)?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*\)$/);if(!t)return null;let n=[mp(t[1]),fp(t[2],100),fp(t[3],100)];return isNaN(n[0])||isNaN(n[1])||isNaN(n[2])?null:n}function bp(e){let t=yp(e);return t?new Xf(t,`hsl`):null}function xp(e){let t=e.match(/^hsla\(\s*([0-9A-Fa-f.]+(?:deg|grad|rad|turn)?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*\)$/);if(!t)return null;let n=[mp(t[1]),fp(t[2],100),fp(t[3],100),fp(t[4],1)];return isNaN(n[0])||isNaN(n[1])||isNaN(n[2])||isNaN(n[3])?null:n}function Sp(e){let t=xp(e);return t?new Xf(t,`hsl`):null}function Cp(e){let t=e.match(/^#([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])$/);if(t)return[parseInt(t[1]+t[1],16),parseInt(t[2]+t[2],16),parseInt(t[3]+t[3],16)];let n=e.match(/^(?:#|0x)([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})$/);return n?[parseInt(n[1],16),parseInt(n[2],16),parseInt(n[3],16)]:null}function wp(e){let t=Cp(e);return t?new Xf(t,`rgb`):null}function Tp(e){let t=e.match(/^#([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])$/);if(t)return[parseInt(t[1]+t[1],16),parseInt(t[2]+t[2],16),parseInt(t[3]+t[3],16),pl(parseInt(t[4]+t[4],16),0,255,0,1)];let n=e.match(/^(?:#|0x)?([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})$/);return n?[parseInt(n[1],16),parseInt(n[2],16),parseInt(n[3],16),pl(parseInt(n[4],16),0,255,0,1)]:null}function Ep(e){let t=Tp(e);return t?new Xf(t,`rgb`):null}function Dp(e){let t=e.match(/^\{\s*r\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*g\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*b\s*:\s*([0-9A-Fa-f.]+%?)\s*\}$/);if(!t)return null;let n=[parseFloat(t[1]),parseFloat(t[2]),parseFloat(t[3])];return isNaN(n[0])||isNaN(n[1])||isNaN(n[2])?null:n}function Op(e){return t=>{let n=Dp(t);return n?ap(n,`rgb`,e):null}}function kp(e){let t=e.match(/^\{\s*r\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*g\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*b\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*a\s*:\s*([0-9A-Fa-f.]+%?)\s*\}$/);if(!t)return null;let n=[parseFloat(t[1]),parseFloat(t[2]),parseFloat(t[3]),parseFloat(t[4])];return isNaN(n[0])||isNaN(n[1])||isNaN(n[2])||isNaN(n[3])?null:n}function Ap(e){return t=>{let n=kp(t);return n?ap(n,`rgb`,e):null}}var jp=[{parser:Cp,result:{alpha:!1,mode:`rgb`,notation:`hex`}},{parser:Tp,result:{alpha:!0,mode:`rgb`,notation:`hex`}},{parser:hp,result:{alpha:!1,mode:`rgb`,notation:`func`}},{parser:_p,result:{alpha:!0,mode:`rgb`,notation:`func`}},{parser:yp,result:{alpha:!1,mode:`hsl`,notation:`func`}},{parser:xp,result:{alpha:!0,mode:`hsl`,notation:`func`}},{parser:Dp,result:{alpha:!1,mode:`rgb`,notation:`object`}},{parser:kp,result:{alpha:!0,mode:`rgb`,notation:`object`}}];function Mp(e){return jp.reduce((t,{parser:n,result:r})=>t||(n(e)?r:null),null)}function Np(e,t=`int`){let n=Mp(e);return n?n.notation===`hex`&&t!==`float`?Object.assign(Object.assign({},n),{type:`int`}):n.notation===`func`?Object.assign(Object.assign({},n),{type:t}):null:null}function Pp(e){let t=[wp,Ep,gp,vp,bp,Sp];e===`int`&&t.push(Op(`int`),Ap(`int`)),e===`float`&&t.push(Op(`float`),Ap(`float`));let n=Zd(t);return t=>{let r=n(t);return r?up(r,e):null}}function Fp(e){let t=Pp(`int`);return typeof e==`string`?t(e)??Xf.black():Xf.black()}function Ip(e){let t=hl(Math.floor(e),0,255).toString(16);return t.length===1?`0${t}`:t}function Lp(e,t=`#`){return`${t}${Hf(e.getComponents(`rgb`)).map(Ip).join(``)}`}function Rp(e,t=`#`){let n=e.getComponents(`rgb`);return`${t}${[n[0],n[1],n[2],n[3]*255].map(Ip).join(``)}`}function zp(e){let t=fl(0);return`rgb(${Hf(up(e,`int`).getComponents(`rgb`)).map(e=>t(e)).join(`, `)})`}function Bp(e){let t=fl(2),n=fl(0);return`rgba(${up(e,`int`).getComponents(`rgb`).map((e,r)=>(r===3?t:n)(e)).join(`, `)})`}function Vp(e){let t=[fl(0),$d,$d];return`hsl(${Hf(up(e,`int`).getComponents(`hsl`)).map((e,n)=>t[n](e)).join(`, `)})`}function Hp(e){let t=[fl(0),$d,$d,fl(2)];return`hsla(${up(e,`int`).getComponents(`hsl`).map((e,n)=>t[n](e)).join(`, `)})`}function Up(e,t){let n=fl(t===`float`?2:0),r=[`r`,`g`,`b`];return`{${Hf(up(e,t).getComponents(`rgb`)).map((e,t)=>`${r[t]}: ${n(e)}`).join(`, `)}}`}function Wp(e){return t=>Up(t,e)}function Gp(e,t){let n=fl(2),r=fl(t===`float`?2:0),i=[`r`,`g`,`b`,`a`];return`{${up(e,t).getComponents(`rgb`).map((e,t)=>{let a=t===3?n:r;return`${i[t]}: ${a(e)}`}).join(`, `)}}`}function Kp(e){return t=>Gp(t,e)}var qp=[{format:{alpha:!1,mode:`rgb`,notation:`hex`,type:`int`},stringifier:Lp},{format:{alpha:!0,mode:`rgb`,notation:`hex`,type:`int`},stringifier:Rp},{format:{alpha:!1,mode:`rgb`,notation:`func`,type:`int`},stringifier:zp},{format:{alpha:!0,mode:`rgb`,notation:`func`,type:`int`},stringifier:Bp},{format:{alpha:!1,mode:`hsl`,notation:`func`,type:`int`},stringifier:Vp},{format:{alpha:!0,mode:`hsl`,notation:`func`,type:`int`},stringifier:Hp},...[`int`,`float`].reduce((e,t)=>[...e,{format:{alpha:!1,mode:`rgb`,notation:`object`,type:t},stringifier:Wp(t)},{format:{alpha:!0,mode:`rgb`,notation:`object`,type:t},stringifier:Kp(t)}],[])];function Jp(e){return qp.reduce((t,n)=>t||(dp(n.format,e)?n.stringifier:null),null)}var Yp=$(`apl`),Xp=class{constructor(e,t){this.onValueChange_=this.onValueChange_.bind(this),this.value=t.value,this.value.emitter.on(`change`,this.onValueChange_),this.element=e.createElement(`div`),this.element.classList.add(Yp()),t.viewProps.bindClassModifiers(this.element),t.viewProps.bindTabIndex(this.element);let n=e.createElement(`div`);n.classList.add(Yp(`b`)),this.element.appendChild(n);let r=e.createElement(`div`);r.classList.add(Yp(`c`)),n.appendChild(r),this.colorElem_=r;let i=e.createElement(`div`);i.classList.add(Yp(`m`)),this.element.appendChild(i),this.markerElem_=i;let a=e.createElement(`div`);a.classList.add(Yp(`p`)),this.markerElem_.appendChild(a),this.previewElem_=a,this.update_()}update_(){let e=this.value.rawValue,t=e.getComponents(`rgb`),n=new Xf([t[0],t[1],t[2],0],`rgb`),r=new Xf([t[0],t[1],t[2],255],`rgb`),i=[`to right`,Bp(n),Bp(r)];this.colorElem_.style.background=`linear-gradient(${i.join(`,`)})`,this.previewElem_.style.backgroundColor=Bp(e);let a=pl(t[3],0,1,0,100);this.markerElem_.style.left=`${a}%`}onValueChange_(){this.update_()}},Zp=class{constructor(e,t){this.onKeyDown_=this.onKeyDown_.bind(this),this.onKeyUp_=this.onKeyUp_.bind(this),this.onPointerDown_=this.onPointerDown_.bind(this),this.onPointerMove_=this.onPointerMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.value=t.value,this.viewProps=t.viewProps,this.view=new Xp(e,{value:this.value,viewProps:this.viewProps}),this.ptHandler_=new uf(this.view.element),this.ptHandler_.emitter.on(`down`,this.onPointerDown_),this.ptHandler_.emitter.on(`move`,this.onPointerMove_),this.ptHandler_.emitter.on(`up`,this.onPointerUp_),this.view.element.addEventListener(`keydown`,this.onKeyDown_),this.view.element.addEventListener(`keyup`,this.onKeyUp_)}handlePointerEvent_(e,t){if(!e.point)return;let n=e.point.x/e.bounds.width,[r,i,a]=this.value.rawValue.getComponents(`hsv`);this.value.setRawValue(new Xf([r,i,a,n],`hsv`),t)}onPointerDown_(e){this.handlePointerEvent_(e.data,{forceEmit:!1,last:!1})}onPointerMove_(e){this.handlePointerEvent_(e.data,{forceEmit:!1,last:!1})}onPointerUp_(e){this.handlePointerEvent_(e.data,{forceEmit:!0,last:!0})}onKeyDown_(e){let t=rf(tp(!0),of(e));if(t===0)return;let[n,r,i,a]=this.value.rawValue.getComponents(`hsv`);this.value.setRawValue(new Xf([n,r,i,a+t],`hsv`),{forceEmit:!1,last:!1})}onKeyUp_(e){rf(tp(!0),of(e))!==0&&this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}},Qp=$(`coltxt`);function $p(e){let t=e.createElement(`select`);return t.appendChild([{text:`RGB`,value:`rgb`},{text:`HSL`,value:`hsl`},{text:`HSV`,value:`hsv`},{text:`HEX`,value:`hex`}].reduce((t,n)=>{let r=e.createElement(`option`);return r.textContent=n.text,r.value=n.value,t.appendChild(r),t},e.createDocumentFragment())),t}var em=class{constructor(e,t){this.element=e.createElement(`div`),this.element.classList.add(Qp()),t.viewProps.bindClassModifiers(this.element);let n=e.createElement(`div`);n.classList.add(Qp(`m`)),this.modeElem_=$p(e),this.modeElem_.classList.add(Qp(`ms`)),n.appendChild(this.modeSelectElement),t.viewProps.bindDisabled(this.modeElem_);let r=e.createElement(`div`);r.classList.add(Qp(`mm`)),r.appendChild($l(e,`dropdown`)),n.appendChild(r),this.element.appendChild(n);let i=e.createElement(`div`);i.classList.add(Qp(`w`)),this.element.appendChild(i),this.inputsElem_=i,this.inputViews_=t.inputViews,this.applyInputViews_(),au(t.mode,e=>{this.modeElem_.value=e})}get modeSelectElement(){return this.modeElem_}get inputViews(){return this.inputViews_}set inputViews(e){this.inputViews_=e,this.applyInputViews_()}applyInputViews_(){nu(this.inputsElem_);let e=this.element.ownerDocument;this.inputViews_.forEach(t=>{let n=e.createElement(`div`);n.classList.add(Qp(`c`)),n.appendChild(t.element),this.inputsElem_.appendChild(n)})}};function tm(e){return fl(e===`float`?2:0)}function nm(e,t,n){let r=Gf(e,t)[n];return new Oc({min:0,max:r})}function rm(e,t,n){return new pf(e,{arrayPosition:n===0?`fst`:n===2?`lst`:`mid`,parser:t.parser,props:Q.fromObject({formatter:tm(t.colorType),keyScale:tp(!1),pointerScale:t.colorType===`float`?.01:1}),value:Ec(0,{constraint:nm(t.colorMode,t.colorType,n)}),viewProps:t.viewProps})}function im(e,t){let n={colorMode:t.colorMode,colorType:t.colorType,parser:ll,viewProps:t.viewProps};return[0,1,2].map(r=>{let i=rm(e,n,r);return nf({primary:t.value,secondary:i.value,forward(e){return up(e,t.colorType).getComponents(t.colorMode)[r]},backward(e,n){let i=t.colorMode,a=up(e,t.colorType).getComponents(i);return a[r]=n,up(ap(Uf(Hf(a),a[3]),i,t.colorType),`int`)}}),i})}function am(e,t){let n=new qd(e,{parser:Pp(`int`),props:Q.fromObject({formatter:Lp}),value:Ec(Xf.black()),viewProps:t.viewProps});return nf({primary:t.value,secondary:n.value,forward:e=>new Xf(Hf(e.getComponents()),e.mode),backward:(e,t)=>new Xf(Uf(Hf(t.getComponents(e.mode)),e.getComponents()[3]),e.mode)}),[n]}function om(e){return e!==`hex`}var sm=class{constructor(e,t){this.onModeSelectChange_=this.onModeSelectChange_.bind(this),this.colorType_=t.colorType,this.value=t.value,this.viewProps=t.viewProps,this.colorMode=Ec(this.value.rawValue.mode),this.ccs_=this.createComponentControllers_(e),this.view=new em(e,{mode:this.colorMode,inputViews:[this.ccs_[0].view,this.ccs_[1].view,this.ccs_[2].view],viewProps:this.viewProps}),this.view.modeSelectElement.addEventListener(`change`,this.onModeSelectChange_)}createComponentControllers_(e){let t=this.colorMode.rawValue;return om(t)?im(e,{colorMode:t,colorType:this.colorType_,value:this.value,viewProps:this.viewProps}):am(e,{value:this.value,viewProps:this.viewProps})}onModeSelectChange_(e){let t=e.currentTarget;this.colorMode.rawValue=t.value,this.ccs_=this.createComponentControllers_(this.view.element.ownerDocument),this.view.inputViews=this.ccs_.map(e=>e.view)}},cm=$(`hpl`),lm=class{constructor(e,t){this.onValueChange_=this.onValueChange_.bind(this),this.value=t.value,this.value.emitter.on(`change`,this.onValueChange_),this.element=e.createElement(`div`),this.element.classList.add(cm()),t.viewProps.bindClassModifiers(this.element),t.viewProps.bindTabIndex(this.element);let n=e.createElement(`div`);n.classList.add(cm(`c`)),this.element.appendChild(n);let r=e.createElement(`div`);r.classList.add(cm(`m`)),this.element.appendChild(r),this.markerElem_=r,this.update_()}update_(){let[e]=this.value.rawValue.getComponents(`hsv`);this.markerElem_.style.backgroundColor=zp(new Xf([e,100,100],`hsv`));let t=pl(e,0,360,0,100);this.markerElem_.style.left=`${t}%`}onValueChange_(){this.update_()}},um=class{constructor(e,t){this.onKeyDown_=this.onKeyDown_.bind(this),this.onKeyUp_=this.onKeyUp_.bind(this),this.onPointerDown_=this.onPointerDown_.bind(this),this.onPointerMove_=this.onPointerMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.value=t.value,this.viewProps=t.viewProps,this.view=new lm(e,{value:this.value,viewProps:this.viewProps}),this.ptHandler_=new uf(this.view.element),this.ptHandler_.emitter.on(`down`,this.onPointerDown_),this.ptHandler_.emitter.on(`move`,this.onPointerMove_),this.ptHandler_.emitter.on(`up`,this.onPointerUp_),this.view.element.addEventListener(`keydown`,this.onKeyDown_),this.view.element.addEventListener(`keyup`,this.onKeyUp_)}handlePointerEvent_(e,t){if(!e.point)return;let n=pl(hl(e.point.x,0,e.bounds.width),0,e.bounds.width,0,360),[,r,i,a]=this.value.rawValue.getComponents(`hsv`);this.value.setRawValue(new Xf([n,r,i,a],`hsv`),t)}onPointerDown_(e){this.handlePointerEvent_(e.data,{forceEmit:!1,last:!1})}onPointerMove_(e){this.handlePointerEvent_(e.data,{forceEmit:!1,last:!1})}onPointerUp_(e){this.handlePointerEvent_(e.data,{forceEmit:!0,last:!0})}onKeyDown_(e){let t=rf(tp(!1),of(e));if(t===0)return;let[n,r,i,a]=this.value.rawValue.getComponents(`hsv`);this.value.setRawValue(new Xf([n+t,r,i,a],`hsv`),{forceEmit:!1,last:!1})}onKeyUp_(e){rf(tp(!1),of(e))!==0&&this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}},dm=$(`svp`),fm=64,pm=class{constructor(e,t){this.onValueChange_=this.onValueChange_.bind(this),this.value=t.value,this.value.emitter.on(`change`,this.onValueChange_),this.element=e.createElement(`div`),this.element.classList.add(dm()),t.viewProps.bindClassModifiers(this.element),t.viewProps.bindTabIndex(this.element);let n=e.createElement(`canvas`);n.height=fm,n.width=fm,n.classList.add(dm(`c`)),this.element.appendChild(n),this.canvasElement=n;let r=e.createElement(`div`);r.classList.add(dm(`m`)),this.element.appendChild(r),this.markerElem_=r,this.update_()}update_(){let e=Zl(this.canvasElement);if(!e)return;let t=this.value.rawValue.getComponents(`hsv`),n=this.canvasElement.width,r=this.canvasElement.height,i=e.getImageData(0,0,n,r),a=i.data;for(let e=0;ee.getComponents()[3],backward:(e,t)=>{let n=e.getComponents();return n[3]=t,new Xf(n,e.mode)}}),this.textsC_=new sm(e,{colorType:t.colorType,value:this.value,viewProps:this.viewProps}),this.view=new Qf(e,{alphaViews:this.alphaIcs_?{palette:this.alphaIcs_.palette.view,text:this.alphaIcs_.text.view}:null,hPaletteView:this.hPaletteC_.view,supportsAlpha:t.supportsAlpha,svPaletteView:this.svPaletteC_.view,textsView:this.textsC_.view,viewProps:this.viewProps})}get textsController(){return this.textsC_}},gm=$(`colsw`),_m=class{constructor(e,t){this.onValueChange_=this.onValueChange_.bind(this),t.value.emitter.on(`change`,this.onValueChange_),this.value=t.value,this.element=e.createElement(`div`),this.element.classList.add(gm()),t.viewProps.bindClassModifiers(this.element);let n=e.createElement(`div`);n.classList.add(gm(`sw`)),this.element.appendChild(n),this.swatchElem_=n;let r=e.createElement(`button`);r.classList.add(gm(`b`)),t.viewProps.bindDisabled(r),this.element.appendChild(r),this.buttonElement=r,this.update_()}update_(){let e=this.value.rawValue;this.swatchElem_.style.backgroundColor=Rp(e)}onValueChange_(){this.update_()}},vm=class{constructor(e,t){this.value=t.value,this.viewProps=t.viewProps,this.view=new _m(e,{value:this.value,viewProps:this.viewProps})}},ym=class{constructor(e,t){this.onButtonBlur_=this.onButtonBlur_.bind(this),this.onButtonClick_=this.onButtonClick_.bind(this),this.onPopupChildBlur_=this.onPopupChildBlur_.bind(this),this.onPopupChildKeydown_=this.onPopupChildKeydown_.bind(this),this.value=t.value,this.viewProps=t.viewProps,this.foldable_=rd.create(t.expanded),this.swatchC_=new vm(e,{value:this.value,viewProps:this.viewProps});let n=this.swatchC_.view.buttonElement;n.addEventListener(`blur`,this.onButtonBlur_),n.addEventListener(`click`,this.onButtonClick_),this.textC_=new qd(e,{parser:t.parser,props:Q.fromObject({formatter:t.formatter}),value:this.value,viewProps:this.viewProps}),this.view=new Ff(e,{foldable:this.foldable_,pickerLayout:t.pickerLayout}),this.view.swatchElement.appendChild(this.swatchC_.view.element),this.view.textElement.appendChild(this.textC_.view.element),this.popC_=t.pickerLayout===`popup`?new Wd(e,{viewProps:this.viewProps}):null;let r=new hm(e,{colorType:t.colorType,supportsAlpha:t.supportsAlpha,value:this.value,viewProps:this.viewProps});r.view.allFocusableElements.forEach(e=>{e.addEventListener(`blur`,this.onPopupChildBlur_),e.addEventListener(`keydown`,this.onPopupChildKeydown_)}),this.pickerC_=r,this.popC_?(this.view.element.appendChild(this.popC_.view.element),this.popC_.view.element.appendChild(r.view.element),nf({primary:this.foldable_.value(`expanded`),secondary:this.popC_.shows,forward:e=>e,backward:(e,t)=>t})):this.view.pickerElement&&(this.view.pickerElement.appendChild(this.pickerC_.view.element),od(this.foldable_,this.view.pickerElement))}get textController(){return this.textC_}onButtonBlur_(e){if(!this.popC_)return;let t=this.view.element,n=fc(e.relatedTarget);(!n||!t.contains(n))&&(this.popC_.shows.rawValue=!1)}onButtonClick_(){this.foldable_.set(`expanded`,!this.foldable_.get(`expanded`)),this.foldable_.get(`expanded`)&&this.pickerC_.view.allFocusableElements[0].focus()}onPopupChildBlur_(e){if(!this.popC_)return;let t=this.popC_.view.element,n=iu(e);n&&t.contains(n)||n&&n===this.swatchC_.view.buttonElement&&!Jl(t.ownerDocument)||(this.popC_.shows.rawValue=!1)}onPopupChildKeydown_(e){this.popC_?e.key===`Escape`&&(this.popC_.shows.rawValue=!1):this.view.pickerElement&&e.key===`Escape`&&this.swatchC_.view.buttonElement.focus()}};function bm(e){return Hf(e.getComponents(`rgb`)).reduce((e,t)=>e<<8|Math.floor(t)&255,0)}function xm(e){return e.getComponents(`rgb`).reduce((e,t,n)=>{let r=Math.floor(n===3?t*255:t)&255;return e<<8|r},0)>>>0}function Sm(e){return new Xf([e>>16&255,e>>8&255,e&255],`rgb`)}function Cm(e){return new Xf([e>>24&255,e>>16&255,e>>8&255,pl(e&255,0,255,0,1)],`rgb`)}function wm(e){return typeof e==`number`?Sm(e):Xf.black()}function Tm(e){return typeof e==`number`?Cm(e):Xf.black()}function Em(e,t){return typeof e!=`object`||pc(e)?!1:t in e&&typeof e[t]==`number`}function Dm(e){return Em(e,`r`)&&Em(e,`g`)&&Em(e,`b`)}function Om(e){return Dm(e)&&Em(e,`a`)}function km(e){return Dm(e)}function Am(e,t){if(e.mode!==t.mode||e.type!==t.type)return!1;let n=e.getComponents(),r=t.getComponents();for(let e=0;e{Of(e,t(n))}:null}function Nm(e){let t=e?xm:bm;return(e,n)=>{Of(e,t(n))}}function Pm(e,t,n){let r=up(t,n).toRgbaObject();e.writeProperty(`r`,r.r),e.writeProperty(`g`,r.g),e.writeProperty(`b`,r.b),e.writeProperty(`a`,r.a)}function Fm(e,t,n){let r=up(t,n).toRgbaObject();e.writeProperty(`r`,r.r),e.writeProperty(`g`,r.g),e.writeProperty(`b`,r.b)}function Im(e,t){return(n,r)=>{e?Pm(n,r,t):Fm(n,r,t)}}function Lm(e){return!!e?.color?.alpha}function Rm(e){return e?e=>Rp(e,`0x`):e=>Lp(e,`0x`)}function zm(e){return`color`in e||e.view===`color`}var Bm=Bu({id:`input-color-number`,type:`input`,accept:(e,t)=>{if(typeof e!=`number`||!zm(t))return null;let n=ep(t);return n?{initialValue:e,params:Object.assign(Object.assign({},n),{supportsAlpha:Lm(t)})}:null},binding:{reader:e=>e.params.supportsAlpha?Tm:wm,equals:Am,writer:e=>Nm(e.params.supportsAlpha)},controller:e=>new ym(e.document,{colorType:`int`,expanded:e.params.expanded??!1,formatter:Rm(e.params.supportsAlpha),parser:Pp(`int`),pickerLayout:e.params.picker??`popup`,supportsAlpha:e.params.supportsAlpha,value:e.value,viewProps:e.viewProps})});function Vm(e,t){return km(e)?t===`int`?new Xf(jm(e),`rgb`):t===`float`?new rp(jm(e),`rgb`):up(Xf.black(),`int`):up(Xf.black(),t)}function Hm(e){return Om(e)}function Um(e){return t=>up(Vm(t,e),`int`)}function Wm(e,t){return n=>e?Gp(n,t):Up(n,t)}var Gm=Bu({id:`input-color-object`,type:`input`,accept:(e,t)=>{if(!km(e))return null;let n=ep(t);return n?{initialValue:e,params:Object.assign(Object.assign({},n),{colorType:np(t)??`int`})}:null},binding:{reader:e=>Um(e.params.colorType),equals:Am,writer:e=>Im(Hm(e.initialValue),e.params.colorType)},controller:e=>{let t=Om(e.initialValue);return new ym(e.document,{colorType:e.params.colorType,expanded:e.params.expanded??!1,formatter:Wm(t,e.params.colorType),parser:Pp(`int`),pickerLayout:e.params.picker??`popup`,supportsAlpha:t,value:e.value,viewProps:e.viewProps})}}),Km=Bu({id:`input-color-string`,type:`input`,accept:(e,t)=>{if(typeof e!=`string`||t.view===`text`)return null;let n=Np(e,np(t));if(!n)return null;let r=Jp(n);if(!r)return null;let i=ep(t);return i?{initialValue:e,params:Object.assign(Object.assign({},i),{format:n,stringifier:r})}:null},binding:{reader:()=>Fp,equals:Am,writer:e=>{let t=Mm(e.params.format);if(!t)throw bc.notBindable();return t}},controller:e=>new ym(e.document,{colorType:e.params.format.type,expanded:e.params.expanded??!1,formatter:e.params.stringifier,parser:Pp(`int`),pickerLayout:e.params.picker??`popup`,supportsAlpha:e.params.format.alpha,value:e.value,viewProps:e.viewProps})}),qm=class{constructor(e){this.components=e.components,this.asm_=e.assembly}constrain(e){let t=this.asm_.toComponents(e).map((e,t)=>this.components[t]?.constrain(e)??e);return this.asm_.fromComponents(t)}},Jm=$(`pndtxt`),Ym=class{constructor(e,t){this.textViews=t.textViews,this.element=e.createElement(`div`),this.element.classList.add(Jm()),this.textViews.forEach(t=>{let n=e.createElement(`div`);n.classList.add(Jm(`a`)),n.appendChild(t.element),this.element.appendChild(n)})}};function Xm(e,t,n){return new pf(e,{arrayPosition:n===0?`fst`:n===t.axes.length-1?`lst`:`mid`,parser:t.parser,props:t.axes[n].textProps,value:Ec(0,{constraint:t.axes[n].constraint}),viewProps:t.viewProps})}var Zm=class{constructor(e,t){this.value=t.value,this.viewProps=t.viewProps,this.acs_=t.axes.map((n,r)=>Xm(e,t,r)),this.acs_.forEach((e,n)=>{nf({primary:this.value,secondary:e.value,forward:e=>t.assembly.toComponents(e)[n],backward:(e,r)=>{let i=t.assembly.toComponents(e);return i[n]=r,t.assembly.fromComponents(i)}})}),this.view=new Ym(e,{textViews:this.acs_.map(e=>e.view)})}get textControllers(){return this.acs_}},Qm=class extends jl{get max(){return this.controller.valueController.sliderController.props.get(`max`)}set max(e){this.controller.valueController.sliderController.props.set(`max`,e)}get min(){return this.controller.valueController.sliderController.props.get(`min`)}set min(e){this.controller.valueController.sliderController.props.set(`min`,e)}};function $m(e,t){let n=[],r=bl(e,t);r&&n.push(r);let i=xl(e);i&&n.push(i);let a=Rd(e.options);return a&&n.push(a),new Nd(n)}var eh=Bu({id:`input-number`,type:`input`,accept:(e,t)=>{if(typeof e!=`number`)return null;let n=Bl(t,e=>Object.assign(Object.assign({},Cl(e)),{options:e.optional.custom(Id),readonly:e.optional.constant(!1)}));return n?{initialValue:e,params:n}:null},binding:{reader:e=>ul,constraint:e=>$m(e.params,e.initialValue),writer:e=>Of},controller:e=>{let t=e.value,n=e.constraint,r=n&&Pd(n,Fd);if(r)return new Vd(e.document,{props:new Q({options:r.values.value(`options`)}),value:t,viewProps:e.viewProps});let i=Sl(e.params,t.rawValue),a=n&&Pd(n,Oc);return a?new yf(e.document,Object.assign(Object.assign({},bf(Object.assign(Object.assign({},i),{keyScale:Ec(i.keyScale),max:a.values.value(`max`),min:a.values.value(`min`)}))),{parser:ll,value:t,viewProps:e.viewProps})):new pf(e.document,{parser:ll,props:Q.fromObject(i),value:t,viewProps:e.viewProps})},api(e){return typeof e.controller.value.rawValue==`number`?e.controller.valueController instanceof yf?new Qm(e.controller):e.controller.valueController instanceof Vd?new Ad(e.controller):null:null}}),th=class{constructor(e=0,t=0){this.x=e,this.y=t}getComponents(){return[this.x,this.y]}static isObject(e){if(pc(e))return!1;let t=e.x,n=e.y;return!(typeof t!=`number`||typeof n!=`number`)}static equals(e,t){return e.x===t.x&&e.y===t.y}toObject(){return{x:this.x,y:this.y}}},nh={toComponents:e=>e.getComponents(),fromComponents:e=>new th(...e)},rh=$(`p2d`),ih=class{constructor(e,t){this.element=e.createElement(`div`),this.element.classList.add(rh()),t.viewProps.bindClassModifiers(this.element),au(t.expanded,Mu(this.element,rh(void 0,`expanded`)));let n=e.createElement(`div`);n.classList.add(rh(`h`)),this.element.appendChild(n);let r=e.createElement(`button`);r.classList.add(rh(`b`)),r.appendChild($l(e,`p2dpad`)),t.viewProps.bindDisabled(r),n.appendChild(r),this.buttonElement=r;let i=e.createElement(`div`);if(i.classList.add(rh(`t`)),n.appendChild(i),this.textElement=i,t.pickerLayout===`inline`){let t=e.createElement(`div`);t.classList.add(rh(`p`)),this.element.appendChild(t),this.pickerElement=t}else this.pickerElement=null}},ah=$(`p2dp`),oh=class{constructor(e,t){this.onFoldableChange_=this.onFoldableChange_.bind(this),this.onPropsChange_=this.onPropsChange_.bind(this),this.onValueChange_=this.onValueChange_.bind(this),this.props_=t.props,this.props_.emitter.on(`change`,this.onPropsChange_),this.element=e.createElement(`div`),this.element.classList.add(ah()),t.layout===`popup`&&this.element.classList.add(ah(void 0,`p`)),t.viewProps.bindClassModifiers(this.element);let n=e.createElement(`div`);n.classList.add(ah(`p`)),t.viewProps.bindTabIndex(n),this.element.appendChild(n),this.padElement=n;let r=e.createElementNS(Gl,`svg`);r.classList.add(ah(`g`)),this.padElement.appendChild(r),this.svgElem_=r;let i=e.createElementNS(Gl,`line`);i.classList.add(ah(`ax`)),i.setAttributeNS(null,`x1`,`0`),i.setAttributeNS(null,`y1`,`50%`),i.setAttributeNS(null,`x2`,`100%`),i.setAttributeNS(null,`y2`,`50%`),this.svgElem_.appendChild(i);let a=e.createElementNS(Gl,`line`);a.classList.add(ah(`ax`)),a.setAttributeNS(null,`x1`,`50%`),a.setAttributeNS(null,`y1`,`0`),a.setAttributeNS(null,`x2`,`50%`),a.setAttributeNS(null,`y2`,`100%`),this.svgElem_.appendChild(a);let o=e.createElementNS(Gl,`line`);o.classList.add(ah(`l`)),o.setAttributeNS(null,`x1`,`50%`),o.setAttributeNS(null,`y1`,`50%`),this.svgElem_.appendChild(o),this.lineElem_=o;let s=e.createElement(`div`);s.classList.add(ah(`m`)),this.padElement.appendChild(s),this.markerElem_=s,t.value.emitter.on(`change`,this.onValueChange_),this.value=t.value,this.update_()}get allFocusableElements(){return[this.padElement]}update_(){let[e,t]=this.value.rawValue.getComponents(),n=this.props_.get(`max`),r=pl(e,-n,+n,0,100),i=pl(t,-n,+n,0,100),a=this.props_.get(`invertsY`)?100-i:i;this.lineElem_.setAttributeNS(null,`x2`,`${r}%`),this.lineElem_.setAttributeNS(null,`y2`,`${a}%`),this.markerElem_.style.left=`${r}%`,this.markerElem_.style.top=`${a}%`}onValueChange_(){this.update_()}onPropsChange_(){this.update_()}onFoldableChange_(){this.update_()}};function sh(e,t,n){return[rf(t[0],of(e)),rf(t[1],af(e))*(n?1:-1)]}var ch=class{constructor(e,t){this.onPadKeyDown_=this.onPadKeyDown_.bind(this),this.onPadKeyUp_=this.onPadKeyUp_.bind(this),this.onPointerDown_=this.onPointerDown_.bind(this),this.onPointerMove_=this.onPointerMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.props=t.props,this.value=t.value,this.viewProps=t.viewProps,this.view=new oh(e,{layout:t.layout,props:this.props,value:this.value,viewProps:this.viewProps}),this.ptHandler_=new uf(this.view.padElement),this.ptHandler_.emitter.on(`down`,this.onPointerDown_),this.ptHandler_.emitter.on(`move`,this.onPointerMove_),this.ptHandler_.emitter.on(`up`,this.onPointerUp_),this.view.padElement.addEventListener(`keydown`,this.onPadKeyDown_),this.view.padElement.addEventListener(`keyup`,this.onPadKeyUp_)}handlePointerEvent_(e,t){if(!e.point)return;let n=this.props.get(`max`),r=pl(e.point.x,0,e.bounds.width,-n,+n),i=pl(this.props.get(`invertsY`)?e.bounds.height-e.point.y:e.point.y,0,e.bounds.height,-n,+n);this.value.setRawValue(new th(r,i),t)}onPointerDown_(e){this.handlePointerEvent_(e.data,{forceEmit:!1,last:!1})}onPointerMove_(e){this.handlePointerEvent_(e.data,{forceEmit:!1,last:!1})}onPointerUp_(e){this.handlePointerEvent_(e.data,{forceEmit:!0,last:!0})}onPadKeyDown_(e){cf(e.key)&&e.preventDefault();let[t,n]=sh(e,[this.props.get(`xKeyScale`),this.props.get(`yKeyScale`)],this.props.get(`invertsY`));t===0&&n===0||this.value.setRawValue(new th(this.value.rawValue.x+t,this.value.rawValue.y+n),{forceEmit:!1,last:!1})}onPadKeyUp_(e){let[t,n]=sh(e,[this.props.get(`xKeyScale`),this.props.get(`yKeyScale`)],this.props.get(`invertsY`));t===0&&n===0||this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}},lh=class{constructor(e,t){var n,r;this.onPopupChildBlur_=this.onPopupChildBlur_.bind(this),this.onPopupChildKeydown_=this.onPopupChildKeydown_.bind(this),this.onPadButtonBlur_=this.onPadButtonBlur_.bind(this),this.onPadButtonClick_=this.onPadButtonClick_.bind(this),this.value=t.value,this.viewProps=t.viewProps,this.foldable_=rd.create(t.expanded),this.popC_=t.pickerLayout===`popup`?new Wd(e,{viewProps:this.viewProps}):null;let i=new ch(e,{layout:t.pickerLayout,props:new Q({invertsY:Ec(t.invertsY),max:Ec(t.max),xKeyScale:t.axes[0].textProps.value(`keyScale`),yKeyScale:t.axes[1].textProps.value(`keyScale`)}),value:this.value,viewProps:this.viewProps});i.view.allFocusableElements.forEach(e=>{e.addEventListener(`blur`,this.onPopupChildBlur_),e.addEventListener(`keydown`,this.onPopupChildKeydown_)}),this.pickerC_=i,this.textC_=new Zm(e,{assembly:nh,axes:t.axes,parser:t.parser,value:this.value,viewProps:this.viewProps}),this.view=new ih(e,{expanded:this.foldable_.value(`expanded`),pickerLayout:t.pickerLayout,viewProps:this.viewProps}),this.view.textElement.appendChild(this.textC_.view.element),(n=this.view.buttonElement)==null||n.addEventListener(`blur`,this.onPadButtonBlur_),(r=this.view.buttonElement)==null||r.addEventListener(`click`,this.onPadButtonClick_),this.popC_?(this.view.element.appendChild(this.popC_.view.element),this.popC_.view.element.appendChild(this.pickerC_.view.element),nf({primary:this.foldable_.value(`expanded`),secondary:this.popC_.shows,forward:e=>e,backward:(e,t)=>t})):this.view.pickerElement&&(this.view.pickerElement.appendChild(this.pickerC_.view.element),od(this.foldable_,this.view.pickerElement))}get textController(){return this.textC_}onPadButtonBlur_(e){if(!this.popC_)return;let t=this.view.element,n=fc(e.relatedTarget);(!n||!t.contains(n))&&(this.popC_.shows.rawValue=!1)}onPadButtonClick_(){this.foldable_.set(`expanded`,!this.foldable_.get(`expanded`)),this.foldable_.get(`expanded`)&&this.pickerC_.view.allFocusableElements[0].focus()}onPopupChildBlur_(e){if(!this.popC_)return;let t=this.popC_.view.element,n=iu(e);n&&t.contains(n)||n&&n===this.view.buttonElement&&!Jl(t.ownerDocument)||(this.popC_.shows.rawValue=!1)}onPopupChildKeydown_(e){this.popC_?e.key===`Escape`&&(this.popC_.shows.rawValue=!1):this.view.pickerElement&&e.key===`Escape`&&this.view.buttonElement.focus()}};function uh(e){return th.isObject(e)?new th(e.x,e.y):new th}function dh(e,t){e.writeProperty(`x`,t.x),e.writeProperty(`y`,t.y)}function fh(e,t){return new qm({assembly:nh,components:[Tf(Object.assign(Object.assign({},e),e.x),t.x),Tf(Object.assign(Object.assign({},e),e.y),t.y)]})}function ph(e,t){if(!pc(e.min)||!pc(e.max))return Math.max(Math.abs(e.min??0),Math.abs(e.max??0));let n=vl(e);return Math.max(Math.abs(n)*10,Math.abs(t)*10)}function mh(e,t){let n=ph(_c(e,e.x??{}),t.x),r=ph(_c(e,e.y??{}),t.y);return Math.max(n,r)}function hh(e){if(!(`y`in e))return!1;let t=e.y;return t&&`inverted`in t?!!t.inverted:!1}var gh=Bu({id:`input-point2d`,type:`input`,accept:(e,t)=>{if(!th.isObject(e))return null;let n=Bl(t,e=>Object.assign(Object.assign({},Cf(e)),{expanded:e.optional.boolean,picker:e.optional.custom(Df),readonly:e.optional.constant(!1),x:e.optional.custom(wf),y:e.optional.object(Object.assign(Object.assign({},Cf(e)),{inverted:e.optional.boolean}))}));return n?{initialValue:e,params:n}:null},binding:{reader:()=>uh,constraint:e=>fh(e.params,e.initialValue),equals:th.equals,writer:()=>dh},controller:e=>{let t=e.document,n=e.value,r=e.constraint,i=[e.params.x,e.params.y];return new lh(t,{axes:n.rawValue.getComponents().map((t,n)=>wl({constraint:r.components[n],initialValue:t,params:_c(e.params,i[n]??{})})),expanded:e.params.expanded??!1,invertsY:hh(e.params),max:mh(e.params,n.rawValue),parser:ll,pickerLayout:e.params.picker??`popup`,value:n,viewProps:e.viewProps})}}),_h=class{constructor(e=0,t=0,n=0){this.x=e,this.y=t,this.z=n}getComponents(){return[this.x,this.y,this.z]}static isObject(e){if(pc(e))return!1;let t=e.x,n=e.y,r=e.z;return!(typeof t!=`number`||typeof n!=`number`||typeof r!=`number`)}static equals(e,t){return e.x===t.x&&e.y===t.y&&e.z===t.z}toObject(){return{x:this.x,y:this.y,z:this.z}}},vh={toComponents:e=>e.getComponents(),fromComponents:e=>new _h(...e)};function yh(e){return _h.isObject(e)?new _h(e.x,e.y,e.z):new _h}function bh(e,t){e.writeProperty(`x`,t.x),e.writeProperty(`y`,t.y),e.writeProperty(`z`,t.z)}function xh(e,t){return new qm({assembly:vh,components:[Tf(Object.assign(Object.assign({},e),e.x),t.x),Tf(Object.assign(Object.assign({},e),e.y),t.y),Tf(Object.assign(Object.assign({},e),e.z),t.z)]})}var Sh=Bu({id:`input-point3d`,type:`input`,accept:(e,t)=>{if(!_h.isObject(e))return null;let n=Bl(t,e=>Object.assign(Object.assign({},Cf(e)),{readonly:e.optional.constant(!1),x:e.optional.custom(wf),y:e.optional.custom(wf),z:e.optional.custom(wf)}));return n?{initialValue:e,params:n}:null},binding:{reader:e=>yh,constraint:e=>xh(e.params,e.initialValue),equals:_h.equals,writer:e=>bh},controller:e=>{let t=e.value,n=e.constraint,r=[e.params.x,e.params.y,e.params.z];return new Zm(e.document,{assembly:vh,axes:t.rawValue.getComponents().map((t,i)=>wl({constraint:n.components[i],initialValue:t,params:_c(e.params,r[i]??{})})),parser:ll,value:t,viewProps:e.viewProps})}}),Ch=class{constructor(e=0,t=0,n=0,r=0){this.x=e,this.y=t,this.z=n,this.w=r}getComponents(){return[this.x,this.y,this.z,this.w]}static isObject(e){if(pc(e))return!1;let t=e.x,n=e.y,r=e.z,i=e.w;return!(typeof t!=`number`||typeof n!=`number`||typeof r!=`number`||typeof i!=`number`)}static equals(e,t){return e.x===t.x&&e.y===t.y&&e.z===t.z&&e.w===t.w}toObject(){return{x:this.x,y:this.y,z:this.z,w:this.w}}},wh={toComponents:e=>e.getComponents(),fromComponents:e=>new Ch(...e)};function Th(e){return Ch.isObject(e)?new Ch(e.x,e.y,e.z,e.w):new Ch}function Eh(e,t){e.writeProperty(`x`,t.x),e.writeProperty(`y`,t.y),e.writeProperty(`z`,t.z),e.writeProperty(`w`,t.w)}function Dh(e,t){return new qm({assembly:wh,components:[Tf(Object.assign(Object.assign({},e),e.x),t.x),Tf(Object.assign(Object.assign({},e),e.y),t.y),Tf(Object.assign(Object.assign({},e),e.z),t.z),Tf(Object.assign(Object.assign({},e),e.w),t.w)]})}var Oh=Bu({id:`input-point4d`,type:`input`,accept:(e,t)=>{if(!Ch.isObject(e))return null;let n=Bl(t,e=>Object.assign(Object.assign({},Cf(e)),{readonly:e.optional.constant(!1),w:e.optional.custom(wf),x:e.optional.custom(wf),y:e.optional.custom(wf),z:e.optional.custom(wf)}));return n?{initialValue:e,params:n}:null},binding:{reader:e=>Th,constraint:e=>Dh(e.params,e.initialValue),equals:Ch.equals,writer:e=>Eh},controller:e=>{let t=e.value,n=e.constraint,r=[e.params.x,e.params.y,e.params.z,e.params.w];return new Zm(e.document,{assembly:wh,axes:t.rawValue.getComponents().map((t,i)=>wl({constraint:n.components[i],initialValue:t,params:_c(e.params,r[i]??{})})),parser:ll,value:t,viewProps:e.viewProps})}});function kh(e){let t=[],n=Rd(e.options);return n&&t.push(n),new Nd(t)}var Ah=Bu({id:`input-string`,type:`input`,accept:(e,t)=>{if(typeof e!=`string`)return null;let n=Bl(t,e=>({readonly:e.optional.constant(!1),options:e.optional.custom(Id)}));return n?{initialValue:e,params:n}:null},binding:{reader:e=>ef,constraint:e=>kh(e.params),writer:e=>Of},controller:e=>{let t=e.document,n=e.value,r=e.constraint,i=r&&Pd(r,Fd);return i?new Vd(t,{props:new Q({options:i.values.value(`options`)}),value:n,viewProps:e.viewProps}):new qd(t,{parser:e=>e,props:Q.fromObject({formatter:tf}),value:n,viewProps:e.viewProps})},api(e){return typeof e.controller.value.rawValue==`string`&&e.controller.valueController instanceof Vd?new Ad(e.controller):null}}),jh={monitor:{defaultInterval:200,defaultRows:3}},Mh=$(`mll`),Nh=class{constructor(e,t){this.onValueUpdate_=this.onValueUpdate_.bind(this),this.formatter_=t.formatter,this.element=e.createElement(`div`),this.element.classList.add(Mh()),t.viewProps.bindClassModifiers(this.element);let n=e.createElement(`textarea`);n.classList.add(Mh(`i`)),n.style.height=`calc(var(${Sf(`containerUnitSize`)}) * ${t.rows})`,n.readOnly=!0,t.viewProps.bindDisabled(n),this.element.appendChild(n),this.textareaElem_=n,t.value.emitter.on(`change`,this.onValueUpdate_),this.value=t.value,this.update_()}update_(){let e=this.textareaElem_,t=e.scrollTop===e.scrollHeight-e.clientHeight,n=[];this.value.rawValue.forEach(e=>{e!==void 0&&n.push(this.formatter_(e))}),e.textContent=n.join(` `),t&&(e.scrollTop=e.scrollHeight)}onValueUpdate_(){this.update_()}},Ph=class{constructor(e,t){this.value=t.value,this.viewProps=t.viewProps,this.view=new Nh(e,{formatter:t.formatter,rows:t.rows,value:this.value,viewProps:this.viewProps})}},Fh=$(`sgl`),Ih=class{constructor(e,t){this.onValueUpdate_=this.onValueUpdate_.bind(this),this.formatter_=t.formatter,this.element=e.createElement(`div`),this.element.classList.add(Fh()),t.viewProps.bindClassModifiers(this.element);let n=e.createElement(`input`);n.classList.add(Fh(`i`)),n.readOnly=!0,n.type=`text`,t.viewProps.bindDisabled(n),this.element.appendChild(n),this.inputElement=n,t.value.emitter.on(`change`,this.onValueUpdate_),this.value=t.value,this.update_()}update_(){let e=this.value.rawValue,t=e[e.length-1];this.inputElement.value=t===void 0?``:this.formatter_(t)}onValueUpdate_(){this.update_()}},Lh=class{constructor(e,t){this.value=t.value,this.viewProps=t.viewProps,this.view=new Ih(e,{formatter:t.formatter,value:this.value,viewProps:this.viewProps})}},Rh=Bu({id:`monitor-bool`,type:`monitor`,accept:(e,t)=>{if(typeof e!=`boolean`)return null;let n=Bl(t,e=>({readonly:e.required.constant(!0),rows:e.optional.number}));return n?{initialValue:e,params:n}:null},binding:{reader:e=>Yd},controller:e=>e.value.rawValue.length===1?new Lh(e.document,{formatter:Xd,value:e.value,viewProps:e.viewProps}):new Ph(e.document,{formatter:Xd,rows:e.params.rows??jh.monitor.defaultRows,value:e.value,viewProps:e.viewProps})}),zh=class extends jl{get max(){return this.controller.valueController.props.get(`max`)}set max(e){this.controller.valueController.props.set(`max`,e)}get min(){return this.controller.valueController.props.get(`min`)}set min(e){this.controller.valueController.props.set(`min`,e)}},Bh=$(`grl`),Vh=class{constructor(e,t){this.onCursorChange_=this.onCursorChange_.bind(this),this.onValueUpdate_=this.onValueUpdate_.bind(this),this.element=e.createElement(`div`),this.element.classList.add(Bh()),t.viewProps.bindClassModifiers(this.element),this.formatter_=t.formatter,this.props_=t.props,this.cursor_=t.cursor,this.cursor_.emitter.on(`change`,this.onCursorChange_);let n=e.createElementNS(Gl,`svg`);n.classList.add(Bh(`g`)),n.style.height=`calc(var(${Sf(`containerUnitSize`)}) * ${t.rows})`,this.element.appendChild(n),this.svgElem_=n;let r=e.createElementNS(Gl,`polyline`);this.svgElem_.appendChild(r),this.lineElem_=r;let i=e.createElement(`div`);i.classList.add(Bh(`t`),$(`tt`)()),this.element.appendChild(i),this.tooltipElem_=i,t.value.emitter.on(`change`,this.onValueUpdate_),this.value=t.value,this.update_()}get graphElement(){return this.svgElem_}update_(){let{clientWidth:e,clientHeight:t}=this.element,n=this.value.rawValue.length-1,r=this.props_.get(`min`),i=this.props_.get(`max`),a=[];this.value.rawValue.forEach((o,s)=>{if(o===void 0)return;let c=pl(s,0,n,0,e),l=pl(o,r,i,t,0);a.push([c,l].join(`,`))}),this.lineElem_.setAttributeNS(null,`points`,a.join(` `));let o=this.tooltipElem_,s=this.value.rawValue[this.cursor_.rawValue];if(s===void 0){o.classList.remove(Bh(`t`,`a`));return}let c=pl(this.cursor_.rawValue,0,n,0,e),l=pl(s,r,i,t,0);o.style.left=`${c}px`,o.style.top=`${l}px`,o.textContent=`${this.formatter_(s)}`,o.classList.contains(Bh(`t`,`a`))||(o.classList.add(Bh(`t`,`a`),Bh(`t`,`in`)),Kl(o),o.classList.remove(Bh(`t`,`in`)))}onValueUpdate_(){this.update_()}onCursorChange_(){this.update_()}},Hh=class{constructor(e,t){if(this.onGraphMouseMove_=this.onGraphMouseMove_.bind(this),this.onGraphMouseLeave_=this.onGraphMouseLeave_.bind(this),this.onGraphPointerDown_=this.onGraphPointerDown_.bind(this),this.onGraphPointerMove_=this.onGraphPointerMove_.bind(this),this.onGraphPointerUp_=this.onGraphPointerUp_.bind(this),this.props=t.props,this.value=t.value,this.viewProps=t.viewProps,this.cursor_=Ec(-1),this.view=new Vh(e,{cursor:this.cursor_,formatter:t.formatter,rows:t.rows,props:this.props,value:this.value,viewProps:this.viewProps}),!Jl(e))this.view.element.addEventListener(`mousemove`,this.onGraphMouseMove_),this.view.element.addEventListener(`mouseleave`,this.onGraphMouseLeave_);else{let e=new uf(this.view.element);e.emitter.on(`down`,this.onGraphPointerDown_),e.emitter.on(`move`,this.onGraphPointerMove_),e.emitter.on(`up`,this.onGraphPointerUp_)}}importProps(e){return Vl(e,null,e=>({max:e.required.number,min:e.required.number}),e=>(this.props.set(`max`,e.max),this.props.set(`min`,e.min),!0))}exportProps(){return Hl(null,{max:this.props.get(`max`),min:this.props.get(`min`)})}onGraphMouseLeave_(){this.cursor_.rawValue=-1}onGraphMouseMove_(e){let{clientWidth:t}=this.view.element;this.cursor_.rawValue=Math.floor(pl(e.offsetX,0,t,0,this.value.rawValue.length))}onGraphPointerDown_(e){this.onGraphPointerMove_(e)}onGraphPointerMove_(e){if(!e.data.point){this.cursor_.rawValue=-1;return}this.cursor_.rawValue=Math.floor(pl(e.data.point.x,0,e.data.bounds.width,0,this.value.rawValue.length))}onGraphPointerUp_(){this.cursor_.rawValue=-1}};function Uh(e){return pc(e.format)?fl(2):e.format}function Wh(e){return e.value.rawValue.length===1?new Lh(e.document,{formatter:Uh(e.params),value:e.value,viewProps:e.viewProps}):new Ph(e.document,{formatter:Uh(e.params),rows:e.params.rows??jh.monitor.defaultRows,value:e.value,viewProps:e.viewProps})}function Gh(e){return new Hh(e.document,{formatter:Uh(e.params),rows:e.params.rows??jh.monitor.defaultRows,props:Q.fromObject({max:e.params.max??100,min:e.params.min??0}),value:e.value,viewProps:e.viewProps})}function Kh(e){return e.view===`graph`}var qh=Bu({id:`monitor-number`,type:`monitor`,accept:(e,t)=>{if(typeof e!=`number`)return null;let n=Bl(t,e=>({format:e.optional.function,max:e.optional.number,min:e.optional.number,readonly:e.required.constant(!0),rows:e.optional.number,view:e.optional.string}));return n?{initialValue:e,params:n}:null},binding:{defaultBufferSize:e=>Kh(e)?64:1,reader:e=>ul},controller:e=>Kh(e.params)?Gh(e):Wh(e),api:e=>e.controller.valueController instanceof Hh?new zh(e.controller):null}),Jh=Bu({id:`monitor-string`,type:`monitor`,accept:(e,t)=>{if(typeof e!=`string`)return null;let n=Bl(t,e=>({multiline:e.optional.boolean,readonly:e.required.constant(!0),rows:e.optional.number}));return n?{initialValue:e,params:n}:null},binding:{reader:e=>ef},controller:e=>{let t=e.value;return t.rawValue.length>1||e.params.multiline?new Ph(e.document,{formatter:tf,rows:e.params.rows??jh.monitor.defaultRows,value:t,viewProps:e.viewProps}):new Lh(e.document,{formatter:tf,value:t,viewProps:e.viewProps})}}),Yh=class{constructor(){this.map_=new Map}get(e){return this.map_.get(e)??null}has(e){return this.map_.has(e)}add(e,t){return this.map_.set(e,t),e.viewProps.handleDispose(()=>{this.map_.delete(e)}),t}},Xh=class{constructor(e){this.target=e.target,this.reader_=e.reader,this.writer_=e.writer}read(){return this.reader_(this.target.read())}write(e){this.writer_(this.target,e)}inject(e){this.write(this.reader_(e))}};function Zh(e,t){let n=e.accept(t.target.read(),t.params);if(pc(n))return null;let r={target:t.target,initialValue:n.initialValue,params:n.params},i=Bl(t.params,e=>({disabled:e.optional.boolean,hidden:e.optional.boolean,label:e.optional.string,tag:e.optional.string})),a=e.binding.reader(r),o=e.binding.constraint?e.binding.constraint(r):void 0,s=new Xh({reader:a,target:t.target,writer:e.binding.writer(r)}),c=new Ml(Ec(a(n.initialValue),{constraint:o,equals:e.binding.equals}),s),l=e.controller({constraint:o,document:t.document,initialValue:n.initialValue,params:n.params,value:c,viewProps:md.create({disabled:i?.disabled,hidden:i?.hidden})});return new bu(t.document,{blade:nd(),props:Q.fromObject({label:`label`in t.params?i?.label??null:t.target.key}),tag:i?.tag,value:c,valueController:l})}var Qh=class{constructor(e){this.target=e.target,this.reader_=e.reader}read(){return this.reader_(this.target.read())}};function $h(e,t){return t===0?new jd:new Md(e,t??jh.monitor.defaultInterval)}function eg(e,t){let n=e.accept(t.target.read(),t.params);if(pc(n))return null;let r={target:t.target,initialValue:n.initialValue,params:n.params},i=Bl(t.params,e=>({bufferSize:e.optional.number,disabled:e.optional.boolean,hidden:e.optional.boolean,interval:e.optional.number,label:e.optional.string})),a=e.binding.reader(r),o=i?.bufferSize??(e.binding.defaultBufferSize&&e.binding.defaultBufferSize(n.params))??1,s=new Eu({binding:new Qh({reader:a,target:t.target}),bufferSize:o,ticker:$h(t.document,i?.interval)}),c=e.controller({document:t.document,params:n.params,value:s,viewProps:md.create({disabled:i?.disabled,hidden:i?.hidden})});return c.viewProps.bindDisabled(s.ticker),c.viewProps.handleDispose(()=>{s.ticker.dispose()}),new Ou(t.document,{blade:nd(),props:Q.fromObject({label:`label`in t.params?i?.label??null:t.target.key}),value:s,valueController:c})}var tg=class{constructor(e){this.pluginsMap_={blades:[],inputs:[],monitors:[]},this.apiCache_=e}getAll(){return[...this.pluginsMap_.blades,...this.pluginsMap_.inputs,...this.pluginsMap_.monitors]}register(e,t){if(!Ef(t.core))throw bc.notCompatible(e,t.id);t.type===`blade`?this.pluginsMap_.blades.unshift(t):t.type===`input`?this.pluginsMap_.inputs.unshift(t):t.type===`monitor`&&this.pluginsMap_.monitors.unshift(t)}createInput_(e,t,n){return this.pluginsMap_.inputs.reduce((r,i)=>r??Zh(i,{document:e,target:t,params:n}),null)}createMonitor_(e,t,n){return this.pluginsMap_.monitors.reduce((r,i)=>r??eg(i,{document:e,params:n,target:t}),null)}createBinding(e,t,n){if(pc(t.read()))throw new bc({context:{key:t.key},type:`nomatchingcontroller`});let r=this.createInput_(e,t,n);if(r)return r;let i=this.createMonitor_(e,t,n);if(i)return i;throw new bc({context:{key:t.key},type:`nomatchingcontroller`})}createBlade(e,t){let n=this.pluginsMap_.blades.reduce((n,r)=>n??kd(r,{document:e,params:t}),null);if(!n)throw new bc({type:`nomatchingview`,context:{params:t}});return n}createInputBindingApi_(e){let t=this.pluginsMap_.inputs.reduce((t,n)=>t||(n.api?.call(n,{controller:e})??null),null);return this.apiCache_.add(e,t??new jl(e))}createMonitorBindingApi_(e){let t=this.pluginsMap_.monitors.reduce((t,n)=>t||(n.api?.call(n,{controller:e})??null),null);return this.apiCache_.add(e,t??new jl(e))}createBindingApi(e){if(this.apiCache_.has(e))return this.apiCache_.get(e);if(xu(e))return this.createInputBindingApi_(e);if(ku(e))return this.createMonitorBindingApi_(e);throw bc.shouldNeverHappen()}createApi(e){if(this.apiCache_.has(e))return this.apiCache_.get(e);if(yu(e))return this.createBindingApi(e);let t=this.pluginsMap_.blades.reduce((t,n)=>t??n.api({controller:e,pool:this}),null);if(!t)throw bc.shouldNeverHappen();return this.apiCache_.add(e,t)}},ng=new Yh;function rg(){let e=new tg(ng);return[gh,Sh,Oh,Ah,eh,Km,Gm,Bm,Nf,Rh,Jh,qh,Vu,dd,Od].forEach(t=>{e.register(`core`,t)}),e}var ig=class extends Tl{constructor(e){super(e),this.emitter_=new Sc,this.controller.value.emitter.on(`change`,e=>{this.emitter_.emit(`change`,new Dl(this,e.rawValue))})}get label(){return this.controller.labelController.props.get(`label`)}set label(e){this.controller.labelController.props.set(`label`,e)}get options(){return this.controller.valueController.props.get(`options`)}set options(e){this.controller.valueController.props.set(`options`,e)}get value(){return this.controller.value.rawValue}set value(e){this.controller.value.rawValue=e}on(e,t){let n=t.bind(this);return this.emitter_.on(e,e=>{n(e)},{key:t}),this}off(e,t){return this.emitter_.off(e,t),this}},ag=class extends Tl{},og=class extends Tl{constructor(e){super(e),this.emitter_=new Sc,this.controller.value.emitter.on(`change`,e=>{this.emitter_.emit(`change`,new Dl(this,e.rawValue))})}get label(){return this.controller.labelController.props.get(`label`)}set label(e){this.controller.labelController.props.set(`label`,e)}get max(){return this.controller.valueController.sliderController.props.get(`max`)}set max(e){this.controller.valueController.sliderController.props.set(`max`,e)}get min(){return this.controller.valueController.sliderController.props.get(`min`)}set min(e){this.controller.valueController.sliderController.props.set(`min`,e)}get value(){return this.controller.value.rawValue}set value(e){this.controller.value.rawValue=e}on(e,t){let n=t.bind(this);return this.emitter_.on(e,e=>{n(e)},{key:t}),this}off(e,t){return this.emitter_.off(e,t),this}},sg=class extends Tl{constructor(e){super(e),this.emitter_=new Sc,this.controller.value.emitter.on(`change`,e=>{this.emitter_.emit(`change`,new Dl(this,e.rawValue))})}get label(){return this.controller.labelController.props.get(`label`)}set label(e){this.controller.labelController.props.set(`label`,e)}get formatter(){return this.controller.valueController.props.get(`formatter`)}set formatter(e){this.controller.valueController.props.set(`formatter`,e)}get value(){return this.controller.value.rawValue}set value(e){this.controller.value.rawValue=e}on(e,t){let n=t.bind(this);return this.emitter_.on(e,e=>{n(e)},{key:t}),this}off(e,t){return this.emitter_.off(e,t),this}},cg=(function(){return{id:`list`,type:`blade`,core:zu,accept(e){let t=Bl(e,e=>({options:e.required.custom(Id),value:e.required.raw,view:e.required.constant(`list`),label:e.optional.string}));return t?{params:t}:null},controller(e){let t=new Fd(Ld(e.params.options)),n=Ec(e.params.value,{constraint:t}),r=new Vd(e.document,{props:new Q({options:t.values.value(`options`)}),value:n,viewProps:e.viewProps});return new gu(e.document,{blade:e.blade,props:Q.fromObject({label:e.params.label}),value:n,valueController:r})},api(e){return!(e.controller instanceof gu)||!(e.controller.valueController instanceof Vd)?null:new ig(e.controller)}}})(),lg=class extends sd{constructor(e,t){super(e,t)}get element(){return this.controller.view.element}},ug=class extends ud{constructor(e,t){super(e,{expanded:t.expanded,blade:t.blade,props:t.props,root:!0,viewProps:t.viewProps})}},dg=$(`spr`),fg=class{constructor(e,t){this.element=e.createElement(`div`),this.element.classList.add(dg()),t.viewProps.bindClassModifiers(this.element);let n=e.createElement(`hr`);n.classList.add(dg(`r`)),this.element.appendChild(n)}},pg=class extends hu{constructor(e,t){super(Object.assign(Object.assign({},t),{view:new fg(e,{viewProps:t.viewProps})}))}},mg={id:`separator`,type:`blade`,core:zu,accept(e){let t=Bl(e,e=>({view:e.required.constant(`separator`)}));return t?{params:t}:null},controller(e){return new pg(e.document,{blade:e.blade,viewProps:e.viewProps})},api(e){return e.controller instanceof pg?new ag(e.controller):null}},hg={id:`slider`,type:`blade`,core:zu,accept(e){let t=Bl(e,e=>({max:e.required.number,min:e.required.number,view:e.required.constant(`slider`),format:e.optional.function,label:e.optional.string,value:e.optional.number}));return t?{params:t}:null},controller(e){let t=e.params.value??0,n=new Oc({max:e.params.max,min:e.params.min}),r=Ec(t,{constraint:n}),i=new yf(e.document,Object.assign(Object.assign({},bf({formatter:e.params.format??dl,keyScale:Ec(1),max:n.values.value(`max`),min:n.values.value(`min`),pointerScale:yl(e.params,t)})),{parser:ll,value:r,viewProps:e.viewProps}));return new gu(e.document,{blade:e.blade,props:Q.fromObject({label:e.params.label}),value:r,valueController:i})},api(e){return!(e.controller instanceof gu)||!(e.controller.valueController instanceof yf)?null:new og(e.controller)}},gg=(function(){return{id:`text`,type:`blade`,core:zu,accept(e){let t=Bl(e,e=>({parse:e.required.function,value:e.required.raw,view:e.required.constant(`text`),format:e.optional.function,label:e.optional.string}));return t?{params:t}:null},controller(e){let t=Ec(e.params.value),n=new qd(e.document,{parser:e.params.parse,props:Q.fromObject({formatter:e.params.format??(e=>String(e))}),value:t,viewProps:e.viewProps});return new gu(e.document,{blade:e.blade,props:Q.fromObject({label:e.params.label}),value:t,valueController:n})},api(e){return!(e.controller instanceof gu)||!(e.controller.valueController instanceof qd)?null:new sg(e.controller)}}})();function _g(e){let t=e.createElement(`div`);return t.classList.add($(`dfw`)()),e.body&&e.body.appendChild(t),t}function vg(e,t,n){if(e.querySelector(`style[data-tp-style=${t}]`))return;let r=e.createElement(`style`);r.dataset.tpStyle=t,r.textContent=n,e.head.appendChild(r)}var yg=class extends lg{constructor(e){let t=e??{},n=t.document??Xl(),r=rg(),i=new ug(n,{expanded:t.expanded,blade:nd(),props:Q.fromObject({title:t.title}),viewProps:md.create()});super(i,r),this.pool_=r,this.containerElem_=t.container??_g(n),this.containerElem_.appendChild(this.element),this.doc_=n,this.usesDefaultWrapper_=!t.container,this.setUpDefaultPlugins_()}get document(){if(!this.doc_)throw bc.alreadyDisposed();return this.doc_}dispose(){let e=this.containerElem_;if(!e)throw bc.alreadyDisposed();if(this.usesDefaultWrapper_){let t=e.parentElement;t&&t.removeChild(e)}this.containerElem_=null,this.doc_=null,super.dispose()}registerPlugin(e){e.css&&vg(this.document,`plugin-${e.id}`,e.css),(`plugin`in e?[e.plugin]:`plugins`in e?e.plugins:[]).forEach(t=>{this.pool_.register(e.id,t)})}setUpDefaultPlugins_(){this.registerPlugin({id:`default`,css:`.tp-tbiv_b,.tp-coltxtv_ms,.tp-colswv_b,.tp-ckbv_i,.tp-sglv_i,.tp-mllv_i,.tp-grlv_g,.tp-txtv_i,.tp-p2dpv_p,.tp-colswv_sw,.tp-rotv_b,.tp-fldv_b,.tp-p2dv_b,.tp-btnv_b,.tp-lstv_s{-webkit-appearance:none;-moz-appearance:none;appearance:none;background-color:rgba(0,0,0,0);border-width:0;font-family:inherit;font-size:inherit;font-weight:inherit;margin:0;outline:none;padding:0}.tp-p2dv_b,.tp-btnv_b,.tp-lstv_s{background-color:var(--btn-bg);border-radius:var(--bld-br);color:var(--btn-fg);cursor:pointer;display:block;font-weight:bold;height:var(--cnt-usz);line-height:var(--cnt-usz);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.tp-p2dv_b:hover,.tp-btnv_b:hover,.tp-lstv_s:hover{background-color:var(--btn-bg-h)}.tp-p2dv_b:focus,.tp-btnv_b:focus,.tp-lstv_s:focus{background-color:var(--btn-bg-f)}.tp-p2dv_b:active,.tp-btnv_b:active,.tp-lstv_s:active{background-color:var(--btn-bg-a)}.tp-p2dv_b:disabled,.tp-btnv_b:disabled,.tp-lstv_s:disabled{opacity:.5}.tp-rotv_c>.tp-cntv.tp-v-lst,.tp-tbpv_c>.tp-cntv.tp-v-lst,.tp-fldv_c>.tp-cntv.tp-v-lst{margin-bottom:calc(-1*var(--cnt-vp))}.tp-rotv_c>.tp-fldv.tp-v-lst .tp-fldv_c,.tp-tbpv_c>.tp-fldv.tp-v-lst .tp-fldv_c,.tp-fldv_c>.tp-fldv.tp-v-lst .tp-fldv_c{border-bottom-left-radius:0}.tp-rotv_c>.tp-fldv.tp-v-lst .tp-fldv_b,.tp-tbpv_c>.tp-fldv.tp-v-lst .tp-fldv_b,.tp-fldv_c>.tp-fldv.tp-v-lst .tp-fldv_b{border-bottom-left-radius:0}.tp-rotv_c>*:not(.tp-v-fst),.tp-tbpv_c>*:not(.tp-v-fst),.tp-fldv_c>*:not(.tp-v-fst){margin-top:var(--cnt-usp)}.tp-rotv_c>.tp-sprv:not(.tp-v-fst),.tp-tbpv_c>.tp-sprv:not(.tp-v-fst),.tp-fldv_c>.tp-sprv:not(.tp-v-fst),.tp-rotv_c>.tp-cntv:not(.tp-v-fst),.tp-tbpv_c>.tp-cntv:not(.tp-v-fst),.tp-fldv_c>.tp-cntv:not(.tp-v-fst){margin-top:var(--cnt-vp)}.tp-rotv_c>.tp-sprv+*:not(.tp-v-hidden),.tp-tbpv_c>.tp-sprv+*:not(.tp-v-hidden),.tp-fldv_c>.tp-sprv+*:not(.tp-v-hidden),.tp-rotv_c>.tp-cntv+*:not(.tp-v-hidden),.tp-tbpv_c>.tp-cntv+*:not(.tp-v-hidden),.tp-fldv_c>.tp-cntv+*:not(.tp-v-hidden){margin-top:var(--cnt-vp)}.tp-rotv_c>.tp-sprv:not(.tp-v-hidden)+.tp-sprv,.tp-tbpv_c>.tp-sprv:not(.tp-v-hidden)+.tp-sprv,.tp-fldv_c>.tp-sprv:not(.tp-v-hidden)+.tp-sprv,.tp-rotv_c>.tp-cntv:not(.tp-v-hidden)+.tp-cntv,.tp-tbpv_c>.tp-cntv:not(.tp-v-hidden)+.tp-cntv,.tp-fldv_c>.tp-cntv:not(.tp-v-hidden)+.tp-cntv{margin-top:0}.tp-tbpv_c>.tp-cntv,.tp-fldv_c>.tp-cntv{margin-left:4px}.tp-tbpv_c>.tp-fldv>.tp-fldv_b,.tp-fldv_c>.tp-fldv>.tp-fldv_b{border-top-left-radius:var(--bld-br);border-bottom-left-radius:var(--bld-br)}.tp-tbpv_c>.tp-fldv.tp-fldv-expanded>.tp-fldv_b,.tp-fldv_c>.tp-fldv.tp-fldv-expanded>.tp-fldv_b{border-bottom-left-radius:0}.tp-tbpv_c .tp-fldv>.tp-fldv_c,.tp-fldv_c .tp-fldv>.tp-fldv_c{border-bottom-left-radius:var(--bld-br)}.tp-tbpv_c>.tp-cntv+.tp-fldv>.tp-fldv_b,.tp-fldv_c>.tp-cntv+.tp-fldv>.tp-fldv_b{border-top-left-radius:0}.tp-tbpv_c>.tp-cntv+.tp-tabv>.tp-tabv_t,.tp-fldv_c>.tp-cntv+.tp-tabv>.tp-tabv_t{border-top-left-radius:0}.tp-tbpv_c>.tp-tabv>.tp-tabv_t,.tp-fldv_c>.tp-tabv>.tp-tabv_t{border-top-left-radius:var(--bld-br)}.tp-tbpv_c .tp-tabv>.tp-tabv_c,.tp-fldv_c .tp-tabv>.tp-tabv_c{border-bottom-left-radius:var(--bld-br)}.tp-rotv_b,.tp-fldv_b{background-color:var(--cnt-bg);color:var(--cnt-fg);cursor:pointer;display:block;height:calc(var(--cnt-usz) + 4px);line-height:calc(var(--cnt-usz) + 4px);overflow:hidden;padding-left:var(--cnt-hp);padding-right:calc(4px + var(--cnt-usz) + var(--cnt-hp));position:relative;text-align:left;text-overflow:ellipsis;white-space:nowrap;width:100%;transition:border-radius .2s ease-in-out .2s}.tp-rotv_b:hover,.tp-fldv_b:hover{background-color:var(--cnt-bg-h)}.tp-rotv_b:focus,.tp-fldv_b:focus{background-color:var(--cnt-bg-f)}.tp-rotv_b:active,.tp-fldv_b:active{background-color:var(--cnt-bg-a)}.tp-rotv_b:disabled,.tp-fldv_b:disabled{opacity:.5}.tp-rotv_m,.tp-fldv_m{background:linear-gradient(to left, var(--cnt-fg), var(--cnt-fg) 2px, transparent 2px, transparent 4px, var(--cnt-fg) 4px);border-radius:2px;bottom:0;content:"";display:block;height:6px;right:calc(var(--cnt-hp) + (var(--cnt-usz) + 4px - 6px)/2 - 2px);margin:auto;opacity:.5;position:absolute;top:0;transform:rotate(90deg);transition:transform .2s ease-in-out;width:6px}.tp-rotv.tp-rotv-expanded .tp-rotv_m,.tp-fldv.tp-fldv-expanded>.tp-fldv_b>.tp-fldv_m{transform:none}.tp-rotv_c,.tp-fldv_c{box-sizing:border-box;height:0;opacity:0;overflow:hidden;padding-bottom:0;padding-top:0;position:relative;transition:height .2s ease-in-out,opacity .2s linear,padding .2s ease-in-out}.tp-rotv.tp-rotv-cpl:not(.tp-rotv-expanded) .tp-rotv_c,.tp-fldv.tp-fldv-cpl:not(.tp-fldv-expanded)>.tp-fldv_c{display:none}.tp-rotv.tp-rotv-expanded .tp-rotv_c,.tp-fldv.tp-fldv-expanded>.tp-fldv_c{opacity:1;padding-bottom:var(--cnt-vp);padding-top:var(--cnt-vp);transform:none;overflow:visible;transition:height .2s ease-in-out,opacity .2s linear .2s,padding .2s ease-in-out}.tp-txtv_i,.tp-p2dpv_p,.tp-colswv_sw{background-color:var(--in-bg);border-radius:var(--bld-br);box-sizing:border-box;color:var(--in-fg);font-family:inherit;height:var(--cnt-usz);line-height:var(--cnt-usz);min-width:0;width:100%}.tp-txtv_i:hover,.tp-p2dpv_p:hover,.tp-colswv_sw:hover{background-color:var(--in-bg-h)}.tp-txtv_i:focus,.tp-p2dpv_p:focus,.tp-colswv_sw:focus{background-color:var(--in-bg-f)}.tp-txtv_i:active,.tp-p2dpv_p:active,.tp-colswv_sw:active{background-color:var(--in-bg-a)}.tp-txtv_i:disabled,.tp-p2dpv_p:disabled,.tp-colswv_sw:disabled{opacity:.5}.tp-lstv,.tp-coltxtv_m{position:relative}.tp-lstv_s{padding:0 20px 0 4px;width:100%}.tp-lstv_m,.tp-coltxtv_mm{bottom:0;margin:auto;pointer-events:none;position:absolute;right:2px;top:0}.tp-lstv_m svg,.tp-coltxtv_mm svg{bottom:0;height:16px;margin:auto;position:absolute;right:0;top:0;width:16px}.tp-lstv_m svg path,.tp-coltxtv_mm svg path{fill:currentColor}.tp-sglv_i,.tp-mllv_i,.tp-grlv_g{background-color:var(--mo-bg);border-radius:var(--bld-br);box-sizing:border-box;color:var(--mo-fg);height:var(--cnt-usz);scrollbar-color:currentColor rgba(0,0,0,0);scrollbar-width:thin;width:100%}.tp-sglv_i::-webkit-scrollbar,.tp-mllv_i::-webkit-scrollbar,.tp-grlv_g::-webkit-scrollbar{height:8px;width:8px}.tp-sglv_i::-webkit-scrollbar-corner,.tp-mllv_i::-webkit-scrollbar-corner,.tp-grlv_g::-webkit-scrollbar-corner{background-color:rgba(0,0,0,0)}.tp-sglv_i::-webkit-scrollbar-thumb,.tp-mllv_i::-webkit-scrollbar-thumb,.tp-grlv_g::-webkit-scrollbar-thumb{background-clip:padding-box;background-color:currentColor;border:rgba(0,0,0,0) solid 2px;border-radius:4px}.tp-pndtxtv,.tp-coltxtv_w{display:flex}.tp-pndtxtv_a,.tp-coltxtv_c{width:100%}.tp-pndtxtv_a+.tp-pndtxtv_a,.tp-coltxtv_c+.tp-pndtxtv_a,.tp-pndtxtv_a+.tp-coltxtv_c,.tp-coltxtv_c+.tp-coltxtv_c{margin-left:2px}.tp-rotv{--bs-bg: var(--tp-base-background-color, hsl(230, 7%, 17%));--bs-br: var(--tp-base-border-radius, 6px);--bs-ff: var(--tp-base-font-family, Roboto Mono, Source Code Pro, Menlo, Courier, monospace);--bs-sh: var(--tp-base-shadow-color, rgba(0, 0, 0, 0.2));--bld-br: var(--tp-blade-border-radius, 2px);--bld-hp: var(--tp-blade-horizontal-padding, 4px);--bld-vw: var(--tp-blade-value-width, 160px);--btn-bg: var(--tp-button-background-color, hsl(230, 7%, 70%));--btn-bg-a: var(--tp-button-background-color-active, #d6d7db);--btn-bg-f: var(--tp-button-background-color-focus, #c8cad0);--btn-bg-h: var(--tp-button-background-color-hover, #bbbcc4);--btn-fg: var(--tp-button-foreground-color, hsl(230, 7%, 17%));--cnt-bg: var(--tp-container-background-color, rgba(187, 188, 196, 0.1));--cnt-bg-a: var(--tp-container-background-color-active, rgba(187, 188, 196, 0.25));--cnt-bg-f: var(--tp-container-background-color-focus, rgba(187, 188, 196, 0.2));--cnt-bg-h: var(--tp-container-background-color-hover, rgba(187, 188, 196, 0.15));--cnt-fg: var(--tp-container-foreground-color, hsl(230, 7%, 75%));--cnt-hp: var(--tp-container-horizontal-padding, 4px);--cnt-vp: var(--tp-container-vertical-padding, 4px);--cnt-usp: var(--tp-container-unit-spacing, 4px);--cnt-usz: var(--tp-container-unit-size, 20px);--in-bg: var(--tp-input-background-color, rgba(187, 188, 196, 0.1));--in-bg-a: var(--tp-input-background-color-active, rgba(187, 188, 196, 0.25));--in-bg-f: var(--tp-input-background-color-focus, rgba(187, 188, 196, 0.2));--in-bg-h: var(--tp-input-background-color-hover, rgba(187, 188, 196, 0.15));--in-fg: var(--tp-input-foreground-color, hsl(230, 7%, 75%));--lbl-fg: var(--tp-label-foreground-color, rgba(187, 188, 196, 0.7));--mo-bg: var(--tp-monitor-background-color, rgba(0, 0, 0, 0.2));--mo-fg: var(--tp-monitor-foreground-color, rgba(187, 188, 196, 0.7));--grv-fg: var(--tp-groove-foreground-color, rgba(187, 188, 196, 0.1))}.tp-btnv_b{width:100%}.tp-btnv_t{text-align:center}.tp-ckbv_l{display:block;position:relative}.tp-ckbv_i{left:0;opacity:0;position:absolute;top:0}.tp-ckbv_w{background-color:var(--in-bg);border-radius:var(--bld-br);cursor:pointer;display:block;height:var(--cnt-usz);position:relative;width:var(--cnt-usz)}.tp-ckbv_w svg{display:block;height:16px;inset:0;margin:auto;opacity:0;position:absolute;width:16px}.tp-ckbv_w svg path{fill:none;stroke:var(--in-fg);stroke-width:2}.tp-ckbv_i:hover+.tp-ckbv_w{background-color:var(--in-bg-h)}.tp-ckbv_i:focus+.tp-ckbv_w{background-color:var(--in-bg-f)}.tp-ckbv_i:active+.tp-ckbv_w{background-color:var(--in-bg-a)}.tp-ckbv_i:checked+.tp-ckbv_w svg{opacity:1}.tp-ckbv.tp-v-disabled .tp-ckbv_w{opacity:.5}.tp-colv{position:relative}.tp-colv_h{display:flex}.tp-colv_s{flex-grow:0;flex-shrink:0;width:var(--cnt-usz)}.tp-colv_t{flex:1;margin-left:4px}.tp-colv_p{height:0;margin-top:0;opacity:0;overflow:hidden;transition:height .2s ease-in-out,opacity .2s linear,margin .2s ease-in-out}.tp-colv.tp-colv-expanded.tp-colv-cpl .tp-colv_p{overflow:visible}.tp-colv.tp-colv-expanded .tp-colv_p{margin-top:var(--cnt-usp);opacity:1}.tp-colv .tp-popv{left:calc(-1*var(--cnt-hp));right:calc(-1*var(--cnt-hp));top:var(--cnt-usz)}.tp-colpv_h,.tp-colpv_ap{margin-left:6px;margin-right:6px}.tp-colpv_h{margin-top:var(--cnt-usp)}.tp-colpv_rgb{display:flex;margin-top:var(--cnt-usp);width:100%}.tp-colpv_a{display:flex;margin-top:var(--cnt-vp);padding-top:calc(var(--cnt-vp) + 2px);position:relative}.tp-colpv_a::before{background-color:var(--grv-fg);content:"";height:2px;left:calc(-1*var(--cnt-hp));position:absolute;right:calc(-1*var(--cnt-hp));top:0}.tp-colpv.tp-v-disabled .tp-colpv_a::before{opacity:.5}.tp-colpv_ap{align-items:center;display:flex;flex:3}.tp-colpv_at{flex:1;margin-left:4px}.tp-svpv{border-radius:var(--bld-br);outline:none;overflow:hidden;position:relative}.tp-svpv.tp-v-disabled{opacity:.5}.tp-svpv_c{cursor:crosshair;display:block;height:calc(var(--cnt-usz)*4);width:100%}.tp-svpv_m{border-radius:100%;border:rgba(255,255,255,.75) solid 2px;box-sizing:border-box;filter:drop-shadow(0 0 1px rgba(0, 0, 0, 0.3));height:12px;margin-left:-6px;margin-top:-6px;pointer-events:none;position:absolute;width:12px}.tp-svpv:focus .tp-svpv_m{border-color:#fff}.tp-hplv{cursor:pointer;height:var(--cnt-usz);outline:none;position:relative}.tp-hplv.tp-v-disabled{opacity:.5}.tp-hplv_c{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAAABCAYAAABubagXAAAAQ0lEQVQoU2P8z8Dwn0GCgQEDi2OK/RBgYHjBgIpfovFh8j8YBIgzFGQxuqEgPhaDOT5gOhPkdCxOZeBg+IDFZZiGAgCaSSMYtcRHLgAAAABJRU5ErkJggg==);background-position:left top;background-repeat:no-repeat;background-size:100% 100%;border-radius:2px;display:block;height:4px;left:0;margin-top:-2px;position:absolute;top:50%;width:100%}.tp-hplv_m{border-radius:var(--bld-br);border:rgba(255,255,255,.75) solid 2px;box-shadow:0 0 2px rgba(0,0,0,.1);box-sizing:border-box;height:12px;left:50%;margin-left:-6px;margin-top:-6px;position:absolute;top:50%;width:12px}.tp-hplv:focus .tp-hplv_m{border-color:#fff}.tp-aplv{cursor:pointer;height:var(--cnt-usz);outline:none;position:relative;width:100%}.tp-aplv.tp-v-disabled{opacity:.5}.tp-aplv_b{background-color:#fff;background-image:linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%),linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%);background-size:4px 4px;background-position:0 0,2px 2px;border-radius:2px;display:block;height:4px;left:0;margin-top:-2px;overflow:hidden;position:absolute;top:50%;width:100%}.tp-aplv_c{inset:0;position:absolute}.tp-aplv_m{background-color:#fff;background-image:linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%),linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%);background-size:12px 12px;background-position:0 0,6px 6px;border-radius:var(--bld-br);box-shadow:0 0 2px rgba(0,0,0,.1);height:12px;left:50%;margin-left:-6px;margin-top:-6px;overflow:hidden;position:absolute;top:50%;width:12px}.tp-aplv_p{border-radius:var(--bld-br);border:rgba(255,255,255,.75) solid 2px;box-sizing:border-box;inset:0;position:absolute}.tp-aplv:focus .tp-aplv_p{border-color:#fff}.tp-colswv{background-color:#fff;background-image:linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%),linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%);background-size:10px 10px;background-position:0 0,5px 5px;border-radius:var(--bld-br);overflow:hidden}.tp-colswv.tp-v-disabled{opacity:.5}.tp-colswv_sw{border-radius:0}.tp-colswv_b{cursor:pointer;display:block;height:var(--cnt-usz);left:0;position:absolute;top:0;width:var(--cnt-usz)}.tp-colswv_b:focus::after{border:rgba(255,255,255,.75) solid 2px;border-radius:var(--bld-br);content:"";display:block;inset:0;position:absolute}.tp-coltxtv{display:flex;width:100%}.tp-coltxtv_m{margin-right:4px}.tp-coltxtv_ms{border-radius:var(--bld-br);color:var(--lbl-fg);cursor:pointer;height:var(--cnt-usz);line-height:var(--cnt-usz);padding:0 18px 0 4px}.tp-coltxtv_ms:hover{background-color:var(--in-bg-h)}.tp-coltxtv_ms:focus{background-color:var(--in-bg-f)}.tp-coltxtv_ms:active{background-color:var(--in-bg-a)}.tp-coltxtv_mm{color:var(--lbl-fg)}.tp-coltxtv.tp-v-disabled .tp-coltxtv_mm{opacity:.5}.tp-coltxtv_w{flex:1}.tp-dfwv{position:absolute;top:8px;right:8px;width:256px}.tp-fldv{position:relative}.tp-fldv_t{padding-left:4px}.tp-fldv_b:disabled .tp-fldv_m{display:none}.tp-fldv_c{padding-left:4px}.tp-fldv_i{bottom:0;color:var(--cnt-bg);left:0;overflow:hidden;position:absolute;top:calc(var(--cnt-usz) + 4px);width:max(var(--bs-br),4px)}.tp-fldv_i::before{background-color:currentColor;bottom:0;content:"";left:0;position:absolute;top:0;width:4px}.tp-fldv_b:hover+.tp-fldv_i{color:var(--cnt-bg-h)}.tp-fldv_b:focus+.tp-fldv_i{color:var(--cnt-bg-f)}.tp-fldv_b:active+.tp-fldv_i{color:var(--cnt-bg-a)}.tp-fldv.tp-v-disabled>.tp-fldv_i{opacity:.5}.tp-grlv{position:relative}.tp-grlv_g{display:block;height:calc(var(--cnt-usz)*3)}.tp-grlv_g polyline{fill:none;stroke:var(--mo-fg);stroke-linejoin:round}.tp-grlv_t{margin-top:-4px;transition:left .05s,top .05s;visibility:hidden}.tp-grlv_t.tp-grlv_t-a{visibility:visible}.tp-grlv_t.tp-grlv_t-in{transition:none}.tp-grlv.tp-v-disabled .tp-grlv_g{opacity:.5}.tp-grlv .tp-ttv{background-color:var(--mo-fg)}.tp-grlv .tp-ttv::before{border-top-color:var(--mo-fg)}.tp-lblv{align-items:center;display:flex;line-height:1.3;padding-left:var(--cnt-hp);padding-right:var(--cnt-hp)}.tp-lblv.tp-lblv-nol{display:block}.tp-lblv_l{color:var(--lbl-fg);flex:1;-webkit-hyphens:auto;hyphens:auto;overflow:hidden;padding-left:4px;padding-right:16px}.tp-lblv.tp-v-disabled .tp-lblv_l{opacity:.5}.tp-lblv.tp-lblv-nol .tp-lblv_l{display:none}.tp-lblv_v{align-self:flex-start;flex-grow:0;flex-shrink:0;width:var(--bld-vw)}.tp-lblv.tp-lblv-nol .tp-lblv_v{width:100%}.tp-lstv_s{padding:0 20px 0 var(--bld-hp);width:100%}.tp-lstv_m{color:var(--btn-fg)}.tp-sglv_i{padding-left:var(--bld-hp);padding-right:var(--bld-hp)}.tp-sglv.tp-v-disabled .tp-sglv_i{opacity:.5}.tp-mllv_i{display:block;height:calc(var(--cnt-usz)*3);line-height:var(--cnt-usz);padding-left:var(--bld-hp);padding-right:var(--bld-hp);resize:none;white-space:pre}.tp-mllv.tp-v-disabled .tp-mllv_i{opacity:.5}.tp-p2dv{position:relative}.tp-p2dv_h{display:flex}.tp-p2dv_b{height:var(--cnt-usz);margin-right:4px;position:relative;width:var(--cnt-usz)}.tp-p2dv_b svg{display:block;height:16px;left:50%;margin-left:-8px;margin-top:-8px;position:absolute;top:50%;width:16px}.tp-p2dv_b svg path{stroke:currentColor;stroke-width:2}.tp-p2dv_b svg circle{fill:currentColor}.tp-p2dv_t{flex:1}.tp-p2dv_p{height:0;margin-top:0;opacity:0;overflow:hidden;transition:height .2s ease-in-out,opacity .2s linear,margin .2s ease-in-out}.tp-p2dv.tp-p2dv-expanded .tp-p2dv_p{margin-top:var(--cnt-usp);opacity:1}.tp-p2dv .tp-popv{left:calc(-1*var(--cnt-hp));right:calc(-1*var(--cnt-hp));top:var(--cnt-usz)}.tp-p2dpv{padding-left:calc(var(--cnt-usz) + 4px)}.tp-p2dpv_p{cursor:crosshair;height:0;overflow:hidden;padding-bottom:100%;position:relative}.tp-p2dpv.tp-v-disabled .tp-p2dpv_p{opacity:.5}.tp-p2dpv_g{display:block;height:100%;left:0;pointer-events:none;position:absolute;top:0;width:100%}.tp-p2dpv_ax{opacity:.1;stroke:var(--in-fg);stroke-dasharray:1}.tp-p2dpv_l{opacity:.5;stroke:var(--in-fg);stroke-dasharray:1}.tp-p2dpv_m{border:var(--in-fg) solid 1px;border-radius:50%;box-sizing:border-box;height:4px;margin-left:-2px;margin-top:-2px;position:absolute;width:4px}.tp-p2dpv_p:focus .tp-p2dpv_m{background-color:var(--in-fg);border-width:0}.tp-popv{background-color:var(--bs-bg);border-radius:var(--bs-br);box-shadow:0 2px 4px var(--bs-sh);display:none;max-width:var(--bld-vw);padding:var(--cnt-vp) var(--cnt-hp);position:absolute;visibility:hidden;z-index:1000}.tp-popv.tp-popv-v{display:block;visibility:visible}.tp-sldv.tp-v-disabled{opacity:.5}.tp-sldv_t{box-sizing:border-box;cursor:pointer;height:var(--cnt-usz);margin:0 6px;outline:none;position:relative}.tp-sldv_t::before{background-color:var(--in-bg);border-radius:1px;content:"";display:block;height:2px;inset:0;margin:auto;position:absolute}.tp-sldv_k{height:100%;left:0;position:absolute;top:0}.tp-sldv_k::before{background-color:var(--in-fg);border-radius:1px;content:"";display:block;height:2px;inset:0;margin-bottom:auto;margin-top:auto;position:absolute}.tp-sldv_k::after{background-color:var(--btn-bg);border-radius:var(--bld-br);bottom:0;content:"";display:block;height:12px;margin-bottom:auto;margin-top:auto;position:absolute;right:-6px;top:0;width:12px}.tp-sldv_t:hover .tp-sldv_k::after{background-color:var(--btn-bg-h)}.tp-sldv_t:focus .tp-sldv_k::after{background-color:var(--btn-bg-f)}.tp-sldv_t:active .tp-sldv_k::after{background-color:var(--btn-bg-a)}.tp-sldtxtv{display:flex}.tp-sldtxtv_s{flex:2}.tp-sldtxtv_t{flex:1;margin-left:4px}.tp-tabv{position:relative}.tp-tabv_t{align-items:flex-end;color:var(--cnt-bg);display:flex;overflow:hidden;position:relative}.tp-tabv_t:hover{color:var(--cnt-bg-h)}.tp-tabv_t:has(*:focus){color:var(--cnt-bg-f)}.tp-tabv_t:has(*:active){color:var(--cnt-bg-a)}.tp-tabv_t::before{background-color:currentColor;bottom:0;content:"";height:2px;left:0;pointer-events:none;position:absolute;right:0}.tp-tabv.tp-v-disabled .tp-tabv_t::before{opacity:.5}.tp-tabv.tp-tabv-nop .tp-tabv_t{height:calc(var(--cnt-usz) + 4px);position:relative}.tp-tabv.tp-tabv-nop .tp-tabv_t::before{background-color:var(--cnt-bg);bottom:0;content:"";height:2px;left:0;position:absolute;right:0}.tp-tabv_i{bottom:0;color:var(--cnt-bg);left:0;overflow:hidden;position:absolute;top:calc(var(--cnt-usz) + 4px);width:max(var(--bs-br),4px)}.tp-tabv_i::before{background-color:currentColor;bottom:0;content:"";left:0;position:absolute;top:0;width:4px}.tp-tabv_t:hover+.tp-tabv_i{color:var(--cnt-bg-h)}.tp-tabv_t:has(*:focus)+.tp-tabv_i{color:var(--cnt-bg-f)}.tp-tabv_t:has(*:active)+.tp-tabv_i{color:var(--cnt-bg-a)}.tp-tabv.tp-v-disabled>.tp-tabv_i{opacity:.5}.tp-tbiv{flex:1;min-width:0;position:relative}.tp-tbiv+.tp-tbiv{margin-left:2px}.tp-tbiv+.tp-tbiv.tp-v-disabled::before{opacity:.5}.tp-tbiv_b{display:block;padding-left:calc(var(--cnt-hp) + 4px);padding-right:calc(var(--cnt-hp) + 4px);position:relative;width:100%}.tp-tbiv_b:disabled{opacity:.5}.tp-tbiv_b::before{background-color:var(--cnt-bg);content:"";inset:0 0 2px;pointer-events:none;position:absolute}.tp-tbiv_b:hover::before{background-color:var(--cnt-bg-h)}.tp-tbiv_b:focus::before{background-color:var(--cnt-bg-f)}.tp-tbiv_b:active::before{background-color:var(--cnt-bg-a)}.tp-tbiv_t{color:var(--cnt-fg);height:calc(var(--cnt-usz) + 4px);line-height:calc(var(--cnt-usz) + 4px);opacity:.5;overflow:hidden;position:relative;text-overflow:ellipsis}.tp-tbiv.tp-tbiv-sel .tp-tbiv_t{opacity:1}.tp-tbpv_c{padding-bottom:var(--cnt-vp);padding-left:4px;padding-top:var(--cnt-vp)}.tp-txtv{position:relative}.tp-txtv_i{padding-left:var(--bld-hp);padding-right:var(--bld-hp)}.tp-txtv.tp-txtv-fst .tp-txtv_i{border-bottom-right-radius:0;border-top-right-radius:0}.tp-txtv.tp-txtv-mid .tp-txtv_i{border-radius:0}.tp-txtv.tp-txtv-lst .tp-txtv_i{border-bottom-left-radius:0;border-top-left-radius:0}.tp-txtv.tp-txtv-num .tp-txtv_i{text-align:right}.tp-txtv.tp-txtv-drg .tp-txtv_i{opacity:.3}.tp-txtv_k{cursor:pointer;height:100%;left:calc(var(--bld-hp) - 5px);position:absolute;top:0;width:12px}.tp-txtv_k::before{background-color:var(--in-fg);border-radius:1px;bottom:0;content:"";height:calc(var(--cnt-usz) - 4px);left:50%;margin-bottom:auto;margin-left:-1px;margin-top:auto;opacity:.1;position:absolute;top:0;transition:border-radius .1s,height .1s,transform .1s,width .1s;width:2px}.tp-txtv_k:hover::before,.tp-txtv.tp-txtv-drg .tp-txtv_k::before{opacity:1}.tp-txtv.tp-txtv-drg .tp-txtv_k::before{border-radius:50%;height:4px;transform:translateX(-1px);width:4px}.tp-txtv_g{bottom:0;display:block;height:8px;left:50%;margin:auto;overflow:visible;pointer-events:none;position:absolute;top:0;visibility:hidden;width:100%}.tp-txtv.tp-txtv-drg .tp-txtv_g{visibility:visible}.tp-txtv_gb{fill:none;stroke:var(--in-fg);stroke-dasharray:1}.tp-txtv_gh{fill:none;stroke:var(--in-fg)}.tp-txtv .tp-ttv{margin-left:6px;visibility:hidden}.tp-txtv.tp-txtv-drg .tp-ttv{visibility:visible}.tp-ttv{background-color:var(--in-fg);border-radius:var(--bld-br);color:var(--bs-bg);padding:2px 4px;pointer-events:none;position:absolute;transform:translate(-50%, -100%)}.tp-ttv::before{border-color:var(--in-fg) rgba(0,0,0,0) rgba(0,0,0,0) rgba(0,0,0,0);border-style:solid;border-width:2px;box-sizing:border-box;content:"";font-size:.9em;height:4px;left:50%;margin-left:-2px;position:absolute;top:100%;width:4px}.tp-rotv{background-color:var(--bs-bg);border-radius:var(--bs-br);box-shadow:0 2px 4px var(--bs-sh);font-family:var(--bs-ff);font-size:11px;font-weight:500;line-height:1;text-align:left}.tp-rotv_b{border-bottom-left-radius:var(--bs-br);border-bottom-right-radius:var(--bs-br);border-top-left-radius:var(--bs-br);border-top-right-radius:var(--bs-br);padding-left:calc(4px + var(--cnt-usz) + var(--cnt-hp));text-align:center}.tp-rotv.tp-rotv-expanded .tp-rotv_b{border-bottom-left-radius:0;border-bottom-right-radius:0;transition-delay:0s;transition-duration:0s}.tp-rotv.tp-rotv-not>.tp-rotv_b{display:none}.tp-rotv_b:disabled .tp-rotv_m{display:none}.tp-rotv_c>.tp-fldv.tp-v-lst>.tp-fldv_c{border-bottom-left-radius:var(--bs-br);border-bottom-right-radius:var(--bs-br)}.tp-rotv_c>.tp-fldv.tp-v-lst>.tp-fldv_i{border-bottom-left-radius:var(--bs-br)}.tp-rotv_c>.tp-fldv.tp-v-lst:not(.tp-fldv-expanded)>.tp-fldv_b{border-bottom-left-radius:var(--bs-br);border-bottom-right-radius:var(--bs-br)}.tp-rotv_c>.tp-fldv.tp-v-lst.tp-fldv-expanded>.tp-fldv_b{transition-delay:0s;transition-duration:0s}.tp-rotv_c .tp-fldv.tp-v-vlst:not(.tp-fldv-expanded)>.tp-fldv_b{border-bottom-right-radius:var(--bs-br)}.tp-rotv.tp-rotv-not .tp-rotv_c>.tp-fldv.tp-v-fst{margin-top:calc(-1*var(--cnt-vp))}.tp-rotv.tp-rotv-not .tp-rotv_c>.tp-fldv.tp-v-fst>.tp-fldv_b{border-top-left-radius:var(--bs-br);border-top-right-radius:var(--bs-br)}.tp-rotv_c>.tp-tabv.tp-v-lst>.tp-tabv_c{border-bottom-left-radius:var(--bs-br);border-bottom-right-radius:var(--bs-br)}.tp-rotv_c>.tp-tabv.tp-v-lst>.tp-tabv_i{border-bottom-left-radius:var(--bs-br)}.tp-rotv.tp-rotv-not .tp-rotv_c>.tp-tabv.tp-v-fst{margin-top:calc(-1*var(--cnt-vp))}.tp-rotv.tp-rotv-not .tp-rotv_c>.tp-tabv.tp-v-fst>.tp-tabv_t{border-top-left-radius:var(--bs-br);border-top-right-radius:var(--bs-br)}.tp-rotv.tp-v-disabled,.tp-rotv .tp-v-disabled{pointer-events:none}.tp-rotv.tp-v-hidden,.tp-rotv .tp-v-hidden{display:none}.tp-sprv_r{background-color:var(--grv-fg);border-width:0;display:block;height:2px;margin:0;width:100%}.tp-sprv.tp-v-disabled .tp-sprv_r{opacity:.5}`,plugins:[cg,mg,hg,Od,gg]})}};new Ru(`4.0.5`);var bg={name:`CopyShader`,uniforms:{tDiffuse:{value:null},opacity:{value:1}},vertexShader:` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); }`,fragmentShader:` uniform float opacity; uniform sampler2D tDiffuse; varying vec2 vUv; void main() { vec4 texel = texture2D( tDiffuse, vUv ); gl_FragColor = opacity * texel; }`},xg=class{constructor(){this.isPass=!0,this.enabled=!0,this.needsSwap=!0,this.clear=!1,this.renderToScreen=!1}setSize(){}render(){console.error(`THREE.Pass: .render() must be implemented in derived pass.`)}dispose(){}},Sg=new ki(-1,1,1,-1,0,1),Cg=new class extends sr{constructor(){super(),this.setAttribute(`position`,new Yn([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute(`uv`,new Yn([0,2,0,0,2,0],2))}},wg=class{constructor(e){this._mesh=new Ar(Cg,e)}dispose(){this._mesh.geometry.dispose()}render(e){e.render(this._mesh,Sg)}get material(){return this._mesh.material}set material(e){this._mesh.material=e}},Tg=class extends xg{constructor(e,t=`tDiffuse`){super(),this.textureID=t,this.uniforms=null,this.material=null,e instanceof ti?(this.uniforms=e.uniforms,this.material=e):e&&(this.uniforms=Qr.clone(e.uniforms),this.material=new ti({name:e.name===void 0?`unspecified`:e.name,defines:Object.assign({},e.defines),uniforms:this.uniforms,vertexShader:e.vertexShader,fragmentShader:e.fragmentShader})),this._fsQuad=new wg(this.material)}render(e,t,n){this.uniforms[this.textureID]&&(this.uniforms[this.textureID].value=n.texture),this._fsQuad.material=this.material,this.renderToScreen?(e.setRenderTarget(null),this._fsQuad.render(e)):(e.setRenderTarget(t),this.clear&&e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil),this._fsQuad.render(e))}dispose(){this.material.dispose(),this._fsQuad.dispose()}},Eg=class extends xg{constructor(e,t){super(),this.scene=e,this.camera=t,this.clear=!0,this.needsSwap=!1,this.inverse=!1}render(e,t,n){let r=e.getContext(),i=e.state;i.buffers.color.setMask(!1),i.buffers.depth.setMask(!1),i.buffers.color.setLocked(!0),i.buffers.depth.setLocked(!0);let a,o;this.inverse?(a=0,o=1):(a=1,o=0),i.buffers.stencil.setTest(!0),i.buffers.stencil.setOp(r.REPLACE,r.REPLACE,r.REPLACE),i.buffers.stencil.setFunc(r.ALWAYS,a,4294967295),i.buffers.stencil.setClear(o),i.buffers.stencil.setLocked(!0),e.setRenderTarget(n),this.clear&&e.clear(),e.render(this.scene,this.camera),e.setRenderTarget(t),this.clear&&e.clear(),e.render(this.scene,this.camera),i.buffers.color.setLocked(!1),i.buffers.depth.setLocked(!1),i.buffers.color.setMask(!0),i.buffers.depth.setMask(!0),i.buffers.stencil.setLocked(!1),i.buffers.stencil.setFunc(r.EQUAL,1,4294967295),i.buffers.stencil.setOp(r.KEEP,r.KEEP,r.KEEP),i.buffers.stencil.setLocked(!0)}},Dg=class extends xg{constructor(){super(),this.needsSwap=!1}render(e){e.state.buffers.stencil.setLocked(!1),e.state.buffers.stencil.setTest(!1)}},Og=class{constructor(e,t){if(this.renderer=e,this._pixelRatio=e.getPixelRatio(),t===void 0){let n=e.getSize(new G);this._width=n.width,this._height=n.height,t=new Dt(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:_}),t.texture.name=`EffectComposer.rt1`}else this._width=t.width,this._height=t.height;this.renderTarget1=t,this.renderTarget2=t.clone(),this.renderTarget2.texture.name=`EffectComposer.rt2`,this.writeBuffer=this.renderTarget1,this.readBuffer=this.renderTarget2,this.renderToScreen=!0,this.passes=[],this.copyPass=new Tg(bg),this.copyPass.material.blending=0,this.timer=new Pi}swapBuffers(){let e=this.readBuffer;this.readBuffer=this.writeBuffer,this.writeBuffer=e}addPass(e){this.passes.push(e),e.setSize(this._width*this._pixelRatio,this._height*this._pixelRatio)}insertPass(e,t){this.passes.splice(t,0,e),e.setSize(this._width*this._pixelRatio,this._height*this._pixelRatio)}removePass(e){let t=this.passes.indexOf(e);t!==-1&&this.passes.splice(t,1)}isLastEnabledPass(e){for(let t=e+1;t varying vec2 vUv; uniform sampler2D colorTexture; uniform vec2 invSize; uniform vec2 direction; uniform float gaussianCoefficients[KERNEL_RADIUS]; void main() { float weightSum = gaussianCoefficients[0]; vec3 diffuseSum = texture2D( colorTexture, vUv ).rgb * weightSum; for ( int i = 1; i < KERNEL_RADIUS; i ++ ) { float x = float( i ); float w = gaussianCoefficients[i]; vec2 uvOffset = direction * invSize * x; vec3 sample1 = texture2D( colorTexture, vUv + uvOffset ).rgb; vec3 sample2 = texture2D( colorTexture, vUv - uvOffset ).rgb; diffuseSum += ( sample1 + sample2 ) * w; } gl_FragColor = vec4( diffuseSum, 1.0 ); }`})}_getCompositeMaterial(e){return new ti({defines:{NUM_MIPS:e},uniforms:{blurTexture1:{value:null},blurTexture2:{value:null},blurTexture3:{value:null},blurTexture4:{value:null},blurTexture5:{value:null},bloomStrength:{value:1},bloomFactors:{value:null},bloomTintColors:{value:null},bloomRadius:{value:0}},vertexShader:` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); }`,fragmentShader:` varying vec2 vUv; uniform sampler2D blurTexture1; uniform sampler2D blurTexture2; uniform sampler2D blurTexture3; uniform sampler2D blurTexture4; uniform sampler2D blurTexture5; uniform float bloomStrength; uniform float bloomRadius; uniform float bloomFactors[NUM_MIPS]; uniform vec3 bloomTintColors[NUM_MIPS]; float lerpBloomFactor( const in float factor ) { float mirrorFactor = 1.2 - factor; return mix( factor, mirrorFactor, bloomRadius ); } void main() { // 3.0 for backwards compatibility with previous alpha-based intensity vec3 bloom = 3.0 * bloomStrength * ( lerpBloomFactor( bloomFactors[ 0 ] ) * bloomTintColors[ 0 ] * texture2D( blurTexture1, vUv ).rgb + lerpBloomFactor( bloomFactors[ 1 ] ) * bloomTintColors[ 1 ] * texture2D( blurTexture2, vUv ).rgb + lerpBloomFactor( bloomFactors[ 2 ] ) * bloomTintColors[ 2 ] * texture2D( blurTexture3, vUv ).rgb + lerpBloomFactor( bloomFactors[ 3 ] ) * bloomTintColors[ 3 ] * texture2D( blurTexture4, vUv ).rgb + lerpBloomFactor( bloomFactors[ 4 ] ) * bloomTintColors[ 4 ] * texture2D( blurTexture5, vUv ).rgb ); float bloomAlpha = max( bloom.r, max( bloom.g, bloom.b ) ); gl_FragColor = vec4( bloom, bloomAlpha ); }`})}};jg.BlurDirectionX=new G(1,0),jg.BlurDirectionY=new G(0,1);var Mg={name:`OutputShader`,uniforms:{tDiffuse:{value:null},toneMappingExposure:{value:1}},vertexShader:` precision highp float; uniform mat4 modelViewMatrix; uniform mat4 projectionMatrix; attribute vec3 position; attribute vec2 uv; varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); }`,fragmentShader:` precision highp float; uniform sampler2D tDiffuse; #include #include varying vec2 vUv; void main() { gl_FragColor = texture2D( tDiffuse, vUv ); // tone mapping #ifdef LINEAR_TONE_MAPPING gl_FragColor.rgb = LinearToneMapping( gl_FragColor.rgb ); #elif defined( REINHARD_TONE_MAPPING ) gl_FragColor.rgb = ReinhardToneMapping( gl_FragColor.rgb ); #elif defined( CINEON_TONE_MAPPING ) gl_FragColor.rgb = CineonToneMapping( gl_FragColor.rgb ); #elif defined( ACES_FILMIC_TONE_MAPPING ) gl_FragColor.rgb = ACESFilmicToneMapping( gl_FragColor.rgb ); #elif defined( AGX_TONE_MAPPING ) gl_FragColor.rgb = AgXToneMapping( gl_FragColor.rgb ); #elif defined( NEUTRAL_TONE_MAPPING ) gl_FragColor.rgb = NeutralToneMapping( gl_FragColor.rgb ); #elif defined( CUSTOM_TONE_MAPPING ) gl_FragColor.rgb = CustomToneMapping( gl_FragColor.rgb ); #endif // color space #ifdef SRGB_TRANSFER gl_FragColor = sRGBTransferOETF( gl_FragColor ); #endif }`},Ng=class extends xg{constructor(){super(),this.isOutputPass=!0,this.uniforms=Qr.clone(Mg.uniforms),this.material=new ni({name:Mg.name,uniforms:this.uniforms,vertexShader:Mg.vertexShader,fragmentShader:Mg.fragmentShader}),this._fsQuad=new wg(this.material),this._outputColorSpace=null,this._toneMapping=null}render(e,t,n){this.uniforms.tDiffuse.value=n.texture,this.uniforms.toneMappingExposure.value=e.toneMappingExposure,(this._outputColorSpace!==e.outputColorSpace||this._toneMapping!==e.toneMapping)&&(this._outputColorSpace=e.outputColorSpace,this._toneMapping=e.toneMapping,this.material.defines={},J.getTransfer(this._outputColorSpace)===`srgb`&&(this.material.defines.SRGB_TRANSFER=``),this._toneMapping===1?this.material.defines.LINEAR_TONE_MAPPING=``:this._toneMapping===2?this.material.defines.REINHARD_TONE_MAPPING=``:this._toneMapping===3?this.material.defines.CINEON_TONE_MAPPING=``:this._toneMapping===4?this.material.defines.ACES_FILMIC_TONE_MAPPING=``:this._toneMapping===6?this.material.defines.AGX_TONE_MAPPING=``:this._toneMapping===7?this.material.defines.NEUTRAL_TONE_MAPPING=``:this._toneMapping===5&&(this.material.defines.CUSTOM_TONE_MAPPING=``),this.material.needsUpdate=!0),this.renderToScreen===!0?(e.setRenderTarget(null),this._fsQuad.render(e)):(e.setRenderTarget(t),this.clear&&e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil),this._fsQuad.render(e))}dispose(){this.material.dispose(),this._fsQuad.dispose()}},Pg=` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); } `,Fg=` uniform sampler2D uFill; uniform sampler2D uGhost; uniform sampler2D uSubdiv; // lerped subdiv depth (drives grid-line opacity fade) uniform sampler2D uSubdivLevel; // integer target level (drives shape-mask geometry, snaps instantly) uniform vec2 uGridSize; // (gridW, gridH) in finest cells uniform vec2 uResolution; // viewport in CSS pixels uniform sampler2D uColPosTex; // Bresenham column boundaries: R32F, width=gridW+1, height=1 uniform sampler2D uRowPosTex; // Bresenham row boundaries: R32F, width=gridH+1, height=1 uniform vec3 uLineColor; uniform float uLineOpacity; uniform float uLineWidth; uniform float uLineBlend; uniform vec4 uNewColor; uniform vec4 uParentColor; uniform vec4 uPruneColor; uniform vec4 uTracerColor; uniform float uTracerBlend; uniform vec4 uWinnerColor; // fill/ghost recolor for locked (victory) squares uniform vec4 uVictoryTracerColor; // celebratory tracer ripple color uniform vec4 uClickFlashColor; uniform vec4 uClickFlashRect; // (gx, gy, gx+span, gy+span) uniform float uClickFlashIntensity; uniform float uTime; uniform float uMaxLevel; // subdivisionLevels (max level index) uniform vec4 uHoverRect; // (gx, gy, gx+span, gy+span) in finest cells uniform float uHoverActive; // 1.0 = hover active uniform float uHoverIsEmpty; // 1.0 = hovering empty tile, 0.0 = filled tile uniform vec3 uHoverEmptyColor; uniform float uHoverEmptyBlend; uniform float uHoverEmptyOpacity; uniform vec3 uHoverFilledColor; uniform float uHoverFilledBlend; uniform float uHoverFilledOpacity; uniform vec3 uHoverParentColor; // highlight color for parent squares / subtree uniform sampler2D uHoverSubtree; // per-cell subtree highlight (R: 0=none, 255=highlighted) uniform float uHoverSubtreeBlend; // blend mode for subtree overlay uniform float uHoverSubtreeOpacity; // opacity of subtree overlay uniform float uCellShape; // 0=square, 1=circle, 2=roundedRect uniform float uCellRadius; // corner radius for roundedRect (0..0.5) uniform float uCellAA; // 1=antialiased edges, 0=hard edges varying vec2 vUv; // Bresenham grid helpers — fetch integer pixel boundary at index i from a // 1-row R32F texture whose width is gridW+1 (col) or gridH+1 (row). float fetchColPos(int i) { return texture2D(uColPosTex, vec2((float(i) + 0.5) / (uGridSize.x + 1.0), 0.5)).r; } float fetchRowPos(int i) { return texture2D(uRowPosTex, vec2((float(i) + 0.5) / (uGridSize.y + 1.0), 0.5)).r; } // Find finest cell index s.t. positions[i] <= x < positions[i+1]. // Initial guess via proportional interpolation; one correction step suffices // because Bresenham cells differ by at most 1 px from the nominal stride. int findCellX(float x) { int n = int(uGridSize.x); int i = int(clamp(x / uResolution.x * uGridSize.x, 0.0, uGridSize.x - 1.0)); if (i < n - 1 && fetchColPos(i + 1) <= x) i = i + 1; else if (i > 0 && fetchColPos(i) > x) i = i - 1; return i; } int findCellY(float y) { int n = int(uGridSize.y); int i = int(clamp(y / uResolution.y * uGridSize.y, 0.0, uGridSize.y - 1.0)); if (i < n - 1 && fetchRowPos(i + 1) <= y) i = i + 1; else if (i > 0 && fetchRowPos(i) > y) i = i - 1; return i; } void main() { vec2 pixel = vUv * uResolution; int fiX = findCellX(pixel.x); int fiY = findCellY(pixel.y); vec2 texelCenter = (vec2(float(fiX), float(fiY)) + 0.5) / uGridSize; vec4 fillSample = texture2D(uFill, texelCenter); float fillEncoded = fillSample.r * 255.0; float state = fillSample.g * 255.0; float animProgress = fillSample.b * 255.0; // 0-254 = animating, 255 = fully visible float animCorner = fillSample.a * 255.0; // 0-3 = corner, 4-7 = edge, 255 = no anim // subdivDepth: lerped float level (drives grid-line opacity fade). float subdivDepth = texture2D(uSubdiv, texelCenter).r * 255.0 / 36.4; // subdivLevel: integer target level (drives shape-mask geometry — snaps // instantly on subdivision change so the visible cell shape doesn't lag // behind the data model). float subdivLevel = floor(texture2D(uSubdivLevel, texelCenter).r * 255.0 + 0.5); // Decode fill float levelFlag = mod(fillEncoded, 8.0); float age = floor(fillEncoded / 8.0); bool isFilled = levelFlag > 0.5; // ── Unified shape mask ── // Cells are inset on the trailing edges so fill never overlaps grid lines: // interior = [snappedMin, snappedMax − lineWidth] // The full mask path runs whenever the shape isn't a square or growth // animation is active; otherwise we take the cheap wipe path below. vec4 ghostSample = texture2D(uGhost, texelCenter); float shapeMask = 1.0; bool needFullMask = uCellShape > 0.5 || uLineWidth > 0.001; bool isAnimating = isFilled && animCorner < 9.0; if (needFullMask || isAnimating) { float ghostLevel = ghostSample.b * 255.0; float maskLevel = isFilled ? (levelFlag - 1.0) : (ghostLevel > 0.1 ? ghostLevel : subdivLevel); int spanF_m = int(round(exp2(uMaxLevel - maskLevel))); int ci_mx = fiX / spanF_m; int ci_my = fiY / spanF_m; vec2 snappedMin = vec2(fetchColPos(ci_mx * spanF_m), fetchRowPos(ci_my * spanF_m)); vec2 snappedMax_pre = vec2(fetchColPos((ci_mx + 1) * spanF_m), fetchRowPos((ci_my + 1) * spanF_m)); vec2 maskSpanPx = snappedMax_pre - snappedMin; // Growth animation progress float growP = 1.0; vec2 growPt = vec2(0.5); if (isAnimating) { growP = animProgress / 255.0; if (animCorner < 0.5) growPt = vec2(0.0, 0.0); // TL else if (animCorner < 1.5) growPt = vec2(1.0, 0.0); // TR else if (animCorner < 2.5) growPt = vec2(0.0, 1.0); // BL else if (animCorner < 3.5) growPt = vec2(1.0, 1.0); // BR else if (animCorner < 4.5) growPt = vec2(0.5, 0.0); // TOP else if (animCorner < 5.5) growPt = vec2(1.0, 0.5); // RIGHT else if (animCorner < 6.5) growPt = vec2(0.5, 1.0); // BOTTOM else if (animCorner < 7.5) growPt = vec2(0.0, 0.5); // LEFT else growPt = vec2(0.5, 0.5); // CENTER } if (needFullMask) { // Full path: snapped bounds + inset + shape SDF vec2 snappedMax = snappedMax_pre; vec2 snappedSpan = maskSpanPx; // Inset only on the trailing edges (where grid lines sit). vec2 insetLo = vec2(0.0); vec2 insetHi = vec2(uLineWidth); vec2 contentMin = snappedMin + insetLo; vec2 contentMax = snappedMax - insetHi; vec2 contentSpan = contentMax - contentMin; vec2 maskPos = (pixel - contentMin) / contentSpan; if (uCellShape < 0.5) { // ── Square with inset ── // Outer cell edges (contentMin/contentMax) stay pixel-binary so the // grid stays crisp. The grow wavefront gets ~1 px AA when uCellAA is on, // giving smooth sub-pixel growth across every grow direction. if (pixel.x < contentMin.x || pixel.x >= contentMax.x || pixel.y < contentMin.y || pixel.y >= contentMax.y) { shapeMask = 0.0; } else if (growP < 1.0) { vec2 gp = maskPos; // Signed distance from this pixel to the grow wavefront // (positive = masked / outside the grown area, negative = inside). float gdist; if (animCorner < 0.5) { gdist = max(gp.x - growP, gp.y - growP); } else if (animCorner < 1.5) { gdist = max((1.0 - growP) - gp.x, gp.y - growP); } else if (animCorner < 2.5) { gdist = max(gp.x - growP, (1.0 - growP) - gp.y); } else if (animCorner < 3.5) { gdist = max((1.0 - growP) - gp.x, (1.0 - growP) - gp.y); } else if (animCorner < 4.5) { gdist = gp.y - growP; } else if (animCorner < 5.5) { gdist = (1.0 - growP) - gp.x; } else if (animCorner < 6.5) { gdist = (1.0 - growP) - gp.y; } else if (animCorner < 7.5) { gdist = gp.x - growP; } else { float margin = (1.0 - growP) * 0.5; vec2 dd = max(margin - gp, gp - (1.0 - margin)); gdist = max(dd.x, dd.y); } if (uCellAA > 0.5) { float aa = min(fwidth(gdist) * 0.5, 0.5); shapeMask = 1.0 - smoothstep(-aa, aa, gdist); } else { shapeMask = gdist <= 0.0 ? 1.0 : 0.0; } } } else { // ── Circle / Rounded Rect ── // Shape fills the content area; SDF coords are already normalized to [0,1]. vec2 sdfPos = maskPos; if (sdfPos.x < 0.0 || sdfPos.x > 1.0 || sdfPos.y < 0.0 || sdfPos.y > 1.0) { shapeMask = 0.0; } if (shapeMask > 0.5) { bool growing = growP > 0.001 && growP < 1.0; bool notStarted = growP <= 0.001; vec2 testPos = notStarted ? vec2(-1.0) : (growing ? growPt + (sdfPos - growPt) / growP : sdfPos); vec2 centered = testPos - 0.5; // SDF signed distance: negative inside, positive outside. // fwidth(dist) naturally accounts for the 1/growP scaling during // grow, giving a 1-screen-pixel AA transition at any grow stage. // The 0.5 clamp guards against degenerate fwidth values. float dist; if (uCellShape < 1.5) { dist = length(centered) - 0.5; } else { float r = uCellRadius; vec2 d = abs(centered) - (0.5 - r); dist = length(max(d, 0.0)) + min(max(d.x, d.y), 0.0) - r; } if (uCellAA > 0.5) { float aa = min(fwidth(dist) * 0.5, 0.5); shapeMask = 1.0 - smoothstep(-aa, aa, dist); } else { shapeMask = dist <= 0.0 ? 1.0 : 0.0; } } } } else { // Cheap path: square, no inset, just growth animation wipe vec2 maskPos = (pixel - snappedMin) / maskSpanPx; if (growP < 1.0) { bool masked = false; if (animCorner < 0.5) { masked = maskPos.x >= growP || maskPos.y >= growP; } else if (animCorner < 1.5) { masked = maskPos.x <= (1.0 - growP) || maskPos.y >= growP; } else if (animCorner < 2.5) { masked = maskPos.x >= growP || maskPos.y <= (1.0 - growP); } else if (animCorner < 3.5) { masked = maskPos.x <= (1.0 - growP) || maskPos.y <= (1.0 - growP); } else if (animCorner < 4.5) { masked = maskPos.y >= growP; } else if (animCorner < 5.5) { masked = maskPos.x <= (1.0 - growP); } else if (animCorner < 6.5) { masked = maskPos.y <= (1.0 - growP); } else if (animCorner < 7.5) { masked = maskPos.x >= growP; } else { float margin = (1.0 - growP) * 0.5; masked = maskPos.x < margin || maskPos.x > (1.0 - margin) || maskPos.y < margin || maskPos.y > (1.0 - margin); } if (masked) shapeMask = 0.0; } } } // ── Decode victory flags from ghost alpha byte ── // bit 7 (>=128) = locked flag, bits 0-6 (0-127) = victory color blend progress float aByte = ghostSample.a * 255.0; float lockedFlag = step(127.5, aByte); float victoryProgress = mod(aByte, 128.0) / 127.0; // ── 1. Compute fill layer ── float fillA = 0.0; vec3 fillCol = vec3(0.0); if (isFilled && shapeMask > 0.0) { float fadeAlpha = clamp(age / 20.0, 0.0, 1.0); // Color interpolation: 64=new, 128=parent, 255=dead end (pruneColor) // RGB blends smoothly; alpha snaps to target state (no blended opacity) float s = state; vec3 stateRGB = uNewColor.rgb; float stateA = uNewColor.a; if (s >= 128.0) { float t = (s - 128.0) / 127.0; stateRGB = mix(uParentColor.rgb, uPruneColor.rgb, t); stateA = t < 0.5 ? uParentColor.a : uPruneColor.a; } else if (s >= 64.0) { float t = (s - 64.0) / 64.0; stateRGB = mix(uNewColor.rgb, uParentColor.rgb, t); stateA = t < 0.5 ? uNewColor.a : uParentColor.a; } // Locked (victory) blend toward winner color, staggered root → tip if (lockedFlag > 0.5 && victoryProgress > 0.0) { stateRGB = mix(stateRGB, uWinnerColor.rgb, victoryProgress); stateA = mix(stateA, uWinnerColor.a, victoryProgress); } fillCol = stateRGB; fillA = stateA * fadeAlpha; } // ── 1b. Ghost layer (dying branch fading out) + tracer ── float ghostA = 0.0; vec3 ghostCol = vec3(0.0); float tracerA = 0.0; vec3 tracerCol = vec3(0.0); { float ghostOpacity = ghostSample.r; float tracerIntensity = ghostSample.g; bool inFadeOut = ghostOpacity > 0.004; // Locked squares fade from a state-blended color (current state mixed // toward winner) — usually fully winner color by the time fade fires. vec3 stateBaseCol = uPruneColor.rgb; float stateBaseA = uPruneColor.a; if (lockedFlag > 0.5) { stateBaseCol = mix(stateBaseCol, uWinnerColor.rgb, victoryProgress); stateBaseA = mix(stateBaseA, uWinnerColor.a, victoryProgress); } if (inFadeOut) { ghostCol = stateBaseCol; ghostA = ghostOpacity * stateBaseA; } if (tracerIntensity > 0.004) { // Tracer color depends on context: locked-and-alive cells use the // celebratory color, doomed/fading cells use the prune tracer color. bool useVictory = lockedFlag > 0.5 && !inFadeOut; vec3 tCol = useVictory ? uVictoryTracerColor.rgb : uTracerColor.rgb; float tA = useVictory ? uVictoryTracerColor.a : uTracerColor.a; tracerCol = tCol; tracerA = tracerIntensity * tA; } } // ── 2. Compute grid lines ── // Outer border: pixels outside [positions[0], positions[gridN]) on either // axis render at full opacity. When the boundary tables span the full // canvas (the default) this check never fires. // Interior lines: trailing lineW px of each finest cell. float border = 0.0; float lineW = uLineWidth; { float gridX0 = fetchColPos(0); float gridXN = fetchColPos(int(uGridSize.x)); float gridY0 = fetchRowPos(0); float gridYN = fetchRowPos(int(uGridSize.y)); if (pixel.x < gridX0 || pixel.x >= gridXN || pixel.y < gridY0 || pixel.y >= gridYN) { // Outer border zone — always level 0 (full opacity). border = 1.0; } else { float rightEdgeX = fetchColPos(fiX + 1); float rightEdgeY = fetchRowPos(fiY + 1); bool onBandX = (fiX < int(uGridSize.x) - 1) && (pixel.x >= rightEdgeX - lineW); bool onBandY = (fiY < int(uGridSize.y) - 1) && (pixel.y >= rightEdgeY - lineW); if (onBandX || onBandY) { float levelX = uMaxLevel; float levelY = uMaxLevel; if (onBandX) { float boundIdx = float(fiX) + 1.0; for (int L = 0; L <= 6; L++) { if (float(L) > uMaxLevel) break; float factor = exp2(uMaxLevel - float(L)); if (mod(boundIdx, factor) < 0.5) { levelX = float(L); break; } } } if (onBandY) { float boundIdx = float(fiY) + 1.0; for (int L = 0; L <= 6; L++) { if (float(L) > uMaxLevel) break; float factor = exp2(uMaxLevel - float(L)); if (mod(boundIdx, factor) < 0.5) { levelY = float(L); break; } } } float lineLevel = min( onBandX ? levelX : 999.0, onBandY ? levelY : 999.0 ); float levelOpacity = (lineLevel < 0.5) ? 1.0 : clamp(subdivDepth - lineLevel + 1.0, 0.0, 1.0); border = levelOpacity; } } } // ── 3. Hover highlight (fill with blend mode) ── float hoverA = 0.0; vec3 hColor = vec3(0.0); float hoverBlend = 0.0; if (uHoverActive > 0.5) { vec2 hMin = vec2(fetchColPos(int(uHoverRect.x)), fetchRowPos(int(uHoverRect.y))); vec2 hMax = vec2(fetchColPos(int(uHoverRect.z)), fetchRowPos(int(uHoverRect.w))); bool inRect = pixel.x >= hMin.x && pixel.x < hMax.x && pixel.y >= hMin.y && pixel.y < hMax.y; if (inRect) { if (uHoverIsEmpty > 0.5) { hColor = uHoverEmptyColor; hoverA = uHoverEmptyOpacity; hoverBlend = uHoverEmptyBlend; } else { hColor = uHoverFilledColor; hoverA = uHoverFilledOpacity; hoverBlend = uHoverFilledBlend; } } } // ── 4. Compose: ghost → fill → hover → subtree → grid → tracer (on top) ── float lineA = uLineOpacity * border; // Start with ghost layer vec3 color = ghostCol * ghostA; float alpha = ghostA; // Fill over ghost color = color * (1.0 - fillA) + fillCol * fillA; alpha = alpha * (1.0 - fillA) + fillA; // Click flash over fill if (uClickFlashIntensity > 0.0) { vec2 cfMin = vec2(fetchColPos(int(uClickFlashRect.x)), fetchRowPos(int(uClickFlashRect.y))); vec2 cfMax = vec2(fetchColPos(int(uClickFlashRect.z)), fetchRowPos(int(uClickFlashRect.w))); if (pixel.x >= cfMin.x && pixel.x < cfMax.x && pixel.y >= cfMin.y && pixel.y < cfMax.y) { float cfA = uClickFlashIntensity * uClickFlashColor.a; color = color * (1.0 - cfA) + uClickFlashColor.rgb * cfA; alpha = alpha * (1.0 - cfA) + cfA; } } // Subtree hover overlay — only fetch texture when hover is active if (uHoverActive > 0.5) { float stFlag = texture2D(uHoverSubtree, texelCenter).r; if (stFlag > 0.5) { float stA = uHoverSubtreeOpacity; vec3 stCol = uHoverParentColor; vec3 stBlended; if (uHoverSubtreeBlend < 0.5) { stBlended = stCol; } else if (uHoverSubtreeBlend < 1.5) { stBlended = color * stCol; } else if (uHoverSubtreeBlend < 2.5) { stBlended = 1.0 - (1.0 - color) * (1.0 - stCol); } else if (uHoverSubtreeBlend < 3.5) { vec3 lo = 2.0 * color * stCol; vec3 hi = 1.0 - 2.0 * (1.0 - color) * (1.0 - stCol); stBlended = mix(lo, hi, step(0.5, color)); } else { stBlended = (1.0 - 2.0 * stCol) * color * color + 2.0 * stCol * color; } color = color * (1.0 - stA) + stBlended * stA; alpha = alpha * (1.0 - stA) + stA; } } // Hover rect fill on top of subtree (with blend mode) if (hoverA > 0.0) { vec3 hBlended; if (hoverBlend < 0.5) { hBlended = hColor; } else if (hoverBlend < 1.5) { hBlended = color * hColor; } else if (hoverBlend < 2.5) { hBlended = 1.0 - (1.0 - color) * (1.0 - hColor); } else if (hoverBlend < 3.5) { vec3 lo = 2.0 * color * hColor; vec3 hi = 1.0 - 2.0 * (1.0 - color) * (1.0 - hColor); hBlended = mix(lo, hi, step(0.5, color)); } else { hBlended = (1.0 - 2.0 * hColor) * color * color + 2.0 * hColor * color; } color = color * (1.0 - hoverA) + hBlended * hoverA; alpha = alpha * (1.0 - hoverA) + hoverA; } // Apply cell shape mask to fill, ghost, hover layers (NOT grid lines or tracer) alpha *= shapeMask; color *= shapeMask; // Grid lines on top — unmasked, always straight lines if (lineA > 0.0) { vec3 blended; if (uLineBlend < 0.5) { blended = uLineColor; } else if (uLineBlend < 1.5) { blended = color * uLineColor; } else if (uLineBlend < 2.5) { blended = 1.0 - (1.0 - color) * (1.0 - uLineColor); } else if (uLineBlend < 3.5) { vec3 lo = 2.0 * color * uLineColor; vec3 hi = 1.0 - 2.0 * (1.0 - color) * (1.0 - uLineColor); blended = mix(lo, hi, step(0.5, color)); } else { blended = (1.0 - 2.0 * uLineColor) * color * color + 2.0 * uLineColor * color; } color = color * (1.0 - lineA) + blended * lineA; alpha = alpha * (1.0 - lineA) + lineA; } // Tracer on top of everything (with blend mode) — masked to cell shape float maskedTracerA = tracerA * shapeMask; if (maskedTracerA > 0.0) { vec3 tBlended; if (uTracerBlend < 0.5) { tBlended = tracerCol; } else if (uTracerBlend < 1.5) { tBlended = color * tracerCol; } else if (uTracerBlend < 2.5) { tBlended = 1.0 - (1.0 - color) * (1.0 - tracerCol); } else if (uTracerBlend < 3.5) { vec3 lo = 2.0 * color * tracerCol; vec3 hi = 1.0 - 2.0 * (1.0 - color) * (1.0 - tracerCol); tBlended = mix(lo, hi, step(0.5, color)); } else { tBlended = (1.0 - 2.0 * tracerCol) * color * color + 2.0 * tracerCol * color; } color = color * (1.0 - maskedTracerA) + tBlended * maskedTracerA; alpha = alpha * (1.0 - maskedTracerA) + maskedTracerA; } if (alpha < 0.005) { gl_FragColor = vec4(0.0); return; } gl_FragColor = vec4(color, alpha); } `,Ig=` uniform sampler2D tDiffuse; uniform float uOffset; varying vec2 vUv; void main() { float r = texture2D(tDiffuse, vUv + vec2( uOffset, 0.0)).r; float g = texture2D(tDiffuse, vUv).g; float b = texture2D(tDiffuse, vUv + vec2(-uOffset, 0.0)).b; float a = texture2D(tDiffuse, vUv).a; gl_FragColor = vec4(r, g, b, a); } `,Lg=` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); } `;function Rg(e,t,n=0){let r=new Float32Array(t+1),i=Math.floor(e/t),a=e%t;r[0]=n;for(let e=0;eMath.floor(e*a/t);r[e+1]=r[e]+i+(n?1:0)}return r}function zg(e,t){let n=e.length-1;if(t<0||t>=e[n])return-1;let r=0,i=n-1;for(;r>1;e[n]<=t?r=n:i=n-1}return r}var Bg={uniforms:{tDiffuse:{value:null},offset:{value:1},darkness:{value:1}},vertexShader:` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position,1.0); } `,fragmentShader:` uniform sampler2D tDiffuse; uniform float offset; uniform float darkness; varying vec2 vUv; void main() { vec4 texel = texture2D(tDiffuse, vUv); vec2 uv = (vUv - 0.5) * vec2(offset); float vign = clamp(1.0 - dot(uv, uv), 0.0, 1.0); texel.rgb *= mix(1.0, vign, darkness); gl_FragColor = texel; } `},Vg={uniforms:{tDiffuse:{value:null},intensity:{value:.1},time:{value:0}},vertexShader:` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position,1.0); } `,fragmentShader:` uniform sampler2D tDiffuse; uniform float intensity; uniform float time; varying vec2 vUv; float hash(vec2 p) { return fract(sin(dot(p, vec2(12.9898, 78.233))) * 43758.5453); } void main() { vec4 texel = texture2D(tDiffuse, vUv); float n = hash(vUv + vec2(time, -time)) - 0.5; texel.rgb += n * intensity; gl_FragColor = texel; } `},Hg={linear:e=>e,easeIn:e=>e*e,easeOut:e=>e*(2-e),easeInOut:e=>e<.5?2*e*e:-1+(4-2*e)*e,expoOut:e=>e===1?1:1-2**(-10*e),expoIn:e=>e===0?0:2**(10*(e-1)),expoInOut:e=>e===0||e===1?e:e<.5?2**(20*e-10)/2:(2-2**(-20*e+10))/2,cubicOut:e=>1-(1-e)**3,cubicIn:e=>e*e*e,backOut:e=>{let t=1.70158;return 1+(t+1)*(e-1)**3+t*(e-1)**2},bounceOut:e=>e<1/2.75?7.5625*e*e:e<2/2.75?(e-=1.5/2.75,7.5625*e*e+.75):e<2.5/2.75?(e-=2.25/2.75,7.5625*e*e+.9375):(e-=2.625/2.75,7.5625*e*e+.984375)},Ug={Linear:`linear`,"Ease In":`easeIn`,"Ease Out":`easeOut`,"Ease In-Out":`easeInOut`,"Expo Out":`expoOut`,"Expo In":`expoIn`,"Expo In-Out":`expoInOut`,"Cubic Out":`cubicOut`,"Cubic In":`cubicIn`,"Back Out":`backOut`,"Bounce Out":`bounceOut`},Wg=0,Gg=1,Kg=2,qg=3,Jg=4,Yg=5,Xg=6,Zg=7,Qg=8,$g=[Wg,Gg,Kg,qg,Jg,Yg,Xg,Zg],e_={cellSize:96,subdivisionLevels:3,outerBorder:!1,lineColor:{r:4,g:4,b:4,a:1},lineWidth:1,lineWidthDp:null,gridSnapToDevicePixels:!0,lineBlend:`normal`,gridLineFade:300,bgColor:`#000000`,seedMode:`random`,seedEdge:`left`,seedCorner:`TL`,seedX:50,seedY:50,seedVarianceX:0,seedVarianceY:0,genSpeed:1400,maxGenerations:1e3,shrinkBias:.35,minChildren:0,maxChildren:4,pruneEnabled:!0,dirTL:!0,dirTR:!0,dirBL:!0,dirBR:!0,dirTop:!0,dirRight:!0,dirBottom:!0,dirLeft:!0,restrictedGenerationsEnabled:!1,restrictedGenerations:10,dirPriorityTL:1,dirPriorityTR:2,dirPriorityBL:3,dirPriorityBR:4,dirPriorityTop:5,dirPriorityRight:6,dirPriorityBottom:7,dirPriorityLeft:8,showSquares:!0,cellShape:`square`,cellRadius:.25,cellAA:!0,growOriginMode:`corner`,newColor:{r:255,g:255,b:255,a:1},parentColor:{r:10,g:0,b:255,a:1},growDurationMode:`interval`,growDuration:700,growEasing:`linear`,fadeInDuration:0,parentTransition:1e3,colorEasing:`expoOut`,pruneColor:{r:121,g:46,b:255,a:1},pruneTransition:500,fadeOutStagger:20,maxStaggerTotal:1e3,fadeOutDuration:0,soothingFinalRetraction:!1,tracerEnabled:!0,tracerColor:{r:255,g:120,b:0,a:1},tracerBlend:`normal`,tracerDuration:100,victoryEnabled:!1,victoryColor:{r:0,g:255,b:136,a:1},victoryTransition:500,victoryTracerEnabled:!0,victoryTracerColor:{r:255,g:255,b:255,a:1},victoryTracerDuration:400,hoverEmptyColor:{r:255,g:255,b:255,a:.15},hoverEmptyBlend:`normal`,hoverFilledColor:{r:255,g:68,b:0,a:1},hoverFilledBlend:`normal`,hoverParentColor:{r:255,g:131,b:0,a:1},hoverSubtreeBlend:`normal`,hoverStagger:10,maxHoverTotal:500,clickFlashColor:{r:255,g:255,b:255,a:.8},clickFlashDuration:300,treeEnabled:!1,treeColor:{r:0,g:255,b:136,a:.6},treeWidth:2,treeRoundedness:.5,treeSegments:12,treeBlend:`screen`,treeHoverColor:{r:255,g:68,b:0,a:1},treeGrowColor:{r:255,g:255,b:255,a:1},treePruneTransition:300,treeGrowTransition:500,treePruneDurationMode:`stagger`,treePruneDuration:400,pregenEnabled:!1,pregenGenerations:10,pregenFadeInDuration:800,pregenFadeInStagger:30,postFxEnabled:!1,bloomEnabled:!1,bloomIntensity:0,bloomThreshold:0,bloomRadius:0,vignetteEnabled:!1,vignetteDarkness:0,vignetteOffset:1,chromaticEnabled:!1,chromaticOffset:0,noiseEnabled:!1,noiseIntensity:.1,noiseStatic:!1,responsive:null},t_=[`mobilePortrait`,`mobileLandscape`,`tablet`,`desktop`],n_={mobilePortrait:`(max-width: 479px)`,mobileLandscape:`(min-width: 480px) and (max-width: 767px)`,tablet:`(min-width: 768px) and (max-width: 991px)`,desktop:`(min-width: 992px)`},r_={desktop:[],tablet:[`tablet`],mobileLandscape:[`tablet`,`mobileLandscape`],mobilePortrait:[`tablet`,`mobileLandscape`,`mobilePortrait`]},i_=500,a_={normal:0,multiply:1,screen:2,overlay:3,softLight:4},o_={square:0,circle:1,roundedRect:2},s_=[{name:`middle`,build:!0,config:{cellSize:64,subdivisionLevels:2,lineColor:{r:59.14142809416118,g:73.13420951671168,b:85.6142578125,a:.23},seedMode:`position`,seedX:75,genSpeed:3e3,maxGenerations:50,shrinkBias:.6,minChildren:1,maxChildren:2,cellShape:`roundedRect`,cellRadius:.18,newColor:{r:192,g:178,b:202,a:1},parentColor:{r:70.42817199248123,g:63.2047697368421,b:109.171875,a:1},fadeInDuration:1e3,parentTransition:2717,colorEasing:`linear`,pruneColor:{r:255,g:131,b:0,a:.725},pruneTransition:2500,fadeOutStagger:400,maxStaggerTotal:1600,fadeOutDuration:600,tracerColor:{r:255,g:162,b:79,a:1},tracerDuration:200,hoverEmptyColor:{r:255,g:255,b:255,a:.049019607843137254},hoverFilledColor:{r:255,g:255,b:255,a:.25},hoverParentColor:{r:255,g:162,b:79,a:.686},pregenEnabled:!0,pregenGenerations:14,pregenFadeInDuration:1200,pregenFadeInStagger:65,postFxEnabled:!0,bloomEnabled:!0,bloomIntensity:.2,bloomThreshold:.25,bloomRadius:.1,vignetteEnabled:!0,vignetteDarkness:1.3,vignetteOffset:1.2,noiseEnabled:!0,noiseIntensity:.05,noiseStatic:!0,responsive:{tablet:{cellSize:48,seedX:50,seedY:17.5},mobileLandscape:{cellSize:42,lineWidthDp:1,lineColor:{r:52,g:52,b:52,a:.696}},mobilePortrait:{cellSize:38}}}},{name:`footer`,build:!0,config:{cellSize:64,subdivisionLevels:2,lineColor:{r:59,g:73,b:86,a:.23},seedMode:`corner`,seedCorner:`BR`,genSpeed:2500,maxGenerations:50,shrinkBias:.6,minChildren:1,cellRadius:.18,growOriginMode:`center`,newColor:{r:192,g:178,b:202,a:1},parentColor:{r:70,g:63,b:109,a:1},fadeInDuration:1e3,parentTransition:2717,colorEasing:`linear`,pruneColor:{r:255,g:131,b:0,a:.725},pruneTransition:2500,fadeOutStagger:400,maxStaggerTotal:1600,fadeOutDuration:600,soothingFinalRetraction:!0,tracerColor:{r:255,g:162,b:79,a:1},tracerDuration:200,hoverEmptyColor:{r:255,g:255,b:255,a:.049},hoverFilledColor:{r:255,g:255,b:255,a:.25},hoverParentColor:{r:255,g:162,b:79,a:.686},pregenEnabled:!0,pregenGenerations:16,pregenFadeInDuration:200,pregenFadeInStagger:85,postFxEnabled:!0,bloomEnabled:!0,bloomIntensity:.2,bloomThreshold:.25,bloomRadius:.1,vignetteEnabled:!0,vignetteDarkness:1.3,vignetteOffset:1.2,noiseEnabled:!0,noiseIntensity:.05,noiseStatic:!0,responsive:{tablet:{cellSize:48,seedMode:`position`,seedX:85,seedY:10},mobileLandscape:{cellSize:42,lineWidthDp:1,lineColor:{r:52,g:52,b:52,a:.696},pregenGenerations:12},mobilePortrait:{cellSize:38}}}},{name:`header`,build:!0,config:{cellSize:64,subdivisionLevels:2,lineColor:{r:59,g:73,b:86,a:.23},seedMode:`position`,seedX:0,seedY:40,genSpeed:2e3,maxGenerations:50,shrinkBias:.6,minChildren:1,maxChildren:3,dirTL:!1,dirBL:!1,dirTop:!1,dirBottom:!1,dirLeft:!1,restrictedGenerationsEnabled:!0,restrictedGenerations:5,dirPriorityBR:2,dirPriorityRight:1,cellShape:`circle`,cellRadius:.18,newColor:{r:192,g:178,b:202,a:1},parentColor:{r:70,g:63,b:109,a:1},fadeInDuration:1e3,parentTransition:2717,colorEasing:`linear`,pruneColor:{r:255,g:131,b:0,a:.725},pruneTransition:2500,fadeOutStagger:400,maxStaggerTotal:1600,fadeOutDuration:600,soothingFinalRetraction:!0,tracerColor:{r:255,g:162,b:79,a:1},tracerDuration:200,victoryEnabled:!0,victoryColor:{r:117,g:107,b:174,a:1},hoverEmptyColor:{r:255,g:255,b:255,a:.049},hoverFilledColor:{r:255,g:255,b:255,a:.25},hoverParentColor:{r:255,g:162,b:79,a:.686},treeEnabled:!0,treeColor:{r:255,g:255,b:255,a:.069},treeWidth:1,treeRoundedness:1,treeSegments:32,treeBlend:`normal`,treeHoverColor:{r:155,g:73,b:0,a:1},treePruneTransition:200,treeGrowTransition:540,treePruneDurationMode:`custom`,treePruneDuration:410,pregenEnabled:!0,pregenGenerations:12,pregenFadeInDuration:1200,pregenFadeInStagger:65,postFxEnabled:!0,bloomEnabled:!0,bloomIntensity:.2,bloomThreshold:.25,bloomRadius:.1,vignetteEnabled:!0,vignetteDarkness:1.3,vignetteOffset:1.2,noiseEnabled:!0,noiseIntensity:.05,noiseStatic:!0,responsive:{tablet:{cellSize:48},mobileLandscape:{cellSize:42,pregenGenerations:12,lineWidthDp:1,lineColor:{r:52,g:52,b:52,a:.696}},mobilePortrait:{cellSize:38,restrictedGenerations:3}}}}],c_=new Y;function l_(e){return new Y(e.r/255,e.g/255,e.b/255).convertSRGBToLinear()}function u_(e,t){e.setRGB(t.r/255,t.g/255,t.b/255).convertSRGBToLinear()}function d_(e){return c_.setRGB(e.r/255,e.g/255,e.b/255).convertSRGBToLinear(),new Tt(c_.r,c_.g,c_.b,e.a)}function f_(e,t){c_.setRGB(t.r/255,t.g/255,t.b/255).convertSRGBToLinear(),e.set(c_.r,c_.g,c_.b,t.a)}function p_(e,t){return e&&typeof e==`object`&&t&&typeof t==`object`?e.r===t.r&&e.g===t.g&&e.b===t.b&&e.a===t.a:e===t}function m_(e,t){switch(e){case`seedEdge`:return t.seedMode===`edge`||t.seedMode===`edgeCenter`;case`seedCorner`:return t.seedMode===`corner`;case`seedX`:case`seedY`:case`seedVarianceX`:case`seedVarianceY`:return t.seedMode===`position`;case`restrictedGenerations`:case`dirPriorityTL`:case`dirPriorityTR`:case`dirPriorityBL`:case`dirPriorityBR`:case`dirPriorityTop`:case`dirPriorityRight`:case`dirPriorityBottom`:case`dirPriorityLeft`:return!!t.restrictedGenerationsEnabled;case`treeColor`:case`treeWidth`:case`treeRoundedness`:case`treeSegments`:case`treeBlend`:case`treeHoverColor`:case`treeGrowColor`:case`treePruneTransition`:case`treeGrowTransition`:case`treePruneDurationMode`:case`treePruneDuration`:return!!t.treeEnabled;case`victoryColor`:case`victoryTransition`:case`victoryTracerEnabled`:case`victoryTracerColor`:case`victoryTracerDuration`:return!!t.victoryEnabled;case`pregenGenerations`:case`pregenFadeInDuration`:case`pregenFadeInStagger`:return!!t.pregenEnabled;case`bloomIntensity`:case`bloomThreshold`:case`bloomRadius`:return!!t.bloomEnabled;case`vignetteDarkness`:case`vignetteOffset`:return!!t.vignetteEnabled;case`chromaticOffset`:return!!t.chromaticEnabled;case`noiseIntensity`:case`noiseStatic`:return!!t.noiseEnabled;case`tracerColor`:case`tracerBlend`:case`tracerDuration`:return!!t.tracerEnabled;case`lineWidthDp`:return t.lineWidthDp!=null;default:return!0}}function h_(e){if(typeof e==`number`)return Math.round(e*1e3)/1e3;if(Array.isArray(e))return e.map(h_);if(e&&typeof e==`object`){let t=`r`in e&&`g`in e&&`b`in e&&`a`in e,n={};for(let[r,i]of Object.entries(e))t&&(r===`r`||r===`g`||r===`b`)&&typeof i==`number`?n[r]=Math.round(i):n[r]=h_(i);return n}return e}var g_=class e{static MAX_GRID_CELLS=65536;constructor(e,t={}){this.canvas=e,this._raf=null,this._disposed=!1,this._paused=!1,this._showGUI=t.gui!==!1,this.config={};for(let e of Object.keys(e_)){let t=e_[e];this.config[e]=t&&typeof t==`object`?{...t}:t}let n=t.config?{...t.config}:null,r=n?.preset;n&&delete n.preset;let i=s_.length-1;if(r!==void 0){let e=parseInt(r);if(!isNaN(e)&&e>=0&&et.name.toLowerCase().includes(e));t!==-1&&(i=t)}}this._initialPresetIndex=i;let a=s_[i].config;for(let[e,t]of Object.entries(a))e in this.config&&(this.config[e]=t&&typeof t==`object`?{...t}:t);n&&(this._migrateLegacyConfig(n),Object.assign(this.config,n)),this._baseConfigForResponsive=this._snapshotConfig(),this._applyResponsiveOverrides({initial:!0}),this.stats={generation:0,totalSquares:0,childrenPossible:0,treeDepth:0,pruning:0},this._awaitingFullPrune=!1,this._soothingActive=!1,this.renderer=new dc({canvas:e,antialias:!1}),this.renderer.setPixelRatio(Math.min(devicePixelRatio,3));let o=e.clientWidth||e.width,s=e.clientHeight||e.height;this.renderer.setSize(o,s,!1),e.style.background=this.config.bgColor,e.parentElement&&(e.parentElement.style.background=this.config.bgColor),e.style.opacity=`0`,this._hasRenderedFirstFrame=!1,this.scene=new pn,this._bgColorObj=new Y(this.config.bgColor),this.scene.background=this._bgColorObj,this.camera=new ki(-1,1,1,-1,0,1),this._clockMs=0,this._clockLastWall=performance.now(),this._perfFrameTimes=[],this._perfLastTime=0,this.perf={fps:0,frameTime:0,subdivMs:0,textureMs:0,hoverMs:0,treeMs:0,guiMs:0,renderMs:0,totalMs:0,squares:0,treeVerts:0,gridCells:0,drawCalls:0,triangles:0},this._initGrid(),this._buildScene(),this._buildTreeLines(),this._buildPostProcessing(),this._showGUI&&this._buildGUI(),this._seedInitial(),this.config.pregenEnabled&&this._pregenerate(),this._resizeObserver=new ResizeObserver(()=>{this._resizeRAF||=requestAnimationFrame(()=>{this._resizeRAF=null,this._onResize()})}),this._resizeObserver.observe(this.canvas),this._hoverRect=null,this._hoverSquare=null,this._lastHoverCell=null,this._hoverStartTime=0,this._hoveredParentId=-1,this._hoverCollected=[],this._hoverSweepDone=!1,this._hoverDirty=!1,this._clickFlashes=[],this._lastTouchEndTime=-1/0,this._onMouseMoveBound=e=>{performance.now()-this._lastTouchEndTime<500||this._onMouseMove(e)},this._onMouseLeaveBound=()=>{this._hoverRect=null,this._hoverSquare=null,this._lastHoverCell=null},this._onTouchEndBound=()=>{this._lastTouchEndTime=performance.now(),this._onMouseLeaveBound()},this._onClickBound=e=>this._onClick(e),this.canvas.addEventListener(`mousemove`,this._onMouseMoveBound),this.canvas.addEventListener(`mouseleave`,this._onMouseLeaveBound),this.canvas.addEventListener(`touchend`,this._onTouchEndBound),this.canvas.addEventListener(`touchcancel`,this._onTouchEndBound),this.canvas.addEventListener(`click`,this._onClickBound),this.canvas.style.cursor=`crosshair`,this._tabHidden=!1,this._onVisibilityBound=()=>this._onVisibilityChange(),this._onPageShowBound=e=>this._onPageShow(e),document.addEventListener(`visibilitychange`,this._onVisibilityBound),window.addEventListener(`pageshow`,this._onPageShowBound),this._contextLost=!1,this._onContextLostBound=e=>this._onContextLost(e),this._onContextRestoredBound=()=>this._onContextRestored(),this.canvas.addEventListener(`webglcontextlost`,this._onContextLostBound,!1),this.canvas.addEventListener(`webglcontextrestored`,this._onContextRestoredBound,!1),this.config.pregenEnabled||(this._lastGenTime=this._clockMs),this._lingerStart=null}_canScheduleFrame(){return!this._disposed&&!this._tabHidden&&!this._contextLost}_canTick(){return this._canScheduleFrame()&&!this._paused}start(){let e=()=>{if(!this._canScheduleFrame()){this._raf=null;return}this._raf=requestAnimationFrame(e),this._canTick()&&this._tick()};this._loop=e,e()}pause(){this._paused=!0}resume(){this._paused&&(this._paused=!1,this._clockLastWall=performance.now())}dispose(){if(this._disposed=!0,cancelAnimationFrame(this._raf),this._resizeRAF&&=(cancelAnimationFrame(this._resizeRAF),null),this._resizeDebounceTimer&&=(clearTimeout(this._resizeDebounceTimer),null),this._resizeObserver&&=(this._resizeObserver.disconnect(),null),this.canvas.removeEventListener(`mousemove`,this._onMouseMoveBound),this.canvas.removeEventListener(`mouseleave`,this._onMouseLeaveBound),this.canvas.removeEventListener(`touchend`,this._onTouchEndBound),this.canvas.removeEventListener(`touchcancel`,this._onTouchEndBound),this.canvas.removeEventListener(`click`,this._onClickBound),this._onVisibilityBound&&document.removeEventListener(`visibilitychange`,this._onVisibilityBound),this._onPageShowBound&&window.removeEventListener(`pageshow`,this._onPageShowBound),this._onContextLostBound&&this.canvas.removeEventListener(`webglcontextlost`,this._onContextLostBound),this._onContextRestoredBound&&this.canvas.removeEventListener(`webglcontextrestored`,this._onContextRestoredBound),this._mqListeners){for(let{mq:e,onChange:t}of this._mqListeners)e.removeEventListener(`change`,t);this._mqListeners=null}this._respTimer&&=(clearTimeout(this._respTimer),null),this.pane&&this.pane.dispose(),this._paneContainer&&this._paneContainer.remove(),this.bloomPass&&this.bloomPass.dispose(),this.vignettePass&&this.vignettePass.dispose(),this.chromaticPass&&this.chromaticPass.dispose(),this.noisePass&&this.noisePass.dispose(),this.composer&&this.composer.dispose(),this.fillTexture&&this.fillTexture.dispose(),this.ghostTexture&&this.ghostTexture.dispose(),this.subdivTexture&&this.subdivTexture.dispose(),this.subdivLevelTexture&&this.subdivLevelTexture.dispose(),this.hoverTexture&&this.hoverTexture.dispose(),this.colPosTexture&&this.colPosTexture.dispose(),this.rowPosTexture&&this.rowPosTexture.dispose(),this.material&&this.material.dispose(),this.quad&&this.quad.geometry.dispose(),this._treeLinesMesh&&this.scene.remove(this._treeLinesMesh),this._treeLinesGeo&&this._treeLinesGeo.dispose(),this._treeLinesMat&&this._treeLinesMat.dispose(),this.renderer.dispose()}_migrateLegacyConfig(e){if(`gridMode`in e&&delete e.gridMode,delete e.gridFit,delete e.gridOrigin,delete e.lineCentered,delete e.lineInset,e.responsive&&e.responsive.mobile){let t=e.responsive.mobile;e.responsive.mobileLandscape={...t,...e.responsive.mobileLandscape||{}},e.responsive.mobilePortrait={...t,...e.responsive.mobilePortrait||{}},delete e.responsive.mobile}`restrictedGenerations`in e&&e.restrictedGenerations>0&&!(`restrictedGenerationsEnabled`in e)&&(e.restrictedGenerationsEnabled=!0)}_snapshotConfig(){let e={};for(let t of Object.keys(this.config)){let n=this.config[t];e[t]=n&&typeof n==`object`?{...n}:n}return e}_activeResponsiveTier(){return window.matchMedia(n_.mobilePortrait).matches?`mobilePortrait`:window.matchMedia(n_.mobileLandscape).matches?`mobileLandscape`:window.matchMedia(n_.tablet).matches?`tablet`:`desktop`}_setupResponsiveListeners(){if(this._mqListeners)return;let e=()=>this._scheduleResponsiveUpdate();this._mqListeners=[];for(let t of t_){let n=window.matchMedia(n_[t]);n.addEventListener(`change`,e),this._mqListeners.push({mq:n,onChange:e})}}_scheduleResponsiveUpdate(){clearTimeout(this._respTimer),this._respTimer=setTimeout(()=>{this._respTimer=null,this._applyResponsiveOverrides()},i_)}_applyResponsiveOverrides({initial:e=!1,silent:t=!1}={}){e&&this._setupResponsiveListeners();let n=this.config.responsive;if(!n)return;let r=this._activeResponsiveTier(),i={},a=r_[r]||[];for(let e of a)n[e]&&Object.assign(i,n[e]);this._migrateLegacyConfig(i);let o=!1;for(let e of Object.keys(this._baseConfigForResponsive)){if(e===`responsive`)continue;let t=this._baseConfigForResponsive[e],n=e in i?i[e]:t;p_(n,this.config[e])||(this.config[e]=n&&typeof n==`object`?{...n}:n,o=!0)}!e&&!t&&o&&(this.pane&&this.pane.refresh(),this._onConfigChange(),this._updatePruneDisabledState&&this._updatePruneDisabledState(),this._updateDirWeightDisabled&&this._updateDirWeightDisabled())}_rebaseResponsive(){this._baseConfigForResponsive=this._snapshotConfig(),this._applyResponsiveOverrides({silent:!0})}_initGrid(){let t=this.canvas.clientWidth||this.canvas.width,n=this.canvas.clientHeight||this.canvas.height;this._viewW=t,this._viewH=n,this._lastResizeW=t,this._lastResizeH=n;let r=this.config.subdivisionLevels,i=2**r,a=this.config.cellSize,o=Math.ceil(t/a)*Math.ceil(n/a)*i*i;if(o>e.MAX_GRID_CELLS){let t=Math.sqrt(o/e.MAX_GRID_CELLS);a*=t}let s=this.renderer.getPixelRatio(),c=this.config.gridSnapToDevicePixels!==!1;this._gridUnitsPerCss=c?s:1;let l;if(this.config.lineWidthDp!=null)l=Math.max(0,Math.round(this.config.lineWidthDp)),c||(l/=s);else{let e=Math.max(0,this.config.lineWidth);l=e===0?0:c?Math.max(1,Math.round(e*s)):e}let u=c?Math.round(t*s):t,d=c?Math.round(n*s):n,f=this.config.outerBorder?l:0,p=u-2*f,m=d-2*f,h=t-2*(f/this._gridUnitsPerCss),g=n-2*(f/this._gridUnitsPerCss),_=Math.max(1,Math.round(h/a)),v=Math.max(1,Math.round(g/a)),y=_*i,b=v*i;this.gridW=y,this.gridH=b,this._colPositions=Rg(p,y,f),this._rowPositions=Rg(m,b,f),this.finestW=h/y,this.finestH=g/b,this._effectiveCellSize=h/_,this._lineWidthPx=l,this._gridUniformResW=u,this._gridUniformResH=d,this._gridOffsetX=0,this._gridOffsetY=0,this.sizesX=[],this.sizesY=[];for(let e=0;e<=r;e++)this.sizesX.push(this.finestW*2**(r-e)),this.sizesY.push(this.finestH*2**(r-e));this.finestSize=this.finestW,this._effective||={cellSize:0},this._effective.cellSize=Math.round(this._effectiveCellSize),this._spanLUT=new Uint32Array(r+1);for(let e=0;e<=r;e++)this._spanLUT[e]=1<this.gridW||t+r>this.gridH)return!1;for(let n=0;ne.ghostStart===0).length,s}_activateSubdivision(e,t,n){for(let r=1;r<=n;r++){let n=this._spanForLevel(r-1),i=Math.floor(e/n)*n,a=Math.floor(t/n)*n;for(let e=0;e=this.gridH))for(let e=0;e=this.gridW)continue;let a=t*this.gridW+n;this._subdivTarget[a]a&&to)continue;let n=e+i===a||e===a+r,l=t+i===o||t===o+r,u=ea,d=to;if(!(n&&d||l&&u||n&&l))continue;let f=Math.abs(e-s)+Math.abs(t-c);fa&&to)continue;let n=e+i===a||e===a+r,l=t+i===o||t===o+r,u=ea,d=to;if(!(n&&d||l&&u))continue;let f=Math.abs(e-s)+Math.abs(t-c);fMath.random();switch(e.seedMode){case`corner`:{let t=e.seedCorner;return{fx:t===`TR`||t===`BR`?1:0,fy:t===`TL`||t===`TR`?0:1}}case`edgeCenter`:{let t=e.seedEdge;return{fx:t===`left`?0:t===`right`?1:.5,fy:t===`top`?0:t===`bottom`?1:.5}}case`edge`:{let n=e.seedEdge;return{fx:n===`top`||n===`bottom`?t():n===`right`?1:0,fy:n===`left`||n===`right`?t():n===`bottom`?1:0}}case`center`:return{fx:.5,fy:.5};case`centerRandom`:return{fx:1/3+t()*1/3,fy:1/3+t()*1/3};case`position`:{let n=(e.seedX??50)/100,r=(e.seedY??50)/100,i=(e.seedVarianceX??0)/100,a=(e.seedVarianceY??0)/100;return i>0&&(n+=(t()-.5)*2*i),a>0&&(r+=(t()-.5)*2*a),{fx:n,fy:r}}default:return{fx:t(),fy:t()}}}_seedInitial(){let{fx:e,fy:t}=this._seedTargetFraction();e=Math.max(0,Math.min(1,e)),t=Math.max(0,Math.min(1,t));let n=this._spanForLevel(0),r=this.gridW-n,i=this.gridH-n,a=this._snapToLevel(Math.max(0,Math.round(e*r)),0),o=this._snapToLevel(Math.max(0,Math.round((1-t)*i)),0);if(this._canPlace(a,o,0)){let e=this._placeSquare(a,o,0,0);e.revealTime=this._clockMs,e.revealed=!0}this._lastGenTime=this._clockMs}_pregenerate(){let e=this.config.pregenGenerations;this._pregenRunning=!0;for(let t=0;t!e._pruned),e===0)break}this._pregenRunning=!1,this._lingerStart=null,this._recomputeSubdivision();let t=this._clockMs,n=this.config.pregenFadeInStagger,r=this.config.pregenFadeInDuration,i=this.stats.generation,a=this.squares,o=Math.min(...a.map(e=>e.generation));a.forEach(e=>{let a=t+(e.generation-o)*n;e.revealTime=a,e.birthTime=a,e.revealed=!0,e._treeRevealTime=a,e.generation===i?(e._fadeInDuration=void 0,e._treeDuration=void 0,e._treeFadeInDuration=void 0):(e.growOrigin=-1,e._treeDuration=n,e._treeFadeInDuration=r>0?r:null,e._fadeInDuration=r);let s=e.generation===i?1:e.childCount>0?2:3;e._colorState=s,e._prevColorState=s,e._stateChangeTime=a});let s=new Float32Array(this.gridW*this.gridH).fill(1/0);for(let e of a){let t=e.revealTime;for(let n=1;n<=e.level;n++){let r=this._spanForLevel(n-1),i=Math.floor(e.gx/r)*r,a=Math.floor(e.gy/r)*r;for(let e=0;e=this.gridH))for(let e=0;e=this.gridW)continue;let a=n*this.gridW+r;t=t?r<.5?e:Math.max(0,e-1):e<=0?r<.5+n*.5?e+1:e:re[t]);this._screenDirAllowDown=this.config.dirBottom||this.config.dirBL||this.config.dirBR,this._screenDirAllowUp=this.config.dirTop||this.config.dirTL||this.config.dirTR,this._screenDirAllowLeft=this.config.dirLeft||this.config.dirTL||this.config.dirBL,this._screenDirAllowRight=this.config.dirRight||this.config.dirTR||this.config.dirBR;let n=this.config;if(n.restrictedGenerationsEnabled&&n.restrictedGenerations>0&&this.stats.generation<=n.restrictedGenerations&&t.length>1){let e=[n.dirPriorityBL,n.dirPriorityBR,n.dirPriorityTL,n.dirPriorityTR,n.dirPriorityBottom,n.dirPriorityRight,n.dirPriorityTop,n.dirPriorityLeft],r=t.slice();for(let e=r.length-1;e>0;e--){let t=Math.floor(Math.random()*(e+1));[r[e],r[t]]=[r[t],r[e]]}return r.sort((t,n)=>e[t]-e[n]),r}for(let e=t.length-1;e>0;e--){let n=Math.floor(Math.random()*(e+1));[t[e],t[n]]=[t[n],t[e]]}return t}_evolveGeneration(){let e=++this.stats.generation,t=this._clockMs,n=[],r=this.squares.filter(e=>!e.hasAttempted&&e.ghostStart===0);for(let e=r.length-1;e>0;e--){let t=Math.floor(Math.random()*(e+1));[r[e],r[t]]=[r[t],r[e]]}let i=this.config.restrictedGenerationsEnabled&&this.config.restrictedGenerations>0&&this.stats.generation<=this.config.restrictedGenerations;for(let a of r){a.hasAttempted=!0;let r=this._allowedDirs(),o=Math.min(this.config.minChildren,r.length);a.manualSpawn&&(o=Math.max(1,o));let s=Math.min(this.config.maxChildren,r.length),c=o>=s?s:o+Math.floor(Math.random()*(s-o+1)),l=i?r.slice(0,c):r,u=0;for(let r of l){if(!i&&u>=c)break;a.cornersUsed.add(r);let o=this._chooseChildLevel(a.level),s=this._dirPosition(a,r,o);if(!s)continue;let[l,d]=s;if(!this._canPlace(l,d,o))continue;let f=this._spanForLevel(a.level),p=this._spanForLevel(o),m=l+p*.5-(a.gx+f*.5),h=d+p*.5-(a.gy+f*.5);if(!(h<-.01&&!this._screenDirAllowDown)&&!(h>.01&&!this._screenDirAllowUp)&&!(m<-.01&&!this._screenDirAllowLeft)&&!(m>.01&&!this._screenDirAllowRight)){let i=this._placeSquare(l,d,o,e,a.id);this.config.growOriginMode===`center`?i.growOrigin=Qg:i.growOrigin=[qg,Kg,Gg,Wg,Xg,Zg,Jg,Yg][r],i.revealTime=t,i.revealed=!0,n.push(i),a.children.push(i),a.childCount++,u++}}}if(this.config.victoryEnabled)for(let e of n)!e.locked&&this._isAtAllowedEdge(e)&&this._lockChain(e);return this.stats.totalSquares=this.squares.filter(e=>e.ghostStart===0).length,n.length===0?(this.stats.generation--,this._lingerStart||(this._lingerStart=t,this._softRestart())):this._lingerStart=null,n.length}_countChildrenPossible(){let e=0;for(let t of this.squares)if(!(t.hasAttempted||t.ghostStart>0))for(let n of $g)for(let r=-1;r<=1;r++){let i=t.level+r;if(i<0||i>this.config.subdivisionLevels)continue;let a=this._dirPosition(t,n,i);if(!a)continue;let[o,s]=a;if(this._canPlace(o,s,i)){e++;break}}this.stats.childrenPossible=e}_isLeaf(e){return e.children.length===0||e.children.every(e=>e._pruned)}_isAtAllowedEdge(e){let t=this._spanForLevel(e.level);return!!(e.gy===0&&this._screenDirAllowDown||e.gy+t===this.gridH&&this._screenDirAllowUp||e.gx===0&&this._screenDirAllowLeft||e.gx+t===this.gridW&&this._screenDirAllowRight)}_lockChain(e){let t=[],n=e;for(;n;)t.push(n),n=n.parentId===null?null:this.squaresById.get(n.parentId);t.reverse();let r=this._clockMs,i=this._pregenRunning,a=Math.max(0,t.length-1);for(let e=0;e0||(n.locked=!0,n.hasAttempted=!0,n._victoryStart===0&&(n._victoryStart=i?-1:r+this._computeStaggerOffset(e,a)))}}_computeTreeDepth(){let e=0,t=e=>{let n=e.children.filter(e=>!e._pruned&&e.ghostStart===0);if(n.length===0)return 0;let r=0;for(let e of n)r=Math.max(r,t(e));return r+1};for(let n of this.squares)n.parentId===null&&n.ghostStart===0&&(e=Math.max(e,t(n)));this.stats.treeDepth=e}_computeStaggerOffset(e,t){let n=this.config.fadeOutStagger,r=t*n,i=this.config.maxStaggerTotal;if(i<=0||r<=i)return e*n;let a=t>0?e/t:0;return a*a*i}_levelAtCell(e,t){return this._subdivTarget[t*this.gridW+e]}_freeOccupation(e){let t=this._spanForLevel(e.level);for(let n=0;n{if(t.has(e.id))return t.get(e.id);if(e._pruned)return t.set(e.id,!0),!0;if(e.locked||e._pendingReseed||e.doomed&&e.manualDoom)return t.set(e.id,!1),!1;if(e.doomed)return t.set(e.id,!0),!0;let r=e.children.filter(e=>!e._pruned),i;return i=r.length===0?e.hasAttempted&&e.childCount===0:r.every(e=>n(e)),t.set(e.id,i),i},r=[];for(let e of this.squares)e._pruned||e.doomed||n(e)&&r.push(e);if(r.length===0)return;for(let t of r)t.doomed=!0,t.doomTime=e;let i=e=>{let t=e.children.filter(e=>!e._pruned);if(t.length===0)return 0;let n=0;for(let e of t)n=Math.max(n,i(e));return n+1},a=0;for(let e of r)e._pruneDepth=i(e),a=Math.max(a,e._pruneDepth);for(let t of r)t.ghostStart=e+this._computeStaggerOffset(t._pruneDepth,a);this._recomputeSubdivision()}_removePrunedSquares(){let e=this._clockMs,t=!1;for(let n of this.squares)if(n.ghostStart>0&&!n._pruned){let r=Math.max(this.config.fadeOutDuration,this._treePruneDuration());if(e-n.ghostStart>=r){if(this._freeOccupation(n),n._pruned=!0,t=!0,n.manualDoom&&n.parentId!==null){let e=this.squaresById.get(n.parentId);e&&!e._pruned&&!e.doomed&&(e.hasAttempted=!1)}this.squaresById.delete(n.id)}}if(t){this.squares=this.squares.filter(e=>!e._pruned);for(let e of this.squares)e.children.some(e=>e._pruned)&&(e.children=e.children.filter(e=>!e._pruned));this._checkPendingReseeds()}this.stats.totalSquares=this.squares.filter(e=>e.ghostStart===0).length,this.stats.pruning=this.squares.filter(e=>e.ghostStart>0).length,this._countChildrenPossible(),this._computeTreeDepth()}_recomputeSubdivision(){this._subdivTarget.fill(0),this._subdivActiveCount=this._subdivFloat.length;for(let e of this.squares)for(let t=1;t<=e.level;t++){let n=this._spanForLevel(t-1),r=Math.floor(e.gx/n)*n,i=Math.floor(e.gy/n)*n;for(let e=0;e=this.gridH))for(let e=0;e=this.gridW)continue;let i=a*this.gridW+n;this._subdivTarget[i]=e?s=t:(s=o/e*t,r++),this._subdivFloat[a]=s,this.subdivData[a]=Math.round(s*36.4)}this._subdivDirty=!0,r===0&&(this._subdivRevealAt=null)}else{let n=this.config.gridLineFade>0?1/(this.config.gridLineFade/1e3):1e3;for(let i=0;it&&(this._subdivFloat[i]=Math.max(t,a-n*e),r++),this.subdivData[i]=Math.round(this._subdivFloat[i]*36.4)}r>0&&(this._subdivDirty=!0)}this._subdivActiveCount=r}_softRestart(){if(!this._pregenRunning)if(this.config.pruneEnabled&&this.squares.length>0){let e=this._clockMs,t=this.config.soothingFinalRetraction,n=[];for(let r of this.squares)!r.doomed&&!r._pruned&&r.ghostStart===0&&(t?r._soothing=!0:(r.doomed=!0,r.doomTime=e),r.hasAttempted=!0,r._pendingReseed=!1,n.push(r));if(t){let t=new Map,r=[];for(let e of n)(e.parentId===null||!this.squaresById.has(e.parentId))&&(t.set(e.id,0),r.push(e));let i=0;for(;ia&&(a=e);for(let r of n){let n=t.get(r.id)??0;r.ghostStart=e+this._computeStaggerOffset(n,a)}this._soothingActive=!0}else{let t=e=>{let n=e.children.filter(e=>!e._pruned);if(n.length===0)return 0;let r=0;for(let e of n)r=Math.max(r,t(e));return r+1},r=0;for(let e of n)r=Math.max(r,t(e));for(let i of n)i.ghostStart=e+this._computeStaggerOffset(t(i),r)}this._recomputeSubdivision(),this._awaitingFullPrune=!0}else this._resetGrid(),this._rebuildTexture(),this._seedInitial(),this.config.pregenEnabled&&this._pregenerate()}_pixelToGrid(e){let t=this.canvas.getBoundingClientRect(),n=this._gridUnitsPerCss||1,r=(e.clientX-t.left)*n,i=(t.height-(e.clientY-t.top))*n,a=zg(this._colPositions,r),o=zg(this._rowPositions,i);return a<0||o<0?null:{gx:a,gy:o}}_squareAt(e,t){for(let n of this.squares){if(n._pruned)continue;let r=this._spanForLevel(n.level);if(e>=n.gx&&e=n.gy&&t0||n.doomed,a=n.hasAttempted&&n.childCount===0&&!i,o=n.generation===this.stats.generation&&!i,s=n.childCount>0&&!i;i?this._reprieveSquare(n):s?this._doomSubtree(n):a?n.hasAttempted=!1:o&&this._forceEvolve(n)}_updateHoverSubtree(){let e=this._hoverSquare;if(!e||e._pruned||e.childCount===0||e.doomed){e&&e._pruned&&(this._hoverRect=null,this._hoverSquare=null),this._hoveredParentId!==-1&&(this.hoverData.fill(0),this._hoveredParentId=-1,this._hoverDirty=!0);return}if(e.id!==this._hoveredParentId){this._hoveredParentId=e.id,this._hoverStartTime=this._clockMs,this._hoverSweepDone=!1;let t=e=>{let n=e.children.filter(e=>!e._pruned&&!e.doomed);if(n.length===0)return 0;let r=0;for(let e of n)r=Math.max(r,t(e));return r+1};this._hoverCollected=[];let n=e=>{if(!(e._pruned||e.doomed)){this._hoverCollected.push({sq:e,depth:t(e)});for(let t of e.children)n(t)}};n(e);let r=t(e),i=0;for(let e of this._hoverCollected)e.dist=Math.abs(e.depth-r),i=Math.max(i,e.dist);this._hoverMaxDist=i}let t=this._hoverCollected.length;if(this._hoverCollected=this._hoverCollected.filter(e=>!e.sq._pruned&&!e.sq.doomed),this._hoverCollected.length!==t&&(this._hoverSweepDone=!1),this._hoverCollected.length===0){this.hoverData.fill(0),this._hoveredParentId=-1,this._hoverDirty=!0;return}if(this._hoverSweepDone)return;this.hoverData.fill(0);let n=this.config.hoverStagger,r=this._hoverMaxDist,i=r*n,a=this.config.maxHoverTotal,o=e=>{if(a<=0||i<=a)return e*n;let t=r>0?e/r:0;return t*t*a},s=this._clockMs-this._hoverStartTime,c=!0;for(let{sq:e,dist:t}of this._hoverCollected)if(s>=o(t)){let t=this._spanForLevel(e.level);for(let n=0;n{if(!(e._pruned||e.doomed)){n.push(e);for(let t of e.children)r(t)}};if(r(e),n.length===0)return;e.manualDoom=!0;for(let e of n)e.doomed=!0,e.doomTime=t,e.hasAttempted=!0,e._pendingReseed=!1;let i=e=>{let t=e.children.filter(e=>!e._pruned);if(t.length===0)return 0;let n=0;for(let e of t)n=Math.max(n,i(e));return n+1},a=0;for(let e of n)e._pruneDepth=i(e),a=Math.max(a,e._pruneDepth);for(let e of n)e.ghostStart=t+this._computeStaggerOffset(e._pruneDepth,a);this._recomputeSubdivision()}_reprieveSquare(e){e._pruned||(e.doomed=!1,e.manualDoom=!1,e.ghostStart=0,e._pendingReseed=!0,this._checkPendingReseeds(),this._recomputeSubdivision())}_checkPendingReseeds(){for(let e of this.squares)e._pendingReseed&&!e.doomed&&!e._pruned&&(e.children.some(e=>e.doomed&&!e._pruned)||(e.hasAttempted=!1,e._pendingReseed=!1))}_forceEvolve(e){if(e.hasAttempted)return;e.hasAttempted=!0;let t=this._clockMs,n=this.stats.generation,r=this._allowedDirs(),i=Math.min(this.config.minChildren,r.length);e.manualSpawn&&(i=Math.max(1,i));let a=Math.min(this.config.maxChildren,r.length),o=i>=a?a:i+Math.floor(Math.random()*(a-i+1)),s=0;for(let i of r){if(s>=o)break;e.cornersUsed.add(i);let r=this._chooseChildLevel(e.level),a=this._dirPosition(e,i,r);if(!a)continue;let[c,l]=a;if(!this._canPlace(c,l,r))continue;let u=this._spanForLevel(e.level),d=this._spanForLevel(r),f=c+d*.5-(e.gx+u*.5),p=l+d*.5-(e.gy+u*.5);if(!(p<-.01&&!this._screenDirAllowDown)&&!(p>.01&&!this._screenDirAllowUp)&&!(f<-.01&&!this._screenDirAllowLeft)&&!(f>.01&&!this._screenDirAllowRight)){let a=this._placeSquare(c,l,r,n,e.id);this.config.growOriginMode===`center`?a.growOrigin=Qg:a.growOrigin=[qg,Kg,Gg,Wg,Xg,Zg,Jg,Yg][i],a.revealTime=t,a.revealed=!0,e.children.push(a),e.childCount++,s++}}this.stats.totalSquares=this.squares.filter(e=>e.ghostStart===0).length}_buildScene(){let e=new qr(2,2);this.fillTexture=this._makeDataTexture(this.fillData,T),this.ghostTexture=this._makeDataTexture(this.ghostData,T),this.subdivTexture=this._makeDataTexture(this.subdivData),this.subdivLevelTexture=this._makeDataTexture(this._subdivTarget),this.hoverTexture=this._makeDataTexture(this.hoverData),this.colPosTexture=this._makePositionTexture(this._colPositions),this.rowPosTexture=this._makePositionTexture(this._rowPositions),this.material=new ti({uniforms:{uFill:{value:this.fillTexture},uGhost:{value:this.ghostTexture},uSubdiv:{value:this.subdivTexture},uSubdivLevel:{value:this.subdivLevelTexture},uColPosTex:{value:this.colPosTexture},uRowPosTex:{value:this.rowPosTexture},uGridSize:{value:new G(this.gridW,this.gridH)},uResolution:{value:new G(this._gridUniformResW??this._viewW,this._gridUniformResH??this._viewH)},uLineColor:{value:l_(this.config.lineColor)},uLineOpacity:{value:this.config.lineColor.a},uLineWidth:{value:this._lineWidthPx??this.config.lineWidth},uLineBlend:{value:0},uNewColor:{value:d_(this.config.newColor)},uParentColor:{value:d_(this.config.parentColor)},uPruneColor:{value:d_(this.config.pruneColor)},uTime:{value:0},uMaxLevel:{value:this.config.subdivisionLevels},uCellShape:{value:0},uCellRadius:{value:this.config.cellRadius},uCellAA:{value:this.config.cellAA?1:0},uTracerColor:{value:d_(this.config.tracerColor)},uTracerBlend:{value:0},uWinnerColor:{value:d_(this.config.victoryColor)},uVictoryTracerColor:{value:d_(this.config.victoryTracerColor)},uClickFlashColor:{value:d_(this.config.clickFlashColor)},uClickFlashRect:{value:new Tt(0,0,0,0)},uClickFlashIntensity:{value:0},uHoverRect:{value:new Tt(0,0,0,0)},uHoverActive:{value:0},uHoverIsEmpty:{value:0},uHoverEmptyColor:{value:l_(this.config.hoverEmptyColor)},uHoverEmptyBlend:{value:0},uHoverEmptyOpacity:{value:this.config.hoverEmptyColor.a},uHoverFilledColor:{value:l_(this.config.hoverFilledColor)},uHoverFilledBlend:{value:0},uHoverFilledOpacity:{value:this.config.hoverFilledColor.a},uHoverParentColor:{value:l_(this.config.hoverParentColor)},uHoverSubtree:{value:this.hoverTexture},uHoverSubtreeBlend:{value:0},uHoverSubtreeOpacity:{value:this.config.hoverParentColor.a}},vertexShader:Pg,fragmentShader:Fg,transparent:!0,premultipliedAlpha:!0,depthWrite:!1,depthTest:!1}),this.quad=new Ar(e,this.material),this.quad.frustumCulled=!1,this.scene.add(this.quad)}_makeDataTexture(e,t=O){let n=new Nr(e,this.gridW,this.gridH,t,u);return n.minFilter=i,n.magFilter=i,n.needsUpdate=!0,n}_makePositionTexture(e){let t=new Nr(e,e.length,1,O,g);return t.minFilter=i,t.magFilter=i,t.needsUpdate=!0,t}_buildPostProcessing(){let e=this._viewW,t=this._viewH;this.composer=new Og(this.renderer),this.composer.addPass(new kg(this.scene,this.camera)),this.bloomPass=new jg(new G(e,t),this.config.bloomIntensity,this.config.bloomRadius,this.config.bloomThreshold),this.composer.addPass(this.bloomPass),this.vignettePass=new Tg(Bg),this.vignettePass.uniforms.offset.value=this.config.vignetteOffset,this.vignettePass.uniforms.darkness.value=this.config.vignetteDarkness,this.composer.addPass(this.vignettePass),this.chromaticPass=new Tg({uniforms:{tDiffuse:{value:null},uOffset:{value:this.config.chromaticOffset}},vertexShader:Lg,fragmentShader:Ig}),this.composer.addPass(this.chromaticPass),this.composer.addPass(new Ng),this.noisePass=new Tg(Vg),this.noisePass.uniforms.intensity.value=this.config.noiseIntensity,this.composer.addPass(this.noisePass)}_buildTreeLines(){this._treeLinesGeo=new sr,this._treeLinesMat=new ti({uniforms:{uOpacity:{value:this.config.treeColor.a},uHalfWidth:{value:this.config.treeWidth*.5}},vertexShader:` attribute float aCross; attribute vec3 aColor; attribute float aVertOpacity; varying float vCross; varying vec3 vColor; varying float vVertOpacity; void main() { vCross = aCross; vColor = aColor; vVertOpacity = aVertOpacity; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); } `,fragmentShader:` uniform float uOpacity; uniform float uHalfWidth; varying float vCross; varying vec3 vColor; varying float vVertOpacity; void main() { float d = abs(vCross); float aaFrac = clamp(1.5 / uHalfWidth, 0.05, 0.5); float aa = 1.0 - smoothstep(1.0 - aaFrac, 1.0, d); gl_FragColor = vec4(vColor, aa * uOpacity * vVertOpacity); } `,transparent:!0,depthWrite:!1,depthTest:!1,side:2}),this._treeLinesMesh=new Ar(this._treeLinesGeo,this._treeLinesMat),this._treeLinesMesh.renderOrder=1,this._treeLinesMesh.frustumCulled=!1,this.scene.add(this._treeLinesMesh),this._treeMaxVerts=192*1024,this._treePosBuf=new Float32Array(this._treeMaxVerts*3),this._treeCrossBuf=new Float32Array(this._treeMaxVerts),this._treeColorBuf=new Float32Array(this._treeMaxVerts*3),this._treeOpacityBuf=new Float32Array(this._treeMaxVerts).fill(1),this._treeLinesGeo.setAttribute(`position`,new Yn(this._treePosBuf,3)),this._treeLinesGeo.setAttribute(`aCross`,new Yn(this._treeCrossBuf,1)),this._treeLinesGeo.setAttribute(`aColor`,new Yn(this._treeColorBuf,3)),this._treeLinesGeo.setAttribute(`aVertOpacity`,new Yn(this._treeOpacityBuf,1)),this._treeLinesGeo.setDrawRange(0,0),this._treeBaseColor=new Y,this._treeHoverColor=new Y,this._treeGrowColor=new Y,this._treeHoverIds=new Set,this._treePts=new Float64Array(128),this._treeNormals=new Float64Array(128)}_updateTreeLines(){if(!this.config.treeEnabled||!this._treeLinesMesh){this._treeLinesMesh&&(this._treeLinesMesh.visible=!1);return}let e=this._clockMs,t=(e-(this._treeLastTime||e))/1e3;this._treeLastTime=e;let n=this.config.treeSegments,r=this.config.treeRoundedness;u_(this._treeBaseColor,this.config.treeColor),u_(this._treeHoverColor,this.config.treeHoverColor),u_(this._treeGrowColor,this.config.treeGrowColor);let i=this._treeBaseColor.r,a=this._treeBaseColor.g,o=this._treeBaseColor.b,s=this._treeHoverColor.r,c=this._treeHoverColor.g,l=this._treeHoverColor.b,u=this._treeGrowColor.r,d=this._treeGrowColor.g,f=this._treeGrowColor.b,p=this.config.treePruneTransition/1e3,m=this.config.treeGrowTransition/1e3,h=this._treeHoverIds;if(h.clear(),this._hoverSquare&&this._hoverSquare.childCount>0&&!this._hoverSquare.doomed){let e=t=>{if(!(t._pruned||t.doomed)){h.add(t.id);for(let n of t.children)e(n)}};e(this._hoverSquare)}let g=this.config.treeWidth,_=this._viewW,v=this._viewH,y=2/this._viewW,b=2/this._viewH,x=this.finestW,S=this.finestH,C=this._gridOffsetX,w=this._gridOffsetY,T=this._treePosBuf,E=this._treeCrossBuf,D=this._treeColorBuf,O=this._treeOpacityBuf,k=0,A=this._treePts,ee=this._treeNormals,te=this._growDuration(),j=this._treePruneDuration(),ne=Hg[this.config.growEasing],M=1-.001**t;for(let N of this.squares){if(N.parentId===null||N._pruned)continue;let P=this.squaresById.get(N.parentId);if(!P||P._pruned)continue;let re=this._spanForLevel(P.level),F=(P.gx+re*.5)*x-C,ie=(P.gy+re*.5)*S-w,ae=F*y-1,oe=ie*b-1,se=this._spanForLevel(N.level),ce=(N.gx+se*.5)*x-C,le=(N.gy+se*.5)*S-w,ue=ce*y-1,de=le*b-1,I=1,L=1,fe=N._treeRevealTime??(N.growOrigin>=0?N.revealTime:null),pe=N._treeDuration??te,me=N._treeFadeInDuration??0;if(fe!==null){let t=e-fe;pe>0&&(I=ne(Math.max(0,Math.min(1,t/pe)))),me>0&&(L=Math.max(0,Math.min(1,t/me)))}if(N.ghostStart>0&&e>=N.ghostStart){let t=j>0?Math.min(1,(e-N.ghostStart)/j):1;I=Math.max(0,1-t)}if(P.ghostStart>0&&e>=P.ghostStart){let t=j>0?Math.min(1,(e-P.ghostStart)/j):1;I=Math.min(I,Math.max(0,1-t))}if(I<=.01)continue;let he=h.has(N.id)&&h.has(P.id),ge=he||N.doomed||P.doomed,_e=!ge&&N.growOrigin>=0&&te>0&&e-N.revealTime0){let e=Math.min(1,t/xe);N._clr+=(ve-N._clr)*e,N._clg+=(ye-N._clg)*e,N._clb+=(be-N._clb)*e}else N._clr=ve,N._clg=ye,N._clb=be;let Se=N._clr,Ce=N._clg,we=N._clb,Te=ae,R=oe;if(P.parentId!==null){let e=this.squaresById.get(P.parentId);if(e&&!e._pruned){let t=this._spanForLevel(e.level),n=((e.gx+t*.5)*x-C)*y-1,i=((e.gy+t*.5)*S-w)*b-1;Te=ae+(n-ae)*r,R=oe+(i-oe)*r}}let Ee=ue,De=de;if(N.children.length>0){for(let e of N.children)if(!e._pruned){let t=this._spanForLevel(e.level),n=((e.gx+t*.5)*x-C)*y-1,i=((e.gy+t*.5)*S-w)*b-1;Ee=ue+(n-ue)*r,De=de+(i-de)*r;break}}N._gpx===void 0?(N._gpx=Te,N._gpy=R,N._gcx=Ee,N._gcy=De):(N._gpx+=(Te-N._gpx)*M,N._gpy+=(R-N._gpy)*M,N._gcx+=(Ee-N._gcx)*M,N._gcy+=(De-N._gcy)*M);let Oe=N._gpx,z=N._gpy,ke=ae,B=oe,V=ue,Ae=de,je=N._gcx,Me=N._gcy,Ne=Math.sqrt(((ue-ae)*_*.5)**2+((de-oe)*v*.5)**2),Pe=Math.max(2,Math.min(Math.ceil(n*I),Math.ceil(Ne/20))),Fe=(Pe+1)*2;Fe>A.length&&(this._treePts=new Float64Array(Fe*2),this._treeNormals=new Float64Array(Fe*2));for(let e=0;e<=Pe;e++){let t=e/Pe*I,n=t*t,r=n*t;A[e*2]=.5*(2*ke+(-Oe+V)*t+(2*Oe-5*ke+4*V-je)*n+(-Oe+3*ke-3*V+je)*r),A[e*2+1]=.5*(2*B+(-z+Ae)*t+(2*z-5*B+4*Ae-Me)*n+(-z+3*B-3*Ae+Me)*r)}for(let e=0;e<=Pe;e++){let t=0,n=0;if(e===0){let e=(A[2]-A[0])*_*.5,r=(A[3]-A[1])*v*.5,i=Math.sqrt(e*e+r*r)||1;t=-r/i,n=e/i}else if(e===Pe){let e=(A[Pe*2]-A[(Pe-1)*2])*_*.5,r=(A[Pe*2+1]-A[(Pe-1)*2+1])*v*.5,i=Math.sqrt(e*e+r*r)||1;t=-r/i,n=e/i}else{let r=(A[e*2]-A[(e-1)*2])*_*.5,i=(A[e*2+1]-A[(e-1)*2+1])*v*.5,a=Math.sqrt(r*r+i*i)||1,o=-i/a,s=r/a,c=(A[(e+1)*2]-A[e*2])*_*.5,l=(A[(e+1)*2+1]-A[e*2+1])*v*.5,u=Math.sqrt(c*c+l*l)||1,d=-l/u,f=c/u;t=o+d,n=s+f;let p=Math.sqrt(t*t+n*n);if(p>.001){t/=p,n/=p;let e=t*o+n*s,r=e>.25?1/e:4;t*=r,n*=r}else t=o,n=s}ee[e*2]=t,ee[e*2+1]=n}let Ie=k+Pe*6;if(Ie>T.length/3){let e=Ie*2,t=new Float32Array(e*3),n=new Float32Array(e),r=new Float32Array(e*3),i=new Float32Array(e).fill(1);t.set(T.subarray(0,k*3)),n.set(E.subarray(0,k)),r.set(D.subarray(0,k*3)),i.set(O.subarray(0,k)),this._treePosBuf=T=t,this._treeCrossBuf=E=n,this._treeColorBuf=D=r,this._treeOpacityBuf=O=i}for(let e=0;e0&&e>=c.ghostStart;if(c._victoryStart<0)t=127;else if(c._victoryStart>0&&e>=c._victoryStart){let n=a>0?Math.min(1,(e-c._victoryStart)/a):1,r=Hg[this.config.colorEasing](n);t=Math.min(127,Math.floor(r*127))}n&&t<127&&(t=127);let i=0;if(s&&!n&&c._victoryStart>0&&o>0){let t=e-c._victoryStart;if(t>=-o&&t0&&(this.ghostData[a+1]=Math.max(this.ghostData[a+1],i)),this.ghostData[a+2]0&&i>0){let t=e-c.ghostStart;if(t>=-i&&t0)for(let e=0;e0&&e>=c.ghostStart){if(!this.config.showSquares)continue;let t=e-c.ghostStart,n=this.config.fadeOutDuration,i=n>0?Math.min(1,t/n):1,a=Math.max(0,1-i);if(a<=0)continue;let o=Math.min(255,Math.round(a*255));for(let e=0;e0?Math.floor(m/h*31):31)),c.doomed?d=4:(d=3,c.generation===this.stats.generation?d=1:c.childCount>0&&(d=2));let g=this._growDuration();if(c.growOrigin>=0&&g>0){let t=Math.min(1,(e-c.revealTime)/g);if(t<1){let e=Hg[this.config.growEasing](t);f=Math.max(0,Math.min(254,Math.floor(e*255))),p=c.growOrigin}}d!==c._colorState&&(c._prevColorState=c._colorState,c._colorState=d,c._stateChangeTime=e);let _=[0,64,128,255,255],v=_[d],y=_[c._prevColorState]||v,b,x=d>=3?this.config.pruneTransition:this.config.parentTransition,S=this.config.colorEasing;if(x>0&&c._prevColorState!==d){let t=Math.min(1,(e-c._stateChangeTime)/x),n=Hg[S](t);b=Math.round(y+(v-y)*n)}else b=v;let C=c.level+1|u<<3;for(let e=0;e60&&this._perfFrameTimes.shift();let r=e;t-this._lastGenTime>=this.config.genSpeed&&(this._lastGenTime=t,this._lingerStart||(this.stats.generation=0;e--){let n=this._clickFlashes[e],r=t-n.startTime;if(r>=l){this._clickFlashes.splice(e,1);continue}let i=r/l,a=i<.5?i*2:(1-i)*2;a>u&&(u=a,d.set(n.gx,n.gy,n.gx+n.span,n.gy+n.span))}this.material.uniforms.uClickFlashIntensity.value=u,f_(this.material.uniforms.uClickFlashColor.value,this.config.clickFlashColor),this._bgColorObj.set(this.config.bgColor),this.config.bgColor!==this._lastCssBg&&(this._lastCssBg=this.config.bgColor,this.canvas.style.background=this.config.bgColor,this.canvas.parentElement&&(this.canvas.parentElement.style.background=this.config.bgColor));let f=this.config.postFxEnabled;this.bloomPass.enabled=f&&this.config.bloomEnabled,this.bloomPass.strength=this.config.bloomIntensity,this.bloomPass.threshold=this.config.bloomThreshold,this.bloomPass.radius=this.config.bloomRadius,this.vignettePass.enabled=f&&this.config.vignetteEnabled,this.vignettePass.uniforms.offset.value=this.config.vignetteOffset,this.vignettePass.uniforms.darkness.value=this.config.vignetteDarkness,this.chromaticPass.enabled=f&&this.config.chromaticEnabled,this.chromaticPass.uniforms.uOffset.value=this.config.chromaticOffset,this.noisePass.enabled=f&&this.config.noiseEnabled,this.noisePass.uniforms.intensity.value=this.config.noiseIntensity,this.noisePass.uniforms.time.value=this.config.noiseStatic?0:t*.001;let p=performance.now();this._updateTreeLines();let m=performance.now(),h=performance.now();this.pane&&this.pane.refresh();let g=performance.now();this.composer.render(),this._hasRenderedFirstFrame||(this._hasRenderedFirstFrame=!0,this.canvas.style.opacity=`1`);let _=performance.now(),v=this._perfFrameTimes.reduce((e,t)=>e+t,0)/this._perfFrameTimes.length;this.perf.fps=Math.round(1e3/v),this.perf.frameTime=+v.toFixed(2);let y=.1;this.perf.subdivMs=+(this.perf.subdivMs*(1-y)+(a-i)*y).toFixed(2),this.perf.textureMs=+(this.perf.textureMs*(1-y)+(o-a)*y).toFixed(2),this.perf.hoverMs=+(this.perf.hoverMs*(1-y)+(c-s)*y).toFixed(2),this.perf.treeMs=+(this.perf.treeMs*(1-y)+(m-p)*y).toFixed(2),this.perf.guiMs=+(this.perf.guiMs*(1-y)+(g-h)*y).toFixed(2),this.perf.renderMs=+(this.perf.renderMs*(1-y)+(_-g)*y).toFixed(2),this.perf.totalMs=+(this.perf.totalMs*(1-y)+(_-r)*y).toFixed(2),this.perf.squares=this.squares.length,this.perf.treeVerts=this._treeVertCount||0,this.perf.gridCells=this.gridW*this.gridH;let b=this.renderer.info;this.perf.drawCalls=b.render.calls,this.perf.triangles=b.render.triangles,(!this._lastPerfLog||t-this._lastPerfLog>3e3)&&(this._lastPerfLog=t,console.log(`[perf] total=${this.perf.totalMs}ms | subdiv=${this.perf.subdivMs} tex=${this.perf.textureMs} hover=${this.perf.hoverMs} tree=${this.perf.treeMs} gui=${this.perf.guiMs} render=${this.perf.renderMs} | sq=${this.perf.squares} treeVerts=${this.perf.treeVerts} draws=${this.perf.drawCalls} tris=${this.perf.triangles}`))}_rebuildTexture(){this.fillTexture&&this.fillTexture.dispose(),this.ghostTexture&&this.ghostTexture.dispose(),this.subdivTexture&&this.subdivTexture.dispose(),this.subdivLevelTexture&&this.subdivLevelTexture.dispose(),this.hoverTexture&&this.hoverTexture.dispose(),this.fillData=new Uint8Array(this.gridW*this.gridH*4),this.ghostData=new Uint8Array(this.gridW*this.gridH*4),this.subdivData=new Uint8Array(this.gridW*this.gridH),this._subdivTarget=new Uint8Array(this.gridW*this.gridH),this._subdivFloat=new Float32Array(this.gridW*this.gridH),this._subdivDirty=!0,this._subdivActiveCount=this._subdivFloat.length,this._fillDirtyCells=null,this._ghostDirtyCells=null,this.hoverData=new Uint8Array(this.gridW*this.gridH),this.fillTexture=this._makeDataTexture(this.fillData,T),this.ghostTexture=this._makeDataTexture(this.ghostData,T),this.subdivTexture=this._makeDataTexture(this.subdivData),this.subdivLevelTexture=this._makeDataTexture(this._subdivTarget),this.hoverTexture=this._makeDataTexture(this.hoverData),this.colPosTexture&&this.colPosTexture.dispose(),this.rowPosTexture&&this.rowPosTexture.dispose(),this.colPosTexture=this._makePositionTexture(this._colPositions),this.rowPosTexture=this._makePositionTexture(this._rowPositions),this.material.uniforms.uFill.value=this.fillTexture,this.material.uniforms.uGhost.value=this.ghostTexture,this.material.uniforms.uSubdiv.value=this.subdivTexture,this.material.uniforms.uSubdivLevel.value=this.subdivLevelTexture,this.material.uniforms.uHoverSubtree.value=this.hoverTexture,this.material.uniforms.uColPosTex.value=this.colPosTexture,this.material.uniforms.uRowPosTex.value=this.rowPosTexture,this.material.uniforms.uGridSize.value.set(this.gridW,this.gridH)}_syncRendererSize(e,t){this.renderer.setSize(e,t,!1);let n=this.renderer.getPixelRatio(),r=this.config.gridSnapToDevicePixels!==!1,i=r?Math.round(e*n):e,a=r?Math.round(t*n):t;this.material.uniforms.uResolution.value.set(i,a),this.composer.setSize(e,t),this.bloomPass.setSize(e,t)}_rebuildAll(){this._initGrid(),this._resetGrid(),this._rebuildTexture(),this._seedInitial(),this.config.pregenEnabled&&this._pregenerate()}_rebuildGPUResources(){this.bloomPass&&this.bloomPass.dispose(),this.vignettePass&&this.vignettePass.dispose(),this.chromaticPass&&this.chromaticPass.dispose(),this.noisePass&&this.noisePass.dispose(),this.composer&&=(this.composer.dispose(),null),this._treeLinesMesh&&=(this.scene.remove(this._treeLinesMesh),null),this._treeLinesMat&&this._treeLinesMat.dispose(),this._treeLinesGeo&&this._treeLinesGeo.dispose();let e=[this.fillTexture,this.ghostTexture,this.subdivTexture,this.subdivLevelTexture,this.hoverTexture,this.colPosTexture,this.rowPosTexture];for(let t of e)t&&(t.needsUpdate=!0);this._buildTreeLines(),this._buildPostProcessing()}_onResize(){let e=this.canvas.clientWidth,t=this.canvas.clientHeight,n=this._lastResizeW??e,r=this._lastResizeH??t;if(e===n&&t===r)return;this._lastResizeW=e,this._lastResizeH=t,this._syncRendererSize(e,t);let i=e!==n,a=Math.abs(t-r);window.matchMedia(`(pointer: coarse)`).matches&&!i&&a<150||(this._resizeDebounceTimer||(this.canvas.style.opacity=`0`),clearTimeout(this._resizeDebounceTimer),this._resizeDebounceTimer=setTimeout(()=>{this._resizeDebounceTimer=null,this._rebuildAll(),this.canvas.style.opacity=`1`},1e3))}_onVisibilityChange(){if(document.hidden){this._suspendForVisibility();return}this._resumeFromVisibility()}_onPageShow(e){e.persisted&&this._resumeFromVisibility()}_suspendForVisibility(){this._tabHidden||(this._tabHidden=!0,this._raf&&=(cancelAnimationFrame(this._raf),null),this._resizeDebounceTimer&&(clearTimeout(this._resizeDebounceTimer),this._resizeDebounceTimer=null,this.canvas.style.opacity=`1`),this._resizeRAF&&=(cancelAnimationFrame(this._resizeRAF),null))}_resumeFromVisibility(){this._tabHidden&&(this._tabHidden=!1,this._clockLastWall=performance.now(),this._onResize(),!this._disposed&&this._loop&&!this._raf&&this._loop())}_onContextLost(e){e.preventDefault(),this._contextLost=!0,this._raf&&=(cancelAnimationFrame(this._raf),null),console.warn(`[subdivision] WebGL context lost`)}_onContextRestored(){this._contextLost=!1,console.warn(`[subdivision] WebGL context restored — rebuilding`),this._rebuildGPUResources(),this._rebuildAll(),this._clockLastWall=performance.now(),!this._disposed&&this._loop&&!this._raf&&this._loop()}_updatePruneDisabledState(){let e=!this.config.pruneEnabled;for(let t of this._pruneSubControls||[])t.disabled=e,t.element.style.opacity=e?`0.35`:``,t.element.style.pointerEvents=e?`none`:``}_addFolderDesc(e,t){let n=document.createElement(`div`);n.className=`tp-folder-desc`,n.textContent=t;let r=e.element.querySelector(`.tp-fldv_b`);r&&r.insertAdjacentElement(`afterend`,n)}_applyPreset(e,t){let n=0,r=[];for(let e of Object.keys(e_)){let t=e_[e];this.config[e]=t&&typeof t==`object`?{...t}:t}for(let[e,i]of Object.entries(t)){if(!(e in this.config)){r.push(`key "${e}" not found`);continue}this.config[e]=i&&typeof i==`object`?{...i}:i,n++}this._rebaseResponsive(),this.pane.refresh(),this._onConfigChange(),this.config.pregenEnabled?this._pregenerate():this._lastGenTime=this._clockMs,this._updatePruneDisabledState(),this._updateDirWeightDisabled?.();let i=`Preset "${e}" applied. ${n} settings applied`;r.length>0&&(i+=`, ${r.length} error${r.length>1?`s`:``}: ${r.join(`; `)}`),this._presetStatus&&(this._presetStatus.textContent=i),console.log(`[subdivision] ${i}`)}_buildGUI(){let e=this.canvas.parentElement;e.style.position=`relative`;let t=document.createElement(`div`);t.style.cssText=[`position: absolute`,`top: 0`,`right: 0`,`width: 310px`,`max-height: 100%`,`overflow-y: auto`,`overflow-x: hidden`,`z-index: 1000`,`pointer-events: auto`].join(`;`),e.appendChild(t),this._paneContainer=t,this.pane=new yg({title:`Life Subdivision`,container:t});let n=t.querySelector(`.tp-rotv`);n&&(n.style.position=`relative`,n.style.width=`100%`,n.style.maxHeight=`none`);let r={Normal:`normal`,Multiply:`multiply`,Screen:`screen`,Overlay:`overlay`,"Soft Light":`softLight`},i={color:{alpha:!0}},a=this.pane.addFolder({title:`Actions & Config`}),o=a.addFolder({title:`Presets`});this._addFolderDesc(o,`Select a preset to apply`);let s=document.createElement(`div`);s.className=`tp-preset-status`,o.element.querySelector(`.tp-fldv_c`).prepend(s),this._presetStatus=s;let c={};for(let e=s_.length-1;e>=0;e--){let t=String(e).padStart(2,`0`)+` — `+s_[e].name;c[t]=e}this._presetSelection={index:this._initialPresetIndex};let l=o.addBinding(this._presetSelection,`index`,{label:``,options:c}),u=l.element,d=u.querySelector(`.tp-lblv_l`);d&&(d.style.display=`none`);let f=u.querySelector(`.tp-lblv_v`);f&&(f.style.flexGrow=`1`),l.on(`change`,e=>{let t=s_[e.value];this._applyPreset(t.name,t.config)}),a.addFolder({title:`Quick Actions`}).addButton({title:`Restart Animation`}).on(`click`,()=>{this._resetGrid(),this._rebuildTexture(),this._seedInitial(),this.config.pregenEnabled&&this._pregenerate()});let p=a.addFolder({title:`Clipboard`});p.addButton({title:`Copy Config (Modified Only)`}).on(`click`,()=>{let e={};for(let t of Object.keys(e_))p_(this.config[t],e_[t])||t!==`responsive`&&!m_(t,this.config)||(e[t]=this.config[t]);let t=JSON.stringify(h_(e));navigator.clipboard.writeText(t).then(()=>{console.log(`[subdivision] Copied data-config to clipboard:`,t)})}),p.addButton({title:`Copy Full Config`}).on(`click`,()=>{let e=JSON.stringify(h_(this.config),null,2);navigator.clipboard.writeText(e).then(()=>{console.log(`[subdivision] Full config copied to clipboard`)})}),p.addButton({title:`Paste & Load Config`}).on(`click`,()=>{let e=prompt(`Paste data-config JSON:`);if(e)try{let t=JSON.parse(e);this._migrateLegacyConfig(t),Object.assign(this.config,t),this._rebaseResponsive(),this.pane.refresh(),this._onConfigChange(),this._updatePruneDisabledState(),this._updateDirWeightDisabled?.(),console.log(`[subdivision] Loaded config:`,Object.keys(t).join(`, `))}catch(e){alert(`Invalid JSON: `+e.message)}});let m=Object.keys(this.config).filter(e=>e!==`responsive`).sort(),h={};for(let e of m)h[e]=e;this._copySingle={key:m[0]},p.addBinding(this._copySingle,`key`,{label:`Setting`,options:h}),p.addButton({title:`Copy Selected Setting (as JSON)`}).on(`click`,()=>{let e=this._copySingle.key,t=this.config[e],n=JSON.stringify(h_({[e]:t}));navigator.clipboard.writeText(n).then(()=>{console.log(`[subdivision] Copied ${e}:`,n)})});let g=this.pane.addFolder({title:`Grid`});this._addFolderDesc(g,`Base grid layout, cell sizing, and line appearance`),g.addBinding(this.config,`cellSize`,{min:16,max:256,step:1,label:`Cell Size (target)`}).on(`change`,()=>{this._onConfigChange(),_&&_.refresh()});let _=g.addBinding(this._effective,`cellSize`,{readonly:!0,label:`Cell Size (effective)`,format:e=>`${e} px`});g.addBinding(this.config,`subdivisionLevels`,{min:0,max:6,step:1,label:`Depth Levels`}).on(`change`,()=>{this._onConfigChange(),_&&_.refresh()}),g.addBinding(this.config,`lineColor`,{label:`Line Color`,...i}),g.addBinding(this.config,`lineWidth`,{min:.25,max:5,step:.25,label:`Line Width`}).on(`change`,()=>{this._onConfigChange(),_&&_.refresh()}),g.addBinding(this.config,`lineBlend`,{label:`Line Blend`,options:r}),g.addBinding(this.config,`gridLineFade`,{min:0,max:2e3,step:50,label:`Line Fade (ms)`}),g.addBinding(this.config,`outerBorder`,{label:`Outer Border`}).on(`change`,()=>this._onConfigChange()),g.addBinding(this.config,`bgColor`,{label:`Background`});let v=this.pane.addFolder({title:`Start Position`});this._addFolderDesc(v,`Where the first square spawns on the canvas`);let y=v.addBinding(this.config,`seedMode`,{label:`Placement`,options:{Random:`random`,Corner:`corner`,"Edge (random)":`edge`,"Edge (center)":`edgeCenter`,Center:`center`,"Center (random)":`centerRandom`,"Position (X, Y)":`position`}}),b=v.addBinding(this.config,`seedCorner`,{label:`Which Corner`,options:{"Top-Left":`TL`,"Top-Right":`TR`,"Bottom-Left":`BL`,"Bottom-Right":`BR`}}),x=v.addBinding(this.config,`seedEdge`,{label:`Which Edge`,options:{Top:`top`,Right:`right`,Bottom:`bottom`,Left:`left`}}),S=v.addBinding(this.config,`seedX`,{label:`X (% width)`,min:0,max:100,step:1}),C=v.addBinding(this.config,`seedY`,{label:`Y (% height)`,min:0,max:100,step:1}),w=v.addBinding(this.config,`seedVarianceX`,{label:`X variance (±%)`,min:0,max:50,step:1}),T=v.addBinding(this.config,`seedVarianceY`,{label:`Y variance (±%)`,min:0,max:50,step:1}),E=()=>{let e=this.config.seedMode;b.hidden=e!==`corner`,x.hidden=e!==`edge`&&e!==`edgeCenter`,S.hidden=e!==`position`,C.hidden=e!==`position`,w.hidden=e!==`position`,T.hidden=e!==`position`};E(),y.on(`change`,()=>{E(),this._onConfigChange()}),b.on(`change`,()=>this._onConfigChange()),x.on(`change`,()=>this._onConfigChange()),S.on(`change`,()=>this._onConfigChange()),C.on(`change`,()=>this._onConfigChange()),w.on(`change`,()=>this._onConfigChange()),T.on(`change`,()=>this._onConfigChange());let D=this.pane.addFolder({title:`Growth Settings`});this._addFolderDesc(D,`Generation timing, children limits, and spawn directions`),D.addBinding(this.config,`genSpeed`,{min:10,max:5e3,step:1,label:`Generation Interval (ms)`}),D.addBinding(this.config,`maxGenerations`,{min:50,max:2e3,step:50,label:`Max Generations`}),D.addBinding(this.config,`shrinkBias`,{min:0,max:1,step:.05,label:`Size Bias (0=big 1=small)`}),D.addBinding(this.config,`minChildren`,{min:0,max:8,step:1,label:`Children Min`}),D.addBinding(this.config,`maxChildren`,{min:0,max:8,step:1,label:`Children Max`});let O=D.addFolder({title:`Growth Directions`});this._addFolderDesc(O,`Which directions children can spawn relative to parent`);let k=O.addBinding(this.config,`dirTL`,{label:`Top Left`}),A=O.addBinding(this.config,`dirTop`,{label:`Top`}),ee=O.addBinding(this.config,`dirTR`,{label:`Top Right`}),te=O.addBinding(this.config,`dirLeft`,{label:`Left`}),j=O.addBinding(this.config,`dirRight`,{label:`Right`}),ne=O.addBinding(this.config,`dirBL`,{label:`Bottom Left`}),M=O.addBinding(this.config,`dirBottom`,{label:`Bottom`}),N=O.addBinding(this.config,`dirBR`,{label:`Bottom Right`}),P=O.addFolder({title:`Temporary Direction Restrictions`,expanded:!0});this._addFolderDesc(P,`Force spawn order for the first N generations (lower priority = picked first). Ties resolve randomly.`);let re=P.addBinding(this.config,`restrictedGenerationsEnabled`,{label:`Enable`}),F=P.addBinding(this.config,`restrictedGenerations`,{min:0,max:100,step:1,label:`Restricted Generations`});this._priorityOrderState={order:``};let ie=P.addBinding(this._priorityOrderState,`order`,{readonly:!0,label:`Order`}),ae=P.addBinding(this.config,`dirPriorityTL`,{min:1,max:8,step:1,label:`Top Left`}),oe=P.addBinding(this.config,`dirPriorityTop`,{min:1,max:8,step:1,label:`Top`}),se=P.addBinding(this.config,`dirPriorityTR`,{min:1,max:8,step:1,label:`Top Right`}),ce=P.addBinding(this.config,`dirPriorityLeft`,{min:1,max:8,step:1,label:`Left`}),le=P.addBinding(this.config,`dirPriorityRight`,{min:1,max:8,step:1,label:`Right`}),ue=P.addBinding(this.config,`dirPriorityBL`,{min:1,max:8,step:1,label:`Bottom Left`}),de=P.addBinding(this.config,`dirPriorityBottom`,{min:1,max:8,step:1,label:`Bottom`}),I=P.addBinding(this.config,`dirPriorityBR`,{min:1,max:8,step:1,label:`Bottom Right`}),L=[{tog:`dirTL`,pri:`dirPriorityTL`,b:ae,label:`Top Left`},{tog:`dirTop`,pri:`dirPriorityTop`,b:oe,label:`Top`},{tog:`dirTR`,pri:`dirPriorityTR`,b:se,label:`Top Right`},{tog:`dirLeft`,pri:`dirPriorityLeft`,b:ce,label:`Left`},{tog:`dirRight`,pri:`dirPriorityRight`,b:le,label:`Right`},{tog:`dirBL`,pri:`dirPriorityBL`,b:ue,label:`Bottom Left`},{tog:`dirBottom`,pri:`dirPriorityBottom`,b:de,label:`Bottom`},{tog:`dirBR`,pri:`dirPriorityBR`,b:I,label:`Bottom Right`}],fe=()=>{let e=L.filter(e=>this.config[e.tog]);e.length===0?this._priorityOrderState.order=`(no directions enabled)`:(e.sort((e,t)=>this.config[e.pri]-this.config[t.pri]),this._priorityOrderState.order=e.map(e=>e.label).join(` → `)),ie.refresh()};this._updateDirWeightDisabled=()=>{let e=!!this.config.restrictedGenerationsEnabled;F.hidden=!e,ie.hidden=!e;for(let t of L)t.b.hidden=!e||!this.config[t.tog];fe()},this._updateDirWeightDisabled(),re.on(`change`,()=>this._updateDirWeightDisabled());for(let e of L)e.b.on(`change`,()=>fe());let pe=[{b:k,tog:`dirTL`,pri:`dirPriorityTL`},{b:A,tog:`dirTop`,pri:`dirPriorityTop`},{b:ee,tog:`dirTR`,pri:`dirPriorityTR`},{b:te,tog:`dirLeft`,pri:`dirPriorityLeft`},{b:j,tog:`dirRight`,pri:`dirPriorityRight`},{b:ne,tog:`dirBL`,pri:`dirPriorityBL`},{b:M,tog:`dirBottom`,pri:`dirPriorityBottom`},{b:N,tog:`dirBR`,pri:`dirPriorityBR`}];for(let e of pe)e.b.on(`change`,t=>{if(t.value===!0){let t=0;for(let n of pe)if(n.tog!==e.tog&&this.config[n.tog]){let e=this.config[n.pri];e>t&&(t=e)}this.config[e.pri]=Math.min(8,t+1),this.pane&&this.pane.refresh()}this._updateDirWeightDisabled()});let me=D.addFolder({title:`Pregeneration`});this._addFolderDesc(me,`Fast-forward N generations at startup, then animate in the surviving state`),me.addBinding(this.config,`pregenEnabled`,{label:`Enable`}),me.addBinding(this.config,`pregenGenerations`,{min:1,max:100,step:1,label:`Generations`}),me.addBinding(this.config,`pregenFadeInDuration`,{min:0,max:2e3,step:50,label:`Fade-In Duration (ms)`}),me.addBinding(this.config,`pregenFadeInStagger`,{min:0,max:2e3,step:5,label:`Stagger Per Generation (ms)`}),me.addButton({title:`Regenerate with Pregeneration`}).on(`click`,()=>{this._resetGrid(),this._rebuildTexture(),this._seedInitial(),this.config.pregenEnabled&&this._pregenerate()});let he=this.pane.addFolder({title:`Background Squares`});this._addFolderDesc(he,`Filled square visibility, colors, and animation`),he.addBinding(this.config,`showSquares`,{label:`Show Background Squares`}),he.addBinding(this.config,`cellShape`,{label:`Cell Shape`,options:{Square:`square`,Circle:`circle`,"Rounded Rect":`roundedRect`}}).on(`change`,()=>{ge.hidden=this.config.cellShape!==`roundedRect`});let ge=he.addBinding(this.config,`cellRadius`,{min:0,max:.5,step:.01,label:`Corner Radius`});ge.hidden=this.config.cellShape!==`roundedRect`,he.addBinding(this.config,`cellAA`,{label:`Antialiasing`}),he.addBinding(this.config,`growOriginMode`,{label:`Growth Origin`,options:{"From Spawn Edge":`corner`,"From Center":`center`}});let _e=he.addFolder({title:`Colors`});this._addFolderDesc(_e,`Color and opacity per lifecycle state`),_e.addBinding(this.config,`newColor`,{label:`New Square`,...i}),_e.addBinding(this.config,`parentColor`,{label:`Base Square`,...i}),_e.addBinding(this.config,`pruneColor`,{label:`Dead Branch`,...i});let ve=he.addFolder({title:`Transitions`});this._addFolderDesc(ve,`Animation and color transition timing per lifecycle state`),ve.addBinding(this.config,`growDurationMode`,{label:`New Square Growth Animation Time (ms)`,options:{"Same as Generation Interval":`interval`,Custom:`custom`}}).on(`change`,()=>{ye.hidden=this.config.growDurationMode===`interval`});let ye=ve.addBinding(this.config,`growDuration`,{min:0,max:5e3,step:1,label:`New Square Growth Animation (ms)`});ye.hidden=this.config.growDurationMode===`interval`,ve.addBinding(this.config,`growEasing`,{label:`New Square Animation Easing`,options:Ug}),ve.addBinding(this.config,`fadeInDuration`,{min:0,max:2500,step:1,label:`New Square Color Fade-In (ms)`}),ve.addBinding(this.config,`parentTransition`,{min:0,max:1e4,step:1,label:`New to Base Transition (ms)`}),ve.addBinding(this.config,`pruneTransition`,{min:0,max:5e3,step:1,label:`Base to Dead Branch Transition (ms)`}),ve.addBinding(this.config,`colorEasing`,{label:`Color Transition Easing`,options:Ug});let be=this.pane.addFolder({title:`Dead Ends & Pruning`});this._addFolderDesc(be,`Dead branch detection and removal`),be.addBinding(this.config,`pruneEnabled`,{label:`Enable Pruning`}).on(`change`,()=>{this._updatePruneDisabledState()});let xe=be.addFolder({title:`Retraction`});this._addFolderDesc(xe,`Staggered fade-out of dead branches`),xe.addBinding(this.config,`fadeOutDuration`,{min:0,max:5e3,step:1,label:`Fade-Out Duration (ms)`}),xe.addBinding(this.config,`fadeOutStagger`,{min:0,max:500,step:1,label:`Stagger per Depth (ms)`}),xe.addBinding(this.config,`maxStaggerTotal`,{min:0,max:1e4,step:50,label:`Max Total Stagger (ms)`}),xe.addBinding(this.config,`soothingFinalRetraction`,{label:`Soothing Reverse Final Retraction`});let Se=be.addFolder({title:`Pruning Tracer`});this._addFolderDesc(Se,`Overlay that traces the pruning wave from leaf to root`),Se.addBinding(this.config,`tracerEnabled`,{label:`Enable Tracer`}),Se.addBinding(this.config,`tracerColor`,{label:`Color`,...i}),Se.addBinding(this.config,`tracerDuration`,{min:0,max:1e3,step:10,label:`Tracer Fade-out (ms)`}),Se.addBinding(this.config,`tracerBlend`,{label:`Blend`,options:r});let Ce=be.addFolder({title:`Victory Conditions`});this._addFolderDesc(Ce,`Branches that reach an allowed canvas edge lock as winners and ripple from root → tip (mirrors pruning, sharing the same per-depth stagger)`),Ce.addBinding(this.config,`victoryEnabled`,{label:`Enable Victory`}),Ce.addBinding(this.config,`victoryColor`,{label:`Winner Color`,...i}),Ce.addBinding(this.config,`victoryTransition`,{min:0,max:5e3,step:1,label:`Color Transition (ms)`}),Ce.addBinding(this.config,`victoryTracerEnabled`,{label:`Enable Tracer`}),Ce.addBinding(this.config,`victoryTracerColor`,{label:`Tracer Color`,...i}),Ce.addBinding(this.config,`victoryTracerDuration`,{min:0,max:2e3,step:10,label:`Tracer Pulse (ms)`}),this._pruneSubControls=[xe,Se,Ce],this._updatePruneDisabledState();let we=this.pane.addFolder({title:`Hover & Click`});this._addFolderDesc(we,`Visual feedback when pointing at or clicking squares`),we.addBinding(this.config,`hoverEmptyColor`,{label:`Empty Cell`,...i}),we.addBinding(this.config,`hoverEmptyBlend`,{label:`Empty Blend`,options:r}),we.addBinding(this.config,`hoverFilledColor`,{label:`Filled Cell`,...i}),we.addBinding(this.config,`hoverFilledBlend`,{label:`Filled Blend`,options:r}),we.addBinding(this.config,`hoverParentColor`,{label:`Subtree`,...i}),we.addBinding(this.config,`hoverSubtreeBlend`,{label:`Subtree Blend`,options:r}),we.addBinding(this.config,`hoverStagger`,{min:0,max:200,step:1,label:`Cascade Delay (ms)`}),we.addBinding(this.config,`maxHoverTotal`,{min:0,max:5e3,step:50,label:`Max Cascade (ms)`});let Te=we.addFolder({title:`Click Flash`});this._addFolderDesc(Te,`Brief flash when clicking or tapping a cell`),Te.addBinding(this.config,`clickFlashColor`,{label:`Color`,...i}),Te.addBinding(this.config,`clickFlashDuration`,{min:0,max:1e3,step:10,label:`Duration (ms)`});let R=this.pane.addFolder({title:`Tree of Life`});this._addFolderDesc(R,`Curved ancestry lines connecting each parent to its children`),R.addBinding(this.config,`treeEnabled`,{label:`Enable`});let Ee=R.addFolder({title:`Line Style`});this._addFolderDesc(Ee,`Stroke appearance and curve shape`),Ee.addBinding(this.config,`treeColor`,{label:`Color`,...i}),Ee.addBinding(this.config,`treeWidth`,{min:.5,max:10,step:.5,label:`Width`}),Ee.addBinding(this.config,`treeBlend`,{label:`Blend`,options:{Normal:`normal`,Screen:`screen`,Multiply:`multiply`}}),Ee.addBinding(this.config,`treeRoundedness`,{min:0,max:1,step:.05,label:`Curvature`}),Ee.addBinding(this.config,`treeSegments`,{min:2,max:32,step:1,label:`Curve Detail`});let De=R.addFolder({title:`New Growth`});this._addFolderDesc(De,`Temporary color for newly added branches`),De.addBinding(this.config,`treeGrowColor`,{label:`Color`,...i}),De.addBinding(this.config,`treeGrowTransition`,{min:0,max:2e3,step:10,label:`Fade to Base (ms)`});let Oe=R.addFolder({title:`Pruning`});this._addFolderDesc(Oe,`Color and retraction animation for dying branches`),Oe.addBinding(this.config,`treeHoverColor`,{label:`Dying Color`,...i}),Oe.addBinding(this.config,`treePruneTransition`,{min:0,max:2e3,step:10,label:`Color Transition (ms)`}),Oe.addBinding(this.config,`treePruneDurationMode`,{label:`Retraction Speed`,options:{"Match Pruning Stagger":`stagger`,Custom:`custom`}}).on(`change`,()=>{z.hidden=this.config.treePruneDurationMode===`stagger`});let z=Oe.addBinding(this.config,`treePruneDuration`,{min:0,max:2e3,step:10,label:`Retraction (ms)`});z.hidden=this.config.treePruneDurationMode===`stagger`;let ke=this.pane.addFolder({title:`Post-Processing`});this._addFolderDesc(ke,`Screen-space post-processing effects`),ke.addBinding(this.config,`postFxEnabled`,{label:`Enable All`});let B=ke.addFolder({title:`Bloom`});this._addFolderDesc(B,`Glow effect on bright areas`),B.addBinding(this.config,`bloomEnabled`,{label:`Enable`}),B.addBinding(this.config,`bloomIntensity`,{min:0,max:3,step:.1,label:`Strength`}),B.addBinding(this.config,`bloomThreshold`,{min:0,max:1,step:.05,label:`Threshold`}),B.addBinding(this.config,`bloomRadius`,{min:0,max:2,step:.1,label:`Spread`});let V=ke.addFolder({title:`Vignette`});this._addFolderDesc(V,`Darkened edges around the viewport`),V.addBinding(this.config,`vignetteEnabled`,{label:`Enable`}),V.addBinding(this.config,`vignetteDarkness`,{min:0,max:3,step:.1,label:`Strength`}),V.addBinding(this.config,`vignetteOffset`,{min:.5,max:2,step:.1,label:`Offset`});let Ae=ke.addFolder({title:`Chromatic Aberration`});this._addFolderDesc(Ae,`RGB channel separation at edges`),Ae.addBinding(this.config,`chromaticEnabled`,{label:`Enable`}),Ae.addBinding(this.config,`chromaticOffset`,{min:0,max:.02,step:.001,label:`Amount`});let je=ke.addFolder({title:`Noise`});this._addFolderDesc(je,`Film grain on final output`),je.addBinding(this.config,`noiseEnabled`,{label:`Enable`}),je.addBinding(this.config,`noiseIntensity`,{min:0,max:.5,step:.01,label:`Intensity`}),je.addBinding(this.config,`noiseStatic`,{label:`Static (no animation)`});let Me=this.pane.addFolder({title:`Stats`});Me.addBinding(this.stats,`generation`,{readonly:!0,label:`Generation`}),Me.addBinding(this.stats,`totalSquares`,{readonly:!0,label:`Total Squares`}),Me.addBinding(this.stats,`childrenPossible`,{readonly:!0,label:`Can Still Spawn`}),Me.addBinding(this.stats,`treeDepth`,{readonly:!0,label:`Deepest Branch`}),Me.addBinding(this.stats,`pruning`,{readonly:!0,label:`Squares Dying`});let Ne=this.pane.addFolder({title:`Performance`});Ne.addBinding(this.perf,`fps`,{readonly:!0,label:`FPS`}),Ne.addBinding(this.perf,`frameTime`,{readonly:!0,label:`Frame (ms)`}),Ne.addBinding(this.perf,`totalMs`,{readonly:!0,label:`Total JS (ms)`}),Ne.addBinding(this.perf,`subdivMs`,{readonly:!0,label:` Subdivision (ms)`}),Ne.addBinding(this.perf,`textureMs`,{readonly:!0,label:` Texture (ms)`}),Ne.addBinding(this.perf,`hoverMs`,{readonly:!0,label:` Hover (ms)`}),Ne.addBinding(this.perf,`treeMs`,{readonly:!0,label:` Tree Lines (ms)`}),Ne.addBinding(this.perf,`guiMs`,{readonly:!0,label:` GUI Refresh (ms)`}),Ne.addBinding(this.perf,`renderMs`,{readonly:!0,label:` Render (ms)`}),Ne.addBinding(this.perf,`squares`,{readonly:!0,label:`Squares`}),Ne.addBinding(this.perf,`treeVerts`,{readonly:!0,label:`Tree Verts`}),Ne.addBinding(this.perf,`gridCells`,{readonly:!0,label:`Grid Cells`}),Ne.addBinding(this.perf,`drawCalls`,{readonly:!0,label:`Draw Calls`}),Ne.addBinding(this.perf,`triangles`,{readonly:!0,label:`Triangles`})}_onConfigChange(){this._initGrid(),this._resetGrid(),this._rebuildTexture(),this._seedInitial(),this.material.uniforms.uResolution.value.set(this._gridUniformResW,this._gridUniformResH),this.material.uniforms.uMaxLevel.value=this.config.subdivisionLevels,this.material.uniforms.uLineWidth.value=this._lineWidthPx??this.config.lineWidth}};function __(e,t){let n=e.getAttribute(t);if(!n)return null;n=n.trim().replace(/^'|'$/g,``).replace(/'/g,`"`);try{return JSON.parse(n)}catch(n){return console.warn(`[subdivision] Invalid ${t} JSON in`,e,n),null}}function v_(e,t={}){getComputedStyle(e).position===`static`&&(e.style.position=`relative`);let n=document.createElement(`canvas`);n.style.position=`absolute`,n.style.inset=`0`,n.style.width=`100%`,n.style.height=`100%`,n.style.display=`block`,e.appendChild(n);let r=new g_(n,{gui:t.gui??!1,config:t.config});if(r.start(),t.observeVisibility!==!1){let t=new IntersectionObserver(([e])=>{e.intersectionRatio>=.2?r.resume():r.pause()},{threshold:[0,.2]});t.observe(e),r._visibilityObserver=t}let i=r.dispose.bind(r);return r.dispose=()=>{r._visibilityObserver&&r._visibilityObserver.disconnect(),i(),n.remove()},r}function y_(){let e=document.querySelectorAll(`[data-subdivision]`);for(let t of e)t._subdivisionInstance||=v_(t,{config:__(t,`data-config`)||{},gui:t.dataset.gui===`true`,observeVisibility:t.dataset.observe!==`false`})}function b_(e){let t=()=>{Promise.resolve(document.fonts&&document.fonts.ready).then(()=>new Promise(e=>requestAnimationFrame(()=>requestAnimationFrame(e)))).then(()=>x_()).then(e)};document.readyState===`complete`?t():window.addEventListener(`load`,t,{once:!0})}function x_(){return new Promise(e=>{let t=document.querySelectorAll(`[data-subdivision]`);if(!t.length)return e();let n=performance.now(),r=new Map;function i(){let a=!0;for(let e of t){let t=e.clientWidth,n=e.clientHeight,i=r.get(e);!i||i.w!==t||i.h!==n||t===0||n===0?(r.set(e,{w:t,h:n,stableFrames:0}),a=!1):(i.stableFrames++,i.stableFrames<2&&(a=!1))}a||performance.now()-n>1500?e():requestAnimationFrame(i)}requestAnimationFrame(i)})}return b_(y_),e.createSubdivision=v_,e})({});