var e=Object.defineProperty,t=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},n=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n||e(r,Symbol.toStringTag,{value:`Module`}),r};(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();function r(e){for(let t=e.length-1;t>=0;--t)if(e[t]>=65535)return!0;return!1}function i(e,t){return new oi[e](t)}function a(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function o(e){return document.createElementNS(`http://www.w3.org/1999/xhtml`,e)}function s(){let e=o(`canvas`);return e.style.display=`block`,e}function c(e){ci=e}function l(){return ci}function u(...e){let t=`THREE.`+e.shift();ci?ci(`log`,t,...e):console.log(t,...e)}function d(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 f(...e){e=d(e);let t=`THREE.`+e.shift();if(ci)ci(`warn`,t,...e);else{let n=e[0];n&&n.isStackTrace?console.warn(n.getError(t)):console.warn(t,...e)}}function p(...e){e=d(e);let t=`THREE.`+e.shift();if(ci)ci(`error`,t,...e);else{let n=e[0];n&&n.isStackTrace?console.error(n.getError(t)):console.error(t,...e)}}function m(...e){let t=e.join(` `);t in si||(si[t]=!0,f(...e))}function h(){return typeof self<`u`&&self.scheduler!==void 0&&self.scheduler.yield!==void 0?self.scheduler.yield():new Promise(e=>{requestAnimationFrame(e)})}function g(){let e=Math.random()*4294967295|0,t=Math.random()*4294967295|0,n=Math.random()*4294967295|0,r=Math.random()*4294967295|0;return(di[e&255]+di[e>>8&255]+di[e>>16&255]+di[e>>24&255]+`-`+di[t&255]+di[t>>8&255]+`-`+di[t>>16&15|64]+di[t>>24&255]+`-`+di[n&63|128]+di[n>>8&255]+`-`+di[n>>16&255]+di[n>>24&255]+di[r&255]+di[r>>8&255]+di[r>>16&255]+di[r>>24&255]).toLowerCase()}function _(e,t,n){return Math.max(t,Math.min(n,e))}function v(e,t){return(e%t+t)%t}function y(e,t,n,r,i){return r+(e-t)*(i-r)/(n-t)}function b(e,t,n){return e===t?0:(n-e)/(t-e)}function x(e,t,n){return(1-n)*e+n*t}function S(e,t,n,r){return x(e,t,1-Math.exp(-n*r))}function C(e,t=1){return t-Math.abs(v(e,t*2)-t)}function w(e,t,n){return e<=t?0:e>=n?1:(e=(e-t)/(n-t),e*e*(3-2*e))}function T(e,t,n){return e<=t?0:e>=n?1:(e=(e-t)/(n-t),e*e*e*(e*(e*6-15)+10))}function E(e,t){return e+Math.floor(Math.random()*(t-e+1))}function D(e,t){return e+Math.random()*(t-e)}function ee(e){return e*(.5-Math.random())}function O(e){e!==void 0&&(fi=e);let t=fi+=1831565813;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}function k(e){return e*pi}function te(e){return e*mi}function A(e){return e>0&&Number.isInteger(e)&&2**Math.round(Math.log2(e))===e}function ne(e){return 2**Math.ceil(Math.log(e)/Math.LN2)}function re(e){return 2**Math.floor(Math.log(e)/Math.LN2)}function ie(e,t,n,r,i){let a=Math.cos,o=Math.sin,s=a(n/2),c=o(n/2),l=a((t+r)/2),u=o((t+r)/2),d=a((t-r)/2),p=o((t-r)/2),m=a((r-t)/2),h=o((r-t)/2);switch(i){case`XYX`:e.set(s*u,c*d,c*p,s*l);break;case`YZY`:e.set(c*p,s*u,c*d,s*l);break;case`ZXZ`:e.set(c*d,c*p,s*u,s*l);break;case`XZX`:e.set(s*u,c*h,c*m,s*l);break;case`YXY`:e.set(c*m,s*u,c*h,s*l);break;case`ZYZ`:e.set(c*h,c*m,s*u,s*l);break;default:f(`MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: `+i)}}function ae(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return e/4294967295;case Uint16Array:return e/65535;case Uint8Array:case Uint8ClampedArray: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(`THREE.MathUtils: Invalid component type.`)}}function j(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:case Uint8ClampedArray: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(`THREE.MathUtils: Invalid component type.`)}}function oe(){let e={enabled:!0,workingColorSpace:Nr,spaces:{},convert:function(e,t,n){return this.enabled===!1||t===n||!t||!n?e:(this.spaces[t].transfer===`srgb`&&(e.r=se(e.r),e.g=se(e.g),e.b=se(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=ce(e.r),e.g=ce(e.g),e.b=ce(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===``?Pr: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 m(`ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace().`),e.workingToColorSpace(t,n)},toWorkingColorSpace:function(t,n){return m(`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({[Nr]:{primaries:t,whitePoint:r,transfer:Pr,toXYZ:xi,fromXYZ:Si,luminanceCoefficients:n,workingColorSpaceConfig:{unpackColorSpace:Mr},outputColorSpaceConfig:{drawingBufferColorSpace:Mr}},[Mr]:{primaries:t,whitePoint:r,transfer:Fr,toXYZ:xi,fromXYZ:Si,luminanceCoefficients:n,outputColorSpaceConfig:{drawingBufferColorSpace:Mr}}}),e}function se(e){return e<.04045?e*.0773993808:(e*.9478672986+.0521327014)**2.4}function ce(e){return e<.0031308?e*12.92:1.055*e**.41666-.055}function le(e){return typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof ImageBitmap<`u`&&e instanceof ImageBitmap?Ti.getDataURL(e):e.data?{data:Array.from(e.data),width:e.width,height:e.height,type:e.data.constructor.name}:(f(`Texture: Unable to serialize Texture.`),{})}function ue(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}function de(e,t,n,r,i){for(let a=0,o=e.length-3;a<=o;a+=3){Ja.fromArray(e,a);let o=i.x*Math.abs(Ja.x)+i.y*Math.abs(Ja.y)+i.z*Math.abs(Ja.z),s=t.dot(Ja),c=n.dot(Ja),l=r.dot(Ja);if(Math.max(-Math.max(s,c,l),Math.min(s,c,l))>o)return!1}return!0}function fe(){let e=new ArrayBuffer(4),t=new Float32Array(e),n=new Uint32Array(e),r=new Uint32Array(512),i=new Uint32Array(512);for(let e=0;e<256;++e){let t=e-127;t<-27?(r[e]=0,r[e|256]=32768,i[e]=24,i[e|256]=24):t<-14?(r[e]=1024>>-t-14,r[e|256]=1024>>-t-14|32768,i[e]=-t-1,i[e|256]=-t-1):t<=15?(r[e]=t+15<<10,r[e|256]=t+15<<10|32768,i[e]=13,i[e|256]=13):t<128?(r[e]=31744,r[e|256]=64512,i[e]=24,i[e|256]=24):(r[e]=31744,r[e|256]=64512,i[e]=13,i[e|256]=13)}let a=new Uint32Array(2048),o=new Uint32Array(64),s=new Uint32Array(64);for(let e=1;e<1024;++e){let t=e<<13,n=0;for(;!(t&8388608);)t<<=1,n-=8388608;t&=-8388609,n+=947912704,a[e]=t|n}for(let e=1024;e<2048;++e)a[e]=939524096+(e-1024<<13);for(let e=1;e<31;++e)o[e]=e<<23;o[31]=1199570944,o[32]=2147483648;for(let e=33;e<63;++e)o[e]=2147483648+(e-32<<23);o[63]=3347054592;for(let e=1;e<64;++e)e!==32&&(s[e]=1024);return{floatView:t,uint32View:n,baseTable:r,shiftTable:i,mantissaTable:a,exponentTable:o,offsetTable:s}}function pe(e){Math.abs(e)>65504&&f(`DataUtils.toHalfFloat(): Value out of range.`),e=_(e,-65504,65504),Ya.floatView[0]=e;let t=Ya.uint32View[0],n=t>>23&511;return Ya.baseTable[n]+((t&8388607)>>Ya.shiftTable[n])}function me(e){let t=e>>10;return Ya.uint32View[0]=Ya.mantissaTable[Ya.offsetTable[t]+(e&1023)]+Ya.exponentTable[t],Ya.floatView[0]}function he(e,t,n,r,i,a){Io.subVectors(e,n).addScalar(.5).multiply(r),i===void 0?Lo.copy(Io):(Lo.x=a*Io.x-i*Io.y,Lo.y=i*Io.x+a*Io.y),e.copy(t),e.x+=Lo.x,e.y+=Lo.y,e.applyMatrix4(Ro)}function ge(e,t,n,r,i,a,o,s){let c;if(c=t.side===1?r.intersectTriangle(o,a,i,!0,s):r.intersectTriangle(i,a,o,t.side===0,s),c===null)return null;ds.copy(s),ds.applyMatrix4(e.matrixWorld);let l=n.ray.origin.distanceTo(ds);return ln.far?null:{distance:l,point:ds.clone(),object:e}}function _e(e,t,n,r,i,a,o,s,c,l){e.getVertexPosition(s,as),e.getVertexPosition(c,os),e.getVertexPosition(l,ss);let u=ge(e,t,n,r,as,os,ss,us);if(u){let e=new P;Pa.getBarycoord(us,as,os,ss,e),i&&(u.uv=Pa.getInterpolatedAttribute(i,s,c,l,e,new N)),a&&(u.uv1=Pa.getInterpolatedAttribute(a,s,c,l,e,new N)),o&&(u.normal=Pa.getInterpolatedAttribute(o,s,c,l,e,new P),u.normal.dot(r.direction)>0&&u.normal.multiplyScalar(-1));let t={a:s,b:c,c:l,normal:new P,materialIndex:0};Pa.getNormal(as,os,ss,t.normal),u.face=t,u.barycoord=e}return u}function ve(e,t){return e-t}function ye(e,t){return e.z-t.z}function be(e,t){return t.z-e.z}function xe(e,t,n=0){let r=t.itemSize;if(e.isInterleavedBufferAttribute||e.array.constructor!==t.array.constructor){let i=e.count;for(let a=0;ar)return;cc.applyMatrix4(e.matrixWorld);let c=t.ray.origin.distanceTo(cc);if(!(ct.far))return{distance:c,point:lc.clone().applyMatrix4(e.matrixWorld),index:o,face:null,faceIndex:null,barycoord:null,object:e}}function we(e,t,n,r,i,a,o){let s=_c.distanceSqToPoint(e);if(si.far)return;a.push({distance:c,distanceToRay:Math.sqrt(s),point:n,index:t,face:null,faceIndex:null,barycoord:null,object:o})}}function Te(){let e=0,t=0,n=0,r=0;function i(i,a,o,s){e=i,t=o,n=-3*i+3*a-2*o-s,r=2*i-2*a+o+s}return{initCatmullRom:function(e,t,n,r,a){i(t,n,a*(n-e),a*(r-t))},initNonuniformCatmullRom:function(e,t,n,r,a,o,s){let c=(t-e)/a-(n-e)/(a+o)+(n-t)/o,l=(n-t)/o-(r-t)/(o+s)+(r-n)/s;c*=o,l*=o,i(t,n,c,l)},calc:function(i){let a=i*i,o=a*i;return e+t*i+n*a+r*o}}}function Ee(e,t,n,r,i){let a=(r-t)*.5,o=(i-n)*.5,s=e*e,c=e*s;return(2*n-2*r+a+o)*c+(-3*n+3*r-2*a-o)*s+a*e+n}function De(e,t){let n=1-e;return n*n*t}function M(e,t){return 2*(1-e)*e*t}function Oe(e,t){return e*e*t}function ke(e,t,n,r){return De(e,t)+M(e,n)+Oe(e,r)}function Ae(e,t){let n=1-e;return n*n*n*t}function je(e,t){let n=1-e;return 3*n*n*e*t}function Me(e,t){return 3*(1-e)*e*e*t}function Ne(e,t){return e*e*e*t}function Pe(e,t,n,r,i){return Ae(e,t)+je(e,n)+Me(e,r)+Ne(e,i)}function Fe(e,t,n=2){let r=t&&t.length,i=r?t[0]*n:e.length,a=Ie(e,0,i,n,!0),o=[];if(!a||a.next===a.prev)return o;let s,c,l;if(r&&(a=Ue(e,t,a,n)),e.length>80*n){s=e[0],c=e[1];let t=s,r=c;for(let a=n;at&&(t=n),i>r&&(r=i)}l=Math.max(t-s,r-c),l=l===0?0:32767/l}return Re(a,o,n,s,c,l,0),o}function Ie(e,t,n,r,i){let a;if(i===pt(e,t,n,r)>0)for(let i=t;i=t;i-=r)a=ut(i/r|0,e[i],e[i+1],a);return a&&nt(a,a.next)&&(dt(a),a=a.next),a}function Le(e,t){if(!e)return e;t||=e;let n=e,r;do if(r=!1,!n.steiner&&(nt(n,n.next)||tt(n.prev,n,n.next)===0)){if(dt(n),n=t=n.prev,n===n.next)break;r=!0}else n=n.next;while(r||n!==t);return t}function Re(e,t,n,r,i,a,o){if(!e)return;!o&&a&&Je(e,r,i,a);let s=e;for(;e.prev!==e.next;){let c=e.prev,l=e.next;if(a?Be(e,r,i,a):ze(e)){t.push(c.i,e.i,l.i),dt(e),e=l.next,s=l.next;continue}if(e=l,e===s){o?o===1?(e=Ve(Le(e),t),Re(e,t,n,r,i,a,2)):o===2&&He(e,t,n,r,i,a):Re(Le(e),t,n,r,i,a,1);break}}}function ze(e){let t=e.prev,n=e,r=e.next;if(tt(t,n,r)>=0)return!1;let i=t.x,a=n.x,o=r.x,s=t.y,c=n.y,l=r.y,u=Math.min(i,a,o),d=Math.min(s,c,l),f=Math.max(i,a,o),p=Math.max(s,c,l),m=r.next;for(;m!==t;){if(m.x>=u&&m.x<=f&&m.y>=d&&m.y<=p&&$e(i,s,a,c,o,l,m.x,m.y)&&tt(m.prev,m,m.next)>=0)return!1;m=m.next}return!0}function Be(e,t,n,r){let i=e.prev,a=e,o=e.next;if(tt(i,a,o)>=0)return!1;let s=i.x,c=a.x,l=o.x,u=i.y,d=a.y,f=o.y,p=Math.min(s,c,l),m=Math.min(u,d,f),h=Math.max(s,c,l),g=Math.max(u,d,f),_=Xe(p,m,t,n,r),v=Xe(h,g,t,n,r),y=e.prevZ,b=e.nextZ;for(;y&&y.z>=_&&b&&b.z<=v;){if(y.x>=p&&y.x<=h&&y.y>=m&&y.y<=g&&y!==i&&y!==o&&$e(s,u,c,d,l,f,y.x,y.y)&&tt(y.prev,y,y.next)>=0||(y=y.prevZ,b.x>=p&&b.x<=h&&b.y>=m&&b.y<=g&&b!==i&&b!==o&&$e(s,u,c,d,l,f,b.x,b.y)&&tt(b.prev,b,b.next)>=0))return!1;b=b.nextZ}for(;y&&y.z>=_;){if(y.x>=p&&y.x<=h&&y.y>=m&&y.y<=g&&y!==i&&y!==o&&$e(s,u,c,d,l,f,y.x,y.y)&&tt(y.prev,y,y.next)>=0)return!1;y=y.prevZ}for(;b&&b.z<=v;){if(b.x>=p&&b.x<=h&&b.y>=m&&b.y<=g&&b!==i&&b!==o&&$e(s,u,c,d,l,f,b.x,b.y)&&tt(b.prev,b,b.next)>=0)return!1;b=b.nextZ}return!0}function Ve(e,t){let n=e;do{let r=n.prev,i=n.next.next;!nt(r,i)&&rt(r,n,n.next,i)&&st(r,i)&&st(i,r)&&(t.push(r.i,n.i,i.i),dt(n),dt(n.next),n=e=i),n=n.next}while(n!==e);return Le(n)}function He(e,t,n,r,i,a){let o=e;do{let e=o.next.next;for(;e!==o.prev;){if(o.i!==e.i&&et(o,e)){let s=lt(o,e);o=Le(o,o.next),s=Le(s,s.next),Re(o,t,n,r,i,a,0),Re(s,t,n,r,i,a,0);return}e=e.next}o=o.next}while(o!==e)}function Ue(e,t,n,r){let i=[];for(let n=0,a=t.length;n=n.next.y&&n.next.y!==n.y){let e=n.x+(i-n.y)*(n.next.x-n.x)/(n.next.y-n.y);if(e<=r&&e>a&&(a=e,o=n.x=n.x&&n.x>=c&&r!==n.x&&Qe(io.x||n.x===o.x&&qe(o,n)))&&(o=n,u=t)}n=n.next}while(n!==s);return o}function qe(e,t){return tt(e.prev,e,t.prev)<0&&tt(t.next,e,e.next)<0}function Je(e,t,n,r){let i=e;do i.z===0&&(i.z=Xe(i.x,i.y,t,n,r)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next;while(i!==e);i.prevZ.nextZ=null,i.prevZ=null,Ye(i)}function Ye(e){let t,n=1;do{let r=e,i;e=null;let a=null;for(t=0;r;){t++;let o=r,s=0;for(let e=0;e0||c>0&&o;)s!==0&&(c===0||!o||r.z<=o.z)?(i=r,r=r.nextZ,s--):(i=o,o=o.nextZ,c--),a?a.nextZ=i:e=i,i.prevZ=a,a=i;r=o}a.nextZ=null,n*=2}while(t>1);return e}function Xe(e,t,n,r,i){return e=(e-n)*i|0,t=(t-r)*i|0,e=(e|e<<8)&16711935,e=(e|e<<4)&252645135,e=(e|e<<2)&858993459,e=(e|e<<1)&1431655765,t=(t|t<<8)&16711935,t=(t|t<<4)&252645135,t=(t|t<<2)&858993459,t=(t|t<<1)&1431655765,e|t<<1}function Ze(e){let t=e,n=e;do(t.x=(e-o)*(a-s)&&(e-o)*(r-s)>=(n-o)*(t-s)&&(n-o)*(a-s)>=(i-o)*(r-s)}function $e(e,t,n,r,i,a,o,s){return(e!==o||t!==s)&&Qe(e,t,n,r,i,a,o,s)}function et(e,t){return e.next.i!==t.i&&e.prev.i!==t.i&&!ot(e,t)&&(st(e,t)&&st(t,e)&&ct(e,t)&&(tt(e.prev,e,t.prev)||tt(e,t.prev,t))||nt(e,t)&&tt(e.prev,e,e.next)>0&&tt(t.prev,t,t.next)>0)}function tt(e,t,n){return(t.y-e.y)*(n.x-t.x)-(t.x-e.x)*(n.y-t.y)}function nt(e,t){return e.x===t.x&&e.y===t.y}function rt(e,t,n,r){let i=at(tt(e,t,n)),a=at(tt(e,t,r)),o=at(tt(n,r,e)),s=at(tt(n,r,t));return!!(i!==a&&o!==s||i===0&&it(e,n,t)||a===0&&it(e,r,t)||o===0&&it(n,e,r)||s===0&&it(n,t,r))}function it(e,t,n){return t.x<=Math.max(e.x,n.x)&&t.x>=Math.min(e.x,n.x)&&t.y<=Math.max(e.y,n.y)&&t.y>=Math.min(e.y,n.y)}function at(e){return e>0?1:e<0?-1:0}function ot(e,t){let n=e;do{if(n.i!==e.i&&n.next.i!==e.i&&n.i!==t.i&&n.next.i!==t.i&&rt(n,n.next,e,t))return!0;n=n.next}while(n!==e);return!1}function st(e,t){return tt(e.prev,e,e.next)<0?tt(e,t,e.next)>=0&&tt(e,e.prev,t)>=0:tt(e,t,e.prev)<0||tt(e,e.next,t)<0}function ct(e,t){let n=e,r=!1,i=(e.x+t.x)/2,a=(e.y+t.y)/2;do n.y>a!=n.next.y>a&&n.next.y!==n.y&&i<(n.next.x-n.x)*(a-n.y)/(n.next.y-n.y)+n.x&&(r=!r),n=n.next;while(n!==e);return r}function lt(e,t){let n=ft(e.i,e.x,e.y),r=ft(t.i,t.x,t.y),i=e.next,a=t.prev;return e.next=t,t.prev=e,n.next=i,i.prev=n,r.next=n,n.prev=r,a.next=r,r.prev=a,r}function ut(e,t,n,r){let i=ft(e,t,n);return r?(i.next=r.next,i.prev=r,r.next.prev=i,r.next=i):(i.prev=i,i.next=i),i}function dt(e){e.next.prev=e.prev,e.prev.next=e.next,e.prevZ&&(e.prevZ.nextZ=e.nextZ),e.nextZ&&(e.nextZ.prevZ=e.prevZ)}function ft(e,t,n){return{i:e,x:t,y:n,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function pt(e,t,n,r){let i=0;for(let a=t,o=n-r;a2&&e[t-1].equals(e[0])&&e.pop()}function ht(e,t){for(let n=0;n=r)){c.push(t.times[e]);for(let n=0;na.tracks[e].times[0]&&(s=a.tracks[e].times[0]);for(let e=0;e=r.times[d]){let e=d*c+s,t=e+c-s;f=r.values.slice(e,t)}else{let e=r.createInterpolant(),t=s,n=c-s;e.evaluate(a),f=e.resultBuffer.slice(t,n)}i===`quaternion`&&new gi().fromArray(f).normalize().conjugate().toArray(f);let p=o.times.length;for(let e=0;et?(e.repeat.x=1,e.repeat.y=n/t,e.offset.x=0,e.offset.y=(1-e.repeat.y)/2):(e.repeat.x=t/n,e.repeat.y=1,e.offset.x=(1-e.repeat.x)/2,e.offset.y=0),e}function Ht(e,t){let n=e.image&&e.image.width?e.image.width/e.image.height:1;return n>t?(e.repeat.x=t/n,e.repeat.y=1,e.offset.x=(1-e.repeat.x)/2,e.offset.y=0):(e.repeat.x=1,e.repeat.y=n/t,e.offset.x=0,e.offset.y=(1-e.repeat.y)/2),e}function Ut(e){return e.repeat.x=1,e.repeat.y=1,e.offset.x=0,e.offset.y=0,e}function Wt(e,t,n,r){let i=Gt(r);switch(n){case Cn:return e*t;case On:return e*t/i.components*i.byteLength;case kn:return e*t/i.components*i.byteLength;case An:return e*t*2/i.components*i.byteLength;case jn:return e*t*2/i.components*i.byteLength;case wn:return e*t*3/i.components*i.byteLength;case Tn:return e*t*4/i.components*i.byteLength;case Nn:return e*t*4/i.components*i.byteLength;case Pn:case Fn:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case In:case Ln:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case zn:case Vn:return Math.max(e,16)*Math.max(t,8)/4;case Rn:case Bn:return Math.max(e,8)*Math.max(t,8)/2;case Hn:case Un:case Gn:case Kn:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case Wn:case qn:case Jn:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case Yn:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case Xn:return Math.floor((e+4)/5)*Math.floor((t+3)/4)*16;case Zn:return Math.floor((e+4)/5)*Math.floor((t+4)/5)*16;case Qn:return Math.floor((e+5)/6)*Math.floor((t+4)/5)*16;case $n:return Math.floor((e+5)/6)*Math.floor((t+5)/6)*16;case er:return Math.floor((e+7)/8)*Math.floor((t+4)/5)*16;case tr:return Math.floor((e+7)/8)*Math.floor((t+5)/6)*16;case nr:return Math.floor((e+7)/8)*Math.floor((t+7)/8)*16;case rr:return Math.floor((e+9)/10)*Math.floor((t+4)/5)*16;case ir:return Math.floor((e+9)/10)*Math.floor((t+5)/6)*16;case ar:return Math.floor((e+9)/10)*Math.floor((t+7)/8)*16;case or:return Math.floor((e+9)/10)*Math.floor((t+9)/10)*16;case sr:return Math.floor((e+11)/12)*Math.floor((t+9)/10)*16;case cr:return Math.floor((e+11)/12)*Math.floor((t+11)/12)*16;case lr:case ur:case dr:return Math.ceil(e/4)*Math.ceil(t/4)*16;case fr:case pr:return Math.ceil(e/4)*Math.ceil(t/4)*8;case mr:case hr:return Math.ceil(e/4)*Math.ceil(t/4)*16}throw Error(`Unable to determine texture byte length for ${n} format.`)}function Gt(e){switch(e){case un:case dn:return{byteLength:1,components:1};case pn:case fn:case _n:return{byteLength:2,components:1};case vn:case yn:return{byteLength:2,components:4};case hn:case mn:case gn:return{byteLength:4,components:1};case xn:case Sn:return{byteLength:4,components:3}}throw Error(`THREE.TextureUtils: Unknown texture type ${e}.`)}var Kt,qt,Jt,Yt,Xt,Zt,Qt,$t,en,tn,nn,rn,an,on,sn,cn,ln,un,dn,fn,pn,mn,hn,gn,_n,vn,yn,bn,xn,Sn,Cn,wn,Tn,En,Dn,On,kn,An,jn,Mn,Nn,Pn,Fn,In,Ln,Rn,zn,Bn,Vn,Hn,Un,Wn,Gn,Kn,qn,Jn,Yn,Xn,Zn,Qn,$n,er,tr,nr,rr,ir,ar,or,sr,cr,lr,ur,dr,fr,pr,mr,hr,gr,_r,vr,yr,br,xr,Sr,Cr,wr,Tr,Er,Dr,Or,kr,Ar,jr,Mr,Nr,Pr,Fr,Ir,Lr,Rr,zr,Br,Vr,Hr,Ur,Wr,Gr,Kr,qr,Jr,Yr,Xr,Zr,Qr,$r,ei,ti,ni,ri,ii,ai,oi,si,ci,li,ui,di,fi,pi,mi,hi,N,gi,P,_i,vi,yi,bi,xi,Si,Ci,wi,Ti,Ei,Di,Oi,ki,Ai,ji,Mi,Ni,Pi,Fi,Ii,Li,Ri,F,zi,Bi,Vi,Hi,Ui,Wi,Gi,Ki,qi,Ji,Yi,Xi,Zi,Qi,$i,ea,ta,na,ra,ia,aa,oa,sa,ca,la,ua,da,I,fa,pa,ma,ha,ga,L,_a,va,ya,ba,xa,Sa,Ca,wa,Ta,Ea,Da,Oa,ka,Aa,ja,Ma,Na,Pa,Fa,Ia,La,Ra,za,Ba,Va,Ha,Ua,Wa,Ga,Ka,qa,Ja,Ya,Xa,Za,Qa,$a,eo,to,no,ro,io,ao,oo,so,co,R,lo,uo,fo,po,mo,ho,go,_o,vo,yo,bo,xo,So,Co,wo,To,Eo,Do,Oo,ko,Ao,jo,Mo,No,Po,Fo,Io,Lo,Ro,zo,Bo,Vo,Ho,Uo,Wo,Go,Ko,qo,Jo,Yo,Xo,Zo,Qo,$o,es,ts,ns,rs,is,as,os,ss,cs,ls,us,ds,z,fs,ps,ms,hs,gs,_s,vs,ys,bs,xs,Ss,Cs,ws,Ts,Es,Ds,Os,ks,As,js,Ms,Ns,Ps,Fs,Is,Ls,Rs,zs,Bs,Vs,Hs,Us,Ws,Gs,Ks,qs,Js,Ys,Xs,Zs,Qs,$s,ec,tc,nc,rc,ic,ac,oc,sc,cc,lc,uc,dc,fc,pc,mc,hc,gc,_c,vc,yc,bc,xc,Sc,Cc,wc,Tc,Ec,Dc,Oc,kc,Ac,jc,Mc,Nc,Pc,Fc,Ic,Lc,Rc,zc,Bc,Vc,Hc,Uc,Wc,Gc,Kc,qc,Jc,Yc,Xc,Zc,Qc,$c,el,tl,nl,rl,il,al,ol,sl,cl,ll,ul,dl,fl,pl,ml,hl,gl,_l,vl,yl,bl,xl,Sl,Cl,wl,Tl,El,Dl,Ol,kl,Al,jl,Ml,Nl,Pl,Fl,Il,Ll,Rl,zl,Bl,Vl,Hl,Ul,Wl,Gl,Kl,ql,Jl,Yl,Xl,Zl,Ql,$l,eu,tu,nu,ru,iu,au,ou,su,cu,lu,uu,du,fu,pu,mu,hu,gu,_u,vu,yu,bu,xu,Su,Cu,wu,Tu,Eu,Du,Ou,ku,Au,ju,Mu,Nu,Pu,Fu,Iu,Lu,Ru,zu,Bu,Vu,Hu,Uu,Wu,Gu,Ku,qu,Ju,Yu,Xu,Zu,Qu,$u,ed,td,nd,rd,id,ad,od,sd,cd,ld,ud,dd,fd,pd,md,hd,gd,_d,vd,yd,bd,xd,Sd,Cd,wd,Td,Ed,Dd,Od,kd,Ad,jd,Md,Nd,Pd,Fd,Id,Ld,Rd,zd,Bd,Vd,Hd,Ud,Wd,Gd,Kd,qd,Jd,Yd,Xd,Zd,Qd,$d,ef,tf,nf,rf,af,of,sf,cf,lf,uf,df,ff,pf,mf,hf,gf,_f,vf,yf,bf,xf,Sf,Cf,wf,Tf,Ef,Df,Of,kf,Af,jf,Mf,Nf,Pf,Ff,If,Lf,Rf,zf,Bf,Vf,Hf,Uf,Wf=t((()=>{Kt={LEFT:0,MIDDLE:1,RIGHT:2,ROTATE:0,DOLLY:1,PAN:2},qt={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},Jt=`attached`,Yt=`detached`,Xt=1e3,Zt=1001,Qt=1002,$t=1003,en=1004,tn=1004,nn=1005,rn=1005,an=1006,on=1007,sn=1007,cn=1008,ln=1008,un=1009,dn=1010,fn=1011,pn=1012,mn=1013,hn=1014,gn=1015,_n=1016,vn=1017,yn=1018,bn=1020,xn=35902,Sn=35899,Cn=1021,wn=1022,Tn=1023,En=1026,Dn=1027,On=1028,kn=1029,An=1030,jn=1031,Mn=1032,Nn=1033,Pn=33776,Fn=33777,In=33778,Ln=33779,Rn=35840,zn=35841,Bn=35842,Vn=35843,Hn=36196,Un=37492,Wn=37496,Gn=37488,Kn=37489,qn=37490,Jn=37491,Yn=37808,Xn=37809,Zn=37810,Qn=37811,$n=37812,er=37813,tr=37814,nr=37815,rr=37816,ir=37817,ar=37818,or=37819,sr=37820,cr=37821,lr=36492,ur=36494,dr=36495,fr=36283,pr=36284,mr=36285,hr=36286,gr=2200,_r=2201,vr=2202,yr=2300,br=2301,xr=2302,Sr=2303,Cr=2400,wr=2401,Tr=2402,Er=2500,Dr=2501,Or=3200,kr=3201,Ar=3202,jr=3203,Mr=`srgb`,Nr=`srgb-linear`,Pr=`linear`,Fr=`srgb`,Ir=7680,Lr=7681,Rr=7682,zr=7683,Br=34055,Vr=34056,Hr=5386,Ur=35044,Wr=35048,Gr=35040,Kr=35045,qr=35049,Jr=35041,Yr=35046,Xr=35050,Zr=35042,Qr=`300 es`,$r=2e3,ei=2001,ti={COMPUTE:`compute`,RENDER:`render`},ni={PERSPECTIVE:`perspective`,LINEAR:`linear`,FLAT:`flat`},ri={NORMAL:`normal`,CENTROID:`centroid`,SAMPLE:`sample`,FIRST:`first`,EITHER:`either`},ii={TEXTURE_COMPARE:`depthTextureCompare`},ai={NONE:0,SHARED:1,FULL:2},oi={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array},si={},ci=null,li={0:1,2:6,4:7,3:5,1:0,6:2,7:4,5:3},ui=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&&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;n0){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(_(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}},P=class e{static{e.prototype.isVector3=!0}constructor(e=0,t=0,n=0){this.x=e,this.y=t,this.z=n}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(`THREE.Vector3: 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(`THREE.Vector3: 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(vi.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(vi.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=_(this.x,e.x,t.x),this.y=_(this.y,e.y,t.y),this.z=_(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=_(this.x,e,t),this.y=_(this.y,e,t),this.z=_(this.z,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(_(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 _i.copy(this).projectOnVector(e),this.sub(_i)}reflect(e){return this.sub(_i.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(_(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}},_i=new P,vi=new gi,yi=class e{static{e.prototype.isMatrix3=!0}constructor(e,t,n,r,i,a,o,s,c){this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,n,r,i,a,o,s,c)}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 m(`Matrix3: .scale() is deprecated. Use .makeScale() instead.`),this.premultiply(bi.makeScale(e,t)),this}rotate(e){return m(`Matrix3: .rotate() is deprecated. Use .makeRotation() instead.`),this.premultiply(bi.makeRotation(-e)),this}translate(e,t){return m(`Matrix3: .translate() is deprecated. Use .makeTranslation() instead.`),this.premultiply(bi.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)}},bi=new yi,xi=new yi().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),Si=new yi().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715),Ci=oe(),Ti=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{wi===void 0&&(wi=o(`canvas`)),wi.width=e.width,wi.height=e.height;let t=wi.getContext(`2d`);e instanceof ImageData?t.putImageData(e,0,0):t.drawImage(e,0,0,e.width,e.height),n=wi}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=o(`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,this.normalized=!1}get width(){return this.source.getSize(Ai).x}get height(){return this.source.getSize(Ai).y}get depth(){return this.source.getSize(Ai).z}get image(){return this.source.data}set image(e){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.normalized=e.normalized,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){f(`Texture.setValues(): parameter '${t}' has value of undefined.`);continue}let r=this[t];if(r===void 0){f(`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,normalized:this.normalized,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 Xt:e.x-=Math.floor(e.x);break;case Zt:e.x=e.x<0?0:1;break;case Qt:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x-=Math.floor(e.x)}if(e.y<0||e.y>1)switch(this.wrapT){case Xt:e.y-=Math.floor(e.y);break;case Zt:e.y=e.y<0?0:1;break;case Qt:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y-=Math.floor(e.y)}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++}},ji.DEFAULT_IMAGE=null,ji.DEFAULT_MAPPING=300,ji.DEFAULT_ANISOTROPY=1,Mi=class e{static{e.prototype.isVector4=!0}constructor(e=0,t=0,n=0,r=1){this.x=e,this.y=t,this.z=n,this.w=r}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(`THREE.Vector4: 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(`THREE.Vector4: 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.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),this.pivot=e.pivot===null?null: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;t.025?(c.inputState.pinching=!1,this.dispatchEvent({type:`pinchend`,handedness:e.handedness,target:this})):!c.inputState.pinching&&o<=.015&&(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,s.eventsEnabled&&s.dispatchEvent({type:`gripUpdated`,data:e,target:this})));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(fa)))}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 I;n.matrixAutoUpdate=!1,n.visible=!1,e.joints[t.jointName]=n,e.add(n)}return e.joints[t.jointName]}},ma={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},ha={h:0,s:0,l:0},ga={h:0,s:0,l:0},L=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=Mr){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,Ci.colorSpaceToWorking(this,t),this}setRGB(e,t,n,r=Ci.workingColorSpace){return this.r=e,this.g=t,this.b=n,Ci.colorSpaceToWorking(this,r),this}setHSL(e,t,n,r=Ci.workingColorSpace){if(e=v(e,1),t=_(t,0,1),n=_(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=ue(i,r,e+1/3),this.g=ue(i,r,e),this.b=ue(i,r,e-1/3)}return Ci.colorSpaceToWorking(this,r),this}setStyle(e,t=Mr){function n(t){t!==void 0&&parseFloat(t)<1&&f(`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:f(`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);f(`Color: Invalid hex color `+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=Mr){let n=ma[e.toLowerCase()];return n===void 0?f(`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=se(e.r),this.g=se(e.g),this.b=se(e.b),this}copyLinearToSRGB(e){return this.r=ce(e.r),this.g=ce(e.g),this.b=ce(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=Mr){return Ci.workingToColorSpace(_a.copy(this),e),Math.round(_(_a.r*255,0,255))*65536+Math.round(_(_a.g*255,0,255))*256+Math.round(_(_a.b*255,0,255))}getHexString(e=Mr){return(`000000`+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=Ci.workingColorSpace){Ci.workingToColorSpace(_a.copy(this),t);let n=_a.r,r=_a.g,i=_a.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?r.multiplyScalar(1/Math.sqrt(i)):r.set(0,0,0)}static getBarycoord(e,t,n,r,i){xa.subVectors(r,t),Sa.subVectors(n,t),Ca.subVectors(e,t);let a=xa.dot(xa),o=xa.dot(Sa),s=xa.dot(Ca),c=Sa.dot(Sa),l=Sa.dot(Ca),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,wa)!==null&&wa.x>=0&&wa.y>=0&&wa.x+wa.y<=1}static getInterpolation(e,t,n,r,i,a,o,s){return this.getBarycoord(e,t,n,r,wa)===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,wa.x),s.addScaledVector(a,wa.y),s.addScaledVector(o,wa.z),s)}static getInterpolatedAttribute(e,t,n,r,i,a){return ja.setScalar(0),Ma.setScalar(0),Na.setScalar(0),ja.fromBufferAttribute(e,t),Ma.fromBufferAttribute(e,n),Na.fromBufferAttribute(e,r),a.setScalar(0),a.addScaledVector(ja,i.x),a.addScaledVector(Ma,i.y),a.addScaledVector(Na,i.z),a}static isFrontFacing(e,t,n,r){return xa.subVectors(n,t),Sa.subVectors(e,t),xa.cross(Sa).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 xa.subVectors(this.c,this.b),Sa.subVectors(this.a,this.b),xa.cross(Sa).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;Ta.subVectors(r,n),Ea.subVectors(i,n),Oa.subVectors(e,n);let s=Ta.dot(Oa),c=Ea.dot(Oa);if(s<=0&&c<=0)return t.copy(n);ka.subVectors(e,r);let l=Ta.dot(ka),u=Ea.dot(ka);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(Ta,a);Aa.subVectors(e,i);let f=Ta.dot(Aa),p=Ea.dot(Aa);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(Ea,o);let h=l*p-f*u;if(h<=0&&u-l>=0&&f-p>=0)return Da.subVectors(i,r),o=(u-l)/(u-l+(f-p)),t.copy(r).addScaledVector(Da,o);let g=1/(h+m+d);return a=m*g,o=d*g,t.copy(n).addScaledVector(Ta,a).addScaledVector(Ea,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}},Fa=class{constructor(e=new P(1/0,1/0,1/0),t=new P(-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,La),La.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(Ga),Ka.subVectors(this.max,Ga),za.subVectors(e.a,Ga),Ba.subVectors(e.b,Ga),Va.subVectors(e.c,Ga),Ha.subVectors(Ba,za),Ua.subVectors(Va,Ba),Wa.subVectors(za,Va);let t=[0,-Ha.z,Ha.y,0,-Ua.z,Ua.y,0,-Wa.z,Wa.y,Ha.z,0,-Ha.x,Ua.z,0,-Ua.x,Wa.z,0,-Wa.x,-Ha.y,Ha.x,0,-Ua.y,Ua.x,0,-Wa.y,Wa.x,0];return!de(t,za,Ba,Va,Ka)||(t=[1,0,0,0,1,0,0,0,1],!de(t,za,Ba,Va,Ka))?!1:(qa.crossVectors(Ha,Ua),t=[qa.x,qa.y,qa.z],de(t,za,Ba,Va,Ka))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,La).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(La).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:(Ia[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),Ia[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),Ia[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),Ia[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),Ia[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),Ia[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),Ia[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),Ia[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(Ia),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}},Ia=[new P,new P,new P,new P,new P,new P,new P,new P],La=new P,Ra=new Fa,za=new P,Ba=new P,Va=new P,Ha=new P,Ua=new P,Wa=new P,Ga=new P,Ka=new P,qa=new P,Ja=new P,Ya=fe(),Xa=class{static toHalfFloat(e){return pe(e)}static fromHalfFloat(e){return me(e)}},Za=new P,Qa=new N,$a=0,eo=class extends ui{constructor(e,t,n=!1){if(super(),Array.isArray(e))throw TypeError(`THREE.BufferAttribute: array should be a Typed Array.`);this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:$a++}),this.name=``,this.array=e,this.itemSize=t,this.count=e===void 0?0:e.length/t,this.normalized=n,this.usage=Ur,this.updateRanges=[],this.gpuType=gn,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;uo.subVectors(e,this.center);let t=uo.lengthSq();if(t>this.radius*this.radius){let e=Math.sqrt(t),n=(e-this.radius)*.5;this.center.addScaledVector(uo,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):(fo.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(uo.copy(e.center).add(fo)),this.expandByPoint(uo.copy(e.center).sub(fo))),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}},mo=0,ho=new F,go=new da,_o=new P,vo=new Fa,yo=new Fa,bo=new P,xo=class e extends ui{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:mo++}),this.uuid=g(),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={},this._transformed=!1}getIndex(){return this.index}setIndex(e){return this.index=Array.isArray(e)?new(r(e)?so:ao)(e,1):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 yi().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._transformed=!0,this}applyQuaternion(e){return ho.makeRotationFromQuaternion(e),this.applyMatrix4(ho),this}rotateX(e){return ho.makeRotationX(e),this.applyMatrix4(ho),this}rotateY(e){return ho.makeRotationY(e),this.applyMatrix4(ho),this}rotateZ(e){return ho.makeRotationZ(e),this.applyMatrix4(ho),this}translate(e,t,n){return ho.makeTranslation(e,t,n),this.applyMatrix4(ho),this}scale(e,t,n){return ho.makeScale(e,t,n),this.applyMatrix4(ho),this}lookAt(e){return go.lookAt(e),go.updateMatrix(),this.applyMatrix4(go.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(_o).negate(),this.translate(_o.x,_o.y,_o.z),this}setFromPoints(e){let t=this.getAttribute(`position`);if(t===void 0){let t=[];for(let n=0,r=e.length;nt.count&&f(`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 Fa);let e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){p(`BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.`,this),this.boundingBox.set(new P(-1/0,-1/0,-1/0),new P(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&&this._transformed!==!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;e1)?null:t.copy(e.start).addScaledVector(r,a)}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||Do.getNormalMatrix(e),r=this.coplanarPoint(To).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)}toJSON(){return{normal:this.normal.toArray(),constant:this.constant}}fromJSON(e){return this.normal.fromArray(e.normal),this.constant=e.constant,this}},ko=0,Ao=class extends ui{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:ko++}),this.uuid=g(),this.name=``,this.type=`Material`,this.blending=1,this.side=0,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=204,this.blendDst=205,this.blendEquation=100,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new L(0,0,0),this.blendAlpha=0,this.depthFunc=3,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=519,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=Ir,this.stencilZFail=Ir,this.stencilZPass=Ir,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.forceSinglePass=!1,this.allowOverride=!0,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(e){this._alphaTest>0!=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){f(`Material: parameter '${t}' has value of undefined.`);continue}let r=this[t];if(r===void 0){f(`Material: '${t}' is not a property of THREE.${this.type}.`);continue}r&&r.isColor?r.set(n):r&&r.isVector2&&n&&n.isVector2||r&&r.isEuler&&n&&n.isEuler||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,n.blending=this.blending,n.side=this.side,n.shadowSide=this.shadowSide,n.vertexColors=this.vertexColors,n.opacity=this.opacity,n.transparent=this.transparent,n.blendSrc=this.blendSrc,n.blendDst=this.blendDst,n.blendEquation=this.blendEquation,n.blendSrcAlpha=this.blendSrcAlpha,n.blendDstAlpha=this.blendDstAlpha,n.blendEquationAlpha=this.blendEquationAlpha,n.blendColor=this.blendColor.getHex(),n.blendAlpha=this.blendAlpha,n.depthFunc=this.depthFunc,n.depthTest=this.depthTest,n.depthWrite=this.depthWrite,n.colorWrite=this.colorWrite,n.clipIntersection=this.clipIntersection,n.clipShadows=this.clipShadows,n.stencilWriteMask=this.stencilWriteMask,n.stencilFunc=this.stencilFunc,n.stencilRef=this.stencilRef,n.stencilFuncMask=this.stencilFuncMask,n.stencilFail=this.stencilFail,n.stencilZFail=this.stencilZFail,n.stencilZPass=this.stencilZPass,n.stencilWrite=this.stencilWrite,n.polygonOffset=this.polygonOffset,n.polygonOffsetFactor=this.polygonOffsetFactor,n.polygonOffsetUnits=this.polygonOffsetUnits,n.dithering=this.dithering,n.alphaTest=this.alphaTest,n.alphaHash=this.alphaHash,n.alphaToCoverage=this.alphaToCoverage,n.premultipliedAlpha=this.premultipliedAlpha,n.forceSinglePass=this.forceSinglePass,n.allowOverride=this.allowOverride,n.visible=this.visible,n.toneMapped=this.toneMapped,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&&(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.retroreflectivity!==void 0&&(n.retroreflectivity=this.retroreflectivity),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&&(n.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(n.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(n.size=this.size),this.sizeAttenuation!==void 0&&(n.sizeAttenuation=this.sizeAttenuation),Array.isArray(this.clippingPlanes)&&this.clippingPlanes.length>0&&(n.clippingPlanes=this.clippingPlanes.map(e=>e.toJSON())),this.rotation!==void 0&&(n.rotation=this.rotation),this.depthPacking!==void 0&&(n.depthPacking=this.depthPacking),this.linewidth!==void 0&&(n.linewidth=this.linewidth),this.linecap!==void 0&&(n.linecap=this.linecap),this.linejoin!==void 0&&(n.linejoin=this.linejoin),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.wireframe!==void 0&&(n.wireframe=this.wireframe),this.wireframeLinewidth!==void 0&&(n.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!==void 0&&(n.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!==void 0&&(n.wireframeLinejoin=this.wireframeLinejoin),this.flatShading!==void 0&&(n.flatShading=this.flatShading),this.fog!==void 0&&(n.fog=this.fog),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}fromJSON(e,t){if(e.uuid!==void 0&&(this.uuid=e.uuid),e.name!==void 0&&(this.name=e.name),e.color!==void 0&&this.color!==void 0&&this.color.setHex(e.color),e.roughness!==void 0&&(this.roughness=e.roughness),e.metalness!==void 0&&(this.metalness=e.metalness),e.sheen!==void 0&&(this.sheen=e.sheen),e.sheenColor!==void 0&&(this.sheenColor=new L().setHex(e.sheenColor)),e.sheenRoughness!==void 0&&(this.sheenRoughness=e.sheenRoughness),e.emissive!==void 0&&this.emissive!==void 0&&this.emissive.setHex(e.emissive),e.specular!==void 0&&this.specular!==void 0&&this.specular.setHex(e.specular),e.specularIntensity!==void 0&&(this.specularIntensity=e.specularIntensity),e.specularColor!==void 0&&this.specularColor!==void 0&&this.specularColor.setHex(e.specularColor),e.shininess!==void 0&&(this.shininess=e.shininess),e.clearcoat!==void 0&&(this.clearcoat=e.clearcoat),e.clearcoatRoughness!==void 0&&(this.clearcoatRoughness=e.clearcoatRoughness),e.dispersion!==void 0&&(this.dispersion=e.dispersion),e.retroreflectivity!==void 0&&(this.retroreflectivity=e.retroreflectivity),e.iridescence!==void 0&&(this.iridescence=e.iridescence),e.iridescenceIOR!==void 0&&(this.iridescenceIOR=e.iridescenceIOR),e.iridescenceThicknessRange!==void 0&&(this.iridescenceThicknessRange=e.iridescenceThicknessRange),e.transmission!==void 0&&(this.transmission=e.transmission),e.thickness!==void 0&&(this.thickness=e.thickness),e.attenuationDistance!==void 0&&(this.attenuationDistance=e.attenuationDistance),e.attenuationColor!==void 0&&this.attenuationColor!==void 0&&this.attenuationColor.setHex(e.attenuationColor),e.anisotropy!==void 0&&(this.anisotropy=e.anisotropy),e.anisotropyRotation!==void 0&&(this.anisotropyRotation=e.anisotropyRotation),e.fog!==void 0&&(this.fog=e.fog),e.flatShading!==void 0&&(this.flatShading=e.flatShading),e.blending!==void 0&&(this.blending=e.blending),e.combine!==void 0&&(this.combine=e.combine),e.side!==void 0&&(this.side=e.side),e.shadowSide!==void 0&&(this.shadowSide=e.shadowSide),e.opacity!==void 0&&(this.opacity=e.opacity),e.transparent!==void 0&&(this.transparent=e.transparent),e.alphaTest!==void 0&&(this.alphaTest=e.alphaTest),e.alphaHash!==void 0&&(this.alphaHash=e.alphaHash),e.depthFunc!==void 0&&(this.depthFunc=e.depthFunc),e.depthTest!==void 0&&(this.depthTest=e.depthTest),e.depthWrite!==void 0&&(this.depthWrite=e.depthWrite),e.colorWrite!==void 0&&(this.colorWrite=e.colorWrite),e.clippingPlanes!==void 0&&(this.clippingPlanes=e.clippingPlanes.map(e=>new Oo().fromJSON(e))),e.clipIntersection!==void 0&&(this.clipIntersection=e.clipIntersection),e.clipShadows!==void 0&&(this.clipShadows=e.clipShadows),e.depthPacking!==void 0&&(this.depthPacking=e.depthPacking),e.blendSrc!==void 0&&(this.blendSrc=e.blendSrc),e.blendDst!==void 0&&(this.blendDst=e.blendDst),e.blendEquation!==void 0&&(this.blendEquation=e.blendEquation),e.blendSrcAlpha!==void 0&&(this.blendSrcAlpha=e.blendSrcAlpha),e.blendDstAlpha!==void 0&&(this.blendDstAlpha=e.blendDstAlpha),e.blendEquationAlpha!==void 0&&(this.blendEquationAlpha=e.blendEquationAlpha),e.blendColor!==void 0&&this.blendColor!==void 0&&this.blendColor.setHex(e.blendColor),e.blendAlpha!==void 0&&(this.blendAlpha=e.blendAlpha),e.stencilWriteMask!==void 0&&(this.stencilWriteMask=e.stencilWriteMask),e.stencilFunc!==void 0&&(this.stencilFunc=e.stencilFunc),e.stencilRef!==void 0&&(this.stencilRef=e.stencilRef),e.stencilFuncMask!==void 0&&(this.stencilFuncMask=e.stencilFuncMask),e.stencilFail!==void 0&&(this.stencilFail=e.stencilFail),e.stencilZFail!==void 0&&(this.stencilZFail=e.stencilZFail),e.stencilZPass!==void 0&&(this.stencilZPass=e.stencilZPass),e.stencilWrite!==void 0&&(this.stencilWrite=e.stencilWrite),e.wireframe!==void 0&&(this.wireframe=e.wireframe),e.wireframeLinewidth!==void 0&&(this.wireframeLinewidth=e.wireframeLinewidth),e.wireframeLinecap!==void 0&&(this.wireframeLinecap=e.wireframeLinecap),e.wireframeLinejoin!==void 0&&(this.wireframeLinejoin=e.wireframeLinejoin),e.rotation!==void 0&&(this.rotation=e.rotation),e.linewidth!==void 0&&(this.linewidth=e.linewidth),e.linecap!==void 0&&(this.linecap=e.linecap),e.linejoin!==void 0&&(this.linejoin=e.linejoin),e.dashSize!==void 0&&(this.dashSize=e.dashSize),e.gapSize!==void 0&&(this.gapSize=e.gapSize),e.scale!==void 0&&(this.scale=e.scale),e.polygonOffset!==void 0&&(this.polygonOffset=e.polygonOffset),e.polygonOffsetFactor!==void 0&&(this.polygonOffsetFactor=e.polygonOffsetFactor),e.polygonOffsetUnits!==void 0&&(this.polygonOffsetUnits=e.polygonOffsetUnits),e.dithering!==void 0&&(this.dithering=e.dithering),e.alphaToCoverage!==void 0&&(this.alphaToCoverage=e.alphaToCoverage),e.premultipliedAlpha!==void 0&&(this.premultipliedAlpha=e.premultipliedAlpha),e.forceSinglePass!==void 0&&(this.forceSinglePass=e.forceSinglePass),e.allowOverride!==void 0&&(this.allowOverride=e.allowOverride),e.visible!==void 0&&(this.visible=e.visible),e.toneMapped!==void 0&&(this.toneMapped=e.toneMapped),e.userData!==void 0&&(this.userData=e.userData),e.vertexColors!==void 0&&(this.vertexColors=typeof e.vertexColors==`number`?e.vertexColors>0:e.vertexColors),e.size!==void 0&&(this.size=e.size),e.sizeAttenuation!==void 0&&(this.sizeAttenuation=e.sizeAttenuation),e.map!==void 0&&(this.map=t[e.map]||null),e.matcap!==void 0&&(this.matcap=t[e.matcap]||null),e.alphaMap!==void 0&&(this.alphaMap=t[e.alphaMap]||null),e.bumpMap!==void 0&&(this.bumpMap=t[e.bumpMap]||null),e.bumpScale!==void 0&&(this.bumpScale=e.bumpScale),e.normalMap!==void 0&&(this.normalMap=t[e.normalMap]||null),e.normalMapType!==void 0&&(this.normalMapType=e.normalMapType),e.normalScale!==void 0){let t=e.normalScale;Array.isArray(t)===!1&&(t=[t,t]),this.normalScale=new N().fromArray(t)}return e.displacementMap!==void 0&&(this.displacementMap=t[e.displacementMap]||null),e.displacementScale!==void 0&&(this.displacementScale=e.displacementScale),e.displacementBias!==void 0&&(this.displacementBias=e.displacementBias),e.roughnessMap!==void 0&&(this.roughnessMap=t[e.roughnessMap]||null),e.metalnessMap!==void 0&&(this.metalnessMap=t[e.metalnessMap]||null),e.emissiveMap!==void 0&&(this.emissiveMap=t[e.emissiveMap]||null),e.emissiveIntensity!==void 0&&(this.emissiveIntensity=e.emissiveIntensity),e.specularMap!==void 0&&(this.specularMap=t[e.specularMap]||null),e.specularIntensityMap!==void 0&&(this.specularIntensityMap=t[e.specularIntensityMap]||null),e.specularColorMap!==void 0&&(this.specularColorMap=t[e.specularColorMap]||null),e.envMap!==void 0&&(this.envMap=t[e.envMap]||null),e.envMapRotation!==void 0&&this.envMapRotation.fromArray(e.envMapRotation),e.envMapIntensity!==void 0&&(this.envMapIntensity=e.envMapIntensity),e.reflectivity!==void 0&&(this.reflectivity=e.reflectivity),e.refractionRatio!==void 0&&(this.refractionRatio=e.refractionRatio),e.lightMap!==void 0&&(this.lightMap=t[e.lightMap]||null),e.lightMapIntensity!==void 0&&(this.lightMapIntensity=e.lightMapIntensity),e.aoMap!==void 0&&(this.aoMap=t[e.aoMap]||null),e.aoMapIntensity!==void 0&&(this.aoMapIntensity=e.aoMapIntensity),e.gradientMap!==void 0&&(this.gradientMap=t[e.gradientMap]||null),e.clearcoatMap!==void 0&&(this.clearcoatMap=t[e.clearcoatMap]||null),e.clearcoatRoughnessMap!==void 0&&(this.clearcoatRoughnessMap=t[e.clearcoatRoughnessMap]||null),e.clearcoatNormalMap!==void 0&&(this.clearcoatNormalMap=t[e.clearcoatNormalMap]||null),e.clearcoatNormalScale!==void 0&&(this.clearcoatNormalScale=new N().fromArray(e.clearcoatNormalScale)),e.iridescenceMap!==void 0&&(this.iridescenceMap=t[e.iridescenceMap]||null),e.iridescenceThicknessMap!==void 0&&(this.iridescenceThicknessMap=t[e.iridescenceThicknessMap]||null),e.transmissionMap!==void 0&&(this.transmissionMap=t[e.transmissionMap]||null),e.thicknessMap!==void 0&&(this.thicknessMap=t[e.thicknessMap]||null),e.anisotropyMap!==void 0&&(this.anisotropyMap=t[e.anisotropyMap]||null),e.sheenColorMap!==void 0&&(this.sheenColorMap=t[e.sheenColorMap]||null),e.sheenRoughnessMap!==void 0&&(this.sheenRoughnessMap=t[e.sheenRoughnessMap]||null),this}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++}},jo=class extends Ao{constructor(e){super(),this.isSpriteMaterial=!0,this.type=`SpriteMaterial`,this.color=new L(16777215),this.map=null,this.alphaMap=null,this.rotation=0,this.sizeAttenuation=!0,this.transparent=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.rotation=e.rotation,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}},No=new P,Po=new P,Fo=new P,Io=new N,Lo=new N,Ro=new F,zo=new P,Bo=new P,Vo=new P,Ho=new N,Uo=new N,Wo=new N,Go=class extends da{constructor(e=new jo){if(super(),this.isSprite=!0,this.type=`Sprite`,Mo===void 0){Mo=new xo;let e=new Float32Array([-.5,-.5,0,0,0,.5,-.5,0,1,0,.5,.5,0,1,1,-.5,.5,0,0,1]),t=new So(e,5);Mo.setIndex([0,1,2,0,2,3]),Mo.setAttribute(`position`,new wo(t,3,0,!1)),Mo.setAttribute(`uv`,new wo(t,2,3,!1))}this.geometry=Mo,this.material=e,this.center=new N(.5,.5),this.count=1}intersectsFrustum(e){return e.intersectsSprite(this)}raycast(e,t){e.camera===null&&p(`Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.`),Po.setFromMatrixScale(this.matrixWorld),Ro.copy(e.camera.matrixWorld),this.modelViewMatrix.multiplyMatrices(e.camera.matrixWorldInverse,this.matrixWorld),Fo.setFromMatrixPosition(this.modelViewMatrix),e.camera.isPerspectiveCamera&&this.material.sizeAttenuation===!1&&Po.multiplyScalar(-Fo.z);let n=this.material.rotation,r,i;n!==0&&(i=Math.cos(n),r=Math.sin(n));let a=this.center;he(zo.set(-.5,-.5,0),Fo,a,Po,r,i),he(Bo.set(.5,-.5,0),Fo,a,Po,r,i),he(Vo.set(.5,.5,0),Fo,a,Po,r,i),Ho.set(0,0),Uo.set(1,0),Wo.set(1,1);let o=e.ray.intersectTriangle(zo,Bo,Vo,!1,No);if(o===null&&(he(Bo.set(-.5,.5,0),Fo,a,Po,r,i),Uo.set(0,1),o=e.ray.intersectTriangle(zo,Vo,Bo,!1,No),o===null))return;let s=e.ray.origin.distanceTo(No);se.far||t.push({distance:s,point:No.clone(),uv:Pa.getInterpolation(No,zo,Bo,Vo,Ho,Uo,Wo,new N),face:null,object:this})}copy(e,t){return super.copy(e,t),e.center!==void 0&&this.center.copy(e.center),this.material=e.material,this}},Ko=new P,qo=new P,Jo=class extends da{constructor(){super(),this.isLOD=!0,this._currentLevel=0,this.type=`LOD`,Object.defineProperties(this,{levels:{enumerable:!0,value:[]}}),this.autoUpdate=!0}copy(e){super.copy(e,!1);let t=e.levels;for(let e=0,n=t.length;e0){let n,r;for(n=1,r=t.length;n0){Ko.setFromMatrixPosition(this.matrixWorld);let n=e.ray.origin.distanceTo(Ko);this.getObjectForDistance(n).raycast(e,t)}}update(e){let t=this.levels;if(t.length>1){Ko.setFromMatrixPosition(e.matrixWorld),qo.setFromMatrixPosition(this.matrixWorld);let n=Ko.distanceTo(qo)/e.zoom;t[0].object.visible=!0;let r,i;for(r=1,i=t.length;r=e)t[r-1].object.visible=!1,t[r].object.visible=!0;else break}for(this._currentLevel=r-1;r0){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(Xo).addScaledVector(Zo,d),f}intersectSphere(e,t){if(e.radius<0)return null;Yo.subVectors(e.center,this.origin);let n=Yo.dot(this.direction),r=Yo.dot(Yo)-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,Yo)!==null}intersectTriangle(e,t,n,r,i){let a=this.origin,o=this.direction,s=o.x,c=o.y,l=o.z,u=e.x-a.x,d=e.y-a.y,f=e.z-a.z,p=t.x-a.x,m=t.y-a.y,h=t.z-a.z,g=n.x-a.x,_=n.y-a.y,v=n.z-a.z,y=Math.abs(s),b=Math.abs(c),x=Math.abs(l),S,C,w,T,E,D,ee,O,k,te,A,ne;if(y>=b&&y>=x?(w=s,D=u,k=p,ne=g,s>=0?(S=c,C=l,T=d,E=f,ee=m,O=h,te=_,A=v):(S=l,C=c,T=f,E=d,ee=h,O=m,te=v,A=_)):b>=x?(w=c,D=d,k=m,ne=_,c>=0?(S=l,C=s,T=f,E=u,ee=h,O=p,te=v,A=g):(S=s,C=l,T=u,E=f,ee=p,O=h,te=g,A=v)):(w=l,D=f,k=h,ne=v,l>=0?(S=s,C=c,T=u,E=d,ee=p,O=m,te=g,A=_):(S=c,C=s,T=d,E=u,ee=m,O=p,te=_,A=g)),w===0)return null;let re=S/w,ie=C/w,ae=1/w,j=T-re*D,oe=E-ie*D,se=ee-re*k,ce=O-ie*k,le=te-re*ne,ue=A-ie*ne,de=le*ce-ue*se,fe=j*ue-oe*le,pe=se*oe-ce*j;if(r){if(de<0||fe<0||pe<0)return null}else if((de<0||fe<0||pe<0)&&(de>0||fe>0||pe>0))return null;let me=de+fe+pe;if(me===0)return null;let he=ae*(de*D+fe*k+pe*ne);return(me>0?he<0:he>0)?null:this.at(he/me,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)}},es=class extends Ao{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type=`MeshBasicMaterial`,this.color=new L(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 Ji,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}},ts=new F,ns=new $o,rs=new po,is=new P,as=new P,os=new P,ss=new P,cs=new P,ls=new P,us=new P,ds=new P,z=class extends da{constructor(e=new xo,t=new es){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))&&(ts.copy(i).invert(),ns.copy(e.ray).applyMatrix4(ts),(n.boundingBox===null||ns.intersectsBox(n.boundingBox)!==!1)&&this._computeIntersections(e,t,ns)))}_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;i0?e.max.x:e.min.x,Rs.y=r.normal.y>0?e.max.y:e.min.y,Rs.z=r.normal.z>0?e.max.z:e.min.z,r.distanceToPoint(Rs)<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)}},Bs=new F,Vs=class e{constructor(){this.coordinateSystem=$r,this._frustums=[],this._count=0}setFromArrayCamera(e){let t=e.cameras,n=this._frustums;for(let e=0;e=i.length&&i.push({start:-1,count:-1,z:-1,index:-1});let o=i[this.index];a.push(o),this.index++,o.start=e,o.count=t,o.z=n,o.index=r}reset(){this.list.length=0,this.index=0}},Us=new F,Ws=new L(1,1,1),Gs=new zs,Ks=new Vs,qs=new Fa,Js=new po,Ys=new P,Xs=new P,Zs=new P,Qs=new Hs,$s=new z,ec=[],tc=class extends z{constructor(e,t,n=t*2,r){super(new xo,r),this.isBatchedMesh=!0,this.perObjectFrustumCulled=!0,this.sortObjects=!0,this.boundingBox=null,this.boundingSphere=null,this.customSort=null,this._instanceInfo=[],this._geometryInfo=[],this._availableInstanceIds=[],this._availableGeometryIds=[],this._nextIndexStart=0,this._nextVertexStart=0,this._geometryCount=0,this._visibilityChanged=!0,this._geometryInitialized=!1,this._maxInstanceCount=e,this._maxVertexCount=t,this._maxIndexCount=n,this._multiDrawCounts=new Int32Array(e),this._multiDrawStarts=new Int32Array(e),this._multiDrawCount=0,this._multiDrawBytesPerElement=1,this._matricesTexture=null,this._indirectTexture=null,this._colorsTexture=null,this._initMatricesTexture(),this._initIndirectTexture()}get maxInstanceCount(){return this._maxInstanceCount}get instanceCount(){return this._instanceInfo.length-this._availableInstanceIds.length}get unusedVertexCount(){return this._maxVertexCount-this._nextVertexStart}get unusedIndexCount(){return this._maxIndexCount-this._nextIndexStart}_initMatricesTexture(){let e=Math.sqrt(this._maxInstanceCount*4);e=Math.ceil(e/4)*4,e=Math.max(e,4);let t=new Float32Array(e*e*4),n=new Cs(t,e,e,Tn,gn);this._matricesTexture=n}_initIndirectTexture(){let e=Math.sqrt(this._maxInstanceCount);e=Math.ceil(e);let t=new Uint32Array(e*e),n=new Cs(t,e,e,kn,hn);this._indirectTexture=n}_initColorsTexture(){let e=Math.sqrt(this._maxInstanceCount);e=Math.ceil(e);let t=new Float32Array(e*e*4).fill(1),n=new Cs(t,e,e,Tn,gn);n.colorSpace=Ci.workingColorSpace,this._colorsTexture=n}_initializeGeometry(e){let t=this.geometry,n=this._maxVertexCount,r=this._maxIndexCount;if(this._geometryInitialized===!1){for(let r in e.attributes){let{array:i,itemSize:a,normalized:o}=e.getAttribute(r),s=new i.constructor(n*a),c=new eo(s,a,o);t.setAttribute(r,c)}if(e.getIndex()!==null){let e=n>65535?new Uint32Array(r):new Uint16Array(r);t.setIndex(new eo(e,1))}this._geometryInitialized=!0}}_validateGeometry(e){let t=this.geometry;if(!!e.getIndex()!=!!t.getIndex())throw Error(`THREE.BatchedMesh: All geometries must consistently have "index".`);for(let n in t.attributes){if(!e.hasAttribute(n))throw Error(`THREE.BatchedMesh: Added geometry missing "${n}". All geometries must have consistent attributes.`);let r=e.getAttribute(n),i=t.getAttribute(n);if(r.itemSize!==i.itemSize||r.normalized!==i.normalized)throw Error(`THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.`)}}validateInstanceId(e){let t=this._instanceInfo;if(e<0||e>=t.length||t[e].active===!1)throw Error(`THREE.BatchedMesh: Invalid instanceId ${e}. Instance is either out of range or has been deleted.`)}validateGeometryId(e){let t=this._geometryInfo;if(e<0||e>=t.length||t[e].active===!1)throw Error(`THREE.BatchedMesh: Invalid geometryId ${e}. Geometry is either out of range or has been deleted.`)}setCustomSort(e){return this.customSort=e,this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new Fa);let e=this.boundingBox,t=this._instanceInfo;e.makeEmpty();for(let n=0,r=t.length;n=this.maxInstanceCount&&this._availableInstanceIds.length===0)throw Error(`THREE.BatchedMesh: Maximum item count reached.`);let t={visible:!0,active:!0,geometryIndex:e},n=null;this._availableInstanceIds.length>0?(this._availableInstanceIds.sort(ve),n=this._availableInstanceIds.shift(),this._instanceInfo[n]=t):(n=this._instanceInfo.length,this._instanceInfo.push(t));let r=this._matricesTexture;Us.identity().toArray(r.image.data,n*16),r.needsUpdate=!0;let i=this._colorsTexture;return i&&(Ws.toArray(i.image.data,n*4),i.needsUpdate=!0),this._visibilityChanged=!0,n}addGeometry(e,t=-1,n=-1){this._initializeGeometry(e),this._validateGeometry(e);let r={vertexStart:-1,vertexCount:-1,reservedVertexCount:-1,indexStart:-1,indexCount:-1,reservedIndexCount:-1,start:-1,count:-1,boundingBox:null,boundingSphere:null,active:!0},i=this._geometryInfo;r.vertexStart=this._nextVertexStart,r.reservedVertexCount=t===-1?e.getAttribute(`position`).count:t;let a=e.getIndex();if(a!==null&&(r.indexStart=this._nextIndexStart,r.reservedIndexCount=n===-1?a.count:n),r.indexStart!==-1&&r.indexStart+r.reservedIndexCount>this._maxIndexCount||r.vertexStart+r.reservedVertexCount>this._maxVertexCount)throw Error(`THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.`);let o;return this._availableGeometryIds.length>0?(this._availableGeometryIds.sort(ve),o=this._availableGeometryIds.shift(),i[o]=r):(o=this._geometryCount,this._geometryCount++,i.push(r)),this.setGeometryAt(o,e),this._nextIndexStart=r.indexStart+r.reservedIndexCount,this._nextVertexStart=r.vertexStart+r.reservedVertexCount,o}setGeometryAt(e,t){if(e>=this._geometryCount)throw Error(`THREE.BatchedMesh: Maximum geometry count reached.`);this._validateGeometry(t);let n=this.geometry,r=n.getIndex()!==null,i=n.getIndex(),a=t.getIndex(),o=this._geometryInfo[e];if(r&&a.count>o.reservedIndexCount||t.attributes.position.count>o.reservedVertexCount)throw Error(`THREE.BatchedMesh: Reserved space not large enough for provided geometry.`);let s=o.vertexStart,c=o.reservedVertexCount;o.vertexCount=t.getAttribute(`position`).count;for(let e in n.attributes){let r=t.getAttribute(e),i=n.getAttribute(e);xe(r,i,s);let a=r.itemSize;for(let e=r.count,t=c;e=t.length||t[e].active===!1)return this;let n=this._instanceInfo;for(let t=0,r=n.length;tt).sort((e,t)=>n[e].vertexStart-n[t].vertexStart),i=this.geometry;for(let a=0,o=n.length;a=this._geometryCount)return null;let n=this.geometry,r=this._geometryInfo[e];if(r.boundingBox===null){let e=new Fa,t=n.index,i=n.attributes.position;for(let n=r.start,a=r.start+r.count;n=this._geometryCount)return null;let n=this.geometry,r=this._geometryInfo[e];if(r.boundingSphere===null){let t=new po;this.getBoundingBoxAt(e,qs),qs.getCenter(t.center);let i=n.index,a=n.attributes.position,o=0;for(let e=r.start,n=r.start+r.count;ee.active);if(Math.max(...n.map(e=>e.vertexStart+e.reservedVertexCount))>e)throw Error(`THREE.BatchedMesh: Geometry vertex values are being used outside the range ${t}. Cannot shrink further.`);if(this.geometry.index&&Math.max(...n.map(e=>e.indexStart+e.reservedIndexCount))>t)throw Error(`THREE.BatchedMesh: Geometry index values are being used outside the range ${t}. Cannot shrink further.`);let r=this.geometry;r.dispose(),this._maxVertexCount=e,this._maxIndexCount=t,this._geometryInitialized&&(this._geometryInitialized=!1,this.geometry=new xo,this._initializeGeometry(r));let i=this.geometry;r.index&&Se(r.index.array,i.index.array);for(let e in r.attributes)Se(r.attributes[e].array,i.attributes[e].array)}raycast(e,t){let n=this._instanceInfo,r=this._geometryInfo,i=this.matrixWorld,a=this.geometry;$s.material=this.material,$s.geometry.index=a.index,$s.geometry.attributes=a.attributes,$s.geometry.boundingBox===null&&($s.geometry.boundingBox=new Fa),$s.geometry.boundingSphere===null&&($s.geometry.boundingSphere=new po);for(let a=0,o=n.length;a({...e,boundingBox:e.boundingBox===null?null:e.boundingBox.clone(),boundingSphere:e.boundingSphere===null?null:e.boundingSphere.clone()})),this._instanceInfo=e._instanceInfo.map(e=>({...e})),this._availableInstanceIds=e._availableInstanceIds.slice(),this._availableGeometryIds=e._availableGeometryIds.slice(),this._nextIndexStart=e._nextIndexStart,this._nextVertexStart=e._nextVertexStart,this._geometryCount=e._geometryCount,this._maxInstanceCount=e._maxInstanceCount,this._maxVertexCount=e._maxVertexCount,this._maxIndexCount=e._maxIndexCount,this._geometryInitialized=e._geometryInitialized,this._multiDrawCounts=e._multiDrawCounts.slice(),this._multiDrawStarts=e._multiDrawStarts.slice(),this._multiDrawBytesPerElement=e._multiDrawBytesPerElement,this._indirectTexture=e._indirectTexture.clone(),this._indirectTexture.image.data=this._indirectTexture.image.data.slice(),this._matricesTexture=e._matricesTexture.clone(),this._matricesTexture.image.data=this._matricesTexture.image.data.slice(),this._colorsTexture!==null&&(this._colorsTexture=e._colorsTexture.clone(),this._colorsTexture.image.data=this._colorsTexture.image.data.slice()),this}dispose(){super.dispose(),this.geometry.dispose(),this._matricesTexture.dispose(),this._matricesTexture=null,this._indirectTexture.dispose(),this._indirectTexture=null,this._colorsTexture!==null&&(this._colorsTexture.dispose(),this._colorsTexture=null)}onBeforeRender(e,t,n,r,i){if(!this._visibilityChanged&&!this.perObjectFrustumCulled&&!this.sortObjects)return;let a=r.getIndex(),o=a===null?1:a.array.BYTES_PER_ELEMENT,s=1;i.wireframe&&(s=2,o=r.attributes.position.count>65535?4:2);let c=this._instanceInfo,l=this._multiDrawStarts,u=this._multiDrawCounts,d=this._geometryInfo,f=this.perObjectFrustumCulled,p=this._indirectTexture,m=p.image.data,h=n.isArrayCamera?Ks:Gs;f&&(n.isArrayCamera?h.setFromArrayCamera(n):(Us.multiplyMatrices(n.projectionMatrix,n.matrixWorldInverse).multiply(this.matrixWorld),h.setFromProjectionMatrix(Us,n.coordinateSystem,n.reversedDepth)));let g=0;if(this.sortObjects){Us.copy(this.matrixWorld).invert(),Ys.setFromMatrixPosition(n.matrixWorld).applyMatrix4(Us),Xs.set(0,0,-1).transformDirection(n.matrixWorld).transformDirection(Us);for(let e=0,t=c.length;e0){let n=e[t[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;e0){let n=e[t[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;e=e.HAVE_CURRENT_DATA&&(this.needsUpdate=!0)}dispose(){this._requestVideoFrameCallbackId!==0&&(this.source.data.cancelVideoFrameCallback(this._requestVideoFrameCallbackId),this._requestVideoFrameCallbackId=0),super.dispose()}},Sc=class extends xc{constructor(e,t,n,r,i,a,o,s){super({},e,t,n,r,i,a,o,s),this.isVideoFrameTexture=!0}update(){}clone(){return new this.constructor().copy(this)}setFrame(e){this.image=e,this.needsUpdate=!0}},Cc=class extends ji{constructor(e,t){super({width:e,height:t}),this.isFramebufferTexture=!0,this.magFilter=$t,this.minFilter=$t,this.generateMipmaps=!1,this.needsUpdate=!0}},wc=class extends ji{constructor(e,t,n,r,i,a,o,s,c,l,u,d){super(null,a,o,s,c,l,r,i,u,d),this.isCompressedTexture=!0,this.image={width:t,height:n},this.mipmaps=e,this.flipY=!1,this.generateMipmaps=!1}},Tc=class extends wc{constructor(e,t,n,r,i,a){super(e,t,n,i,a),this.isCompressedArrayTexture=!0,this.image.depth=r,this.wrapR=Zt,this.layerUpdates=new Set}copy(e){return super.copy(e),this.wrapR=e.wrapR,this}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}},Ec=class extends wc{constructor(e,t,n){super(void 0,e[0].width,e[0].height,t,n,301),this.isCompressedCubeTexture=!0,this.isCubeTexture=!0,this.image=e}},Dc=class extends ji{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}},Oc=class extends ji{constructor(e,t,n,r,i,a,o,s,c){super(e,t,n,r,i,a,o,s,c),this.isCanvasTexture=!0,this.needsUpdate=!0}},kc=class extends ji{constructor(e,t,n,r,i,a,o,s,c){super(e,t,n,r,i,a,o,s,c),this.isHTMLTexture=!0,this.generateMipmaps=!1,this.needsUpdate=!0;let l=e?e.parentNode:null;l!==null&&`requestPaint`in l&&(l.onpaint=()=>{this.needsUpdate=!0},l.requestPaint())}dispose(){let e=this.image?this.image.parentNode:null;e!==null&&`onpaint`in e&&(e.onpaint=null),super.dispose()}},Ac=class extends ji{constructor(e,t,n=hn,r,i,a,o=$t,s=$t,c,l=En,u=1){if(l!==1026&&l!==1027)throw Error(`THREE.DepthTexture: format must be either THREE.DepthFormat or THREE.DepthStencilFormat`);super({width:e,height:t,depth:u},r,i,a,o,s,l,n,c),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new Di(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){let t=super.toJSON(e);return t.compareFunction=this.compareFunction,t}},jc=class extends Ac{constructor(e,t=hn,n=301,r,i,a=$t,o=$t,s,c=En){let l={width:e,height:e,depth:1},u=[l,l,l,l,l,l];super(e,e,t,n,r,i,a,o,s,c),this.image=u,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images(e){this.image=e}},Mc=class extends ji{constructor(e=null){super(),this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}},Nc=class e extends xo{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 R(c,3)),this.setAttribute(`normal`,new R(l,3)),this.setAttribute(`uv`,new R(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 P;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){let e=(_-1)*m;for(let t=0;t0&&v(!0),t>0&&v(!1)),this.setIndex(l),this.setAttribute(`position`,new R(u,3)),this.setAttribute(`normal`,new R(d,3)),this.setAttribute(`uv`,new R(f,2));function _(){let a=new P,_=new P,v=0,y=(t-e)/n;for(let c=0;c<=i;c++){let l=[],g=c/i,v=g*(t-e)+e;for(let e=0;e<=r;e++){let t=e/r,i=t*s+o,c=Math.sin(i),m=Math.cos(i);_.x=v*c,_.y=-g*n+h,_.z=v*m,u.push(_.x,_.y,_.z),a.set(c,y,m).normalize(),d.push(a.x,a.y,a.z),f.push(t,1-g),l.push(p++)}m.push(l)}for(let n=0;n0||r!==0)&&(l.push(a,o,c),v+=3),(t>0||r!==i-1)&&(l.push(o,s,c),v+=3)}c.addGroup(g,v,0),g+=v}function v(n){let i=p,a=new N,m=new P,_=0,v=n===!0?e:t,y=n===!0?1:-1;for(let e=1;e<=r;e++)u.push(0,h*y,0),d.push(0,y,0),f.push(.5,.5),p++;let b=p;for(let e=0;e<=r;e++){let t=e/r*s+o,n=Math.cos(t),i=Math.sin(t);m.x=v*i,m.y=h*y,m.z=v*n,u.push(m.x,m.y,m.z),d.push(0,y,0),a.x=n*.5+.5,a.y=i*.5*y+.5,f.push(a.x,a.y),p++}for(let e=0;e.9&&Math.min(t,n,r)<.1&&(t<.2&&(a[e+0]+=1),n<.2&&(a[e+2]+=1),r<.2&&(a[e+4]+=1))}}function d(e){i.push(e.x,e.y,e.z)}function f(t,n){let r=t*3;n.x=e[r+0],n.y=e[r+1],n.z=e[r+2]}function p(){let e=new P,t=new P,n=new P,r=new P,o=new N,s=new N,c=new N;for(let l=0,u=0;l0)s=r-1;else{s=r;break}if(r=s,n[r]===a)return r/(i-1);let l=n[r],u=n[r+1]-l,d=(a-l)/u;return(r+d)/(i-1)}getTangent(e,t){let n=1e-4,r=e-n,i=e+n;r<0&&(r=0),i>1&&(i=1);let a=this.getPoint(r),o=this.getPoint(i),s=t||(a.isVector2?new N:new P);return s.copy(o).sub(a).normalize(),s}getTangentAt(e,t){let n=this.getUtoTmapping(e);return this.getTangent(n,t)}computeFrenetFrames(e,t=!1){let n=new P,r=[],i=[],a=[],o=new P,s=new F;for(let t=0;t<=e;t++){let n=t/e;r[t]=this.getTangentAt(n,new P)}i[0]=new P,a[0]=new P;let c=Number.MAX_VALUE,l=Math.abs(r[0].x),u=Math.abs(r[0].y),d=Math.abs(r[0].z);l<=c&&(c=l,n.set(1,0,0)),u<=c&&(c=u,n.set(0,1,0)),d<=c&&n.set(0,0,1),o.crossVectors(r[0],n).normalize(),i[0].crossVectors(r[0],o),a[0].crossVectors(r[0],i[0]);for(let t=1;t<=e;t++){if(i[t]=i[t-1].clone(),a[t]=a[t-1].clone(),o.crossVectors(r[t-1],r[t]),o.length()>2**-52){o.normalize();let e=Math.acos(_(r[t-1].dot(r[t]),-1,1));i[t].applyMatrix4(s.makeRotationAxis(o,e))}a[t].crossVectors(r[t],i[t])}if(t===!0){let t=Math.acos(_(i[0].dot(i[e]),-1,1));t/=e,r[0].dot(o.crossVectors(i[0],i[e]))>0&&(t=-t);for(let n=1;n<=e;n++)i[n].applyMatrix4(s.makeRotationAxis(r[n],t*n)),a[n].crossVectors(r[n],i[n])}return{tangents:r,normals:i,binormals:a}}clone(){return new this.constructor().copy(this)}copy(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}toJSON(){let e={metadata:{version:4.7,type:`Curve`,generator:`Curve.toJSON`}};return e.arcLengthDivisions=this.arcLengthDivisions,e.type=this.type,e}fromJSON(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}},Kc=class extends Gc{constructor(e=0,t=0,n=1,r=1,i=0,a=Math.PI*2,o=!1,s=0){super(),this.isEllipseCurve=!0,this.type=`EllipseCurve`,this.aX=e,this.aY=t,this.xRadius=n,this.yRadius=r,this.aStartAngle=i,this.aEndAngle=a,this.aClockwise=o,this.aRotation=s}getPoint(e,t=new N){let n=t,r=Math.PI*2,i=this.aEndAngle-this.aStartAngle,a=Math.abs(i)<2**-52;for(;i<0;)i+=r;for(;i>r;)i-=r;i<2**-52&&(i=a?0:r),this.aClockwise===!0&&!a&&(i===r?i=-r:i-=r);let o=this.aStartAngle+e*i,s=this.aX+this.xRadius*Math.cos(o),c=this.aY+this.yRadius*Math.sin(o);if(this.aRotation!==0){let e=Math.cos(this.aRotation),t=Math.sin(this.aRotation),n=s-this.aX,r=c-this.aY;s=n*e-r*t+this.aX,c=n*t+r*e+this.aY}return n.set(s,c)}copy(e){return super.copy(e),this.aX=e.aX,this.aY=e.aY,this.xRadius=e.xRadius,this.yRadius=e.yRadius,this.aStartAngle=e.aStartAngle,this.aEndAngle=e.aEndAngle,this.aClockwise=e.aClockwise,this.aRotation=e.aRotation,this}toJSON(){let e=super.toJSON();return e.aX=this.aX,e.aY=this.aY,e.xRadius=this.xRadius,e.yRadius=this.yRadius,e.aStartAngle=this.aStartAngle,e.aEndAngle=this.aEndAngle,e.aClockwise=this.aClockwise,e.aRotation=this.aRotation,e}fromJSON(e){return super.fromJSON(e),this.aX=e.aX,this.aY=e.aY,this.xRadius=e.xRadius,this.yRadius=e.yRadius,this.aStartAngle=e.aStartAngle,this.aEndAngle=e.aEndAngle,this.aClockwise=e.aClockwise,this.aRotation=e.aRotation,this}},qc=class extends Kc{constructor(e,t,n,r,i,a){super(e,t,n,n,r,i,a),this.isArcCurve=!0,this.type=`ArcCurve`}},Jc=new P,Yc=new P,Xc=new Te,Zc=new Te,Qc=new Te,$c=class extends Gc{constructor(e=[],t=!1,n=`centripetal`,r=.5){super(),this.isCatmullRomCurve3=!0,this.type=`CatmullRomCurve3`,this.points=e,this.closed=t,this.curveType=n,this.tension=r}getPoint(e,t=new P){let n=t,r=this.points,i=r.length,a=(i-+!this.closed)*e,o=Math.floor(a),s=a-o;this.closed?o+=o>0?0:(Math.floor(Math.abs(o)/i)+1)*i:s===0&&o===i-1&&(o=i-2,s=1);let c,l;this.closed||o>0?c=r[(o-1)%i]:(Yc.subVectors(r[0],r[1]).add(r[0]),c=Yc);let u=r[o%i],d=r[(o+1)%i];if(this.closed||o+2r.length-2?r.length-1:a+1],u=r[a>r.length-3?r.length-1:a+2];return n.set(Ee(o,s.x,c.x,l.x,u.x),Ee(o,s.y,c.y,l.y,u.y)),n}copy(e){super.copy(e),this.points=[];for(let t=0,n=e.points.length;t=n){let e=r[i]-n,a=this.curves[i],o=a.getLength(),s=o===0?0:1-e/o;return a.getPointAt(s,t)}i++}return null}getLength(){let e=this.getCurveLengths();return e[e.length-1]}updateArcLengths(){this.needsUpdate=!0,this.cacheLengths=null,this.getCurveLengths()}getCurveLengths(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;let e=[],t=0;for(let n=0,r=this.curves.length;n1&&!t[t.length-1].equals(t[0])&&t.push(t[0]),t}copy(e){super.copy(e),this.curves=[];for(let t=0,n=e.curves.length;t0){let e=c.getPoint(0);e.equals(this.currentPoint)||this.lineTo(e.x,e.y)}this.curves.push(c);let l=c.getPoint(1);return this.currentPoint.copy(l),this}copy(e){return super.copy(e),this.currentPoint.copy(e.currentPoint),this}toJSON(){let e=super.toJSON();return e.currentPoint=this.currentPoint.toArray(),e}fromJSON(e){return super.fromJSON(e),this.currentPoint.fromArray(e.currentPoint),this}},ul=class extends ll{constructor(e){super(e),this.uuid=g(),this.type=`Shape`,this.holes=[]}getPointsHoles(e){let t=[];for(let n=0,r=this.holes.length;n2**-52){let d=Math.sqrt(u),f=Math.sqrt(c*c+l*l),p=t.x-s/d,m=t.y+o/d,h=n.x-l/f,g=n.y+c/f,_=((h-p)*l-(g-m)*c)/(o*l-s*c);r=p+o*_-e.x,i=m+s*_-e.y;let v=r*r+i*i;if(v<=2)return new N(r,i);a=Math.sqrt(v/2)}else{let e=!1;o>2**-52?c>2**-52&&(e=!0):o<-(2**-52)?c<-(2**-52)&&(e=!0):Math.sign(s)===Math.sign(l)&&(e=!0),e?(r=-s,i=o,a=Math.sqrt(u)):(r=o,i=s,a=Math.sqrt(u/2))}return new N(r/a,i/a)}let A=[];for(let e=0,t=ee.length,n=t-1,r=e+1;e=0;e--){let t=e/m,n=u*Math.cos(t*Math.PI/2),r=d*Math.sin(t*Math.PI/2)+f;for(let e=0,t=ee.length;e=0;){let r=n,i=n-1;i<0&&(i=e.length-1);for(let e=0,n=s+m*2;e0)&&f.push(t,i,c),(e!==n-1||s0&&(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}fromJSON(e,t){if(super.fromJSON(e,t),e.uniforms!==void 0)for(let n in e.uniforms){let r=e.uniforms[n];switch(this.uniforms[n]={},r.type){case`t`:this.uniforms[n].value=t[r.value]||null;break;case`c`:this.uniforms[n].value=new L().setHex(r.value);break;case`v2`:this.uniforms[n].value=new N().fromArray(r.value);break;case`v3`:this.uniforms[n].value=new P().fromArray(r.value);break;case`v4`:this.uniforms[n].value=new Mi().fromArray(r.value);break;case`m3`:this.uniforms[n].value=new yi().fromArray(r.value);break;case`m4`:this.uniforms[n].value=new F().fromArray(r.value);break;default:this.uniforms[n].value=r.value}}if(e.defines!==void 0&&(this.defines=e.defines),e.vertexShader!==void 0&&(this.vertexShader=e.vertexShader),e.fragmentShader!==void 0&&(this.fragmentShader=e.fragmentShader),e.glslVersion!==void 0&&(this.glslVersion=e.glslVersion),e.extensions!==void 0)for(let t in e.extensions)this.extensions[t]=e.extensions[t];return e.lights!==void 0&&(this.lights=e.lights),e.clipping!==void 0&&(this.clipping=e.clipping),this}},Ml=class extends jl{constructor(e){super(e),this.isRawShaderMaterial=!0,this.type=`RawShaderMaterial`}},Nl=class extends Ao{constructor(e){super(),this.isMeshStandardMaterial=!0,this.type=`MeshStandardMaterial`,this.defines={STANDARD:``},this.color=new L(16777215),this.roughness=1,this.metalness=0,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new L(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new N(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.roughnessMap=null,this.metalnessMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Ji,this.envMapIntensity=1,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap=`round`,this.wireframeLinejoin=`round`,this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={STANDARD:``},this.color.copy(e.color),this.roughness=e.roughness,this.metalness=e.metalness,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.roughnessMap=e.roughnessMap,this.metalnessMap=e.metalnessMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.envMapIntensity=e.envMapIntensity,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}},Pl=class extends Nl{constructor(e){super(),this.isMeshPhysicalMaterial=!0,this.defines={STANDARD:``,PHYSICAL:``},this.type=`MeshPhysicalMaterial`,this.anisotropyRotation=0,this.anisotropyMap=null,this.clearcoatMap=null,this.clearcoatRoughness=0,this.clearcoatRoughnessMap=null,this.clearcoatNormalScale=new N(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return _(2.5*(this.ior-1)/(this.ior+1),0,1)},set:function(e){this.ior=(1+.4*e)/(1-.4*e)}}),this.iridescenceMap=null,this.iridescenceIOR=1.3,this.iridescenceThicknessRange=[100,400],this.iridescenceThicknessMap=null,this.sheenColor=new L(0),this.sheenColorMap=null,this.sheenRoughness=1,this.sheenRoughnessMap=null,this.transmissionMap=null,this.thickness=0,this.thicknessMap=null,this.attenuationDistance=1/0,this.attenuationColor=new L(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new L(1,1,1),this.specularColorMap=null,this._anisotropy=0,this._clearcoat=0,this._dispersion=0,this._iridescence=0,this._retroreflectivity=0,this._sheen=0,this._transmission=0,this.setValues(e)}get anisotropy(){return this._anisotropy}set anisotropy(e){this._anisotropy>0!=e>0&&this.version++,this._anisotropy=e}get clearcoat(){return this._clearcoat}set clearcoat(e){this._clearcoat>0!=e>0&&this.version++,this._clearcoat=e}get iridescence(){return this._iridescence}set iridescence(e){this._iridescence>0!=e>0&&this.version++,this._iridescence=e}get dispersion(){return this._dispersion}set dispersion(e){this._dispersion>0!=e>0&&this.version++,this._dispersion=e}get retroreflectivity(){return this._retroreflectivity}set retroreflectivity(e){this._retroreflectivity>0!=e>0&&this.version++,this._retroreflectivity=e}get sheen(){return this._sheen}set sheen(e){this._sheen>0!=e>0&&this.version++,this._sheen=e}get transmission(){return this._transmission}set transmission(e){this._transmission>0!=e>0&&this.version++,this._transmission=e}copy(e){return super.copy(e),this.defines={STANDARD:``,PHYSICAL:``},this.anisotropy=e.anisotropy,this.anisotropyRotation=e.anisotropyRotation,this.anisotropyMap=e.anisotropyMap,this.clearcoat=e.clearcoat,this.clearcoatMap=e.clearcoatMap,this.clearcoatRoughness=e.clearcoatRoughness,this.clearcoatRoughnessMap=e.clearcoatRoughnessMap,this.clearcoatNormalMap=e.clearcoatNormalMap,this.clearcoatNormalScale.copy(e.clearcoatNormalScale),this.dispersion=e.dispersion,this.ior=e.ior,this.iridescence=e.iridescence,this.iridescenceMap=e.iridescenceMap,this.iridescenceIOR=e.iridescenceIOR,this.iridescenceThicknessRange=[...e.iridescenceThicknessRange],this.iridescenceThicknessMap=e.iridescenceThicknessMap,this.retroreflectivity=e.retroreflectivity,this.sheen=e.sheen,this.sheenColor.copy(e.sheenColor),this.sheenColorMap=e.sheenColorMap,this.sheenRoughness=e.sheenRoughness,this.sheenRoughnessMap=e.sheenRoughnessMap,this.transmission=e.transmission,this.transmissionMap=e.transmissionMap,this.thickness=e.thickness,this.thicknessMap=e.thicknessMap,this.attenuationDistance=e.attenuationDistance,this.attenuationColor.copy(e.attenuationColor),this.specularIntensity=e.specularIntensity,this.specularIntensityMap=e.specularIntensityMap,this.specularColor.copy(e.specularColor),this.specularColorMap=e.specularColorMap,this}},Fl=class extends Ao{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type=`MeshPhongMaterial`,this.color=new L(16777215),this.specular=new L(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new L(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new N(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Ji,this.combine=0,this.reflectivity=1,this.envMapIntensity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap=`round`,this.wireframeLinejoin=`round`,this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.specular.copy(e.specular),this.shininess=e.shininess,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,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.envMapIntensity=e.envMapIntensity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}},Il=class extends Ao{constructor(e){super(),this.isMeshToonMaterial=!0,this.defines={TOON:``},this.type=`MeshToonMaterial`,this.color=new L(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new L(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new N(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,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.gradientMap=e.gradientMap,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}},Ll=class extends Ao{constructor(e){super(),this.isMeshNormalMaterial=!0,this.type=`MeshNormalMaterial`,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new N(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.setValues(e)}copy(e){return super.copy(e),this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.flatShading=e.flatShading,this}},Rl=class extends Ao{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type=`MeshLambertMaterial`,this.color=new L(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new L(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new N(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Ji,this.combine=0,this.reflectivity=1,this.envMapIntensity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap=`round`,this.wireframeLinejoin=`round`,this.flatShading=!1,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.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,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.envMapIntensity=e.envMapIntensity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}},zl=class extends Ao{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type=`MeshDepthMaterial`,this.depthPacking=Or,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}},Bl=class extends Ao{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}},Vl=class extends Ao{constructor(e){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:``},this.type=`MeshMatcapMaterial`,this.color=new L(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new N(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={MATCAP:``},this.color.copy(e.color),this.matcap=e.matcap,this.map=e.map,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.flatShading=e.flatShading,this.fog=e.fog,this}},Hl=class extends nc{constructor(e){super(),this.isLineDashedMaterial=!0,this.type=`LineDashedMaterial`,this.scale=1,this.dashSize=3,this.gapSize=1,this.setValues(e)}copy(e){return super.copy(e),this.scale=e.scale,this.dashSize=e.dashSize,this.gapSize=e.gapSize,this}},Ul=class{static convertArray(e,t){return St(e,t)}static isTypedArray(e){return a(e)}static hasTangents(e){return Ct(e)}static getKeyframeOrder(e){return wt(e)}static sortedArray(e,t,n){return Tt(e,t,n)}static flattenJSON(e,t,n,r){Et(e,t,n,r)}static subclip(e,t,n,r,i=30){return Dt(e,t,n,r,i)}static makeClipAdditive(e,t=0,n=e,r=30){return Ot(e,t,n,r)}},Wl=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&&(p(`KeyframeTrack: Invalid value size in track.`,this),e=!1);let n=this.times,r=this.values,i=n.length;i===0&&(p(`KeyframeTrack: Track is empty.`,this),e=!1);let o=null;for(let t=0;t!==i;t++){let r=n[t];if(typeof r==`number`&&isNaN(r)){p(`KeyframeTrack: Time is not a valid number.`,this,t,r),e=!1;break}if(o!==null&&o>r){p(`KeyframeTrack: Out of order keys.`,this,t,r,o),e=!1;break}o=r}if(r!==void 0&&a(r))for(let t=0,n=r.length;t!==n;++t){let n=r[t];if(isNaN(n)){p(`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()===xr,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,Ct(this.settings)&&(r.settings={inTangents:this.settings.inTangents.slice(),outTangents:this.settings.outTangents.slice()}),r}},Yl.prototype.ValueTypeName=``,Yl.prototype.TimeBufferType=Float32Array,Yl.prototype.ValueBufferType=Float32Array,Yl.prototype.DefaultInterpolation=br,Xl=class extends Yl{constructor(e,t,n){super(e,t,n)}},Xl.prototype.ValueTypeName=`bool`,Xl.prototype.ValueBufferType=Array,Xl.prototype.DefaultInterpolation=yr,Xl.prototype.InterpolantFactoryMethodLinear=void 0,Xl.prototype.InterpolantFactoryMethodSmooth=void 0,Zl=class extends Yl{constructor(e,t,n,r){super(e,t,n,r)}},Zl.prototype.ValueTypeName=`color`,Ql=class extends Yl{constructor(e,t,n,r){super(e,t,n,r)}},Ql.prototype.ValueTypeName=`number`,$l=class extends Wl{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)gi.slerpFlat(i,0,a,c-o,a,c,s);return i}},eu=class extends Yl{constructor(e,t,n,r){super(e,t,n,r)}InterpolantFactoryMethodLinear(e){return new $l(this.times,this.values,this.getValueSize(),e)}},eu.prototype.ValueTypeName=`quaternion`,eu.prototype.InterpolantFactoryMethodSmooth=void 0,tu=class extends Yl{constructor(e,t,n){super(e,t,n)}},tu.prototype.ValueTypeName=`string`,tu.prototype.ValueBufferType=Array,tu.prototype.DefaultInterpolation=yr,tu.prototype.InterpolantFactoryMethodLinear=void 0,tu.prototype.InterpolantFactoryMethodSmooth=void 0,nu=class extends Yl{constructor(e,t,n,r){super(e,t,n,r)}},nu.prototype.ValueTypeName=`vector`,ru=class{constructor(e=``,t=-1,n=[],r=Er){this.name=e,this.tracks=n,this.duration=t,this.blendMode=r,this.uuid=g(),this.userData={},this.duration<0&&this.resetDuration()}static parse(e){let t=[],n=e.tracks,r=1/(e.fps||1);for(let e=0,i=n.length;e!==i;++e)t.push(Pt(n[e]).scale(r));let i=new this(e.name,e.duration,t,e.blendMode);return i.uuid=e.uuid,i.userData=JSON.parse(e.userData||`{}`),i}static toJSON(e){let t=[],n=e.tracks,r={name:e.name,duration:e.duration,tracks:t,uuid:e.uuid,blendMode:e.blendMode,userData:JSON.stringify(e.userData)};for(let e=0,r=n.length;e!==r;++e)t.push(Yl.toJSON(n[e]));return r}static CreateFromMorphTargetSequence(e,t,n,r){let i=t.length,a=[];for(let e=0;e1){let e=a[1],t=r[e];t||(r[e]=t=[]),t.push(n)}}let a=[];for(let e in r)a.push(this.CreateFromMorphTargetSequence(e,r[e],t,n));return a}resetDuration(){let e=this.tracks,t=0;for(let n=0,r=e.length;n!==r;++n){let e=this.tracks[n];t=Math.max(t,e.times[e.times.length-1])}return this.duration=t,this}trim(){for(let e=0;e{t&&t(i),this.manager.itemEnd(e)},0);return}if(cu[e]!==void 0){cu[e].push({onLoad:t,onProgress:n,onError:r});return}cu[e]=[],cu[e].push({onLoad:t,onProgress:n,onError:r});let a=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?`include`:`same-origin`,signal:typeof AbortSignal.any==`function`?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal}),o=this.mimeType,s=this.responseType;fetch(a).then(t=>{if(t.status===200||t.status===0){if(t.status===0&&f(`FileLoader: HTTP Status 0 received.`),typeof ReadableStream>`u`||t.body===void 0||t.body.getReader===void 0)return t;let n=cu[e],r=t.body.getReader(),i=t.headers.get(`X-File-Size`)||t.headers.get(`Content-Length`),a=i?parseInt(i):0,o=a!==0,s=0,c=new ReadableStream({start(e){t();function t(){r.read().then(({done:r,value:i})=>{if(r)e.close();else{s+=i.byteLength;let r=new ProgressEvent(`progress`,{lengthComputable:o,loaded:s,total:a});for(let e=0,t=n.length;e{e.error(t)})}}});return new Response(c)}throw new lu(`fetch for "${t.url}" responded with ${t.status}: ${t.statusText}`,t)}).then(e=>{switch(s){case`arraybuffer`:return e.arrayBuffer();case`blob`:return e.blob();case`document`:return e.text().then(e=>new DOMParser().parseFromString(e,o));case`json`:return e.json();default:if(o===``)return e.text();{let t=/charset="?([^;"\s]*)"?/i.exec(o),n=t&&t[1]?t[1].toLowerCase():void 0,r=new TextDecoder(n);return e.arrayBuffer().then(e=>r.decode(e))}}}).then(t=>{iu.add(`file:${e}`,t);let n=cu[e];delete cu[e];for(let e=0,r=n.length;e{let n=cu[e];if(n===void 0)throw this.manager.itemError(e),t;delete cu[e];for(let e=0,r=n.length;e{this.manager.itemEnd(e)}),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}},du=class extends su{constructor(e){super(e)}load(e,t,n,r){let i=this,a=new uu(this.manager);a.setPath(this.path),a.setRequestHeader(this.requestHeader),a.setWithCredentials(this.withCredentials),a.load(e,function(n){try{t(i.parse(JSON.parse(n)))}catch(t){r?r(t):p(t),i.manager.itemError(e)}},n,r)}parse(e){let t=[];for(let n=0;n0){let n=new au(t);a=new mu(n),a.setCrossOrigin(this.crossOrigin);for(let t=0,n=e.length;t0){r=new mu(this.manager),r.setCrossOrigin(this.crossOrigin);for(let t=0,r=e.length;t{let t=null,n=null;return e.boundingBox!==void 0&&(t=new Fa().fromJSON(e.boundingBox)),e.boundingSphere!==void 0&&(n=new po().fromJSON(e.boundingSphere)),{...e,boundingBox:t,boundingSphere:n}}),a._instanceInfo=e.instanceInfo,a._availableInstanceIds=e._availableInstanceIds,a._availableGeometryIds=e._availableGeometryIds,a._nextIndexStart=e.nextIndexStart,a._nextVertexStart=e.nextVertexStart,a._geometryCount=e.geometryCount,a._maxInstanceCount=e.maxInstanceCount,a._maxVertexCount=e.maxVertexCount,a._maxIndexCount=e.maxIndexCount,a._geometryInitialized=e.geometryInitialized,a._matricesTexture=c(e.matricesTexture.uuid),a._indirectTexture=c(e.indirectTexture.uuid),e.colorsTexture!==void 0&&(a._colorsTexture=c(e.colorsTexture.uuid)),e.boundingSphere!==void 0&&(a.boundingSphere=new po().fromJSON(e.boundingSphere)),e.boundingBox!==void 0&&(a.boundingBox=new Fa().fromJSON(e.boundingBox));break;case`LOD`:a=new Jo;break;case`Line`:a=new uc(o(e.geometry),s(e.material));break;case`LineLoop`:a=new mc(o(e.geometry),s(e.material));break;case`LineSegments`:a=new pc(o(e.geometry),s(e.material));break;case`PointCloud`:case`Points`:a=new bc(o(e.geometry),s(e.material));break;case`Sprite`:a=new Go(s(e.material));break;case`Group`:a=new I;break;case`Bone`:a=new Ss;break;default:a=new da}if(a.uuid=e.uuid,e.name!==void 0&&(a.name=e.name),e.matrix===void 0?(e.position!==void 0&&a.position.fromArray(e.position),e.rotation!==void 0&&a.rotation.fromArray(e.rotation),e.quaternion!==void 0&&a.quaternion.fromArray(e.quaternion),e.scale!==void 0&&a.scale.fromArray(e.scale)):(a.matrix.fromArray(e.matrix),e.matrixAutoUpdate!==void 0&&(a.matrixAutoUpdate=e.matrixAutoUpdate),a.matrixAutoUpdate&&a.matrix.decompose(a.position,a.quaternion,a.scale)),e.up!==void 0&&a.up.fromArray(e.up),e.pivot!==void 0&&(a.pivot=new P().fromArray(e.pivot)),e.morphTargetDictionary!==void 0&&(a.morphTargetDictionary=Object.assign({},e.morphTargetDictionary)),e.morphTargetInfluences!==void 0&&(a.morphTargetInfluences=e.morphTargetInfluences.slice()),e.castShadow!==void 0&&(a.castShadow=e.castShadow),e.receiveShadow!==void 0&&(a.receiveShadow=e.receiveShadow),e.shadow&&(e.shadow.intensity!==void 0&&(a.shadow.intensity=e.shadow.intensity),e.shadow.bias!==void 0&&(a.shadow.bias=e.shadow.bias),e.shadow.normalBias!==void 0&&(a.shadow.normalBias=e.shadow.normalBias),e.shadow.radius!==void 0&&(a.shadow.radius=e.shadow.radius),e.shadow.blurSamples!==void 0&&(a.shadow.blurSamples=e.shadow.blurSamples),e.shadow.focus!==void 0&&(a.shadow.focus=e.shadow.focus),e.shadow.aspect!==void 0&&(a.shadow.aspect=e.shadow.aspect),e.shadow.mapSize!==void 0&&a.shadow.mapSize.fromArray(e.shadow.mapSize),e.shadow.camera!==void 0&&(a.shadow.camera=this.parseObject(e.shadow.camera))),e.visible!==void 0&&(a.visible=e.visible),e.frustumCulled!==void 0&&(a.frustumCulled=e.frustumCulled),e.renderOrder!==void 0&&(a.renderOrder=e.renderOrder),e.static!==void 0&&(a.static=e.static),e.userData!==void 0&&(a.userData=e.userData),e.layers!==void 0&&(a.layers.mask=e.layers),e.children!==void 0){let o=e.children;for(let e=0;e`u`&&f(`ImageBitmapLoader: createImageBitmap() not supported.`),typeof fetch>`u`&&f(`ImageBitmapLoader: fetch() not supported.`),this.options={premultiplyAlpha:`none`},this._abortController=new AbortController}setOptions(e){return this.options=e,this}load(e,t,n,r){e===void 0&&(e=``),this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);let i=this,a=iu.get(`image-bitmap:${e}`);if(a!==void 0){if(i.manager.itemStart(e),a.then){a.then(n=>{$u.has(a)===!0?(r&&r($u.get(a)),i.manager.itemError(e),i.manager.itemEnd(e)):(t&&t(n),i.manager.itemEnd(e))});return}setTimeout(function(){t&&t(a),i.manager.itemEnd(e)},0);return}let o={};o.credentials=this.crossOrigin===`anonymous`?`same-origin`:`include`,o.headers=this.requestHeader,o.signal=typeof AbortSignal.any==`function`?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal;let s=fetch(e,o).then(function(e){return e.blob()}).then(function(e){return createImageBitmap(e,Object.assign({},i.options,{colorSpaceConversion:`none`}))}).then(function(n){return iu.add(`image-bitmap:${e}`,n),t&&t(n),i.manager.itemEnd(e),n}).catch(function(t){r&&r(t),$u.set(s,t),iu.remove(`image-bitmap:${e}`),i.manager.itemError(e),i.manager.itemEnd(e)});iu.add(`image-bitmap:${e}`,s),i.manager.itemStart(e)}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}},nd=class{static getContext(){return td===void 0&&(td=new(window.AudioContext||window.webkitAudioContext)),td}static setContext(e){td=e}},rd=class extends su{constructor(e){super(e)}load(e,t,n,r){let i=this,a=new uu(this.manager);a.setResponseType(`arraybuffer`),a.setPath(this.path),a.setRequestHeader(this.requestHeader),a.setWithCredentials(this.withCredentials),a.load(e,function(n){try{let r=n.slice(0),a=nd.getContext(),s=e+`#decode`;i.manager.itemStart(s),a.decodeAudioData(r,function(e){t(e),i.manager.itemEnd(s)}).catch(function(e){o(e),i.manager.itemEnd(s)})}catch(e){o(e)}},n,r);function o(t){r?r(t):p(t),i.manager.itemError(e)}}},id=new F,ad=new F,od=new F,sd=class{constructor(){this.type=`StereoCamera`,this.aspect=1,this.eyeSep=.064,this.cameraL=new ju,this.cameraL.layers.enable(1),this.cameraL.matrixAutoUpdate=!1,this.cameraR=new ju,this.cameraR.layers.enable(2),this.cameraR.matrixAutoUpdate=!1,this._cache={focus:null,fov:null,aspect:null,near:null,far:null,zoom:null,eyeSep:null}}update(e){let t=this._cache;if(t.focus!==e.focus||t.fov!==e.fov||t.aspect!==e.aspect*this.aspect||t.near!==e.near||t.far!==e.far||t.zoom!==e.zoom||t.eyeSep!==this.eyeSep){t.focus=e.focus,t.fov=e.fov,t.aspect=e.aspect*this.aspect,t.near=e.near,t.far=e.far,t.zoom=e.zoom,t.eyeSep=this.eyeSep,od.copy(e.projectionMatrix);let n=t.eyeSep/2,r=n*t.near/t.focus,i=t.near*Math.tan(pi*t.fov*.5)/t.zoom,a,o;ad.elements[12]=-n,id.elements[12]=n,a=-i*t.aspect+r,o=i*t.aspect+r,od.elements[0]=2*t.near/(o-a),od.elements[8]=(o+a)/(o-a),this.cameraL.projectionMatrix.copy(od),a=-i*t.aspect-r,o=i*t.aspect-r,od.elements[0]=2*t.near/(o-a),od.elements[8]=(o+a)/(o-a),this.cameraR.projectionMatrix.copy(od)}this.cameraL.matrix.copy(e.matrixWorld).multiply(ad),this.cameraL.matrixWorldNeedsUpdate=!0,this.cameraR.matrix.copy(e.matrixWorld).multiply(id),this.cameraR.matrixWorldNeedsUpdate=!0}},cd=-90,ld=1,ud=class extends da{constructor(e,t,n){super(),this.type=`CubeCamera`,this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;let r=new ju(cd,ld,e,t);r.layers=this.layers,this.add(r);let i=new ju(cd,ld,e,t);i.layers=this.layers,this.add(i);let a=new ju(cd,ld,e,t);a.layers=this.layers,this.add(a);let o=new ju(cd,ld,e,t);o.layers=this.layers,this.add(o);let s=new ju(cd,ld,e,t);s.layers=this.layers,this.add(s);let c=new ju(cd,ld,e,t);c.layers=this.layers,this.add(c)}updateCoordinateSystem(){let e=this.coordinateSystem,t=this.children.concat(),[n,r,i,a,o,s]=t;for(let e of t)this.remove(e);if(e===2e3)n.up.set(0,1,0),n.lookAt(1,0,0),r.up.set(0,1,0),r.lookAt(-1,0,0),i.up.set(0,0,-1),i.lookAt(0,1,0),a.up.set(0,0,1),a.lookAt(0,-1,0),o.up.set(0,1,0),o.lookAt(0,0,1),s.up.set(0,1,0),s.lookAt(0,0,-1);else if(e===2001)n.up.set(0,-1,0),n.lookAt(-1,0,0),r.up.set(0,-1,0),r.lookAt(1,0,0),i.up.set(0,0,1),i.lookAt(0,1,0),a.up.set(0,0,-1),a.lookAt(0,-1,0),o.up.set(0,-1,0),o.lookAt(0,0,1),s.up.set(0,-1,0),s.lookAt(0,0,-1);else throw Error(`THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: `+e);for(let e of t)this.add(e),e.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();let{renderTarget:n,activeMipmapLevel:r}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());let[i,a,o,s,c,l]=this.children,u=e.getRenderTarget(),d=e.getActiveCubeFace(),f=e.getActiveMipmapLevel(),p=e.xr.enabled;e.xr.enabled=!1;let m=n.texture.generateMipmaps;n.texture.generateMipmaps=!1;let h=!1;h=e.isWebGLRenderer===!0?e.state.buffers.depth.getReversed():e.reversedDepthBuffer,e.setRenderTarget(n,0,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,i),e.setRenderTarget(n,1,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,a),e.setRenderTarget(n,2,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,o),e.setRenderTarget(n,3,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,s),e.setRenderTarget(n,4,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,c),n.texture.generateMipmaps=m,e.setRenderTarget(n,5,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,l),e.setRenderTarget(u,d,f),e.xr.enabled=p,n.texture.needsPMREMUpdate=!0}},dd=class extends ju{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}},fd=class{constructor(){this._previousTime=0,this._currentTime=0,this._startTime=performance.now(),this._delta=0,this._elapsed=0,this._timescale=1,this._document=null,this._pageVisibilityHandler=null}connect(e){this._document=e,e.hidden!==void 0&&(this._pageVisibilityHandler=It.bind(this),e.addEventListener(`visibilitychange`,this._pageVisibilityHandler,!1))}disconnect(){this._pageVisibilityHandler!==null&&(this._document.removeEventListener(`visibilitychange`,this._pageVisibilityHandler),this._pageVisibilityHandler=null),this._document=null}getDelta(){return this._delta/1e3}getElapsed(){return this._elapsed/1e3}getTimescale(){return this._timescale}setTimescale(e){return this._timescale=e,this}reset(){return this._currentTime=performance.now()-this._startTime,this}dispose(){this.disconnect()}update(e){return this._pageVisibilityHandler!==null&&this._document.hidden===!0?this._delta=0:(this._previousTime=this._currentTime,this._currentTime=(e===void 0?performance.now():e)-this._startTime,this._delta=(this._currentTime-this._previousTime)*this._timescale,this._elapsed+=this._delta),this}},pd=new P,md=new gi,hd=new P,gd=new P,_d=new P,vd=class extends da{constructor(){super(),this.type=`AudioListener`,this.context=nd.getContext(),this.gain=this.context.createGain(),this.gain.connect(this.context.destination),this.filter=null,this.timeDelta=0,this._timer=new fd}getInput(){return this.gain}removeFilter(){return this.filter!==null&&(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination),this.gain.connect(this.context.destination),this.filter=null),this}getFilter(){return this.filter}setFilter(e){return this.filter===null?this.gain.disconnect(this.context.destination):(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination)),this.filter=e,this.gain.connect(this.filter),this.filter.connect(this.context.destination),this}getMasterVolume(){return this.gain.gain.value}setMasterVolume(e){return this.gain.gain.setTargetAtTime(e,this.context.currentTime,.01),this}updateMatrixWorld(e){super.updateMatrixWorld(e),this._timer.update();let t=this.context.listener;if(this.timeDelta=this._timer.getDelta(),this.matrixWorld.decompose(pd,md,hd),gd.set(0,0,-1).applyQuaternion(md),_d.set(0,1,0).applyQuaternion(md),t.positionX){let e=this.context.currentTime+this.timeDelta;t.positionX.linearRampToValueAtTime(pd.x,e),t.positionY.linearRampToValueAtTime(pd.y,e),t.positionZ.linearRampToValueAtTime(pd.z,e),t.forwardX.linearRampToValueAtTime(gd.x,e),t.forwardY.linearRampToValueAtTime(gd.y,e),t.forwardZ.linearRampToValueAtTime(gd.z,e),t.upX.linearRampToValueAtTime(_d.x,e),t.upY.linearRampToValueAtTime(_d.y,e),t.upZ.linearRampToValueAtTime(_d.z,e)}else t.setPosition(pd.x,pd.y,pd.z),t.setOrientation(gd.x,gd.y,gd.z,_d.x,_d.y,_d.z)}},yd=class extends da{constructor(e){super(),this.type=`Audio`,this.listener=e,this.context=e.context,this.gain=this.context.createGain(),this.gain.connect(e.getInput()),this.autoplay=!1,this.buffer=null,this.detune=0,this.loop=!1,this.loopStart=0,this.loopEnd=0,this.offset=0,this.duration=void 0,this.playbackRate=1,this.isPlaying=!1,this.hasPlaybackControl=!0,this.source=null,this.sourceType=`empty`,this._startedAt=0,this._progress=0,this._connected=!1,this.filters=[]}getOutput(){return this.gain}setNodeSource(e){return this.hasPlaybackControl=!1,this.sourceType=`audioNode`,this.source=e,this.connect(),this}setMediaElementSource(e){return this.hasPlaybackControl=!1,this.sourceType=`mediaNode`,this.source=this.context.createMediaElementSource(e),this.connect(),this}setMediaStreamSource(e){return this.hasPlaybackControl=!1,this.sourceType=`mediaStreamNode`,this.source=this.context.createMediaStreamSource(e),this.connect(),this}setBuffer(e){return this.buffer=e,this.sourceType=`buffer`,this.autoplay&&this.play(),this}play(e=0){if(this.isPlaying===!0){f(`Audio: Audio is already playing.`);return}if(this.hasPlaybackControl===!1){f(`Audio: this Audio has no playback control.`);return}this._startedAt=this.context.currentTime+e;let t=this.context.createBufferSource();return t.buffer=this.buffer,t.loop=this.loop,t.loopStart=this.loopStart,t.loopEnd=this.loopEnd,t.onended=this.onEnded.bind(this),t.start(this._startedAt,this._progress+this.offset,this.duration),this.isPlaying=!0,this.source=t,this.setDetune(this.detune),this.setPlaybackRate(this.playbackRate),this.connect()}pause(){if(this.hasPlaybackControl===!1){f(`Audio: this Audio has no playback control.`);return}return this.isPlaying===!0&&(this._progress+=Math.max(this.context.currentTime-this._startedAt,0)*this.playbackRate,this.loop===!0&&(this._progress%=this.duration||this.buffer.duration),this.source.stop(),this.source.onended=null,this.isPlaying=!1),this}stop(e=0){if(this.hasPlaybackControl===!1){f(`Audio: this Audio has no playback control.`);return}return this._progress=0,this.source!==null&&(this.source.stop(this.context.currentTime+e),this.source.onended=null),this.isPlaying=!1,this}connect(){if(this.filters.length>0){this.source.connect(this.filters[0]);for(let e=1,t=this.filters.length;e0){this.source.disconnect(this.filters[0]);for(let e=1,t=this.filters.length;e0&&this._mixBufferRegionAdditive(n,r,this._addIndex*t,1,t);for(let e=t,i=t+t;e!==i;++e)if(n[e]!==n[e+t]){o.setValue(n,r);break}}saveOriginalState(){let e=this.binding,t=this.buffer,n=this.valueSize,r=n*this._origIndex;e.getValue(t,r);for(let e=n,i=r;e!==i;++e)t[e]=t[r+e%n];this._setIdentity(),this.cumulativeWeight=0,this.cumulativeWeightAdditive=0}restoreOriginalState(){let e=this.valueSize*3;this.binding.setValue(this.buffer,e)}_setAdditiveIdentityNumeric(){let e=this._addIndex*this.valueSize,t=e+this.valueSize;for(let n=e;n=.5)for(let r=0;r!==i;++r)e[t+r]=e[n+r]}_slerp(e,t,n,r){gi.slerpFlat(e,t,e,t,e,n,r)}_slerpAdditive(e,t,n,r,i){let a=this._workIndex*i;gi.multiplyQuaternionsFlat(e,a,e,t,e,n),gi.slerpFlat(e,t,e,t,e,a,r)}_lerp(e,t,n,r,i){let a=1-r;for(let o=0;o!==i;++o){let i=t+o;e[i]=e[i]*a+e[n+o]*r}}_lerpAdditive(e,t,n,r,i){for(let a=0;a!==i;++a){let i=t+a;e[i]=e[i]+e[n+a]*r}}},Dd=`\\[\\]\\.:\\/`,Od=RegExp(`[\\[\\]\\.:\\/]`,`g`),kd=`[^\\[\\]\\.:\\/]`,Ad=`[^`+Dd.replace(`\\.`,``)+`]`,jd=`((?:WC+[\\/:])*)`.replace(`WC`,kd),Md=`(WCOD+)?`.replace(`WCOD`,Ad),Nd=`(?:\\.(WC+)(?:\\[(.+)\\])?)?`.replace(`WC`,kd),Pd=`\\.(WC+)(?:\\[(.+)\\])?`.replace(`WC`,kd),Fd=RegExp(`^`+jd+Md+Nd+Pd+`$`),Id=[`material`,`materials`,`bones`,`map`],Ld=class{constructor(e,t,n){let r=n||Rd.parseTrackName(t);this._targetGroup=e,this._bindings=e.subscribe_(t,r)}getValue(e,t){this.bind();let n=this._targetGroup.nCachedObjects_,r=this._bindings[n];r!==void 0&&r.getValue(e,t)}setValue(e,t){let n=this._bindings;for(let r=this._targetGroup.nCachedObjects_,i=n.length;r!==i;++r)n[r].setValue(e,t)}bind(){let e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,n=e.length;t!==n;++t)e[t].bind()}unbind(){let e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,n=e.length;t!==n;++t)e[t].unbind()}},Rd=class e{constructor(t,n,r){this.path=n,this.parsedPath=r||e.parseTrackName(n),this.node=e.findNode(t,this.parsedPath.nodeName),this.rootNode=t,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(t,n,r){return t&&t.isAnimationObjectGroup?new e.Composite(t,n,r):new e(t,n,r)}static sanitizeNodeName(e){return e.replace(/\s/g,`_`).replace(Od,``)}static parseTrackName(e){let t=Fd.exec(e);if(t===null)throw Error(`THREE.PropertyBinding: Cannot parse trackName: `+e);let n={nodeName:t[2],objectName:t[3],objectIndex:t[4],propertyName:t[5],propertyIndex:t[6]},r=n.nodeName&&n.nodeName.lastIndexOf(`.`);if(r!==void 0&&r!==-1){let e=n.nodeName.substring(r+1);Id.indexOf(e)!==-1&&(n.nodeName=n.nodeName.substring(0,r),n.objectName=e)}if(n.propertyName===null||n.propertyName.length===0)throw Error(`THREE.PropertyBinding: can not parse propertyName from trackName: `+e);return n}static findNode(e,t){if(t===void 0||t===``||t===`.`||t===-1||t===e.name||t===e.uuid)return e;if(e.skeleton){let n=e.skeleton.getBoneByName(t);if(n!==void 0)return n}if(e.children){let n=function(e){for(let r=0;r=i){let a=i++,l=e[a];t[l.uuid]=c,e[c]=l,t[s]=a,e[a]=o;for(let e=0,t=r;e!==t;++e){let t=n[e],r=t[a],i=t[c];t[c]=r,t[a]=i}}}this.nCachedObjects_=i}uncache(){let e=this._objects,t=this._indicesByUUID,n=this._bindings,r=n.length,i=this.nCachedObjects_,a=e.length;for(let o=0,s=arguments.length;o!==s;++o){let s=arguments[o].uuid,c=t[s];if(c!==void 0){if(delete t[s],c0){let e=this._interpolants,t=this._propertyBindings;switch(this.blendMode){case Dr:for(let n=0,r=e.length;n!==r;++n)e[n].evaluate(a),t[n].accumulateAdditive(o);break;case Er:default:for(let n=0,i=e.length;n!==i;++n)e[n].evaluate(a),t[n].accumulate(r,o)}}}_updateWeight(e){let t=0;if(this.enabled){t=this.weight;let n=this._weightInterpolant;if(n!==null){let r=n.evaluate(e)[0];t*=r,e>n.parameterPositions[1]&&(this.stopFading(),r===0&&(this.enabled=!1))}}return this._effectiveWeight=t,t}_updateTimeScale(e){let t=0;if(!this.paused){t=this.timeScale;let n=this._timeScaleInterpolant;if(n!==null){let r=n.evaluate(e)[0];t*=r,e>n.parameterPositions[1]&&(t===0?this.paused=!0:(this._restoreTimeScale!==null&&(t=this._restoreTimeScale),this.timeScale=t),this.stopWarping())}}return this._effectiveTimeScale=t,t}_updateTime(e){let t=this._clip.duration,n=this.loop,r=this.time+e,i=this._loopCount,a=n===vr;if(e===0)return i===-1?r:a&&(i&1)==1?t-r:r;if(n===2200){i===-1&&(this._loopCount=0,this._setEndings(!0,!0,!1));handle_stop:{if(r>=t)r=t;else if(r<0)r=0;else{this.time=r;break handle_stop}this.clampWhenFinished?this.paused=!0:this.enabled=!1,this.time=r,this._mixer.dispatchEvent({type:`finished`,action:this,direction:e<0?-1:1})}}else{if(i===-1&&(e>=0?(i=0,this._setEndings(!0,this.repetitions===0,a)):this._setEndings(this.repetitions===0,!0,a)),r>=t||r<0){let n=Math.floor(r/t);r-=t*n,i+=Math.abs(n);let o=this.repetitions-i;if(o<=0)this.clampWhenFinished?this.paused=!0:this.enabled=!1,r=e>0?t:0,this.time=r,this._mixer.dispatchEvent({type:`finished`,action:this,direction:e>0?1:-1});else{if(o===1){let t=e<0;this._setEndings(t,!t,a)}else this._setEndings(!1,!1,a);this._loopCount=i,this.time=r,this._mixer.dispatchEvent({type:`loop`,action:this,loopDelta:n})}}else this._loopCount=i,this.time=r;if(a&&(i&1)==1)return t-r}return r}_setEndings(e,t,n){let r=this._interpolantSettings;n?(r.endingStart=wr,r.endingEnd=wr):(r.endingStart=e?this.zeroSlopeAtStart?wr:Cr:Tr,r.endingEnd=t?this.zeroSlopeAtEnd?wr:Cr:Tr)}_scheduleFading(e,t,n){let r=this._mixer,i=r.time,a=this._weightInterpolant;a===null&&(a=r._lendControlInterpolant(),this._weightInterpolant=a);let o=a.parameterPositions,s=a.sampleValues;return o[0]=i,s[0]=t,o[1]=i+e,s[1]=n,this}},Vd=new Float32Array(1),Hd=class extends ui{constructor(e){super(),this._root=e,this._initMemoryManager(),this._accuIndex=0,this.time=0,this.timeScale=1,typeof __THREE_DEVTOOLS__<`u`&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent(`observe`,{detail:this}))}_bindAction(e,t){let n=e._localRoot||this._root,r=e._clip.tracks,i=r.length,a=e._propertyBindings,o=e._interpolants,s=n.uuid,c=this._bindingsByRootAndName,l=c[s];l===void 0&&(l={},c[s]=l);for(let e=0;e!==i;++e){let i=r[e],c=i.name,u=l[c];if(u!==void 0)++u.referenceCount,a[e]=u;else{if(u=a[e],u!==void 0){u._cacheIndex===null&&(++u.referenceCount,this._addInactiveBinding(u,s,c));continue}let r=t&&t._propertyBindings[e].binding.parsedPath;u=new Ed(Rd.create(n,c,r),i.ValueTypeName,i.getValueSize()),++u.referenceCount,this._addInactiveBinding(u,s,c),a[e]=u}o[e].resultBuffer=u.buffer}}_activateAction(e){if(!this._isActiveAction(e)){if(e._cacheIndex===null){let t=(e._localRoot||this._root).uuid,n=e._clip.uuid,r=this._actionsByClip[n];this._bindAction(e,r&&r.knownActions[0]),this._addInactiveAction(e,n,t)}let t=e._propertyBindings;for(let e=0,n=t.length;e!==n;++e){let n=t[e];n.useCount++===0&&(this._lendBinding(n),n.saveOriginalState())}this._lendAction(e)}}_deactivateAction(e){if(this._isActiveAction(e)){let t=e._propertyBindings;for(let e=0,n=t.length;e!==n;++e){let n=t[e];--n.useCount===0&&(n.restoreOriginalState(),this._takeBackBinding(n))}this._takeBackAction(e)}}_initMemoryManager(){this._actions=[],this._nActiveActions=0,this._actionsByClip={},this._bindings=[],this._nActiveBindings=0,this._bindingsByRootAndName={},this._controlInterpolants=[],this._nActiveControlInterpolants=0;let e=this;this.stats={actions:{get total(){return e._actions.length},get inUse(){return e._nActiveActions}},bindings:{get total(){return e._bindings.length},get inUse(){return e._nActiveBindings}},controlInterpolants:{get total(){return e._controlInterpolants.length},get inUse(){return e._nActiveControlInterpolants}}}}_isActiveAction(e){let t=e._cacheIndex;return t!==null&&t=0;--n)e[n].stop();return this}update(e){e*=this.timeScale;let t=this._actions,n=this._nActiveActions,r=this.time+=e,i=Math.sign(e),a=this._accuIndex^=1;for(let o=0;o!==n;++o)t[o]._update(r,e,i,a);let o=this._bindings,s=this._nActiveBindings;for(let e=0;e!==s;++e)o[e].apply(a);return this}setTime(e){this.time=0;for(let e=0;e=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y}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}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))}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}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,tf).distanceTo(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}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)}},rf=new P,af=new P,of=new P,sf=new P,cf=new P,lf=new P,uf=new P,df=class{constructor(e=new P,t=new P){this.start=e,this.end=t}set(e,t){return this.start.copy(e),this.end.copy(t),this}copy(e){return this.start.copy(e.start),this.end.copy(e.end),this}getCenter(e){return e.addVectors(this.start,this.end).multiplyScalar(.5)}delta(e){return e.subVectors(this.end,this.start)}distanceSq(){return this.start.distanceToSquared(this.end)}distance(){return this.start.distanceTo(this.end)}at(e,t){return this.delta(t).multiplyScalar(e).add(this.start)}closestPointToPointParameter(e,t){rf.subVectors(e,this.start),af.subVectors(this.end,this.start);let n=af.dot(af);if(n===0)return 0;let r=af.dot(rf)/n;return t&&(r=_(r,0,1)),r}closestPointToPoint(e,t,n){let r=this.closestPointToPointParameter(e,t);return this.delta(n).multiplyScalar(r).add(this.start)}distanceSqToLine3(e,t=lf,n=uf){let r=1e-8*1e-8,i,a,o=this.start,s=e.start,c=this.end,l=e.end;of.subVectors(c,o),sf.subVectors(l,s),cf.subVectors(o,s);let u=of.dot(of),d=sf.dot(sf),f=sf.dot(cf);if(u<=r&&d<=r)return t.copy(o),n.copy(s),t.sub(n),t.dot(t);if(u<=r)i=0,a=f/d,a=_(a,0,1);else{let e=of.dot(cf);if(d<=r)a=0,i=_(-e/u,0,1);else{let t=of.dot(sf),n=u*d-t*t;i=n===0?0:_((t*f-e*d)/n,0,1),a=(t*i+f)/d,a<0?(a=0,i=_(-e/u,0,1)):a>1&&(a=1,i=_((t-e)/u,0,1))}}return t.copy(o).addScaledVector(of,i),n.copy(s).addScaledVector(sf,a),t.distanceToSquared(n)}applyMatrix4(e){return this.start.applyMatrix4(e),this.end.applyMatrix4(e),this}equals(e){return e.start.equals(this.start)&&e.end.equals(this.end)}clone(){return new this.constructor().copy(this)}},ff=new P,pf=class extends da{constructor(e,t){super(),this.light=e,this.matrixAutoUpdate=!1,this.color=t,this.type=`SpotLightHelper`;let n=new xo,r=[0,0,0,0,0,1,0,0,0,1,0,1,0,0,0,-1,0,1,0,0,0,0,1,1,0,0,0,0,-1,1];for(let e=0,t=1;e<32;e++,t++){let n=e/32*Math.PI*2,i=t/32*Math.PI*2;r.push(Math.cos(n),Math.sin(n),1,Math.cos(i),Math.sin(i),1)}n.setAttribute(`position`,new R(r,3));let i=new nc({fog:!1,toneMapped:!1});this.cone=new pc(n,i),this.add(this.cone),this.update()}dispose(){super.dispose(),this.cone.geometry.dispose(),this.cone.material.dispose()}update(){this.light.updateWorldMatrix(!0,!1),this.light.target.updateWorldMatrix(!0,!1),this.parent?(this.parent.updateWorldMatrix(!0),this.matrix.copy(this.parent.matrixWorld).invert().multiply(this.light.matrixWorld)):this.matrix.copy(this.light.matrixWorld),this.matrixWorldNeedsUpdate=!0;let e=this.light.distance?this.light.distance:1e3,t=e*Math.tan(this.light.angle);this.cone.scale.set(t,t,e),ff.setFromMatrixPosition(this.light.target.matrixWorld),this.cone.lookAt(ff),this.color===void 0?this.cone.material.color.copy(this.light.color):this.cone.material.color.set(this.color)}},mf=new P,hf=new F,gf=new F,_f=class extends pc{constructor(e){let t=zt(e),n=new xo,r=[],i=[];for(let e=0;e1)for(let n=0;n.99999)this.quaternion.set(0,0,0,1);else if(e.y<-.99999)this.quaternion.set(1,0,0,0);else{If.set(e.z,0,-e.x).normalize();let t=Math.acos(e.y);this.quaternion.setFromAxisAngle(If,t)}}setLength(e,t=e*.2,n=t*.2){this.line.scale.set(1,Math.max(1e-4,e-t),1),this.line.updateMatrix(),this.cone.scale.set(n,t,n),this.cone.position.y=e,this.cone.updateMatrix()}setColor(e){this.line.material.color.set(e),this.cone.material.color.set(e)}copy(e){return super.copy(e,!1),this.line.copy(e.line),this.cone.copy(e.cone),this}dispose(){super.dispose(),this.line.geometry.dispose(),this.line.material.dispose(),this.cone.geometry.dispose(),this.cone.material.dispose()}},Bf=class extends pc{constructor(e=1){let t=[0,0,0,e,0,0,0,0,0,0,e,0,0,0,0,0,0,e],n=[1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],r=new xo;r.setAttribute(`position`,new R(t,3)),r.setAttribute(`color`,new R(n,3));let i=new nc({vertexColors:!0,toneMapped:!1});super(r,i),this.type=`AxesHelper`}setColors(e,t,n){let r=new L,i=this.geometry.attributes.color.array;return r.set(e),r.toArray(i,0),r.toArray(i,3),r.set(t),r.toArray(i,6),r.toArray(i,9),r.set(n),r.toArray(i,12),r.toArray(i,15),this.geometry.attributes.color.needsUpdate=!0,this}dispose(){super.dispose(),this.geometry.dispose(),this.material.dispose()}},Vf=class{constructor(){this.type=`ShapePath`,this.color=new L,this.subPaths=[],this.currentPath=null,this.userData={}}moveTo(e,t){return this.currentPath=new ll,this.subPaths.push(this.currentPath),this.currentPath.moveTo(e,t),this}lineTo(e,t){return this.currentPath.lineTo(e,t),this}quadraticCurveTo(e,t,n,r){return this.currentPath.quadraticCurveTo(e,t,n,r),this}bezierCurveTo(e,t,n,r,i,a){return this.currentPath.bezierCurveTo(e,t,n,r,i,a),this}splineThru(e){return this.currentPath.splineThru(e),this}toShapes(){function e(e,t){let n=!1,r=t.length;for(let i=0,a=r-1;ie.y!=o.y>e.y&&e.x<(o.x-r.x)*(e.y-r.y)/(o.y-r.y)+r.x&&(n=!n)}return n}function t(t,n){let r=n.getCenter(new N);if(e(r,t))return r;let i=r.y,a=[],o=t.length;for(let e=0;ei!=r.y>i){let e=n.x+(i-n.y)*(r.x-n.x)/(r.y-n.y);a.push(e)}}return a.length>1&&(a.sort((e,t)=>e-t),r.x=(a[0]+a[1])/2),r}let n=this.userData.style&&this.userData.style.fillRule||`nonzero`;n!==`nonzero`&&n!==`evenodd`&&(f(`Fill-rule "`+n+`" is not supported, falling back to "nonzero".`),n=`nonzero`);let r=n===`nonzero`?(e=>e!==0):(e=>!!(e&1)),i=[];for(let e of this.subPaths){let n=e.getPoints();if(n.length<3)continue;let r=fl.area(n);if(r===0)continue;let a=new nf;for(let e=0;et.absArea-e.absArea);for(let t=0;t=0;r--){let t=i[r];if(t.boundingBox.containsBox(n.boundingBox)&&e(n.interiorPoint,t.points)){n.container=t.exclude?t.container:t,a=t.winding,n.winding+=a;break}}r(n.winding)===r(a)&&(n.exclude=!0)}for(let e of i)e.exclude||(e.role=e.container===null||e.container.role===`hole`?`outer`:`hole`);let a=[],o=new Map;for(let e of i){if(e.exclude||e.role!==`outer`)continue;let t=new ul;t.curves=e.subPath.curves,a.push(t),o.set(e,t)}for(let e of i){if(e.exclude||e.role!==`hole`)continue;let t=o.get(e.container);if(!t)continue;let n=new ll;n.curves=e.subPath.curves,t.holes.push(n)}return a}},Hf=class extends ui{constructor(e,t=null){super(),this.object=e,this.domElement=t,this.enabled=!0,this.state=-1,this.keys={},this.mouseButtons={LEFT:null,MIDDLE:null,RIGHT:null},this.touches={ONE:null,TWO:null}}connect(e){this.domElement!==null&&this.disconnect(),this.domElement=e}disconnect(){}dispose(){}update(){}},Uf=class{static contain(e,t){return Vt(e,t)}static cover(e,t){return Ht(e,t)}static fill(e){return Ut(e)}static getByteLength(e,t,n,r){return Wt(e,t,n,r)}},typeof __THREE_DEVTOOLS__<`u`&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent(`register`,{detail:{revision:`186`}})),typeof window<`u`&&(window.__THREE__?f(`WARNING: Multiple instances of Three.js being imported.`):window.__THREE__=`186`)})),Gf=n({ACESFilmicToneMapping:()=>4,AONode:()=>aT,AddEquation:()=>100,AddOperation:()=>2,AdditiveAnimationBlendMode:()=>Dr,AdditiveBlending:()=>2,AgXToneMapping:()=>6,AlphaFormat:()=>Cn,AlwaysCompare:()=>519,AlwaysDepth:()=>1,AlwaysStencilFunc:()=>519,AmbientLight:()=>zu,AmbientLightNode:()=>pL,AnalyticLightNode:()=>PP,AnimationAction:()=>Bd,AnimationClip:()=>ru,AnimationLoader:()=>du,AnimationMixer:()=>Hd,AnimationObjectGroup:()=>zd,AnimationUtils:()=>Ul,ArcCurve:()=>qc,ArrayCamera:()=>dd,ArrayElementNode:()=>fh,ArrayNode:()=>y_,ArrowHelper:()=>zf,AssignNode:()=>x_,AtomicFunctionNode:()=>cN,AttachedBindMode:()=>Jt,AttributeNode:()=>Ab,Audio:()=>yd,AudioAnalyser:()=>Td,AudioContext:()=>nd,AudioListener:()=>vd,AudioLoader:()=>rd,AxesHelper:()=>Bf,BackSide:()=>1,Backend:()=>MR,BarrierNode:()=>eN,BasicDepthPacking:()=>Or,BasicEnvironmentNode:()=>uE,BasicLightMapNode:()=>dE,BasicNodeLibrary:()=>RV,BasicShadowMap:()=>0,BatchedMesh:()=>tc,BezierInterpolant:()=>Jl,BitcastNode:()=>Nk,BitcountNode:()=>Bk,BlendMode:()=>Ok,Bone:()=>Ss,BooleanKeyframeTrack:()=>Xl,Box2:()=>nf,Box3:()=>Fa,Box3Helper:()=>Pf,BoxGeometry:()=>Nc,BoxHelper:()=>Nf,BufferAttribute:()=>eo,BufferAttributeNode:()=>Qy,BufferGeometry:()=>xo,BufferGeometryLoader:()=>qu,BufferNode:()=>qb,BuiltinNode:()=>Qb,BumpMapNode:()=>kC,BundleGroup:()=>EV,BypassNode:()=>hb,ByteType:()=>dn,Cache:()=>iu,Camera:()=>Du,CameraHelper:()=>jf,CanvasTarget:()=>ZL,CanvasTexture:()=>Oc,CapsuleGeometry:()=>Pc,CatmullRomCurve3:()=>$c,CineonToneMapping:()=>3,CircleGeometry:()=>Fc,ClampToEdgeWrapping:()=>Zt,ClippingGroup:()=>zV,ClippingNode:()=>jT,Clock:()=>Zd,CodeNode:()=>AM,Color:()=>L,ColorKeyframeTrack:()=>Zl,ColorManagement:()=>Ci,ColorSpaceNode:()=>zy,Compatibility:()=>ii,CompressedArrayTexture:()=>Tc,CompressedCubeTexture:()=>Ec,CompressedTexture:()=>wc,CompressedTextureLoader:()=>fu,ComputeBuiltinNode:()=>qM,ComputeNode:()=>ub,ConditionalNode:()=>yy,ConeGeometry:()=>Lc,ConstNode:()=>Sh,ConstantAlphaFactor:()=>213,ConstantColorFactor:()=>211,ContextNode:()=>xy,Controls:()=>Hf,ConvertNode:()=>ph,CubeCamera:()=>ud,CubeDepthTexture:()=>jc,CubeMapNode:()=>cE,CubeReflectionMapping:()=>301,CubeRefractionMapping:()=>302,CubeRenderTarget:()=>oE,CubeTexture:()=>Dc,CubeTextureLoader:()=>hu,CubeTextureNode:()=>RS,CubeUVReflectionMapping:()=>306,CubicBezierCurve:()=>el,CubicBezierCurve3:()=>tl,CubicInterpolant:()=>Gl,CullFaceBack:()=>1,CullFaceFront:()=>2,CullFaceFrontBack:()=>3,CullFaceNone:()=>0,Curve:()=>Gc,CurvePath:()=>cl,CustomBlending:()=>5,CustomToneMapping:()=>5,CylinderGeometry:()=>Ic,Cylindrical:()=>$d,Data3DTexture:()=>Li,DataArrayTexture:()=>Fi,DataTexture:()=>Cs,DataTextureLoader:()=>gu,DataUtils:()=>Xa,DebugNode:()=>Eb,DecrementStencilOp:()=>zr,DecrementWrapStencilOp:()=>Vr,DefaultLoadingManager:()=>ou,DepthFormat:()=>En,DepthStencilFormat:()=>Dn,DepthTexture:()=>Ac,DetachedBindMode:()=>Yt,DirectRenderPipeline:()=>OV,DirectionalLight:()=>Ru,DirectionalLightHelper:()=>Of,DirectionalLightNode:()=>mL,DiscreteInterpolant:()=>ql,DodecahedronGeometry:()=>zc,DoubleSide:()=>2,DstAlphaFactor:()=>206,DstColorFactor:()=>208,DynamicCopyUsage:()=>Xr,DynamicDrawUsage:()=>Wr,DynamicReadUsage:()=>qr,EdgesGeometry:()=>Wc,EllipseCurve:()=>Kc,EnvironmentNode:()=>lO,EqualCompare:()=>514,EqualDepth:()=>4,EqualStencilFunc:()=>514,EquirectangularReflectionMapping:()=>303,EquirectangularRefractionMapping:()=>304,Euler:()=>Ji,EventDispatcher:()=>ui,EventNode:()=>vw,ExpressionNode:()=>vb,ExternalTexture:()=>Mc,ExtrudeGeometry:()=>pl,FileLoader:()=>uu,FlipNode:()=>yh,Float16BufferAttribute:()=>co,Float32BufferAttribute:()=>R,FloatType:()=>gn,Fog:()=>ya,FogExp2:()=>va,FramebufferTexture:()=>Cc,FrontFacingNode:()=>dS,FrontSide:()=>0,Frustum:()=>zs,FrustumArray:()=>Vs,FunctionCallNode:()=>C_,FunctionNode:()=>FM,FunctionOverloadingNode:()=>DA,GLBufferAttribute:()=>Jd,GLSL1:()=>`100`,GLSL3:()=>Qr,GLSLNodeBuilder:()=>kR,GLSLNodeParser:()=>ML,GreaterCompare:()=>516,GreaterDepth:()=>6,GreaterEqualCompare:()=>518,GreaterEqualDepth:()=>5,GreaterEqualStencilFunc:()=>518,GreaterStencilFunc:()=>516,GridHelper:()=>Cf,Group:()=>I,HTMLTexture:()=>kc,HalfFloatType:()=>_n,HemisphereLight:()=>yu,HemisphereLightHelper:()=>Sf,HemisphereLightNode:()=>hL,IESSpotLight:()=>SV,IESSpotLightNode:()=>_L,IcosahedronGeometry:()=>hl,ImageBitmapLoader:()=>ed,ImageLoader:()=>mu,ImageUtils:()=>Ti,IncrementStencilOp:()=>Rr,IncrementWrapStencilOp:()=>Br,IndexNode:()=>rb,IndirectStorageBufferAttribute:()=>PV,InputNode:()=>bh,InspectorBase:()=>Ob,InspectorNode:()=>kb,InstancedBufferAttribute:()=>Ds,InstancedBufferGeometry:()=>Ku,InstancedInterleavedBuffer:()=>qd,InstancedMesh:()=>Fs,Int16BufferAttribute:()=>io,Int32BufferAttribute:()=>oo,Int8BufferAttribute:()=>to,IntType:()=>mn,InterleavedBuffer:()=>So,InterleavedBufferAttribute:()=>wo,Interpolant:()=>Wl,InterpolateBezier:()=>Sr,InterpolateDiscrete:()=>yr,InterpolateLinear:()=>br,InterpolateSmooth:()=>xr,InterpolationSamplingMode:()=>ri,InterpolationSamplingType:()=>ni,InvertStencilOp:()=>Hr,IrradianceNode:()=>cT,IsolateNode:()=>pb,JoinNode:()=>hh,KeepStencilOp:()=>Ir,KeyframeTrack:()=>Yl,LOD:()=>Jo,LatheGeometry:()=>gl,Layers:()=>Yi,LessCompare:()=>513,LessDepth:()=>2,LessEqualCompare:()=>515,LessEqualDepth:()=>3,LessEqualStencilFunc:()=>515,LessStencilFunc:()=>513,Light:()=>vu,LightProbe:()=>Hu,LightProbeNode:()=>vL,LightShadow:()=>Cu,Lighting:()=>GL,LightingContextNode:()=>oT,LightingModel:()=>fE,LightingNode:()=>iT,LightsNode:()=>tP,Line:()=>uc,Line2NodeMaterial:()=>tE,Line3:()=>df,LineBasicMaterial:()=>nc,LineBasicNodeMaterial:()=>UT,LineCurve:()=>nl,LineCurve3:()=>rl,LineDashedMaterial:()=>Hl,LineDashedNodeMaterial:()=>GT,LineLoop:()=>mc,LineSegments:()=>pc,LinearFilter:()=>an,LinearInterpolant:()=>Kl,LinearMipMapLinearFilter:()=>ln,LinearMipMapNearestFilter:()=>sn,LinearMipmapLinearFilter:()=>cn,LinearMipmapNearestFilter:()=>on,LinearSRGBColorSpace:()=>Nr,LinearToneMapping:()=>1,LinearTransfer:()=>Pr,Loader:()=>su,LoaderUtils:()=>Gu,LoadingManager:()=>au,LoopNode:()=>Yw,LoopOnce:()=>gr,LoopPingPong:()=>vr,LoopRepeat:()=>_r,MOUSE:()=>Kt,MRTNode:()=>jk,Material:()=>Ao,MaterialBlending:()=>6,MaterialLoader:()=>Wu,MaterialNode:()=>J,MaterialReferenceNode:()=>GS,MathNode:()=>q,MathUtils:()=>hi,Matrix2:()=>ef,Matrix3:()=>yi,Matrix4:()=>F,MaxEquation:()=>104,MaxMipLevelNode:()=>Fb,MemberNode:()=>Ch,Mesh:()=>z,MeshBasicMaterial:()=>es,MeshBasicNodeMaterial:()=>Y,MeshDepthMaterial:()=>zl,MeshDistanceMaterial:()=>Bl,MeshLambertMaterial:()=>Rl,MeshLambertNodeMaterial:()=>SE,MeshMatcapMaterial:()=>Vl,MeshMatcapNodeMaterial:()=>TO,MeshNormalMaterial:()=>Ll,MeshNormalNodeMaterial:()=>rE,MeshPhongMaterial:()=>Fl,MeshPhongNodeMaterial:()=>wE,MeshPhysicalMaterial:()=>Pl,MeshPhysicalNodeMaterial:()=>gO,MeshSSSNodeMaterial:()=>vO,MeshStandardMaterial:()=>Nl,MeshStandardNodeMaterial:()=>mO,MeshToonMaterial:()=>Il,MeshToonNodeMaterial:()=>SO,MinEquation:()=>103,MirroredRepeatWrapping:()=>Qt,MixOperation:()=>1,ModelNode:()=>Wx,MultiplyBlending:()=>4,MultiplyOperation:()=>0,NearestFilter:()=>$t,NearestMipMapLinearFilter:()=>rn,NearestMipMapNearestFilter:()=>tn,NearestMipmapLinearFilter:()=>nn,NearestMipmapNearestFilter:()=>en,NeutralToneMapping:()=>7,NeverCompare:()=>512,NeverDepth:()=>0,NeverStencilFunc:()=>512,NoBlending:()=>0,NoColorSpace:()=>``,NoNormalPacking:()=>``,NoToneMapping:()=>0,Node:()=>dh,NodeAccess:()=>ih,NodeAttribute:()=>MI,NodeBuilder:()=>uL,NodeCache:()=>RI,NodeCode:()=>II,NodeError:()=>Lb,NodeFrame:()=>dL,NodeFunctionInput:()=>fL,NodeLoader:()=>FV,NodeMaterial:()=>VT,NodeMaterialLoader:()=>IV,NodeMaterialObserver:()=>Km,NodeObjectLoader:()=>LV,NodeShaderStage:()=>th,NodeType:()=>rh,NodeUniform:()=>NI,NodeUpdateType:()=>nh,NodeUtils:()=>eh,NodeVar:()=>PI,NodeVarying:()=>FI,NormalAnimationBlendMode:()=>Er,NormalBlending:()=>1,NormalGAPacking:()=>`ga`,NormalMapNode:()=>TC,NormalRGPacking:()=>`rg`,NotEqualCompare:()=>517,NotEqualDepth:()=>7,NotEqualStencilFunc:()=>517,NumberKeyframeTrack:()=>Ql,Object3D:()=>da,Object3DNode:()=>Ix,ObjectLoader:()=>Yu,ObjectSpaceNormalMap:()=>1,OctahedronGeometry:()=>_l,OneFactor:()=>201,OneMinusConstantAlphaFactor:()=>214,OneMinusConstantColorFactor:()=>212,OneMinusDstAlphaFactor:()=>207,OneMinusDstColorFactor:()=>209,OneMinusSrcAlphaFactor:()=>205,OneMinusSrcColorFactor:()=>203,OperatorNode:()=>E_,OrthographicCamera:()=>Iu,OutputStructNode:()=>Ek,OverrideContextNode:()=>vk,PCFShadowMap:()=>1,PCFSoftShadowMap:()=>2,PMREMGenerator:()=>iO,PMREMNode:()=>oO,PackFloatNode:()=>Yk,Packed4x8IntegerNode:()=>tA,ParameterNode:()=>yk,PassNode:()=>mM,Path:()=>ll,PerspectiveCamera:()=>ju,PhongLightingModel:()=>bE,PhysicalLightingModel:()=>yD,Plane:()=>Oo,PlaneGeometry:()=>vl,PlaneHelper:()=>Ff,PointLight:()=>Fu,PointLightHelper:()=>vf,PointLightNode:()=>LP,PointShadowNode:()=>MP,PointUVNode:()=>kj,Points:()=>bc,PointsMaterial:()=>hc,PointsNodeMaterial:()=>MO,PolarGridHelper:()=>wf,PolyhedronGeometry:()=>Rc,PositionalAudio:()=>wd,PostProcessing:()=>kV,ProjectorLight:()=>CV,ProjectorLightNode:()=>bL,PropertyBinding:()=>Rd,PropertyMixer:()=>Ed,PropertyNode:()=>Ag,QuadMesh:()=>dj,QuadraticBezierCurve:()=>il,QuadraticBezierCurve3:()=>al,Quaternion:()=>gi,QuaternionKeyframeTrack:()=>eu,QuaternionLinearInterpolant:()=>$l,R11_EAC_Format:()=>Gn,RED_GREEN_RGTC2_Format:()=>mr,RED_RGTC1_Format:()=>fr,REVISION:()=>`186`,RG11_EAC_Format:()=>qn,RGBADepthPacking:()=>kr,RGBAFormat:()=>Tn,RGBAIntegerFormat:()=>Nn,RGBA_ASTC_10x10_Format:()=>or,RGBA_ASTC_10x5_Format:()=>rr,RGBA_ASTC_10x6_Format:()=>ir,RGBA_ASTC_10x8_Format:()=>ar,RGBA_ASTC_12x10_Format:()=>sr,RGBA_ASTC_12x12_Format:()=>cr,RGBA_ASTC_4x4_Format:()=>Yn,RGBA_ASTC_5x4_Format:()=>Xn,RGBA_ASTC_5x5_Format:()=>Zn,RGBA_ASTC_6x5_Format:()=>Qn,RGBA_ASTC_6x6_Format:()=>$n,RGBA_ASTC_8x5_Format:()=>er,RGBA_ASTC_8x6_Format:()=>tr,RGBA_ASTC_8x8_Format:()=>nr,RGBA_BPTC_Format:()=>lr,RGBA_ETC2_EAC_Format:()=>Wn,RGBA_PVRTC_2BPPV1_Format:()=>Vn,RGBA_PVRTC_4BPPV1_Format:()=>Bn,RGBA_S3TC_DXT1_Format:()=>Fn,RGBA_S3TC_DXT3_Format:()=>In,RGBA_S3TC_DXT5_Format:()=>Ln,RGBDepthPacking:()=>Ar,RGBFormat:()=>wn,RGBIntegerFormat:()=>Mn,RGB_BPTC_SIGNED_Format:()=>ur,RGB_BPTC_UNSIGNED_Format:()=>dr,RGB_ETC1_Format:()=>Hn,RGB_ETC2_Format:()=>Un,RGB_PVRTC_2BPPV1_Format:()=>zn,RGB_PVRTC_4BPPV1_Format:()=>Rn,RGB_S3TC_DXT1_Format:()=>Pn,RGDepthPacking:()=>jr,RGFormat:()=>An,RGIntegerFormat:()=>jn,RTTNode:()=>mj,RangeNode:()=>GM,RawShaderMaterial:()=>Ml,Ray:()=>$o,Raycaster:()=>Xd,ReadbackBuffer:()=>AV,RectAreaLight:()=>Bu,RectAreaLightNode:()=>wL,RedFormat:()=>On,RedIntegerFormat:()=>kn,ReferenceBaseNode:()=>Wy,ReferenceElementNode:()=>Uy,ReferenceNode:()=>HS,ReflectorNode:()=>ij,ReinhardToneMapping:()=>2,RenderObjectRefreshType:()=>ai,RenderOutputNode:()=>wb,RenderPipeline:()=>DV,RenderTarget:()=>Ni,RenderTarget3D:()=>Ud,Renderer:()=>oR,RendererReferenceNode:()=>Ky,RendererUtils:()=>fj,RepeatWrapping:()=>Xt,ReplaceStencilOp:()=>Lr,ReverseSubtractEquation:()=>102,RingGeometry:()=>yl,RotateNode:()=>EO,SIGNED_R11_EAC_Format:()=>Kn,SIGNED_RED_GREEN_RGTC2_Format:()=>hr,SIGNED_RED_RGTC1_Format:()=>pr,SIGNED_RG11_EAC_Format:()=>Jn,SRGBColorSpace:()=>Mr,SRGBTransfer:()=>Fr,SampleNode:()=>Cj,Scene:()=>ba,ScreenNode:()=>nx,SetNode:()=>vh,ShaderMaterial:()=>jl,ShadowBaseNode:()=>lP,ShadowMaterial:()=>Ol,ShadowNode:()=>yP,ShadowNodeMaterial:()=>IO,Shape:()=>ul,ShapeGeometry:()=>bl,ShapePath:()=>Vf,ShapeUtils:()=>fl,ShortType:()=>fn,Skeleton:()=>Es,SkeletonHelper:()=>_f,SkinnedMesh:()=>xs,Source:()=>Oi,Sphere:()=>po,SphereGeometry:()=>xl,Spherical:()=>Qd,SphericalHarmonics3:()=>Vu,SplineCurve:()=>ol,SplitNode:()=>_h,SpotLight:()=>Nu,SpotLightHelper:()=>pf,SpotLightNode:()=>gL,Sprite:()=>Go,SpriteMaterial:()=>jo,SpriteNodeMaterial:()=>kO,SrcAlphaFactor:()=>204,SrcAlphaSaturateFactor:()=>210,SrcColorFactor:()=>202,StackNode:()=>xk,StackTrace:()=>Jm,StandardNodeLibrary:()=>wV,StaticCopyUsage:()=>Yr,StaticDrawUsage:()=>Ur,StaticReadUsage:()=>Kr,StereoCamera:()=>sd,Storage3DTexture:()=>MV,StorageArrayElementNode:()=>kw,StorageArrayTexture:()=>NV,StorageBufferAttribute:()=>Ej,StorageBufferNode:()=>jw,StorageInstancedBufferAttribute:()=>Tj,StorageTexture:()=>jV,StorageTexture3DNode:()=>Rj,StorageTextureNode:()=>Fj,StreamCopyUsage:()=>Zr,StreamDrawUsage:()=>Gr,StreamReadUsage:()=>Jr,StringKeyframeTrack:()=>tu,StructNode:()=>wk,StructTypeNode:()=>Ck,SubBuildNode:()=>Ay,SubgroupFunctionNode:()=>bN,SubtractEquation:()=>101,SubtractiveBlending:()=>3,TOUCH:()=>qt,TSL:()=>X,TangentSpaceNormalMap:()=>0,TempNode:()=>mh,TetrahedronGeometry:()=>Sl,Texture:()=>ji,Texture3DNode:()=>Vj,TextureLoader:()=>_u,TextureNode:()=>zb,TextureSizeNode:()=>Nb,TextureSource:()=>Di,TextureUtils:()=>Uf,Timer:()=>fd,TimestampQuery:()=>ti,ToneMappingNode:()=>Jy,ToonOutlinePassNode:()=>vM,TorusGeometry:()=>Cl,TorusKnotGeometry:()=>wl,Triangle:()=>Pa,TriangleFanDrawMode:()=>2,TriangleStripDrawMode:()=>1,TrianglesDrawMode:()=>0,TubeGeometry:()=>Tl,UVMapping:()=>300,Uint16BufferAttribute:()=>ao,Uint32BufferAttribute:()=>so,Uint8BufferAttribute:()=>no,Uint8ClampedBufferAttribute:()=>ro,Uniform:()=>Wd,UniformArrayNode:()=>Xb,UniformGroupNode:()=>d_,UniformNode:()=>__,UniformsGroup:()=>Kd,UnpackFloatNode:()=>vA,UnsignedByteType:()=>un,UnsignedInt101111Type:()=>Sn,UnsignedInt248Type:()=>bn,UnsignedInt5999Type:()=>xn,UnsignedIntType:()=>hn,UnsignedShort4444Type:()=>vn,UnsignedShort5551Type:()=>yn,UnsignedShortType:()=>pn,UserDataNode:()=>Gj,VSMShadowMap:()=>3,VarNode:()=>Ty,VaryingNode:()=>My,Vector2:()=>N,Vector3:()=>P,Vector4:()=>Mi,VectorKeyframeTrack:()=>nu,VelocityNode:()=>Jj,VertexColorNode:()=>zT,VideoFrameTexture:()=>Sc,VideoTexture:()=>xc,ViewportDepthNode:()=>vT,ViewportDepthTextureNode:()=>gT,ViewportSharedTextureNode:()=>lM,ViewportTextureNode:()=>uT,VolumeNodeMaterial:()=>VO,WGSLNodeBuilder:()=>PB,WebGL3DRenderTarget:()=>Ri,WebGLArrayRenderTarget:()=>Ii,WebGLBackend:()=>QR,WebGLCapabilities:()=>KR,WebGLCoordinateSystem:()=>$r,WebGLRenderTarget:()=>Pi,WebGPUBackend:()=>xV,WebGPUCoordinateSystem:()=>ei,WebGPURenderer:()=>TV,WebXRController:()=>pa,WireframeGeometry:()=>El,WorkgroupInfoNode:()=>oN,WrapAroundEnding:()=>Tr,ZeroCurvatureEnding:()=>Cr,ZeroFactor:()=>200,ZeroSlopeEnding:()=>wr,ZeroStencilOp:()=>0,createCanvasElement:()=>s,defaultBuildStages:()=>oh,defaultShaderStages:()=>ah,error:()=>p,getConsoleFunction:()=>l,log:()=>u,setConsoleFunction:()=>c,shaderStages:()=>sh,vectorComponents:()=>ch,warn:()=>f,warnOnce:()=>m});function Kf(e){let t=/(?:at\s+(.+?)\s+\()?(?:(.+?)@)?([^@\s()]+):(\d+):(\d+)/;return e.split(` `).map(e=>{let n=e.match(t);if(!n)return null;let r=n[1]||n[2]||``,i=n[3].split(`?`)[0],a=parseInt(n[4],10),o=parseInt(n[5],10);return{fn:r,file:i.split(`/`).pop(),line:a,column:o}}).filter(e=>e&&!qm.some(t=>t.test(e.file)))}function qf(e,t=0){let n=3735928559^t,r=1103547991^t;if(Array.isArray(e))for(let t=0,i;t>>16,2246822507),n^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&r)+(n>>>0)}function Jf(e){return Qm.get(e)}function Yf(e){if(/[iu]?vec\d/.test(e))return e.startsWith(`ivec`)?Int32Array:e.startsWith(`uvec`)?Uint32Array:Float32Array;if(/mat\d/.test(e)||/float/.test(e))return Float32Array;if(/uint/.test(e))return Uint32Array;if(/int/.test(e))return Int32Array;throw Error(`THREE.NodeUtils: Unsupported type: ${e}`)}function Xf(e){if(/float|int|uint|bool/.test(e))return 1;if(/vec2/.test(e))return 2;if(/vec3/.test(e))return 3;if(/vec4/.test(e)||/mat2/.test(e))return 4;if(/mat3/.test(e))return 9;if(/mat4/.test(e))return 16;p(`TSL: Unsupported type: ${e}`,new Jm)}function Zf(e){if(/float|int|uint|bool/.test(e))return 1;if(/vec2/.test(e))return 2;if(/vec3/.test(e))return 3;if(/vec4/.test(e)||/mat2/.test(e))return 4;if(/mat3/.test(e))return 12;if(/mat4/.test(e))return 16;p(`TSL: Unsupported type: ${e}`,new Jm)}function Qf(e){if(/float|int|uint|bool/.test(e))return 1;if(/vec2/.test(e))return 2;if(/vec3/.test(e)||/vec4/.test(e))return 4;if(/mat2/.test(e))return 2;if(/mat3/.test(e)||/mat4/.test(e))return 4;p(`TSL: Unsupported type: ${e}`,new Jm)}function $f(e){if(e==null)return null;let t=typeof e;return e.isNode===!0?`node`:t===`number`?`float`:t===`boolean`?`bool`:t===`string`?`string`:t===`function`?`shader`:e.isVector2===!0?`vec2`:e.isVector3===!0?`vec3`:e.isVector4===!0?`vec4`:e.isMatrix2===!0?`mat2`:e.isMatrix3===!0?`mat3`:e.isMatrix4===!0?`mat4`:e.isColor===!0?`color`:e instanceof ArrayBuffer?`ArrayBuffer`:null}function ep(e){if(e.isDepthTexture===!0)return`float`;let t=e.format,n;n=t===1028||t===1029||t===1026||t===1027||t===1021?1:t===1030||t===1031?2:t===1022||t===1032?3:4;let r;if(r=e.type===1014?`uint`:e.type===1013?`int`:`float`,n===1)return r;let i=Jf(n);return r!==`float`&&(i=r[0]+i),i}function tp(e,...t){let n=e?e.slice(-4):void 0;return t.length===1&&(n===`vec2`?t=[t[0],t[0]]:n===`vec3`?t=[t[0],t[0],t[0]]:n===`vec4`&&(t=[t[0],t[0],t[0],t[0]])),e===`color`?new L(...t):n===`vec2`?new N(...t):n===`vec3`?new P(...t):n===`vec4`?new Mi(...t):n===`mat2`?new ef(...t):n===`mat3`?new yi(...t):n===`mat4`?new F(...t):e===`bool`?t[0]||!1:e===`float`||e===`int`||e===`uint`?t[0]||0:e===`string`?t[0]||``:e===`ArrayBuffer`?ip(t[0]):null}function np(e){let t=$m.get(e);return t===void 0&&(t={},$m.set(e,t)),t}function rp(e){let t=``,n=new Uint8Array(e);for(let e=0;ee.charCodeAt(0)).buffer}function ap(e){return e[0]!==void 0&&e[0]!==null&&(e[0].isNode||Object.getPrototypeOf(e[0])!==Object.prototype)}function B(e,t){if(Th.has(e)){f(`TSL: Redefinition of method chaining '${e}'.`);return}if(typeof t!=`function`)throw Error(`THREE.TSL: Node element ${e} is not a function`);Th.set(e,t),e!==`assign`&&(dh.prototype[e]=function(...e){return this.isStackNode?this.addToStack(t(...e)):t(this,...e)},dh.prototype[e+`Assign`]=function(...e){return this.isStackNode?this.assign(e[0],t(...e)):this.assign(t(this,...e))})}function op(e,t,n){Oh[e]=Oh[t]=Oh[n]={get(){this._cache=this._cache||{};let t=this._cache[e];return t===void 0&&(t=new _h(this,e),this._cache[e]=t),t},set(t){this[e].assign(Qh(t))}};let r=e.toUpperCase(),i=t.toUpperCase(),a=n.toUpperCase();dh.prototype[`set`+r]=dh.prototype[`set`+i]=dh.prototype[`set`+a]=function(t){let n=Dh(e);return new vh(this,n,Qh(t))},dh.prototype[`flip`+r]=dh.prototype[`flip`+i]=dh.prototype[`flip`+a]=function(){let t=Dh(e);return new yh(this,t)}}function sp(e){let t;return eg(e),t=ap(e)?[...e]:e[0],t}function cp(e){let t=0;return eg(e),new Proxy(e,{get:(n,r,i)=>{let a;if(r===`length`)return a=e.length,a;if(Symbol.iterator===r)a=function*(){for(let t of e)yield Qh(t)};else{if(e.length>0){if(Object.getPrototypeOf(e[0])===Object.prototype){let n=e[0];a=n[r]===void 0?n[t++]:Reflect.get(n,r,i)}else e[0]instanceof dh&&(a=e[r]===void 0?e[t++]:Reflect.get(e,r,i))}else a=Reflect.get(n,r,i);a=Qh(a)}return a}})}function lp(e){return e&&e.isNode&&e.traverse(t=>{t.isConstNode&&(e=t.value)}),!!e}function up(e,t){return new Rh(e,t)}function V(e,t=null){let n=new og(e,t);return new Proxy(()=>{},{apply(e,t,r){return n.call(...r)},get(e,t,r){return Reflect.get(n,t,r)},set(e,t,r,i){return Reflect.set(n,t,r,i)}})}function dp(e){return wh&&wh.addToStack(e),e}function fp(e,t,n=null){return Sy(n,{getShadow:({light:n,shadowColorNode:r})=>t===n?r.mul(e):r})}function pp(e,t=null){return Sy(t,{getAO:(t,{material:n})=>n.transparent===!0?t:t===null?e:t.mul(e)})}function mp(e,t,n=null){let r=e.max(.001);return Sy(n,{getAO:(e,{material:t})=>t.transparent===!0?e:e===null?r:e.mul(r),getGI:(e,{material:n})=>{if(n.transparent===!0)return e;let i=t.div(r);return e===null?i:e.add(i)}})}function hp(e,t){return f(`TSL: "label()" has been deprecated. Use "setName()" instead.`),wy(e,t)}function gp(e,t){let n=Zy.get(e);return n===void 0&&(n=new So(e,t),Zy.set(e,n)),n}function _p(e,t=null,n=0,r=0,i=Ur,a=!1){return t===`mat3`||t===null&&e.itemSize===9?Tg(new Qy(e,`vec3`,9,0).setUsage(i).setInstanced(a),new Qy(e,`vec3`,9,3).setUsage(i).setInstanced(a),new Qy(e,`vec3`,9,6).setUsage(i).setInstanced(a)):t===`mat4`||t===null&&e.itemSize===16?Eg(new Qy(e,`vec4`,16,0).setUsage(i).setInstanced(a),new Qy(e,`vec4`,16,4).setUsage(i).setInstanced(a),new Qy(e,`vec4`,16,8).setUsage(i).setInstanced(a),new Qy(e,`vec4`,16,12).setUsage(i).setInstanced(a)):new Qy(e,t,n,r).setUsage(i)}function vp(e,t=!0){return f(`TSL: "cache()" has been deprecated. Use "isolate()" instead.`),mb(e).setParent(t)}function yp(e,t,n,r=U(0),i=U(1)){return _b(e,t,n,r,i,!0)}function bp(e,t=``,n=null){return e=Qh(e),e.before(new kb(e,t,n))}function xp(e){f(`TSL: AddNodeElement has been removed in favor of tree-shaking. Trying add`,e)}function Sp(e,t){let n,r=Math.max(t.count,1);if(t.isStorageInstancedBufferAttribute===!0)n=Mw(t,`mat4`,r).element(ab);else if(r*16*4<=e.getUniformBufferLimit())n=Jb(t.array,`mat4`,r).element(ab);else{let e=Nw.get(t);e||(e=new qd(t.array,16,1),Nw.set(t,e));let r=t.usage===35048?nb:tb,i=[r(e,`vec4`,16,0),r(e,`vec4`,16,4),r(e,`vec4`,16,8),r(e,`vec4`,16,12)];n=Eg(...i)}return n}function Cp(e,t,n){let r=Fw.get(e);if(r===void 0){let i=t.clone();r={previousInstanceMatrix:i,node:Sp(n,i)},Fw.set(e,r)}return r.node}function wp(e,t){let n=W(Pb(Ub(e),0).x).toConst(),r=U(t).mul(4).toInt().toConst(),i=r.mod(n).toConst(),a=r.div(n).toConst();return Eg(Ub(e,mg(i,a)),Ub(e,mg(i.add(1),a)),Ub(e,mg(i.add(2),a)),Ub(e,mg(i.add(3),a)))}function Tp(e,t){let n=zw.get(e);if(n===void 0){let{image:r,format:i,type:a}=e._matricesTexture,o=new Cs(r.data.slice(),r.width,r.height,i,a);n={previousMatricesTexture:o,node:wp(o,t)},zw.set(e,n)}return n.node}function Ep(e){return{element:t=>{let n=W(Pb(e).x).toConst(),r=W(t).mul(4).toConst(),i=r.div(n).toConst(),a=r.sub(i.mul(n)).toConst();return Eg(e.load(mg(a,i)),e.load(mg(a.add(1),i)),e.load(mg(a.add(2),i)),e.load(mg(a.add(3),i)))}}}function Dp(e,t){let n;if(t.bones.length*16*4<=e.getUniformBufferLimit())n=WS(`skeleton.boneMatrices`,`mat4`,t.bones.length);else{t.boneTexture===null&&t.computeBoneTexture();let e=Vb(t.boneTexture);bw(({object:t})=>{let n=t.skeleton;n.boneTexture===null&&n.computeBoneTexture(),e.value=n.boneTexture}),n=Ep(e)}return n}function Op(e,t,n,r,i,a){let o=e.element(i.x),s=e.element(i.y),c=e.element(i.z),l=e.element(i.w),u=n.mul(t),d=D_(o.mul(a.x).mul(u),s.mul(a.y).mul(u),c.mul(a.z).mul(u),l.mul(a.w).mul(u));return r.mul(d).xyz}function kp(e,t,n,r,i,a,o){let s=e.element(a.x),c=e.element(a.y),l=e.element(a.z),u=e.element(a.w),d=D_(o.x.mul(s),o.y.mul(c),o.z.mul(l),o.w.mul(u));d=i.mul(d).mul(r);let f=Tg(d);return{skinNormal:f.mul(t),skinTangent:f.mul(n)}}function Ap(e,t,n,r,i,a){let o=t.skeleton,s=Kw.get(o);if(s===void 0){if(o.update(),o.bones.length*16*4<=e.getUniformBufferLimit()){let e=new Float32Array(o.boneMatrices);s={previousBoneMatrices:e,previousBoneTexture:null,node:Jb(e,`mat4`,o.bones.length)}}else{o.boneTexture===null&&o.computeBoneTexture();let{width:e,height:t}=o.boneTexture.image,n=new Float32Array(o.boneMatrices),r=new Cs(n,e,t,Tn,gn);r.needsUpdate=!0,s={previousBoneMatrices:n,previousBoneTexture:r,node:Ep(Vb(r))}}Kw.set(o,s)}return Op(s.node,oS,n,r,i,a)}function jp(e){let t=e.morphAttributes.position!==void 0,n=e.morphAttributes.normal!==void 0,r=e.morphAttributes.color!==void 0,i=e.morphAttributes.position||e.morphAttributes.normal||e.morphAttributes.color,a=i===void 0?0:i.length,o=$w.get(e);if(o===void 0||o.count!==a){o!==void 0&&o.texture.dispose();let i=e.morphAttributes.position||[],s=e.morphAttributes.normal||[],c=e.morphAttributes.color||[],l=0;t===!0&&(l=1),n===!0&&(l=2),r===!0&&(l=3);let u=e.attributes.position.count*l,d=1,f=4096;u>f&&(d=Math.ceil(u/f),u=f);let p=new Float32Array(u*d*4*a),m=new Fi(p,u,d,a);m.type=gn,m.needsUpdate=!0;let h=l*4;for(let e=0;e0}function Np(e){let t=e.target;t.removeEventListener(`dispose`,Np);let n=sE.get(t);n!==void 0&&(sE.delete(t),n.dispose())}function Pp(e,t){t===303?e.mapping=301:t===304&&(e.mapping=302)}function Fp(e){let t=[],n=[],r=e,i=e-UD+1+WD;for(let e=0;e2?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],i=nO[e];c.set(r,18*i);for(let e=0;e<6;e++){let t=s[e*2]*2-1,n=s[e*2+1]*2-1;i===0?eO.set(1,n,t):i===1?eO.set(-t,1,-n):i===2?eO.set(-t,n,1):i===3?eO.set(-1,n,-t):i===4?eO.set(-t,-1,n):eO.set(t,n,-1),eO.toArray(l,(i*6+e)*3)}}let u=new xo;u.setAttribute(`position`,new eo(c,3)),u.setAttribute(`outputDirection`,new eo(l,3)),n.push(new z(u,null)),r>UD&&r--}return{lodMeshes:n,sizeLods:t}}function Ip(e,t,n){let r=new Ni(e,t,{magFilter:an,minFilter:an,generateMipmaps:!1,type:_n,format:Tn,colorSpace:Nr,depthBuffer:n});return r.texture.mapping=306,r.texture.name=`PMREM.cubeUv`,r.texture.isPMREMTexture=!0,r.scissorTest=!0,r}function Lp(e){let t=new VT;return t.depthTest=!1,t.depthWrite=!1,t.blending=0,t.name=`PMREM_${e}`,t}function Rp(e,t,n){let r={envMap:Vb(),sigma:v_(0),mipInt:v_(0),CUBEUV_TEXEL_WIDTH:U(1/t),CUBEUV_TEXEL_HEIGHT:U(1/n),CUBEUV_MAX_MIP:U(e)},i=Lp(`blur`);return i.fragmentNode=RD({...r,outputDirection:rO,SAMPLES:W(GD)}),tO.set(i,r),i}function zp(e,t,n){let r={envMap:Vb(),roughness:v_(0),mipInt:v_(0),CUBEUV_TEXEL_WIDTH:U(1/t),CUBEUV_TEXEL_HEIGHT:U(1/n),CUBEUV_MAX_MIP:U(e)},i=Lp(`ggx`);return i.fragmentNode=HD({...r,N_immutable:rO,GGX_SAMPLES:G(KD)}),tO.set(i,r),i}function Bp(e){let t=Lp(`cubemap`);return t.fragmentNode=BS(e,rO),t}function Vp(e){let t=Lp(`equirect`);return t.fragmentNode=Vb(e,iE(rO),0),t}function Hp(e){let t=Math.log2(e)-2,n=1/e;return{texelWidth:1/(3*Math.max(2**t,112)),texelHeight:n,maxMip:t}}function Up(e,t,n){let r=Wp(t),i=r.get(e);if((i===void 0?-1:i.pmremVersion)!==e.pmremVersion){let t=e.image;if(e.isCubeTexture){if(Gp(t))i=n.fromCubemap(e,i);else return null}else if(Kp(t))i=n.fromEquirectangular(e,i);else return null;if(i.pmremVersion=e.pmremVersion,r.has(e)===!1){let t=()=>{e.removeEventListener(`dispose`,t);let n=r.get(e);n!==void 0&&(n.dispose(),r.delete(e))};e.addEventListener(`dispose`,t)}r.set(e,i)}return i.texture}function Wp(e){let t=aO.get(e);return t===void 0&&(t=new WeakMap,aO.set(e,t)),t}function Gp(e){if(e==null)return!1;let t=0;for(let n=0;n<6;n++)e[n]!==void 0&&t++;return t===6}function Kp(e){return e!=null&&e.height>0}function qp(e){let t=Object.keys(e),n=GO.get(e.constructor);if(n===void 0){n=[];let t=Object.getPrototypeOf(e);for(;t;){let e=Object.getOwnPropertyDescriptors(t);for(let t in e){let r=e[t];r&&typeof r.get==`function`&&n.push(t)}t=Object.getPrototypeOf(t)}GO.set(e.constructor,n)}for(let e=0;e=65535?so:ao)(t,1);return i.version=Jp(e),i.__id=Yp(e),i}function Zp(e,t){return e.groupOrder===t.groupOrder?e.renderOrder===t.renderOrder?e.z===t.z?e.id-t.id:e.z-t.z:e.renderOrder-t.renderOrder:e.groupOrder-t.groupOrder}function Qp(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 $p(e){return(e.transmission>0||e.transmissionNode&&e.transmissionNode.isNode)&&e.side===2&&e.forceSinglePass===!1}function em(e){e.id=null,e.object=null,e.geometry=null,e.material=null,e.groupOrder=null,e.renderOrder=null,e.z=null,e.group=null,e.clippingContext=null}function tm(e){let{textures:t,activeCubeFace:n,activeMipmapLevel:r}=e,i=[n,r];for(let e of t)i.push(e.id);return Xm(i)}function nm(e,t=null,n=null){if(t&&t.isNode){let e=t;t=()=>e}return new vk(new Map([[e,t]]),n)}function rm(e,t=null){let n=new Map;for(let[t,r]of e){let e=r===null?null:typeof r==`function`?r:()=>r;n.set(t,e)}return new vk(n,t)}function im(e){return Object.entries(e).map(([e,t])=>typeof t==`string`?{name:e,type:t,atomic:!1}:{name:e,type:t.type,atomic:t.atomic||!1})}function am(e,t){for(let n=0;ne})}function cm(e,t={}){return t.toneMapping=e.toneMapping,t.toneMappingExposure=e.toneMappingExposure,t.outputColorSpace=e.outputColorSpace,t.renderTarget=e.getRenderTarget(),t.activeCubeFace=e.getActiveCubeFace(),t.activeMipmapLevel=e.getActiveMipmapLevel(),t.renderObjectFunction=e.getRenderObjectFunction(),t.pixelRatio=e.getPixelRatio(),t.mrt=e.getMRT(),t.clearColor=e.getClearColor(t.clearColor||new L),t.clearAlpha=e.getClearAlpha(),t.autoClear=e.autoClear,t.scissorTest=e.getScissorTest(),t}function lm(e,t){return t=cm(e,t),e.setMRT(null),e.setRenderObjectFunction(null),e.setClearColor(0,1),e.autoClear=!0,t}function um(e,t){e.toneMapping=t.toneMapping,e.toneMappingExposure=t.toneMappingExposure,e.outputColorSpace=t.outputColorSpace,e.setRenderTarget(t.renderTarget,t.activeCubeFace,t.activeMipmapLevel),e.setRenderObjectFunction(t.renderObjectFunction),e.setPixelRatio(t.pixelRatio),e.setMRT(t.mrt),e.setClearColor(t.clearColor,t.clearAlpha),e.autoClear=t.autoClear,e.setScissorTest(t.scissorTest)}function dm(e,t={}){return t.background=e.background,t.backgroundNode=e.backgroundNode,t.overrideMaterial=e.overrideMaterial,t}function fm(e,t){return t=dm(e,t),e.background=null,e.backgroundNode=null,e.overrideMaterial=null,t}function pm(e,t){e.background=t.background,e.backgroundNode=t.backgroundNode,e.overrideMaterial=t.overrideMaterial}function mm(e,t,n={}){return n=cm(e,n),n=dm(t,n),n}function hm(e,t,n){return n=lm(e,n),n=fm(t,n),n}function gm(e,t,n){um(e,n),pm(t,n)}function _m(e){let t=qj.get(e);return t===void 0&&(t={},qj.set(e,t)),t}function vm(e,t=0){let n=_m(e),r=n[t];return r===void 0&&(n[t]=r=new F,n[t].copy(e.matrixWorld)),r}function ym(e){let t,n=e.context.getViewZ;return n!==void 0&&(t=n(this)),(t||lS.z).negate()}function bm(e){KN||=new WeakMap;let t=KN.get(e);return t===void 0&&KN.set(e,t={}),t}function xm(e){let t=bm(e);return t.shadowMatrix||=v_(`mat4`).setGroup(h_).onRenderUpdate(t=>((e.castShadow!==!0||t.renderer.shadowMap.enabled===!1)&&(e.shadow.camera.coordinateSystem!==t.camera.coordinateSystem&&(e.shadow.camera.coordinateSystem=t.camera.coordinateSystem,e.shadow.camera.updateProjectionMatrix()),e.shadow.updateMatrices(e)),e.shadow.matrix))}function Sm(e,t=sS){let n=xm(e).mul(t);return n.xyz.div(n.w)}function Cm(e){let t=bm(e);return t.position||=v_(new P).setGroup(h_).onRenderUpdate((t,n)=>n.value.setFromMatrixPosition(e.matrixWorld))}function wm(e){let t=bm(e);return t.targetPosition||=v_(new P).setGroup(h_).onRenderUpdate((t,n)=>n.value.setFromMatrixPosition(e.target.matrixWorld))}function Tm(e){let t=bm(e);return t.viewPosition||=v_(new P).setGroup(h_).onRenderUpdate(({camera:t},n)=>{n.value=n.value||new P,n.value.setFromMatrixPosition(e.matrixWorld),n.value.applyMatrix4(t.matrixWorldInverse)})}function Em(e,t,n){qL.setFromMatrixPosition(t.matrixWorld),JL.setFromMatrixPosition(n.matrixWorld);let r=qL.distanceTo(JL),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 Dm(e,t){t===null?e.matrixWorld.copy(e.matrix):e.matrixWorld.multiplyMatrices(t.matrixWorld,e.matrix),e.matrixWorldInverse.copy(e.matrixWorld).invert()}function Om(e,t,n){n===null?e.matrix.copy(t.matrixWorld):(e.matrix.copy(n.matrixWorld),e.matrix.invert(),e.matrix.multiply(t.matrixWorld)),e.matrix.decompose(e.position,e.quaternion,e.scale),e.updateMatrixWorld(!0),e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse),e.isPerspectiveCamera&&(e.fov=mi*2*Math.atan(1/e.projectionMatrix.elements[5]),e.zoom=1)}function km(e){let t=this._controllerInputSources.indexOf(e.inputSource);if(t===-1)return;let n=this._controllers[t];if(n!==void 0){let t=this.getReferenceSpace();n.update(e.inputSource,e.frame,t),n.dispatchEvent({type:e.type,data:e.inputSource})}}function Am(){let e=this._session,t=this._renderer;e.removeEventListener(`select`,this._onSessionEvent),e.removeEventListener(`selectstart`,this._onSessionEvent),e.removeEventListener(`selectend`,this._onSessionEvent),e.removeEventListener(`squeeze`,this._onSessionEvent),e.removeEventListener(`squeezestart`,this._onSessionEvent),e.removeEventListener(`squeezeend`,this._onSessionEvent),e.removeEventListener(`end`,this._onSessionEnd),e.removeEventListener(`inputsourceschange`,this._onInputSourcesChange);for(let e=0;e=0&&(n[a]=null,t[a].disconnect(i))}for(let r=0;r=n.length){n.push(i),a=e;break}else if(n[e]===null){n[e]=i,a=e;break}if(a===-1)break}let o=t[a];o&&o.connect(i)}}function Mm(e){return e.type===`quad`?this._glBinding.createQuadLayer({transform:new XRRigidTransform(e.translation,e.quaternion),width:e.width/2,height:e.height/2,space:this._referenceSpace,viewPixelWidth:e.pixelwidth,viewPixelHeight:e.pixelheight,clearOnAccess:!1}):this._glBinding.createCylinderLayer({transform:new XRRigidTransform(e.translation,e.quaternion),radius:e.radius,centralAngle:e.centralAngle,aspectRatio:e.aspectRatio,space:this._referenceSpace,viewPixelWidth:e.pixelwidth,viewPixelHeight:e.pixelheight,clearOnAccess:!1})}function Nm(e,t){if(t===void 0)return;let n=this._cameraXR,r=this._renderer,i=r.backend,a=this._glBaseLayer,o=this.getReferenceSpace(),s=t.getViewerPose(o);if(this._xrFrame=t,s!==null){let e=s.views,t=this._isWebGPUSession()?this._getWebGPUViewData(e):null;this._glBaseLayer!==null&&t===null&&i.setXRTarget(a.framebuffer);let o=!1;e.length!==n.cameras.length&&(n.cameras.length=0,o=!0);for(let r=0;r{Wf(),Vm=`alphaMap.alphaTest.anisotropy.anisotropyMap.anisotropyRotation.aoMap.aoMapIntensity.attenuationColor.attenuationDistance.bumpMap.bumpScale.clearcoat.clearcoatMap.clearcoatNormalMap.clearcoatNormalScale.clearcoatRoughness.color.dashOffset.dashSize.dispersion.displacementBias.displacementMap.displacementScale.emissive.emissiveIntensity.emissiveMap.envMap.envMapIntensity.envMapRotation.gapSize.gradientMap.ior.iridescence.iridescenceIOR.iridescenceMap.iridescenceThickness.iridescenceThicknessMap.lightMap.lightMapIntensity.linewidth.map.matcap.metalness.metalnessMap.normalMap.normalScale.opacity.reflectivity.retroreflectivity.rotation.roughness.roughnessMap.scale.sheen.sheenColor.sheenColorMap.sheenRoughness.sheenRoughnessMap.shininess.size.specular.specularColor.specularColorMap.specularIntensity.specularIntensityMap.specularMap.steps.thickness.transmission.transmissionMap.wireframe`.split(`.`),Hm=new WeakMap,Um=new WeakMap,Wm=new WeakMap,Gm=new WeakMap,Km=class{constructor(e){this.renderObjects=new WeakMap,this.hasNode=this.containsNode(e),this.hasAnimation=e.object.isSkinnedMesh===!0,this.refreshUniforms=Vm,this.renderId=0}firstInitialization(e){return this.renderObjects.has(e)===!1&&(this.getRenderObjectData(e),!0)}hasDynamicInstancing(e){return e.isInstancedMesh===!0&&(e.instanceMatrix.usage===35048||e.instanceColor!==null&&e.instanceColor.usage===35048)}needsVelocity(e){let t=e.getMRT();return t!==null&&t.has(`velocity`)}getRenderObjectData(e){let t=this.renderObjects.get(e);if(t===void 0){let{geometry:n,object:r}=e;t={geometryId:n.id,geometryVersion:this.getGeometryData(n)._version,materialVersion:this.getMaterialData(e.material)._version,worldMatrix:r.matrixWorld.clone()},r.center&&(t.center=r.center.clone()),r.morphTargetInfluences&&(t.morphTargetInfluences=r.morphTargetInfluences.slice()),r.isInstancedMesh===!0&&(t.instanceMatrixVersion=r.instanceMatrix.version,t.instanceColorVersion=r.instanceColor===null?null:r.instanceColor.version,t.morphTextureVersion=r.morphTexture===null?null:r.morphTexture.version),r.isBatchedMesh===!0&&(t.matricesTextureVersion=r._matricesTexture.version,t.colorsTextureVersion=r._colorsTexture===null?null:r._colorsTexture.version,t.indirectTextureVersion=r._indirectTexture.version),e.bundle!==null&&(t.version=e.bundle.version);let{width:i,height:a}=e.context;t.bufferWidth=i,t.bufferHeight=a;let{environmentIntensity:o,environmentRotation:s}=e.scene;t.environmentIntensity=o,t.environmentRotation=s.clone(),t.lights=this.getLightsData(e.lightsNode.getBuiltinLights(),[]),this.renderObjects.set(e,t)}return t}getAttributesData(e){let t={};for(let n in e){let r=e[n];t[n]={id:r.isInterleavedBufferAttribute?r.data.uuid:r.id,version:r.isInterleavedBufferAttribute?r.data.version:r.version}}return t}containsNode(e){let t=e.material;for(let e in t)if(t[e]&&t[e].isNode)return!0;return!!(e.context.modelViewMatrix||e.context.modelNormalViewMatrix||e.context.getAO||e.context.getShadow)}getGeometryData(e){let t=Wm.get(e);return t===void 0&&(t={_renderId:-1,_version:0,attributes:this.getAttributesData(e.attributes),indexId:e.index?e.index.id:null,indexVersion:e.index?e.index.version:null,drawRange:{start:e.drawRange.start,count:e.drawRange.count}},e.addEventListener(`dispose`,()=>{t._version++}),Wm.set(e,t)),t}getTextureData(e){let t=Gm.get(e);if(t===void 0){t={_version:0};let n=()=>{t._version++};e.renderTarget===null?e.addEventListener(`dispose`,n):e.renderTarget.addEventListener(`dispose`,n),Gm.set(e,t)}return t}getMaterialData(e){let t=Um.get(e);if(t===void 0){t={_renderId:-1,_version:0};for(let n of this.refreshUniforms){let r=e[n];r!==void 0&&(r===null?t[n]=null:typeof r==`object`&&r.clone!==void 0?r.isTexture===!0?t[n]={id:r.id,version:0,cacheVersion:this.getTextureData(r)._version}:t[n]=r.clone():t[n]=r)}Um.set(e,t)}return t}equals(e,t,n){let{object:r,material:i,geometry:a}=e,o=this.getRenderObjectData(e);if(o.worldMatrix.equals(r.matrixWorld)!==!0)return o.worldMatrix.copy(r.matrixWorld),!1;let s=this.getMaterialData(e.material);if(s._renderId!==n){s._renderId=n;let e=!1;for(let t in s){let n=s[t],r=i[t];if(t!==`_renderId`&&t!==`_version`){if(n===null||r==null)n!==(r===void 0?null:r)&&(s[t]=r==null?null:r.isTexture===!0?{id:r.id,version:r.version,cacheVersion:this.getTextureData(r)._version}:typeof r==`object`&&r.clone!==void 0?r.clone():r,e=!0);else if(n.equals!==void 0)n.equals(r)===!1&&(n.copy(r),e=!0);else if(r.isTexture===!0){let t=this.getTextureData(r);(n.id!==r.id||n.version!==r.version||n.cacheVersion!==t._version)&&(n.id=r.id,n.version=r.version,n.cacheVersion=t._version,e=!0)}else n!==r&&(s[t]=r,e=!0)}}e===!0&&s._version++}if(o.materialVersion!==s._version)return o.materialVersion=s._version,!1;let{width:c,height:l}=e.context;if(o.bufferWidth!==c||o.bufferHeight!==l)return o.bufferWidth=c,o.bufferHeight=l,!1;if(o.geometryId!==a.id)return o.geometryId=a.id,o.geometryVersion=this.getGeometryData(a)._version,!1;let u=this.getGeometryData(e.geometry);if(u._renderId!==n){u._renderId=n;let e=!1,t=a.attributes,r=u.attributes,i=0,o=0;for(let e in t)i++;for(let n in r){o++;let i=r[n],a=t[n];if(a===void 0){delete r[n],e=!0;continue}let s=a.isInterleavedBufferAttribute?a.data.uuid:a.id,c=a.isInterleavedBufferAttribute?a.data.version:a.version;(i.id!==s||i.version!==c)&&(i.id=s,i.version=c,e=!0)}o!==i&&(u.attributes=this.getAttributesData(t),e=!0);let s=a.index,c=s?s.id:null,l=s?s.version:null;(u.indexId!==c||u.indexVersion!==l)&&(u.indexId=c,u.indexVersion=l,e=!0),(u.drawRange.start!==a.drawRange.start||u.drawRange.count!==a.drawRange.count)&&(u.drawRange.start=a.drawRange.start,u.drawRange.count=a.drawRange.count,e=!0),e===!0&&u._version++}if(o.geometryVersion!==u._version)return o.geometryVersion=u._version,!1;if(o.morphTargetInfluences){let e=!1;for(let t=0;t{let t=`${e.file}:${e.line}:${e.column}`;return e.fn?` at ${e.fn} (${t})`:` at ${t}`}).join(` `)}`}},Ym=e=>qf(e),Xm=e=>qf(e),Zm=(...e)=>qf(e),Qm=new Map([[1,`float`],[2,`vec2`],[3,`vec3`],[4,`vec4`],[9,`mat3`],[16,`mat4`]]),$m=new WeakMap,eh=Object.freeze({__proto__:null,arrayBufferToBase64:rp,base64ToArrayBuffer:ip,getAlignmentFromType:Qf,getDataFromObject:np,getLengthFromType:Xf,getMemoryLengthFromType:Zf,getTextureType:ep,getTypeFromLength:Jf,getTypedArrayFromType:Yf,getValueFromType:tp,getValueType:$f,hash:Zm,hashArray:Xm,hashString:Ym,isArrayAsParameter:ap}),th={VERTEX:`vertex`,FRAGMENT:`fragment`},nh={NONE:`none`,FRAME:`frame`,RENDER:`render`,OBJECT:`object`},rh={BOOLEAN:`bool`,INTEGER:`int`,FLOAT:`float`,VECTOR2:`vec2`,VECTOR3:`vec3`,VECTOR4:`vec4`,MATRIX2:`mat2`,MATRIX3:`mat3`,MATRIX4:`mat4`},ih={READ_ONLY:`readOnly`,WRITE_ONLY:`writeOnly`,READ_WRITE:`readWrite`},ah=[`fragment`,`vertex`],oh=[`setup`,`analyze`,`generate`],sh=[...ah,`compute`],ch=[`x`,`y`,`z`,`w`],lh={analyze:`setup`,generate:`analyze`},uh=0,dh=class e extends ui{static get type(){return`Node`}constructor(t=null){super(),this.nodeType=t,this.updateType=nh.NONE,this.updateBeforeType=nh.NONE,this.updateAfterType=nh.NONE,this.version=0,this.name=``,this.global=!1,this.parents=!1,this.isNode=!0,this._beforeNodes=null,this._cacheKey=null,this._uuid=null,this._cacheKeyVersion=0,this.id=uh++,this.stackTrace=null,e.captureStackTrace===!0&&(this.stackTrace=new Jm)}set needsUpdate(e){e===!0&&this.version++}get uuid(){return this._uuid===null&&(this._uuid=hi.generateUUID()),this._uuid}get type(){return this.constructor.type}onUpdate(e,t){return this.updateType=t,this.update=e.bind(this),this}onFrameUpdate(e){return this.onUpdate(e,nh.FRAME)}onRenderUpdate(e){return this.onUpdate(e,nh.RENDER)}onObjectUpdate(e){return this.onUpdate(e,nh.OBJECT)}onReference(e){return this.updateReference=e.bind(this),this}updateReference(){return this}isGlobal(){return this.global}*getChildren(){for(let{childNode:e}of this._getChildren())yield e}dispose(){this.dispatchEvent({type:`dispose`})}traverse(e){e(this);for(let t of this.getChildren())t.traverse(e)}_getChildren(e=new Set){let t=[];e.add(this);for(let n of Object.getOwnPropertyNames(this)){let r=this[n];if(!(n.startsWith(`_`)===!0||e.has(r))){if(Array.isArray(r)===!0)for(let e=0;e0&&(e.inputNodes=n)}deserialize(e){if(e.inputNodes!==void 0){let t=e.meta.nodes;for(let n in e.inputNodes)if(Array.isArray(e.inputNodes[n])){let r=[];for(let i of e.inputNodes[n])r.push(t[i]);this[n]=r}else if(typeof e.inputNodes[n]==`object`){let r={};for(let i in e.inputNodes[n])r[i]=t[e.inputNodes[n][i]];this[n]=r}else{let r=e.inputNodes[n];this[n]=t[r]}}}toJSON(e){let{uuid:t,type:n}=this,r=e===void 0||typeof e==`string`;r&&(e={textures:{},images:{},nodes:{}});let i=e.nodes[t];i===void 0&&(i={uuid:t,type:n,meta:e,metadata:{version:4.7,type:`Node`,generator:`Node.toJSON`}},r!==!0&&(e.nodes[i.uuid]=i),this.serialize(i),delete i.meta);function a(e){let t=[];for(let n in e){let r=e[n];delete r.metadata,t.push(r)}return t}if(r){let t=a(e.textures),n=a(e.images),r=a(e.nodes);t.length>0&&(i.textures=t),n.length>0&&(i.images=n),r.length>0&&(i.nodes=r)}return i}},dh.captureStackTrace=!1,fh=class extends dh{static get type(){return`ArrayElementNode`}constructor(e,t){super(),this.node=e,this.indexNode=t,this.isArrayElementNode=!0}generateNodeType(e){return this.node.getElementType(e)}getMemberType(e,t){return this.node.getMemberType(e,t)}generate(e){let t=this.indexNode.getNodeType(e);return`${this.node.build(e)}[ ${this.indexNode.build(e,!e.isVector(t)&&e.isInteger(t)?t:`uint`)} ]`}},ph=class extends dh{static get type(){return`ConvertNode`}constructor(e,t){super(),this.node=e,this.convertTo=t}generateNodeType(e){let t=this.node.getNodeType(e),n=null;for(let r of this.convertTo.split(`|`))(n===null||e.getTypeLength(t)===e.getTypeLength(r))&&(n=r);return n}serialize(e){super.serialize(e),e.convertTo=this.convertTo}deserialize(e){super.deserialize(e),this.convertTo=e.convertTo}generate(e,t){let n=this.node,r=this.getNodeType(e),i=n.build(e,r);return e.format(i,r,t)}},mh=class extends dh{static get type(){return`TempNode`}constructor(e=null){super(e),this.isTempNode=!0}hasDependencies(e){return e.getDataFromNode(this).usageCount>1}build(e,t){if(e.getBuildStage()===`generate`){let n=e.getVectorType(this.getNodeType(e,t)),r=e.getDataFromNode(this);if(r.propertyName!==void 0)return e.format(r.propertyName,n,t);if(n!==`void`&&t!==`void`&&this.hasDependencies(e)){let i=super.build(e,n),a=e.getVarFromNode(this,null,n),o=e.getPropertyName(a);return e.addLineFlowCode(`${o} = ${i}`,this),r.snippet=i,r.propertyName=o,e.format(r.propertyName,n,t)}}return super.build(e,t)}},hh=class extends mh{static get type(){return`JoinNode`}constructor(e=[],t=null){super(t),this.nodes=e}generateNodeType(e){return this.nodeType===null?e.getTypeFromLength(this.nodes.reduce((t,n)=>t+e.getTypeLength(n.getNodeType(e)),0)):e.getVectorType(this.nodeType)}generate(e,t){let n=this.getNodeType(e),r=e.getTypeLength(n),i=this.nodes,a=e.getComponentType(n),o=[],s=0;for(let t of i){if(s>=r){p(`TSL: Length of parameters exceeds maximum length of function '${n}()' type.`,this.stackTrace);break}let i=t.getNodeType(e),c=e.getTypeLength(i),l;if(s+c>r&&(p(`TSL: Length of '${n}()' data exceeds maximum length of output type.`,this.stackTrace),c=r-s,i=e.getTypeFromLength(c)),s+=c,l=t.build(e,i),e.getComponentType(i)!==a){let t=e.getTypeFromLength(c,a);l=e.format(l,i,t)}o.push(l)}let c=`${e.getType(n)}( ${o.join(`, `)} )`;return e.format(c,n,t)}},gh=ch.join(``),_h=class extends dh{static get type(){return`SplitNode`}constructor(e,t=`x`){super(),this.node=e,this.components=t,this.isSplitNode=!0}getVectorLength(){let e=this.components.length;for(let t of this.components)e=Math.max(ch.indexOf(t)+1,e);return e}getComponentType(e){return e.getComponentType(this.node.getNodeType(e))}generateNodeType(e){return e.getTypeFromLength(this.components.length,this.getComponentType(e))}getScope(){return this.node.getScope()}generate(e,t){let n=this.node,r=e.getTypeLength(n.getNodeType(e)),i=null;if(r>1){let a=null;this.getVectorLength()>=r&&(a=e.getTypeFromLength(this.getVectorLength(),this.getComponentType(e)));let o=n.build(e,a);i=this.components.length===r&&this.components===gh.slice(0,this.components.length)?e.format(o,a,t):e.format(`${o}.${this.components}`,this.getNodeType(e),t)}else i=n.build(e,t);return i}serialize(e){super.serialize(e),e.components=this.components}deserialize(e){super.deserialize(e),this.components=e.components}},vh=class extends mh{static get type(){return`SetNode`}constructor(e,t,n){super(),this.sourceNode=e,this.components=t,this.targetNode=n}generateNodeType(e){return this.sourceNode.getNodeType(e)}generate(e){let{sourceNode:t,components:n,targetNode:r}=this,i=this.getNodeType(e),a=e.getComponentType(r.getNodeType(e)),o=e.getTypeFromLength(n.length,a),s=r.build(e,o),c=t.build(e,i),l=e.getTypeLength(i),u=[];for(let e=0;ee.replace(/r|s/g,`x`).replace(/g|t/g,`y`).replace(/b|p/g,`z`).replace(/a|q/g,`w`),Dh=e=>Eh(e).split(``).sort().join(``),dh.prototype.assign=function(...e){if(this.isStackNode!==!0)return wh===null?p(`TSL: No stack defined for assign operation. Make sure the assign is inside a Fn().`,new Jm):wh.assign(this,...e),this;{let t=Th.get(`assign`);return this.addToStack(t(...e))}},dh.prototype.toVarIntent=function(){return this},dh.prototype.get=function(e){return new Ch(this,e)},Oh={},kh=[`x`,`y`,`z`,`w`],Ah=[`r`,`g`,`b`,`a`],jh=[`s`,`t`,`p`,`q`];for(let e=0;e<4;e++){let t=kh[e],n=Ah[e],r=jh[e];op(t,n,r);for(let i=0;i<4;i++){t=kh[e]+kh[i],n=Ah[e]+Ah[i],r=jh[e]+jh[i],op(t,n,r);for(let a=0;a<4;a++){t=kh[e]+kh[i]+kh[a],n=Ah[e]+Ah[i]+Ah[a],r=jh[e]+jh[i]+jh[a],op(t,n,r);for(let o=0;o<4;o++)t=kh[e]+kh[i]+kh[a]+kh[o],n=Ah[e]+Ah[i]+Ah[a]+Ah[o],r=jh[e]+jh[i]+jh[a]+jh[o],op(t,n,r)}}}for(let e=0;e<32;e++)Oh[e]={get(){this._cache=this._cache||{};let t=this._cache[e];return t===void 0&&(t=new fh(this,new Sh(e,`uint`)),this._cache[e]=t),t},set(t){this[e].assign(Qh(t))}};Object.defineProperties(dh.prototype,Oh),Mh=function(e,t=null){let n=$f(e);return n===`node`?e:t===null&&(n===`float`||n===`boolean`)||n&&n!==`shader`&&n!==`string`?Qh(Yh(e,t)):n===`shader`?e.isFn?e:V(e):e},Nh=function(e,t=null){for(let n in e)e[n]=Qh(e[n],t);return e},Ph=function(e,t=null){let n=e.length;for(let r=0;rc?(p(`TSL: "${n}" parameter length exceeds limit.`,new Jm),t.slice(0,c)):t}return t===null?a=(...t)=>i(new e(...tg(l(t)))):n===null?a=(...n)=>i(new e(t,...tg(l(n)))):(n=Qh(n),a=(...r)=>i(new e(t,...tg(l(r)),n))),a.setParameterLength=(...e)=>(e.length===1?s=c=e[0]:e.length===2&&([s,c]=e),a),a.setName=e=>(o=e,a),a},Ih=function(e,...t){return new e(...tg(t))},Lh=class extends dh{constructor(e,t){super(),this.shaderNode=e,this.rawInputs=t,this.isShaderCallNodeInternal=!0}generateNodeType(e){return this.shaderNode.nodeType||this.getOutputNode(e).getNodeType(e)}getElementType(e){return this.getOutputNode(e).getElementType(e)}getMemberType(e,t){return this.getOutputNode(e).getMemberType(e,t)}call(e){let{shaderNode:t,rawInputs:n}=this,r=e.getNodeProperties(t),i=e.getClosestSubBuild(t.subBuilds)||``,a=i||`default`;if(r[a])return r[a];let o=e.subBuildFn,s=e.fnCall;e.subBuildFn=i,e.fnCall=this;let c=null;if(t.layout){if(n){let r=t.layout.inputs;if(ap(n)){let t=n;for(let n=0;n{let r;return r=Symbol.iterator===t?function*(){yield void 0}:Reflect.get(e,t,n),r}}),i=n?cp(n):null,a=Array.isArray(n)?n.length>0:n!==null,o=t.jsFunc,s=a||o.length>1?o(i,r):o(r);c=Qh(s)}return e.subBuildFn=o,e.fnCall=s,t.once&&(r[a]=c),c}setupOutput(e){return e.addStack(),e.stack.outputNode=this.call(e),e.removeStack()}getOutputNode(e){let t=e.getNodeProperties(this),n=e.getSubBuildOutput(this);return t[n]=t[n]||this.setupOutput(e),t[n].subBuild=e.getClosestSubBuild(this),t[n]}build(e,t=null){let n=null,r=e.getBuildStage(),i=e.getNodeProperties(this),a=e.getSubBuildOutput(this),o=this.getOutputNode(e),s=e.fnCall;if(e.fnCall=this,r===`setup`){let t=e.getSubBuildProperty(`initialized`,this);if(i[t]!==!0&&(i[t]=!0,i[a]=this.getOutputNode(e),i[a].build(e),this.shaderNode.subBuilds))for(let t of e.chaining){let n=e.getDataFromNode(t,`any`);n.subBuilds=n.subBuilds||new Set;for(let e of this.shaderNode.subBuilds)n.subBuilds.add(e)}n=i[a]}else r===`analyze`?o.build(e,t):r===`generate`&&(n=o.build(e,t)||``);return e.fnCall=s,n}},Rh=class extends dh{constructor(e,t){super(t),this.jsFunc=e,this.layout=null,this.global=!0,this.once=!1}setLayout(e){return this.layout=e,this}getLayout(){return this.layout}call(e=null){return new Lh(this,e)}setup(){return this.call()}},zh=[!1,!0],Bh=[0,1,2,3],Vh=[-1,-2],Hh=[.5,1.5,1/3,1e-6,1e6,Math.PI,Math.PI*2,1/Math.PI,2/Math.PI,1/(Math.PI*2),Math.PI/2],Uh=new Map;for(let e of zh)Uh.set(e,new Sh(e));Wh=new Map;for(let e of Bh)Wh.set(e,new Sh(e,`uint`));Gh=new Map([...Wh].map(e=>new Sh(e.value,`int`)));for(let e of Vh)Gh.set(e,new Sh(e,`int`));Kh=new Map([...Gh].map(e=>new Sh(e.value)));for(let e of Hh)Kh.set(e,new Sh(e));for(let e of Hh)Kh.set(-e,new Sh(-e));qh={bool:Uh,uint:Wh,ints:Gh,float:Kh},Jh=new Map([...Uh,...Kh]),Yh=(e,t)=>Jh.has(e)?Jh.get(e):e.isNode===!0?e:new Sh(e,t),Xh=function(e,t=null){return(...n)=>{for(let t of n)if(t===void 0)return p(`TSL: Invalid parameter for the type "${e}".`,new Jm),new Sh(0,e);if((n.length===0||![`bool`,`float`,`int`,`uint`].includes(e)&&n.every(e=>{let t=typeof e;return t!==`object`&&t!==`function`}))&&(n=[tp(e,...n)]),n.length===1&&t!==null&&t.has(n[0]))return $h(t.get(n[0]));if(n.length===1){let t=Yh(n[0],e);return t.nodeType===e?$h(t):$h(new ph(t,e))}let r=n.map(e=>Yh(e));return $h(new hh(r,e))}},Zh=e=>e==null?null:e.nodeType||e.convertTo||(typeof e==`string`?e:null),Qh=(e,t=null)=>Mh(e,t),$h=(e,t=null)=>Qh(e,t).toVarIntent(),eg=(e,t=null)=>new Nh(e,t),tg=(e,t=null)=>new Ph(e,t),ng=(e,t=null,n=null,r=null)=>new Fh(e,t,n,r),rg=(e,...t)=>new Ih(e,...t),H=(e,t=null,n=null,r={})=>new Fh(e,t,n,{...r,intent:!0}),ig=(e,t)=>new Proxy(e,{get(e,n,r){return Reflect.get(t,n,r)},set(e,n,r){return Reflect.set(t,n,r)}}),ag=0,og=class extends dh{constructor(e,t=null){super();let n=null;t!==null&&(typeof t==`object`?n=t.return:(typeof t==`string`?n=t:p(`TSL: Invalid layout type.`,new Jm),t=null)),this.shaderNode=new up(e,n),t!==null&&this.setLayout(t),this.isFn=!0}setLayout(e){let t=this.shaderNode.nodeType;if(typeof e.inputs!=`object`){let n={name:`fn`+ag++,type:t,inputs:[]};for(let t in e)t!==`return`&&n.inputs.push({name:t,type:e[t]});e=n}return this.shaderNode.setLayout(e),this}generateNodeType(e){return this.shaderNode.getNodeType(e)||`float`}call(...e){let t=this.shaderNode.call(e);return this.shaderNode.nodeType===`void`&&t.toStack(),t.toVarIntent()}once(e=null){return this.shaderNode.once=!0,this.shaderNode.subBuilds=e,this}generate(e){let t=this.getNodeType(e);return p(`TSL: "Fn()" was declared but not invoked. Try calling it like "Fn()( ...params )".`,this.stackTrace),e.generateConst(t)}},sg=e=>{wh=e},cg=()=>wh,lg=(...e)=>wh.If(...e),ug=(...e)=>wh.Switch(...e),B(`toStack`,dp),dg=new Xh(`color`),U=new Xh(`float`,qh.float),W=new Xh(`int`,qh.ints),G=new Xh(`uint`,qh.uint),fg=new Xh(`bool`,qh.bool),pg=new Xh(`vec2`),mg=new Xh(`ivec2`),hg=new Xh(`uvec2`),gg=new Xh(`bvec2`),K=new Xh(`vec3`),_g=new Xh(`ivec3`),vg=new Xh(`uvec3`),yg=new Xh(`bvec3`),bg=new Xh(`vec4`),xg=new Xh(`ivec4`),Sg=new Xh(`uvec4`),Cg=new Xh(`bvec4`),wg=new Xh(`mat2`),Tg=new Xh(`mat3`),Eg=new Xh(`mat4`),B(`toColor`,dg),B(`toFloat`,U),B(`toInt`,W),B(`toUint`,G),B(`toBool`,fg),B(`toVec2`,pg),B(`toIVec2`,mg),B(`toUVec2`,hg),B(`toBVec2`,gg),B(`toVec3`,K),B(`toIVec3`,_g),B(`toUVec3`,vg),B(`toBVec3`,yg),B(`toVec4`,bg),B(`toIVec4`,xg),B(`toUVec4`,Sg),B(`toBVec4`,Cg),B(`toMat2`,wg),B(`toMat3`,Tg),B(`toMat4`,Eg),Dg=ng(fh).setParameterLength(2),Og=(e,t)=>new ph(Qh(e),t),kg=(e,t)=>new _h(Qh(e),t),B(`element`,Dg),B(`convert`,Og),Ag=class extends dh{static get type(){return`PropertyNode`}constructor(e,t=null,n=!1,r=null){super(e),this.name=t,this.varying=n,this.placeholderNode=Qh(r),this.isPropertyNode=!0,this.global=!0}getNodeType(e){let t=super.getNodeType(e);return t===`output`?e.getOutputType():t}customCacheKey(){return Ym(this.type+`:`+(this.name||``)+`:`+(this.varying?`1`:`0`))}getHash(e){return this.name||super.getHash(e)}generate(e){let t;if(this.varying===!0)t=e.getVaryingFromNode(this,this.name),t.needsInterpolation=!0;else if(t=e.getVarFromNode(this,this.name),this.placeholderNode!==null&&e.hasWriteUsage(this)===!1){let n=this.placeholderNode.build(e,this.getNodeType(e));e.addLineFlowCode(`${e.getPropertyName(t)} = ${n}`,this)}return e.getPropertyName(t)}},jg=(e,t,n=null)=>new Ag(e,t,!1,n),Mg=(e,t,n=null)=>new Ag(e,t,!0,n),Ng=rg(Ag,`vec4`,`DiffuseColor`),Pg=rg(Ag,`vec3`,`DiffuseContribution`),Fg=rg(Ag,`vec3`,`EmissiveColor`),Ig=rg(Ag,`float`,`Roughness`),Lg=rg(Ag,`float`,`Metalness`),Rg=rg(Ag,`float`,`Clearcoat`),zg=rg(Ag,`float`,`ClearcoatRoughness`),Bg=rg(Ag,`vec3`,`Sheen`),Vg=rg(Ag,`float`,`SheenRoughness`),Hg=rg(Ag,`float`,`Iridescence`),Ug=rg(Ag,`float`,`IridescenceIOR`),Wg=rg(Ag,`float`,`IridescenceThickness`),Gg=rg(Ag,`float`,`AlphaT`),Kg=rg(Ag,`float`,`Anisotropy`),qg=rg(Ag,`vec3`,`AnisotropyT`),Jg=rg(Ag,`vec3`,`AnisotropyB`),Yg=rg(Ag,`color`,`SpecularColor`),Xg=rg(Ag,`color`,`SpecularColorBlended`),Zg=rg(Ag,`float`,`SpecularF90`),Qg=rg(Ag,`float`,`Shininess`),$g=rg(Ag,`output`,`Output`),e_=rg(Ag,`float`,`dashSize`),t_=rg(Ag,`float`,`gapSize`),n_=rg(Ag,`float`,`pointWidth`),r_=rg(Ag,`float`,`IOR`),i_=rg(Ag,`float`,`Transmission`),a_=rg(Ag,`float`,`Thickness`),o_=rg(Ag,`float`,`AttenuationDistance`),s_=rg(Ag,`color`,`AttenuationColor`),c_=rg(Ag,`float`,`Dispersion`),l_=rg(Ag,`float`,`Retroreflectivity`),u_=rg(Ag,`float`,`AmbientOcclusion`,!1,1),d_=class extends dh{static get type(){return`UniformGroupNode`}constructor(e,t=!1,n=1,r=null){super(`string`),this.name=e,this.shared=t,this.order=n,this.updateType=r,this.isUniformGroup=!0}update(){this.needsUpdate=!0}serialize(e){super.serialize(e),e.name=this.name,e.version=this.version,e.shared=this.shared}deserialize(e){super.deserialize(e),this.name=e.name,this.version=e.version,this.shared=e.shared}},f_=(e,t=1,n=null)=>new d_(e,!1,t,n),p_=(e,t=0,n=null)=>new d_(e,!0,t,n),m_=p_(`frame`,0,nh.FRAME),h_=p_(`render`,0,nh.RENDER),g_=f_(`object`,1,nh.OBJECT),__=class extends bh{static get type(){return`UniformNode`}constructor(e,t=null){super(e,t),this.isUniformNode=!0,this.name=``,this.groupNode=g_}setName(e){return this.name=e,this}label(e){return f(`TSL: "label()" has been deprecated. Use "setName()" instead.`,new Jm),this.setName(e)}setGroup(e){return this.groupNode=e,this}getGroup(){return this.groupNode}getUniformHash(e){return this.getHash(e)}getSharedNode(e){let t=this.getUniformHash(e),n=e.getNodeFromHash(t);return n===void 0&&(e.setHashNode(this,t),n=this),n}onUpdate(e,t){return e=e.bind(this),super.onUpdate(t=>{let n=e(t,this);n!==void 0&&(this.value=n)},t)}getInputType(e){let t=super.getInputType(e);return t===`bool`&&(t=`uint`),t}generate(e,t){let n=this.getNodeType(e),r=this.getSharedNode(e),i=r.getInputType(e),a=e.getUniformFromNode(r,i,e.shaderStage,this.name||e.context.nodeName),o=e.getPropertyName(a);e.context.nodeName!==void 0&&delete e.context.nodeName;let s=o;if(n===`bool`){let t=e.getDataFromNode(this),r=t.propertyName;if(r===void 0){let a=e.getVarFromNode(this,null,`bool`);r=e.getPropertyName(a),t.propertyName=r,s=e.format(o,i,n),e.addLineFlowCode(`${r} = ${s}`,this)}s=r}return e.format(s,n,t)}},v_=(e,t)=>{let n=Zh(t||e);if(n===e&&(e=tp(n)),e&&e.isNode===!0){let t=e.value;e.traverse(e=>{e.isConstNode===!0&&(t=e.value)}),e=t}return new __(e,n)},y_=class extends mh{static get type(){return`ArrayNode`}constructor(e,t,n=null){super(e),this.count=t,this.values=n,this.isArrayNode=!0}getArrayCount(){return this.count}generateNodeType(e){return this.nodeType===null?this.values[0].getNodeType(e):this.nodeType}getElementType(e){return this.getNodeType(e)}getMemberType(e,t){return this.nodeType===null?this.values[0].getMemberType(e,t):super.getMemberType(e,t)}generate(e){let t=this.getNodeType(e);return e.generateArray(t,this.count,this.values)}},b_=(...e)=>{let t;if(e.length===1){let n=e[0].map(e=>Qh(e));t=new y_(null,n.length,n)}else{let n=e[0],r=e[1];t=new y_(n,r)}return t},B(`toArray`,(e,t)=>b_(Array(t).fill(e))),x_=class extends mh{static get type(){return`AssignNode`}constructor(e,t){super(),this.targetNode=e,this.sourceNode=t,this.isAssignNode=!0}hasDependencies(){return!1}generateNodeType(e,t){return t===`void`?`void`:this.targetNode.getNodeType(e)}needsSplitAssign(e){let{targetNode:t}=this;if(e.isAvailable(`swizzleAssign`)===!1&&t.isSplitNode&&t.components.length>1){let n=e.getTypeLength(t.node.getNodeType(e));return ch.join(``).slice(0,n)!==t.components}return!1}setup(e){let{targetNode:t,sourceNode:n}=this,r=t.getScope(),i=e.getDataFromNode(r);i.assign=!0;let a=e.getNodeProperties(this);a.sourceNode=n,a.targetNode=t.context({assign:!0})}generate(e,t){let{targetNode:n,sourceNode:r}=e.getNodeProperties(this),i=this.needsSplitAssign(e),a=n.build(e),o=n.getNodeType(e),s=r.build(e,o),c=r.getNodeType(e),l=e.getDataFromNode(this),u;if(l.initialized===!0)t!==`void`&&(u=a);else if(i){let r=e.getVarFromNode(this,null,o),i=e.getPropertyName(r);e.addLineFlowCode(`${i} = ${s}`,this);let c=n.node,l=c.node.context({assign:!0}).build(e);for(let t=0;t{let r=n.type,i=r===`pointer`,a;return a=i?`&`+t.build(e):t.build(e,r),a};if(Array.isArray(i)){if(i.length>r.length)p(`TSL: The number of provided parameters exceeds the expected number of inputs in 'Fn()'.`),i.length=r.length;else if(i.length(t=t.length>1||t[0]&&t[0].isNode===!0?tg(t):eg(t[0]),new C_(Qh(e),t)),B(`call`,w_),T_={"==":`equal`,"!=":`notEqual`,"<":`lessThan`,">":`greaterThan`,"<=":`lessThanEqual`,">=":`greaterThanEqual`,"%":`mod`},E_=class e extends mh{static get type(){return`OperatorNode`}constructor(t,n,r,...i){if(super(),i.length>0){let a=new e(t,n,r);for(let n=0;n>`||n===`<<`)return e.getIntegerType(a);if(n===`&&`||n===`||`||n===`^^`)return`bool`;if(n===`!`){let t=e.getTypeLength(a);return t>1?`bvec${t}`:`bool`}if(n===`==`||n===`!=`||n===`<`||n===`>`||n===`<=`||n===`>=`){let t=Math.max(e.getTypeLength(a),e.getTypeLength(o));return t>1?`bvec${t}`:`bool`}if(e.isMatrix(a)){if(o===`float`)return a;if(e.isVector(o))return e.getVectorFromMatrix(a);if(e.isMatrix(o))return a}else if(e.isMatrix(o)){if(a===`float`)return o;if(e.isVector(a))return e.getVectorFromMatrix(o)}return e.getTypeLength(o)>e.getTypeLength(a)?o:a}generate(e,t){let n=this.op,{aNode:r,bNode:i}=this,a=this.getNodeType(e,t),o=null,s=null;a===`void`?o=s=a:(o=r.getNodeType(e),s=i?i.getNodeType(e):null,n===`<`||n===`>`||n===`<=`||n===`>=`||n===`==`||n===`!=`?e.isVector(o)?s=o:e.isVector(s)?o=s:o!==s&&(o=s=`float`):n===`>>`||n===`<<`?(o=a,s=e.changeComponentType(s,`uint`)):n===`%`?(o=a,s=e.isInteger(o)&&e.isInteger(s)?s:o):e.isMatrix(o)?s===`float`?s=`float`:e.isVector(s)?s=e.getVectorFromMatrix(o):e.isMatrix(s)||(o=s=a):o=e.isMatrix(s)?o===`float`?`float`:e.isVector(o)?e.getVectorFromMatrix(s):s=a:s=a);let c=r.build(e,o),l=i?i.build(e,s):null,u=e.getFunctionOperator(n);if(t!==`void`){let r=e.renderer.coordinateSystem===$r;if(n===`==`||n===`!=`||n===`<`||n===`>`||n===`<=`||n===`>=`)return r&&e.isVector(o)?e.format(`${this.getOperatorMethod(e,t)}( ${c}, ${l} )`,a,t):e.format(`( ${c} ${n} ${l} )`,a,t);if(n===`%`)return e.isInteger(s)?e.format(`( ${c} % ${l} )`,a,t):e.format(`${this.getOperatorMethod(e,a)}( ${c}, ${l} )`,a,t);if(n===`!`)return r&&e.isVector(o)?e.format(`not( ${c} )`,t):e.format(`( ${n} ${c} )`,o,t);if(n===`~`)return e.format(`( ${n} ${c} )`,o,t);if(u)return e.format(`${u}( ${c}, ${l} )`,a,t);if(e.isMatrix(o)&&s===`float`)return e.format(`( ${l} ${n} ${c} )`,a,t);if(o===`float`&&e.isMatrix(s))return e.format(`${c} ${n} ${l}`,a,t);{let i=`( ${c} ${n} ${l} )`;return!r&&a===`bool`&&e.isVector(o)&&e.isVector(s)&&(i=`all${i}`),e.format(i,a,t)}}if(o!==`void`)return u?e.format(`${u}( ${c}, ${l} )`,a,t):e.isMatrix(o)&&s===`float`?e.format(`${l} ${n} ${c}`,a,t):e.format(`${c} ${n} ${l}`,a,t)}serialize(e){super.serialize(e),e.op=this.op}deserialize(e){super.deserialize(e),this.op=e.op}},D_=H(E_,`+`).setParameterLength(2,1/0).setName(`add`),O_=H(E_,`-`).setParameterLength(2,1/0).setName(`sub`),k_=H(E_,`*`).setParameterLength(2,1/0).setName(`mul`),A_=H(E_,`/`).setParameterLength(2,1/0).setName(`div`),j_=H(E_,`%`).setParameterLength(2).setName(`mod`),M_=H(E_,`==`).setParameterLength(2).setName(`equal`),N_=H(E_,`!=`).setParameterLength(2).setName(`notEqual`),P_=H(E_,`<`).setParameterLength(2).setName(`lessThan`),F_=H(E_,`>`).setParameterLength(2).setName(`greaterThan`),I_=H(E_,`<=`).setParameterLength(2).setName(`lessThanEqual`),L_=H(E_,`>=`).setParameterLength(2).setName(`greaterThanEqual`),R_=H(E_,`&&`).setParameterLength(2,1/0).setName(`and`),z_=H(E_,`||`).setParameterLength(2,1/0).setName(`or`),B_=H(E_,`!`).setParameterLength(1).setName(`not`),V_=H(E_,`^^`).setParameterLength(2).setName(`xor`),H_=H(E_,`&`).setParameterLength(2).setName(`bitAnd`),U_=H(E_,`~`).setParameterLength(1).setName(`bitNot`),W_=H(E_,`|`).setParameterLength(2).setName(`bitOr`),G_=H(E_,`^`).setParameterLength(2).setName(`bitXor`),K_=H(E_,`<<`).setParameterLength(2).setName(`shiftLeft`),q_=H(E_,`>>`).setParameterLength(2).setName(`shiftRight`),J_=V(([e])=>(e.addAssign(1),e)),Y_=V(([e])=>(e.subAssign(1),e)),X_=V(([e])=>{let t=W(e).toConst();return e.addAssign(1),t}),Z_=V(([e])=>{let t=W(e).toConst();return e.subAssign(1),t}),B(`add`,D_),B(`sub`,O_),B(`mul`,k_),B(`div`,A_),B(`mod`,j_),B(`equal`,M_),B(`notEqual`,N_),B(`lessThan`,P_),B(`greaterThan`,F_),B(`lessThanEqual`,I_),B(`greaterThanEqual`,L_),B(`and`,R_),B(`or`,z_),B(`not`,B_),B(`xor`,V_),B(`bitAnd`,H_),B(`bitNot`,U_),B(`bitOr`,W_),B(`bitXor`,G_),B(`shiftLeft`,K_),B(`shiftRight`,q_),B(`incrementBefore`,J_),B(`decrementBefore`,Y_),B(`increment`,X_),B(`decrement`,Z_),q=class e extends mh{static get type(){return`MathNode`}constructor(t,n,r=null,i=null){if(super(),(t===e.MAX||t===e.MIN)&&arguments.length>3){let a=new e(t,n,r);for(let n=3;na&&i>o?t:a>o?n:o>i?r:t}generateNodeType(t){let n=this.method;return n===e.LENGTH||n===e.DISTANCE||n===e.DOT||n===e.DETERMINANT?`float`:n===e.CROSS?`vec3`:n===e.ALL||n===e.ANY?`bool`:n===e.EQUALS?t.changeComponentType(this.aNode.getNodeType(t),`bool`):this.getInputType(t)}setup(t){let{aNode:n,bNode:r,method:i}=this,a=null;if(i===e.ONE_MINUS)a=O_(1,n);else if(i===e.RECIPROCAL)a=A_(1,n);else if(i===e.DIFFERENCE)a=Av(O_(n,r));else if(i===e.TRANSFORM_DIRECTION){let e,i;t.isMatrix(n.getNodeType(t))?(e=n,i=r):(e=r,i=n),a=gv(k_(e,bg(K(i),0)).xyz)}return a===null?super.setup(t):a}generate(t,n){if(t.getNodeProperties(this).outputNode)return super.generate(t,n);let r=this.method,i=this.getNodeType(t),a=this.getInputType(t),o=this.aNode,s=this.bNode,c=this.cNode,l=t.renderer.coordinateSystem;if(r===e.NEGATE)return t.format(`( - `+o.build(t,a)+` )`,i,n);{let u=[];return r===e.CROSS?u.push(o.build(t,i),s.build(t,i)):l===2e3&&r===e.STEP?u.push(o.build(t,t.getTypeLength(o.getNodeType(t))===1?`float`:a),s.build(t,a)):l===2e3&&(r===e.MIN||r===e.MAX)?u.push(o.build(t,a),s.build(t,t.getTypeLength(s.getNodeType(t))===1?t.getComponentType(a):a)):r===e.REFRACT?u.push(o.build(t,a),s.build(t,a),c.build(t,`float`)):r===e.MIX?u.push(o.build(t,a),s.build(t,a),c.build(t,t.getTypeLength(c.getNodeType(t))===1?`float`:a)):(l===2001&&r===e.ATAN&&s!==null&&(r=`atan2`),t.shaderStage!==`fragment`&&(r===e.DFDX||r===e.DFDY)&&(p(`TSL: '${r}' is not supported in the ${t.shaderStage} stage.`,this.stackTrace),r=`/*`+r+`*/`),u.push(o.build(t,a)),s!==null&&u.push(s.build(t,a)),c!==null&&u.push(c.build(t,a))),t.format(`${t.getMethod(r,i)}( ${u.join(`, `)} )`,i,n)}}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}},q.ALL=`all`,q.ANY=`any`,q.RADIANS=`radians`,q.DEGREES=`degrees`,q.EXP=`exp`,q.EXP2=`exp2`,q.LOG=`log`,q.LOG2=`log2`,q.SQRT=`sqrt`,q.INVERSE_SQRT=`inversesqrt`,q.FLOOR=`floor`,q.CEIL=`ceil`,q.NORMALIZE=`normalize`,q.FRACT=`fract`,q.SIN=`sin`,q.SINH=`sinh`,q.COS=`cos`,q.COSH=`cosh`,q.TAN=`tan`,q.TANH=`tanh`,q.ASIN=`asin`,q.ASINH=`asinh`,q.ACOS=`acos`,q.ACOSH=`acosh`,q.ATAN=`atan`,q.ATANH=`atanh`,q.ABS=`abs`,q.SIGN=`sign`,q.LENGTH=`length`,q.NEGATE=`negate`,q.ONE_MINUS=`oneMinus`,q.DFDX=`dFdx`,q.DFDY=`dFdy`,q.ROUND=`round`,q.RECIPROCAL=`reciprocal`,q.TRUNC=`trunc`,q.FWIDTH=`fwidth`,q.TRANSPOSE=`transpose`,q.DETERMINANT=`determinant`,q.INVERSE=`inverse`,q.EQUALS=`equals`,q.MIN=`min`,q.MAX=`max`,q.STEP=`step`,q.REFLECT=`reflect`,q.DISTANCE=`distance`,q.DIFFERENCE=`difference`,q.DOT=`dot`,q.CROSS=`cross`,q.POW=`pow`,q.TRANSFORM_DIRECTION=`transformDirection`,q.MIX=`mix`,q.CLAMP=`clamp`,q.REFRACT=`refract`,q.SMOOTHSTEP=`smoothstep`,q.FACEFORWARD=`faceforward`,Q_=U(1e-6),$_=U(1e6),ev=U(Math.PI),tv=U(Math.PI*2),nv=U(Math.PI*2),rv=U(Math.PI*.5),iv=H(q,q.ALL).setParameterLength(1),av=H(q,q.ANY).setParameterLength(1),ov=H(q,q.RADIANS).setParameterLength(1),sv=H(q,q.DEGREES).setParameterLength(1),cv=H(q,q.EXP).setParameterLength(1),lv=H(q,q.EXP2).setParameterLength(1),uv=H(q,q.LOG).setParameterLength(1),dv=H(q,q.LOG2).setParameterLength(1),fv=H(q,q.SQRT).setParameterLength(1),pv=H(q,q.INVERSE_SQRT).setParameterLength(1),mv=H(q,q.FLOOR).setParameterLength(1),hv=H(q,q.CEIL).setParameterLength(1),gv=H(q,q.NORMALIZE).setParameterLength(1),_v=H(q,q.FRACT).setParameterLength(1),vv=H(q,q.SIN).setParameterLength(1),yv=H(q,q.SINH).setParameterLength(1),bv=H(q,q.COS).setParameterLength(1),xv=H(q,q.COSH).setParameterLength(1),Sv=H(q,q.TAN).setParameterLength(1),Cv=H(q,q.TANH).setParameterLength(1),wv=H(q,q.ASIN).setParameterLength(1),Tv=H(q,q.ASINH).setParameterLength(1),Ev=H(q,q.ACOS).setParameterLength(1),Dv=H(q,q.ACOSH).setParameterLength(1),Ov=H(q,q.ATAN).setParameterLength(1,2),kv=H(q,q.ATANH).setParameterLength(1),Av=H(q,q.ABS).setParameterLength(1),jv=H(q,q.SIGN).setParameterLength(1),Mv=H(q,q.LENGTH).setParameterLength(1),Nv=H(q,q.NEGATE).setParameterLength(1),Pv=H(q,q.ONE_MINUS).setParameterLength(1),Fv=H(q,q.DFDX).setParameterLength(1),Iv=H(q,q.DFDY).setParameterLength(1),Lv=H(q,q.ROUND).setParameterLength(1),Rv=H(q,q.RECIPROCAL).setParameterLength(1),zv=H(q,q.TRUNC).setParameterLength(1),Bv=H(q,q.FWIDTH).setParameterLength(1),Vv=H(q,q.TRANSPOSE).setParameterLength(1),Hv=H(q,q.DETERMINANT).setParameterLength(1),Uv=H(q,q.INVERSE).setParameterLength(1),Wv=H(q,q.MIN).setParameterLength(2,1/0),Gv=H(q,q.MAX).setParameterLength(2,1/0),Kv=H(q,q.STEP).setParameterLength(2),qv=H(q,q.REFLECT).setParameterLength(2),Jv=H(q,q.DISTANCE).setParameterLength(2),Yv=H(q,q.DIFFERENCE).setParameterLength(2),Xv=H(q,q.DOT).setParameterLength(2),Zv=H(q,q.CROSS).setParameterLength(2),Qv=H(q,q.POW).setParameterLength(2),$v=e=>k_(e,e),ey=e=>k_(e,e,e),ty=e=>k_(e,e,e,e),ny=H(q,q.TRANSFORM_DIRECTION).setParameterLength(2),ry=(e,t)=>gv(k_(t,bg(K(e),0)).xyz),iy=(e,t)=>gv(bg(K(e),0).mul(t).xyz),ay=e=>k_(jv(e),Qv(Av(e),1/3)),oy=e=>Xv(e,e),sy=H(q,q.MIX).setParameterLength(3),cy=(e,t=0,n=1)=>new q(q.CLAMP,Qh(e),Qh(t),Qh(n)),ly=e=>cy(e),uy=H(q,q.REFRACT).setParameterLength(3),dy=H(q,q.SMOOTHSTEP).setParameterLength(3),fy=H(q,q.FACEFORWARD).setParameterLength(3),py=V(([e])=>{let t=Xv(e.xy,pg(12.9898,78.233)),n=j_(t,ev);return _v(vv(n).mul(43758.5453))}),my=(e,t,n)=>sy(t,n,e),hy=(e,t,n)=>dy(t,n,e),gy=(e,t)=>Kv(t,e),_y=fy,vy=pv,B(`all`,iv),B(`any`,av),B(`radians`,ov),B(`degrees`,sv),B(`exp`,cv),B(`exp2`,lv),B(`log`,uv),B(`log2`,dv),B(`sqrt`,fv),B(`inverseSqrt`,pv),B(`floor`,mv),B(`ceil`,hv),B(`normalize`,gv),B(`fract`,_v),B(`sin`,vv),B(`sinh`,yv),B(`cos`,bv),B(`cosh`,xv),B(`tan`,Sv),B(`tanh`,Cv),B(`asin`,wv),B(`asinh`,Tv),B(`acos`,Ev),B(`acosh`,Dv),B(`atan`,Ov),B(`atanh`,kv),B(`abs`,Av),B(`sign`,jv),B(`length`,Mv),B(`lengthSq`,oy),B(`negate`,Nv),B(`oneMinus`,Pv),B(`dFdx`,Fv),B(`dFdy`,Iv),B(`round`,Lv),B(`reciprocal`,Rv),B(`trunc`,zv),B(`fwidth`,Bv),B(`min`,Wv),B(`max`,Gv),B(`step`,gy),B(`reflect`,qv),B(`distance`,Jv),B(`dot`,Xv),B(`cross`,Zv),B(`pow`,Qv),B(`pow2`,$v),B(`pow3`,ey),B(`pow4`,ty),B(`transformDirection`,ny),B(`transformNormalByViewMatrix`,ry),B(`transformNormalByInverseViewMatrix`,iy),B(`mix`,my),B(`clamp`,cy),B(`refract`,uy),B(`smoothstep`,hy),B(`faceForward`,fy),B(`difference`,Yv),B(`saturate`,ly),B(`cbrt`,ay),B(`transpose`,Vv),B(`determinant`,Hv),B(`inverse`,Uv),B(`rand`,py),yy=class extends dh{static get type(){return`ConditionalNode`}constructor(e,t,n=null){super(),this.condNode=e,this.ifNode=t,this.elseNode=n}generateNodeType(e){let{ifNode:t,elseNode:n}=e.getNodeProperties(this);if(t===void 0)return e.flowBuildStage(this,`setup`),this.getNodeType(e);let r=t.getNodeType(e);if(n!==null){let t=n.getNodeType(e);if(e.getTypeLength(t)>e.getTypeLength(r))return t}return r}setup(e){let t=this.condNode,n=this.ifNode.isolate(),r=this.elseNode?this.elseNode.isolate():null,i=e.context.nodeBlock;e.getDataFromNode(n).parentNodeBlock=i,r!==null&&(e.getDataFromNode(r).parentNodeBlock=i);let a=e.context.uniformFlow,o=e.getNodeProperties(this);o.condNode=t,o.ifNode=a?n:n.context({nodeBlock:n}),o.elseNode=r?a?r:r.context({nodeBlock:r}):null}generate(e,t){let n=this.getNodeType(e),r=e.getDataFromNode(this);if(r.nodeProperty!==void 0)return r.nodeProperty;let{condNode:i,ifNode:a,elseNode:o}=e.getNodeProperties(this),s=e.currentFunctionNode,c=t!==`void`,l=c?jg(n).build(e):``;r.nodeProperty=l;let u=i.build(e,`bool`);if(e.context.uniformFlow&&o!==null){let r=a.build(e,n),i=o.build(e,n),s=e.getTernary(u,r,i);return e.format(s,n,t)}e.addFlowCode(`\n${e.tab}if ( ${u} ) {\n\n`).addFlowTab();let d=a.build(e,n);if(d&&(c?d=l+` = `+d+`;`:(d=`return `+d+`;`,s===null&&(f(`TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values.`,this.stackTrace),d=`// `+d))),e.removeFlowTab().addFlowCode(e.tab+` `+d+` `+e.tab+`}`),o!==null){e.addFlowCode(` else { `).addFlowTab();let t=o.build(e,n);t&&(c?t=l+` = `+t+`;`:(t=`return `+t+`;`,s===null&&(f(`TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values.`,this.stackTrace),t=`// `+t))),e.removeFlowTab().addFlowCode(e.tab+` `+t+` `+e.tab+`} `)}else e.addFlowCode(` `);return e.format(l,n,t)}},by=ng(yy).setParameterLength(2,3),B(`select`,by),xy=class extends dh{static get type(){return`ContextNode`}constructor(e=null,t={}){super(),this.isContextNode=!0,this.node=e,this.value=t}getScope(){return this.node.getScope()}generateNodeType(e){return this.node.getNodeType(e)}getFlowContextData(){let e=[];return this.traverse(t=>{t.isContextNode===!0&&e.push(t.value)}),Object.assign({},...e)}getMemberType(e,t){return this.node.getMemberType(e,t)}analyze(e){if(e.increaseUsage(this)===1){let t=e.addContext(this.value);this.node.build(e,this),e.setContext(t)}}setup(e){let t=e.addContext(this.value),n=this.node.build(e);return e.setContext(t),n}generate(e,t){let n=e.addContext(this.value),r=this.node.build(e,t);return e.setContext(n),r}},Sy=(e=null,t={})=>{let n=e;return(n===null||n.isNode!==!0)&&(t=n||t,n=null),new xy(n,t)},Cy=e=>Sy(e,{uniformFlow:!0}),wy=(e,t)=>Sy(e,{nodeName:t}),B(`context`,Sy),B(`label`,hp),B(`uniformFlow`,Cy),B(`setName`,wy),B(`builtinShadowContext`,(e,t,n)=>fp(t,n,e)),B(`builtinAOContext`,(e,t)=>pp(t,e)),B(`builtinGIContext`,(e,t,n)=>mp(t,n,e)),Ty=class extends dh{static get type(){return`VarNode`}constructor(e,t=null,n=!1){super(),this.node=e,this.name=t,this.global=!0,this.isVarNode=!0,this.readOnly=n,this.parents=!0,this.intent=!1}setIntent(e){return this.intent=e,this}isIntent(e){return e.getDataFromNode(this).forceDeclaration!==!0&&this.intent}getIntent(){return this.intent}getMemberType(e,t){return this.node.getMemberType(e,t)}getElementType(e){return this.node.getElementType(e)}generateNodeType(e){return this.node.getNodeType(e)}getArrayCount(e){return this.node.getArrayCount(e)}isAssign(e){return e.getDataFromNode(this).assign}build(...e){let t=e[0],n=this.getShared(t);if(this!==n)return n.build(...e);if(this._hasStack(t)===!1&&t.buildStage===`setup`&&(t.context.nodeLoop||t.context.nodeBlock)){let e=!1;if(this.node.isShaderCallNodeInternal&&this.node.shaderNode.getLayout()===null&&t.fnCall&&t.fnCall.shaderNode&&t.getDataFromNode(this.node.shaderNode).hasLoop){let n=t.getDataFromNode(this);n.forceDeclaration=!0,e=!0}let n=t.getBaseStack();e?n.addToStackBefore(this):n.addToStack(this)}return this.isIntent(t)&&this.isAssign(t)!==!0?this.node.build(...e):super.build(...e)}generate(e){let{node:t,name:n,readOnly:r}=this,{renderer:i}=e,a=i.backend.isWebGPUBackend===!0,o=!1,s=!1;r&&(o=e.isDeterministic(t),s=a?r:o);let c=this.getNodeType(e);if(c==`void`)return this.isIntent(e)!==!0&&p(`TSL: ".toVar()" can not be used with void type.`,this.stackTrace),t.build(e);let l=e.getVectorType(c),u=t.build(e,l),d=e.getVarFromNode(this,n,l,void 0,s),f=e.getPropertyName(d),m=f;if(s){if(a)m=o?`const ${f}`:`let ${f}`;else{let n=t.getArrayCount(e);m=`const ${e.getVar(d.type,f,n)}`}}return e.addLineFlowCode(`${m} = ${u}`,this),f}_hasStack(e){return e.getDataFromNode(this).stack!==void 0}},Ey=ng(Ty),Dy=(e,t=null)=>Ey(e,t).toStack(),Oy=(e,t=null)=>Ey(e,t,!0).toStack(),ky=e=>Ey(e).setIntent(!0).toStack(),B(`toVar`,Dy),B(`toConst`,Oy),B(`toVarIntent`,ky),Ay=class extends dh{static get type(){return`SubBuild`}constructor(e,t,n=null){super(n),this.node=e,this.name=t,this.isSubBuildNode=!0}generateNodeType(e){if(this.nodeType!==null)return this.nodeType;e.addSubBuild(this.name);let t=this.node.getNodeType(e);return e.removeSubBuild(),t}build(e,...t){e.addSubBuild(this.name);let n=this.node.build(e,...t);return e.removeSubBuild(),n}},jy=(e,t,n=null)=>new Ay(Qh(e),t,n),My=class extends dh{static get type(){return`VaryingNode`}constructor(e,t=null){super(),this.node=jy(e,`VERTEX`),this.name=t,this.isVaryingNode=!0,this.interpolationType=null,this.interpolationSampling=null,this.global=!0}setInterpolation(e,t=null){return this.interpolationType=e,this.interpolationSampling=t,this}getHash(e){return this.name||super.getHash(e)}generateNodeType(e){return this.node.getNodeType(e)}setupVarying(e){let t=e.getNodeProperties(this),n=t.varying;if(n===void 0){let r=this.name,i=this.getNodeType(e),a=this.interpolationType,o=this.interpolationSampling;t.varying=n=e.getVaryingFromNode(this,r,i,a,o),t.node=jy(this.node,`VERTEX`)}return n.needsInterpolation||(n.needsInterpolation=e.shaderStage===`fragment`),n}setup(e){this.setupVarying(e),e.flowNodeFromShaderStage(th.VERTEX,this.node)}analyze(e){this.setupVarying(e),e.flowNodeFromShaderStage(th.VERTEX,this.node)}generate(e){let t=e.getSubBuildProperty(`property`,e.currentStack),n=e.getNodeProperties(this),r=this.setupVarying(e);if(n[t]===void 0){let i=this.getNodeType(e),a=e.getPropertyName(r,th.VERTEX);if(e.shaderStage===th.VERTEX){let t=n.node.build(e,i);e.addLineFlowCode(`${a} = ${t}`,this)}else e.flowNodeFromShaderStage(th.VERTEX,n.node,i,a);n[t]=a}return e.getPropertyName(r)}},Ny=ng(My).setParameterLength(1,2),Py=e=>Ny(e),B(`toVarying`,Ny),B(`toVertexStage`,Py),Fy=V(([e])=>{let t=e.mul(.9478672986).add(.0521327014).pow(2.4),n=e.mul(.0773993808),r=e.lessThanEqual(.04045);return sy(t,n,r)}).setLayout({name:`sRGBTransferEOTF`,type:`vec3`,inputs:[{name:`color`,type:`vec3`}]}),Iy=V(([e])=>{let t=e.pow(.41666).mul(1.055).sub(.055),n=e.mul(12.92),r=e.lessThanEqual(.0031308);return sy(t,n,r)}).setLayout({name:`sRGBTransferOETF`,type:`vec3`,inputs:[{name:`color`,type:`vec3`}]}),Ly=`WorkingColorSpace`,Ry=`OutputColorSpace`,zy=class extends mh{static get type(){return`ColorSpaceNode`}constructor(e,t,n){super(`vec4`),this.colorNode=e,this.source=t,this.target=n}resolveColorSpace(e,t){return t===Ly?Ci.workingColorSpace:t===Ry?e.context.outputColorSpace||e.renderer.outputColorSpace:t}setup(e){let{colorNode:t}=this,n=this.resolveColorSpace(e,this.source),r=this.resolveColorSpace(e,this.target),i=t;return Ci.enabled===!1||n===r||!n||!r?i:(Ci.getTransfer(n)===`srgb`&&(i=bg(Fy(i.rgb),i.a)),Ci.getPrimaries(n)!==Ci.getPrimaries(r)&&(i=bg(Tg(Ci._getMatrix(new yi,n,r)).mul(i.rgb),i.a)),Ci.getTransfer(r)===`srgb`&&(i=bg(Iy(i.rgb),i.a)),i)}},By=(e,t)=>new zy(Qh(e),Ly,t),Vy=(e,t)=>new zy(Qh(e),t,Ly),Hy=(e,t,n)=>new zy(Qh(e),t,n),B(`workingToColorSpace`,By),B(`colorSpaceToWorking`,Vy),Uy=class extends fh{static get type(){return`ReferenceElementNode`}constructor(e,t){super(e,t),this.referenceNode=e,this.isReferenceElementNode=!0}generateNodeType(){return this.referenceNode.uniformType}generate(e){let t=super.generate(e),n=this.referenceNode.getNodeType(e),r=this.getNodeType(e);return e.format(t,n,r)}},Wy=class extends dh{static get type(){return`ReferenceBaseNode`}constructor(e,t,n=null,r=null){super(),this.property=e,this.uniformType=t,this.object=n,this.count=r,this.properties=e.split(`.`),this.reference=n,this.node=null,this.group=null,this.updateType=nh.OBJECT}setGroup(e){return this.group=e,this}element(e){return new Uy(this,Qh(e))}setNodeType(e){let t=v_(null,e);this.group!==null&&t.setGroup(this.group),this.node=t}generateNodeType(e){return this.node===null&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){let{properties:t}=this,n=e[t[0]];for(let e=1;enew Wy(e,t,n),Ky=class extends Wy{static get type(){return`RendererReferenceNode`}constructor(e,t,n=null){super(e,t,n),this.renderer=n,this.setGroup(h_)}updateReference(e){return this.reference=this.renderer===null?e.renderer:this.renderer,this.reference}},qy=(e,t,n=null)=>new Ky(e,t,n),Jy=class extends mh{static get type(){return`ToneMappingNode`}constructor(e,t=Xy,n=null){super(`vec3`),this._toneMapping=e,this.exposureNode=t,this.colorNode=n}customCacheKey(){return Zm(this._toneMapping)}setToneMapping(e){return this._toneMapping=e,this}getToneMapping(){return this._toneMapping}setup(e){let t=this.colorNode||e.context.color,n=this._toneMapping;if(n===0)return t;let r=null,i=e.renderer.library.getToneMappingFunction(n);return i===null?(p(`ToneMappingNode: Unsupported Tone Mapping configuration.`,n),r=t):r=bg(i(t.rgb,this.exposureNode),t.a),r}},Yy=(e,t,n)=>new Jy(e,Qh(t),Qh(n)),Xy=qy(`toneMappingExposure`,`float`),B(`toneMapping`,(e,t,n)=>Yy(t,n,e)),Zy=new WeakMap,Qy=class extends bh{static get type(){return`BufferAttributeNode`}constructor(e,t=null,n=0,r=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferStride=n,this.bufferOffset=r,this.usage=Ur,this.instanced=!1,this.attribute=null,this.global=!0,e&&e.isBufferAttribute===!0&&e.itemSize<=4&&(this.attribute=e,this.usage=e.usage,this.instanced=e.isInstancedBufferAttribute)}getHash(e){let t;if(this.bufferStride===0&&this.bufferOffset===0){let n=e.globalCache.getData(this.value);n===void 0&&(n={node:this},e.globalCache.setData(this.value,n)),t=n.node.id}else t=this.id;return String(t)}generateNodeType(e){return this.bufferType===null&&(this.bufferType=e.getTypeFromAttribute(this.attribute)),this.bufferType}setup(e){if(this.attribute!==null)return;let t=this.getNodeType(e),n=e.getTypeLength(t),r=this.value,i=this.bufferStride||n,a=this.bufferOffset,o;o=r.isInterleavedBuffer===!0?r:r.isBufferAttribute===!0?gp(r.array,i):gp(r,i);let s=new wo(o,n,a);o.setUsage(this.usage),this.attribute=s,this.attribute.isInstancedBufferAttribute=this.instanced}generate(e){let t=this.getNodeType(e),n=e.context.nodeName;n!==void 0&&delete e.context.nodeName;let r=e.getBufferAttributeFromNode(this,t,n),i=e.getPropertyName(r),a=null;if(e.shaderStage===`vertex`||e.shaderStage===`compute`)this.name=i,a=i;else{let r;n&&(r=n+`Varying`),a=Ny(this,r).build(e,t)}return a}getInputType(){return`bufferAttribute`}setUsage(e){return this.usage=e,this.attribute&&this.attribute.isBufferAttribute===!0&&(this.attribute.usage=e),this}setInstanced(e){return this.instanced=e,this}},$y=(e,t=null,n=0,r=0)=>_p(e,t,n,r),eb=(e,t=null,n=0,r=0)=>_p(e,t,n,r,Wr),tb=(e,t=null,n=0,r=0)=>_p(e,t,n,r,Ur,!0),nb=(e,t=null,n=0,r=0)=>_p(e,t,n,r,Wr,!0),B(`toAttribute`,e=>$y(e.value,e.bufferType)),rb=class e extends dh{static get type(){return`IndexNode`}constructor(e){super(`uint`),this.scope=e,this.isIndexNode=!0}generate(t){let n=this.getNodeType(t),r=this.scope,i;if(r===e.VERTEX)i=t.getVertexIndex();else if(r===e.INSTANCE)i=t.getInstanceIndex();else if(r===e.DRAW)i=t.getDrawIndex();else if(r===e.INVOCATION_LOCAL)i=t.getInvocationLocalIndex();else if(r===e.INVOCATION_SUBGROUP)i=t.getInvocationSubgroupIndex();else if(r===e.SUBGROUP)i=t.getSubgroupIndex();else throw Error(`THREE.IndexNode: Unknown scope: `+r);let a;return a=t.shaderStage===`vertex`||t.shaderStage===`compute`?i:Ny(this).build(t,n),a}},rb.VERTEX=`vertex`,rb.INSTANCE=`instance`,rb.SUBGROUP=`subgroup`,rb.INVOCATION_LOCAL=`invocationLocal`,rb.INVOCATION_SUBGROUP=`invocationSubgroup`,rb.DRAW=`draw`,ib=rg(rb,rb.VERTEX),ab=rg(rb,rb.INSTANCE),ob=rg(rb,rb.SUBGROUP),sb=rg(rb,rb.INVOCATION_SUBGROUP),cb=rg(rb,rb.INVOCATION_LOCAL),lb=rg(rb,rb.DRAW),ub=class extends dh{static get type(){return`ComputeNode`}constructor(e,t){super(`void`),this.isComputeNode=!0,this.computeNode=e,this.workgroupSize=t,this.count=null,this.dispatchSize=null,this.version=1,this.name=``,this.onInitFunction=null,this.countNode=null,this.updateBeforeType=nh.FRAME}setName(e){return this.name=e,this}label(e){return f(`TSL: "label()" has been deprecated. Use "setName()" instead.`,new Jm),this.setName(e)}onInit(e){return this.onInitFunction=e,this}getUpdateBeforeType(e){return e.compute===this?nh.NONE:this.updateBeforeType}updateBefore({renderer:e}){e.compute(this)}setup(e){this.count!==null&&this.countNode===null&&(this.countNode=v_(this.count,`uint`).onObjectUpdate(()=>this.count));let t=this.computeNode.build(e);if(t){let n=e.getNodeProperties(this);n.outputComputeNode=t.outputNode,t.outputNode=null}return t}generate(e,t){let{shaderStage:n}=e;if(n===`compute`){let t=this.computeNode.build(e,`void`);if(t!==``&&e.addLineFlowCode(t,this),this.count!==null&&e.allowEarlyReturns===!0){let t=this.countNode.build(e,`uint`),n=ab.build(e,`uint`);e.flow.code=`${e.tab}if ( ${n} >= ${t} ) { return; }\n\n${e.flow.code}`}}else{let n=e.getNodeProperties(this).outputComputeNode;if(n)return n.build(e,t)}}},db=(e,t=[64])=>{(t.length===0||t.length>3)&&p(`TSL: compute() workgroupSize must have 1, 2, or 3 elements`,new Jm);for(let e=0;e{let r=db(e,n);return typeof t==`number`?r.count=t:r.dispatchSize=t,r},B(`compute`,fb),B(`computeKernel`,db),pb=class extends dh{static get type(){return`IsolateNode`}constructor(e,t=!0){super(),this.node=e,this.parent=t,this.isIsolateNode=!0}generateNodeType(e){let t=e.getCache(),n=e.getCacheFromNode(this,this.parent);e.setCache(n);let r=this.node.getNodeType(e);return e.setCache(t),r}build(e,...t){let n=e.getCache(),r=e.getCacheFromNode(this,this.parent);e.setCache(r);let i=this.node.build(e,...t);return e.setCache(n),i}setParent(e){return this.parent=e,this}getParent(){return this.parent}},mb=e=>new pb(Qh(e)),B(`cache`,vp),B(`isolate`,mb),hb=class extends dh{static get type(){return`BypassNode`}constructor(e,t){super(),this.isBypassNode=!0,this.outputNode=e,this.callNode=t}generateNodeType(e){return this.outputNode.getNodeType(e)}generate(e){let t=this.callNode.build(e,`void`);return t!==``&&e.addLineFlowCode(t,this),this.outputNode.build(e)}},gb=ng(hb).setParameterLength(2),B(`bypass`,gb),_b=V(([e,t,n,r=U(0),i=U(1),a=fg(!1)])=>{let o=e.sub(t).div(n.sub(t));return lp(a)&&(o=o.clamp()),o.mul(i.sub(r)).add(r)}),B(`remap`,_b),B(`remapClamp`,yp),vb=class extends dh{static get type(){return`ExpressionNode`}constructor(e=``,t=`void`){super(t),this.snippet=e}generate(e,t){let n=this.getNodeType(e),r=this.snippet;if(n===`void`)e.addLineFlowCode(r,this);else return e.format(r,n,t)}},yb=ng(vb).setParameterLength(1,2),bb=e=>(e?by(e,yb(`discard`)):yb(`discard`)).toStack(),xb=()=>yb(`return`).toStack(),B(`discard`,bb),Sb=V(([e])=>bg(e.rgb.mul(e.a),e.a),{color:`vec4`,return:`vec4`}),Cb=V(([e])=>e.a.equal(0).select(bg(0),bg(e.rgb.div(e.a),e.a)),{color:`vec4`,return:`vec4`}),wb=class extends mh{static get type(){return`RenderOutputNode`}constructor(e,t,n){super(`vec4`),this.colorNode=e,this._toneMapping=t,this.outputColorSpace=n,this.isRenderOutputNode=!0}setToneMapping(e){return this._toneMapping=e,this}getToneMapping(){return this._toneMapping}setup({context:e}){let t=this.colorNode||e.color;t=bg(t.rgb,t.a.clamp(0,1)),t=Cb(t);let n=(this._toneMapping===null?e.toneMapping:this._toneMapping)||0,r=(this.outputColorSpace===null?e.outputColorSpace:this.outputColorSpace)||``;return n!==0&&(t=t.toneMapping(n)),r!==``&&r!==Ci.workingColorSpace&&(t=t.workingToColorSpace(r)),t=Sb(t),t}},Tb=(e,t=null,n=null)=>new wb(Qh(e),t,n),B(`renderOutput`,Tb),Eb=class extends mh{static get type(){return`DebugNode`}constructor(e,t=null){super(),this.node=e,this.callback=t}generateNodeType(e){return this.node.getNodeType(e)}setup(e){return this.node.build(e)}analyze(e){return this.node.build(e)}generate(e){let t=this.callback,n=this.node.build(e);if(t!==null)t(e,n);else{let t=`--- TSL debug - `+e.shaderStage+` shader ---`,r=`-`.repeat(t.length),i=``;i+=`// #`+t+`# `,i+=e.flow.code.replace(/^\t/gm,``)+` `,i+=`/* ... */ `+n+` /* ... */ `,i+=`// #`+r+`# `,u(i)}return n}},Db=(e,t=null)=>new Eb(Qh(e),t).toStack(),B(`debug`,Db),Ob=class extends ui{constructor(){super(),this._renderer=null,this.currentFrame=null,this.isRunning=!1,this.enabled=!0}get nodeFrame(){return this._renderer._nodes.nodeFrame}setRenderer(e){return this._renderer=e,this}getRenderer(){return this._renderer}begin(){this.isRunning=!0}finish(){this.isRunning=!1}inspect(){}computeAsync(){}beginCompute(){}finishCompute(){}beginRender(){}finishRender(){}copyTextureToTexture(){}copyFramebufferToTexture(){}dispose(){this.isRunning===!0&&this.finish(),this.dispatchEvent({type:`dispose`})}},kb=class extends dh{static get type(){return`InspectorNode`}constructor(e,t=``,n=null){super(),this.node=e,this.name=t,this.callback=n,this.updateType=nh.FRAME,this.isInspectorNode=!0}getName(){return this.name||this.node.name}update(e){e.renderer.inspector.inspect(this)}generateNodeType(e){return this.node.getNodeType(e)}setup(e){let t=this.node;return e.context.inspector===!0&&this.callback!==null&&(t=this.callback(t)),e.renderer.backend.isWebGPUBackend!==!0&&e.renderer.inspector.constructor!==Ob&&m(`TSL: ".toInspector()" is only available with WebGPU.`),t}},B(`toInspector`,bp),Ab=class extends dh{static get type(){return`AttributeNode`}constructor(e,t=null){super(t),this.global=!0,this._attributeName=e}getHash(e){return this.getAttributeName(e)}generateNodeType(e){let t=this.nodeType;if(t===null){let n=this.getAttributeName(e);if(e.hasGeometryAttribute(n)){let r=e.geometry.getAttribute(n);t=e.getTypeFromAttribute(r)}else t=`float`}return t}setAttributeName(e){return this._attributeName=e,this}getAttributeName(){return this._attributeName}generate(e){let t=this.getAttributeName(e),n=this.getNodeType(e);if(e.hasGeometryAttribute(t)===!0){let r=e.geometry.getAttribute(t),i=e.getTypeFromAttribute(r),a=e.getAttribute(t,i);return e.shaderStage===`vertex`?e.format(a.name,i,n):Ny(this).build(e,n)}return f(`AttributeNode: Vertex attribute "${t}" not found on geometry.`),e.generateConst(n)}serialize(e){super.serialize(e),e.global=this.global,e._attributeName=this._attributeName}deserialize(e){super.deserialize(e),this.global=e.global,this._attributeName=e._attributeName}},jb=(e,t=null)=>new Ab(e,t),Mb=(e=0)=>jb(`uv`+(e>0?e:``),`vec2`),Nb=class extends dh{static get type(){return`TextureSizeNode`}constructor(e,t=null){super(`uvec2`),this.isTextureSizeNode=!0,this.textureNode=e,this.levelNode=t}generate(e){let t=this.textureNode.build(e,`property`),n=this.levelNode===null?`0`:this.levelNode.build(e,`int`),r=e.generateTextureSize(this.textureNode.value,t,n);return e.format(r,this.getNodeType(e))}},Pb=ng(Nb).setParameterLength(1,2),Fb=class extends __{static get type(){return`MaxMipLevelNode`}constructor(e){super(0),this._textureNode=e,this.updateType=nh.FRAME}get textureNode(){return this._textureNode}get texture(){return this._textureNode.value}update(){let e=this.texture,t=e.images,n=t&&t.length>0?t[0]&&t[0].image||t[0]:e.image;if(n&&n.width!==void 0){let{width:e,height:t}=n;this.value=Math.log2(Math.max(e,t))}}},Ib=ng(Fb).setParameterLength(1),Lb=class extends Error{constructor(e,t=null){super(e),this.name=`NodeError`,this.stackTrace=t}},Rb=new ji,zb=class extends __{static get type(){return`TextureNode`}constructor(e=Rb,t=null,n=null,r=null){super(e),this.isTextureNode=!0,this.uvNode=t,this.levelNode=n,this.biasNode=r,this.compareNode=null,this.depthNode=null,this.gradNode=null,this.gatherNode=null,this.offsetNode=null,this.sampler=!0,this.updateMatrix=!1,this.updateType=nh.NONE,this.referenceNode=null,this._value=e,this._matrixUniform=null,this._flipYUniform=null,this._samplerComparison=!1,this.setUpdateMatrix(t===null)}set value(e){this.referenceNode?this.referenceNode.value=e:this._value=e}get value(){return this.referenceNode?this.referenceNode.value:this._value}getUniformHash(){return this.value.uuid}generateNodeType(){return this.gatherNode===null?ep(this.value):`vec4`}getInputType(){return`texture`}getDefaultUV(){return Mb(this.value.channel)}updateReference(){return this.value}getTransformedUV(e){return this._matrixUniform===null&&(this._matrixUniform=v_(this.value.matrix)),this._matrixUniform.mul(K(e,1)).xy}setUpdateMatrix(e){return this.updateMatrix=e,this}setupUV(e,t){return e.isFlipY()&&(this._flipYUniform===null&&(this._flipYUniform=v_(!1)),t=t.toVar(),t=this.sampler?this._flipYUniform.select(t.flipY(),t):this._flipYUniform.select(t.setY(W(Pb(this,this.levelNode).y).sub(t.y).sub(1)),t)),t}setup(e){let t=e.getNodeProperties(this);t.referenceNode=this.referenceNode;let n=this.value;if(!n||n.isTexture!==!0)throw new Lb("THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().",this.stackTrace);let r=V(()=>{let t=this.uvNode;return(t===null||e.context.forceUVContext===!0)&&e.context.getUV&&(t=e.context.getUV(this,e)),t||=this.getDefaultUV(),this.updateMatrix===!0&&(t=this.getTransformedUV(t)),t=this.setupUV(e,t),this.updateType=this._matrixUniform!==null||this._flipYUniform!==null?nh.OBJECT:nh.NONE,t})(),i=this.levelNode;i===null&&e.context.getTextureLevel&&(i=e.context.getTextureLevel(this));let a=null,o=null;if(this.compareNode!==null){if(e.renderer.hasCompatibility(ii.TEXTURE_COMPARE))a=this.compareNode;else{let e=n.compareFunction;e===null||e===513||e===515||e===516||e===518?o=this.compareNode:(a=this.compareNode,m(`TSL: Only "LessCompare", "LessEqualCompare", "GreaterCompare" and "GreaterEqualCompare" are supported for depth texture comparison fallback.`))}}t.uvNode=r,t.levelNode=i,t.biasNode=this.biasNode,t.compareNode=a,t.compareStepNode=o,t.gradNode=this.gradNode,t.gatherNode=this.gatherNode,t.depthNode=this.depthNode,t.offsetNode=this.offsetNode}generateUV(e,t){return t.build(e,this.sampler===!0?`vec2`:`ivec2`)}generateOffset(e,t){return t.build(e,`ivec2`)}generateSnippet(e,t,n,r,i,a,o,s,c,l,u){let d=this.value,f;return f=i?e.generateTextureBias(d,t,n,i,a,l):s?e.generateTextureGrad(d,t,n,s,a,l):c?o?e.generateTextureGatherCompare(d,t,n,o,a,l,u):e.generateTextureGather(d,t,n,c,a,l,u):o?e.generateTextureCompare(d,t,n,o,a,l):this.sampler===!1?e.generateTextureLoad(d,t,n,r,a,l):r?e.generateTextureLevel(d,t,n,r,a,l):e.generateTexture(d,t,n,a,l),f}generate(e,t){let n=this.value,r=e.getNodeProperties(this),i=super.generate(e,`property`);if(/^sampler/.test(t)){if(t===`samplerComparison`){this._samplerComparison=!0;let t=this.getSharedNode(e);t._samplerComparison=!0}return i+`_sampler`}if(e.isReference(t))return i;{let a=e.getDataFromNode(this),o=this.getNodeType(e),s=a.propertyName;if(s===void 0){let{uvNode:t,levelNode:c,biasNode:l,compareNode:u,compareStepNode:d,depthNode:f,gradNode:p,gatherNode:m,offsetNode:h}=r,g=this.generateUV(e,t),_=c?c.build(e,`float`):null,v=l?l.build(e,`float`):null,y=f?f.build(e,`int`):null,b=u?u.build(e,`float`):null,x=d?d.build(e,`float`):null,S=p?[p[0].build(e,`vec2`),p[1].build(e,`vec2`)]:null,C=m?m.build(e,`int`):null,w=h?this.generateOffset(e,h):null,T=this._flipYUniform?this._flipYUniform.build(e,`bool`):null,E=y;E===null&&n.isArrayTexture&&this.isTexture3DNode!==!0&&(E=`0`);let D=e.getVarFromNode(this);s=e.getPropertyName(D);let ee=this.generateSnippet(e,i,g,_,v,E,b,S,C,w,T),O;if(O=n.isDepthTexture===!0&&C===null?`float`:n.type===1014?`uvec4`:n.type===1013?`ivec4`:`vec4`,ee=e.format(ee,O,o),x!==null){let t=n.compareFunction;ee=t===516||t===518?Kv(yb(ee,o),yb(x,`float`)).build(e,o):Kv(yb(x,`float`),yb(ee,o)).build(e,o)}e.addLineFlowCode(`${s} = ${ee}`,this),a.snippet=ee,a.propertyName=s}let c=s;return e.needsToWorkingColorSpace(n)&&(c=Vy(yb(c,o),n.colorSpace).setup(e).build(e,o)),e.format(c,o,t)}}setSampler(e){return this.sampler=e,this}getSampler(){return this.sampler}sample(e){let t=this.clone();return t.uvNode=Qh(e),t.referenceNode=this.getBase(),Qh(t)}load(e){return this.sample(e).setSampler(!1)}blur(e){let t=this.clone();t.biasNode=Qh(e).mul(Ib(t)),t.referenceNode=this.getBase();let n=t.value;return t.generateMipmaps===!1&&(n&&n.generateMipmaps===!1||n.minFilter===1003||n.magFilter===1003)&&(f(`TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture.`),t.biasNode=null),Qh(t)}level(e){let t=this.clone();return t.levelNode=Qh(e),t.referenceNode=this.getBase(),Qh(t)}size(e){return Pb(this,e)}bias(e){let t=this.clone();return t.biasNode=Qh(e),t.referenceNode=this.getBase(),Qh(t)}getBase(){return this.referenceNode?this.referenceNode.getBase():this}compare(e){let t=this.clone();return t.compareNode=Qh(e),t.referenceNode=this.getBase(),Qh(t)}grad(e,t){let n=this.clone();return n.gradNode=[Qh(e),Qh(t)],n.referenceNode=this.getBase(),Qh(n)}gather(e=0){let t=this.clone();return t.gatherNode=Qh(e),t.referenceNode=this.getBase(),Qh(t)}isSampleCompare(){return this.compareNode!==null||this._samplerComparison===!0}depth(e){let t=this.clone();return t.depthNode=Qh(e),t.referenceNode=this.getBase(),Qh(t)}offset(e){let t=this.clone();return t.offsetNode=Qh(e),t.referenceNode=this.getBase(),Qh(t)}serialize(e){super.serialize(e),e.value=this.value.toJSON(e.meta).uuid,e.sampler=this.sampler,e.updateMatrix=this.updateMatrix,e.updateType=this.updateType}deserialize(e){super.deserialize(e),this.value=e.meta.textures[e.value],this.sampler=e.sampler,this.updateMatrix=e.updateMatrix,this.updateType=e.updateType}update(){let e=this.value,t=this._matrixUniform;t!==null&&(t.value=e.matrix),e.matrixAutoUpdate===!0&&e.updateMatrix();let n=this._flipYUniform;n!==null&&(n.value=e.image instanceof ImageBitmap&&e.flipY===!0||e.isRenderTargetTexture===!0||e.isFramebufferTexture===!0||e.isDepthTexture===!0)}clone(){let e=new this.constructor(this.value,this.uvNode,this.levelNode,this.biasNode);return e.sampler=this.sampler,e.depthNode=this.depthNode,e.compareNode=this.compareNode,e.gradNode=this.gradNode,e.gatherNode=this.gatherNode,e.offsetNode=this.offsetNode,e}},Bb=ng(zb).setParameterLength(1,4).setName(`texture`),Vb=(e=Rb,t=null,n=null,r=null)=>{let i;return e&&e.isTextureNode===!0?(i=Qh(e.clone()),i.referenceNode=e.getBase(),t!==null&&(i.uvNode=Qh(t)),n!==null&&(i.levelNode=Qh(n)),r!==null&&(i.biasNode=Qh(r))):i=Bb(e,t,n,r),i},Hb=(e=Rb)=>Vb(e),Ub=(...e)=>Vb(...e).setSampler(!1),Wb=(e,t,n)=>Vb(e,t).level(n),Gb=e=>(e.isNode===!0?e:Vb(e)).convert(`sampler`),Kb=e=>(e.isNode===!0?e:Vb(e)).convert(`samplerComparison`),qb=class extends __{static get type(){return`BufferNode`}constructor(e,t,n=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferCount=n,this.updateRanges=[]}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}getElementType(e){return this.getNodeType(e)}getInputType(){return`buffer`}},Jb=(e,t,n)=>new qb(e,t,n),Yb=class extends fh{static get type(){return`UniformArrayElementNode`}constructor(e,t){super(e,t),this.isArrayBufferElementNode=!0}generate(e){let t=super.generate(e),n=this.getNodeType(e),r=this.node.getPaddedType();return e.format(t,r,n)}},Xb=class extends qb{static get type(){return`UniformArrayNode`}constructor(e,t=null){super(null),this.array=e,this.elementType=t===null?$f(e[0]):t,this.paddedType=this.getPaddedType(),this.updateType=nh.RENDER,this.isArrayBufferNode=!0}generateNodeType(){return this.paddedType}getElementType(){return this.elementType}getPaddedType(){let e=this.elementType,t=`vec4`;return e===`mat2`?t=`mat2`:/mat/.test(e)===!0?t=`mat4`:e.charAt(0)===`i`?t=`ivec4`:e.charAt(0)===`u`&&(t=`uvec4`),t}update(){this.updateBuffer()}onUpdate(e,t){return e=e.bind(this),super.onUpdate((t,n)=>{e(t,n),this.updateBuffer()},t)}updateBuffer(){let{array:e,value:t}=this,n=this.elementType;if(n===`float`||n===`int`||n===`uint`)for(let n=0;nnew Xb(e,t),Qb=class extends dh{constructor(e){super(`float`),this.name=e,this.isBuiltinNode=!0}generate(){return this.name}},$b=ng(Qb).setParameterLength(1),nx=class e extends dh{static get type(){return`ScreenNode`}constructor(e){super(),this.scope=e,this.isViewportNode=!0}generateNodeType(){return this.scope===e.VIEWPORT?`vec4`:`vec2`}update({renderer:t}){let n=t.getRenderTarget();this.scope===e.VIEWPORT?n===null?(t.getViewport(tx),tx.multiplyScalar(t.getPixelRatio())):tx.copy(n.viewport):n===null?t.getDrawingBufferSize(ex):(ex.width=n.width,ex.height=n.height)}setup(){let t=this.scope,n=null;n=t===e.SIZE?v_(ex||=new N).setGroup(h_):t===e.VIEWPORT?v_(tx||=new Mi).setGroup(h_):pg(ox.div(ax));let r=nh.NONE;return(this.scope===e.SIZE||this.scope===e.VIEWPORT)&&(r=nh.RENDER),this.updateType=r,n}generate(t){if(this.scope===e.COORDINATE){let e=t.getFragCoord();if(t.isFlipY()){let n=t.getNodeProperties(ax).outputNode.build(t);e=`${t.getType(`vec2`)}( ${e}.x, ${n}.y - ${e}.y )`}return e}return super.generate(t)}},nx.COORDINATE=`coordinate`,nx.VIEWPORT=`viewport`,nx.SIZE=`size`,nx.UV=`uv`,rx=v_(1).setGroup(h_).onRenderUpdate(({renderer:e})=>e.getPixelRatio()),ix=rg(nx,nx.UV),ax=rg(nx,nx.SIZE),ox=rg(nx,nx.COORDINATE),sx=rg(nx,nx.VIEWPORT),cx=sx.zw,lx=ox.sub(sx.xy),ux=lx.div(cx),dx=null,fx=null,px=null,mx=null,hx=null,gx=null,_x=null,vx=null,yx=null,bx=null,xx=null,Sx=null,Cx=null,wx=null,Tx=v_(0,`uint`).setName(`u_cameraIndex`).setGroup(p_(`cameraIndex`)).toVarying(`v_cameraIndex`),Ex=v_(`float`).setName(`cameraNear`).setGroup(h_).onRenderUpdate(({camera:e})=>e.near),Dx=v_(`float`).setName(`cameraFar`).setGroup(h_).onRenderUpdate(({camera:e})=>e.far),Ox=V(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){let n=[];for(let t of e.cameras)n.push(t.projectionMatrix);fx===null?fx=Zb(n).setGroup(h_).setName(`cameraProjectionMatrices`):fx.array=n,t=fx.element(e.isMultiViewCamera?$b(`gl_ViewID_OVR`):Tx)}else dx===null&&(dx=v_(e.projectionMatrix).setName(`cameraProjectionMatrix`).setGroup(h_).onRenderUpdate(({camera:e})=>e.projectionMatrix)),t=dx;return t}).once()(),kx=V(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){let n=[];for(let t of e.cameras)n.push(t.projectionMatrixInverse);mx===null?mx=Zb(n).setGroup(h_).setName(`cameraProjectionMatricesInverse`):mx.array=n,t=mx.element(e.isMultiViewCamera?$b(`gl_ViewID_OVR`):Tx)}else px===null&&(px=v_(e.projectionMatrixInverse).setName(`cameraProjectionMatrixInverse`).setGroup(h_).onRenderUpdate(({camera:e})=>e.projectionMatrixInverse)),t=px;return t}).once()(),Ax=V(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){let n=[];for(let t of e.cameras)n.push(t.matrixWorldInverse);gx===null?gx=Zb(n).setGroup(h_).setName(`cameraViewMatrices`):gx.array=n,t=gx.element(e.isMultiViewCamera?$b(`gl_ViewID_OVR`):Tx)}else hx===null&&(hx=v_(e.matrixWorldInverse).setName(`cameraViewMatrix`).setGroup(h_).onRenderUpdate(({camera:e})=>e.matrixWorldInverse)),t=hx;return t}).once()(),jx=V(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){let n=[];for(let t of e.cameras)n.push(t.matrixWorld);vx===null?vx=Zb(n).setGroup(h_).setName(`cameraWorldMatrices`):vx.array=n,t=vx.element(e.isMultiViewCamera?$b(`gl_ViewID_OVR`):Tx)}else _x===null&&(_x=v_(e.matrixWorld).setName(`cameraWorldMatrix`).setGroup(h_).onRenderUpdate(({camera:e})=>e.matrixWorld)),t=_x;return t}).once()(),Mx=V(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){let n=[];for(let t of e.cameras)n.push(t.normalMatrix);bx===null?bx=Zb(n).setGroup(h_).setName(`cameraNormalMatrices`):bx.array=n,t=bx.element(e.isMultiViewCamera?$b(`gl_ViewID_OVR`):Tx)}else yx===null&&(yx=v_(e.normalMatrix).setName(`cameraNormalMatrix`).setGroup(h_).onRenderUpdate(({camera:e})=>e.normalMatrix)),t=yx;return t}).once()(),Nx=V(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){let n=[];for(let t=0,r=e.cameras.length;t{let n=e.cameras,r=t.array;for(let e=0,t=n.length;et.value.setFromMatrixPosition(e.matrixWorld))),t=xx;return t}).once()(),Px=V(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){let n=[];for(let t of e.cameras)n.push(t.viewport);wx===null?wx=Zb(n,`vec4`).setGroup(h_).setName(`cameraViewports`):wx.array=n,t=wx.element(Tx)}else Cx===null&&(Cx=bg(0,0,ax.x,ax.y).toConst(`cameraViewport`)),t=Cx;return t}).once()(),Fx=new po,Ix=class e extends dh{static get type(){return`Object3DNode`}constructor(e,t=null){super(),this.scope=e,this.object3d=t,this.updateType=nh.OBJECT,this.uniformNode=new __(null)}generateNodeType(){let t=this.scope;if(t===e.WORLD_MATRIX)return`mat4`;if(t===e.POSITION||t===e.VIEW_POSITION||t===e.DIRECTION||t===e.SCALE)return`vec3`;if(t===e.RADIUS)return`float`}update(t){let n=this.object3d,r=this.uniformNode,i=this.scope;if(i===e.WORLD_MATRIX)r.value=n.matrixWorld;else if(i===e.POSITION)r.value=r.value||new P,r.value.setFromMatrixPosition(n.matrixWorld);else if(i===e.SCALE)r.value=r.value||new P,r.value.setFromMatrixScale(n.matrixWorld);else if(i===e.DIRECTION)r.value=r.value||new P,n.getWorldDirection(r.value);else if(i===e.VIEW_POSITION){let e=t.camera;r.value=r.value||new P,r.value.setFromMatrixPosition(n.matrixWorld),r.value.applyMatrix4(e.matrixWorldInverse)}else if(i===e.RADIUS){let e=t.object.geometry;e.boundingSphere===null&&e.computeBoundingSphere(),Fx.copy(e.boundingSphere).applyMatrix4(n.matrixWorld),r.value=Fx.radius}}generate(t){let n=this.scope;return n===e.WORLD_MATRIX?this.uniformNode.nodeType=`mat4`:n===e.POSITION||n===e.VIEW_POSITION||n===e.DIRECTION||n===e.SCALE?this.uniformNode.nodeType=`vec3`:n===e.RADIUS&&(this.uniformNode.nodeType=`float`),this.uniformNode.build(t)}serialize(e){super.serialize(e),e.scope=this.scope}deserialize(e){super.deserialize(e),this.scope=e.scope}},Ix.WORLD_MATRIX=`worldMatrix`,Ix.POSITION=`position`,Ix.SCALE=`scale`,Ix.VIEW_POSITION=`viewPosition`,Ix.DIRECTION=`direction`,Ix.RADIUS=`radius`,Lx=ng(Ix,Ix.DIRECTION).setParameterLength(1),Rx=ng(Ix,Ix.WORLD_MATRIX).setParameterLength(1),zx=ng(Ix,Ix.POSITION).setParameterLength(1),Bx=ng(Ix,Ix.SCALE).setParameterLength(1),Vx=ng(Ix,Ix.VIEW_POSITION).setParameterLength(1),Hx=ng(Ix,Ix.RADIUS).setParameterLength(1),Ux=new F,Wx=class extends Ix{static get type(){return`ModelNode`}constructor(e){super(e)}update(e){this.object3d=e.object,super.update(e)}},Gx=rg(Wx,Wx.DIRECTION),Kx=rg(Wx,Wx.WORLD_MATRIX),qx=rg(Wx,Wx.POSITION),Jx=rg(Wx,Wx.SCALE),Yx=rg(Wx,Wx.VIEW_POSITION),Xx=rg(Wx,Wx.RADIUS),Zx=v_(new yi).onObjectUpdate(({object:e},t)=>t.value.getNormalMatrix(e.matrixWorld)),Qx=v_(new F).onObjectUpdate(({object:e},t)=>t.value.copy(e.matrixWorld).invert()),$x=V(e=>e.context.modelViewMatrix||eS).once()().toVar(`modelViewMatrix`),eS=Ax.mul(Kx),tS=V(e=>{e.context.isHighPrecisionModelViewMatrix=!0;let t=e.camera,n;if(t.isArrayCamera&&t.cameras.length>0){let e=[];for(let n=0;n{let r=t.cameras,i=n.array;for(let t=0,n=r.length;te.modelViewMatrix.multiplyMatrices(t.matrixWorldInverse,e.matrixWorld));return n}).once()().toVar(`highpModelViewMatrix`),nS=V(e=>{let t=e.context.isHighPrecisionModelViewMatrix,n=e.camera,r;if(n.isArrayCamera&&n.cameras.length>0){let e=[];for(let t=0;t{let r=t.cameras,i=n.array;for(let t=0,n=r.length;t(t!==!0&&e.modelViewMatrix.multiplyMatrices(n.matrixWorldInverse,e.matrixWorld),e.normalMatrix.getNormalMatrix(e.modelViewMatrix)));return r}).once()().toVar(`highpModelNormalViewMatrix`),rS=V(e=>e.shaderStage===`fragment`?e.context.clipSpace.toVarying(`v_clipSpace`):(m("TSL: `clipSpace` is only available in fragment stage."),bg())).once()(),iS=jb(`position`,`vec3`),aS=iS.toVarying(`positionLocal`),oS=iS.toVarying(`positionPrevious`),sS=V(e=>Kx.mul(aS).xyz.toVarying(e.getSubBuildProperty(`v_positionWorld`)),`vec3`).once([`POSITION`])(),cS=V(()=>aS.transformDirection(Kx).toVarying(`v_positionWorldDirection`).normalize().toVar(`positionWorldDirection`),`vec3`).once([`POSITION`])(),lS=V(e=>{if(e.shaderStage===`fragment`&&e.material.vertexNode){let e=kx.mul(rS);return e.xyz.div(e.w).toVar(`positionView`)}return e.context.setupPositionView().toVarying(`v_positionView`)},`vec3`).once([`POSITION`,`VERTEX`])(),uS=V(e=>{let t;return t=e.camera.isOrthographicCamera?K(0,0,1):lS.negate().toVarying(`v_positionViewDirection`).normalize(),t.toVar(`positionViewDirection`)},`vec3`).once([`POSITION`])(),dS=class extends dh{static get type(){return`FrontFacingNode`}constructor(){super(`bool`),this.isFrontFacingNode=!0}generate(e){if(e.shaderStage!==`fragment`)return`true`;let{material:t}=e;return t.side===1?`false`:e.getFrontFacing()}},fS=rg(dS),pS=U(fS).mul(2).sub(1),mS=V(([e],{material:t})=>{let n=t.side;return n===1?e=e.mul(-1):n===2&&(e=e.mul(pS)),e}),hS=e=>(m(`TSL: "directionToFaceDirection()" has been renamed to "negateOnBackSide()".`),mS(e)),gS=jb(`normal`,`vec3`),_S=V(e=>e.geometry.hasAttribute(`normal`)===!1?(f(`TSL: Vertex attribute "normal" not found on geometry.`),K(0,1,0)):gS,`vec3`).once()().toVar(`normalLocal`),vS=lS.dFdx().cross(lS.dFdy()).normalize().toVar(`normalFlat`),yS=V(e=>{let t;return t=e.isFlatShading()?vS:TS(_S).toVarying(`v_normalViewGeometry`).normalize(),t},`vec3`).once()().toVar(`normalViewGeometry`),bS=V(e=>{let t=yS.transformNormalByInverseViewMatrix(Ax);return e.isFlatShading()!==!0&&(t=t.toVarying(`v_normalWorldGeometry`)),t.normalize().toVar(`normalWorldGeometry`)},`vec3`).once()(),xS=V(e=>{let t;return e.subBuildFn===`NORMAL`||e.subBuildFn===`VERTEX`?(t=yS,e.isFlatShading()!==!0&&(t=mS(t))):t=e.context.setupNormal().context({getUV:null,getTextureLevel:null}),t},`vec3`).once([`NORMAL`,`VERTEX`])().toVar(`normalView`),SS=xS.transformNormalByInverseViewMatrix(Ax).toVar(`normalWorld`),CS=V(({subBuildFn:e,context:t})=>{let n;return n=e===`NORMAL`||e===`VERTEX`?xS:t.setupClearcoatNormal().context({getUV:null,getTextureLevel:null}),n},`vec3`).once([`NORMAL`,`VERTEX`])().toVar(`clearcoatNormalView`),wS=V(([e,t=Kx])=>Tg(t).inverse().transpose().mul(e).normalize()),B(`transformNormal`,wS),TS=V(([e],t)=>{let n=t.context.modelNormalViewMatrix;return n?e.transformNormalByViewMatrix(n):Zx.mul(e).transformNormalByViewMatrix(Ax)}),ES=V(()=>(f(`TSL: "transformedNormalView" is deprecated. Use "normalView" instead.`),xS)).once([`NORMAL`,`VERTEX`])(),DS=V(()=>(f(`TSL: "transformedNormalWorld" is deprecated. Use "normalWorld" instead.`),SS)).once([`NORMAL`,`VERTEX`])(),OS=V(()=>(f(`TSL: "transformedClearcoatNormalView" is deprecated. Use "clearcoatNormalView" instead.`),CS)).once([`NORMAL`,`VERTEX`])(),kS=new F,AS=v_(0).onReference(({material:e})=>e).onObjectUpdate(({material:e})=>e.refractionRatio),jS=v_(1).onReference(({material:e})=>e).onObjectUpdate(function({material:e,scene:t}){return e.envMap?e.envMapIntensity:t.environmentIntensity}),MS=v_(new F).onReference(function(e){return e.material}).onObjectUpdate(function({material:e,scene:t}){let n=(t.environment!==null||t.environmentNode&&t.environmentNode.isNode)&&e.envMap===null?t.environmentRotation:e.envMapRotation;return n?kS.makeRotationFromEuler(n).transpose():kS.identity(),kS}),NS=uS.negate().reflect(xS),PS=uS.negate().refract(xS,AS),FS=NS.transformDirection(jx).toVar(`reflectVector`),IS=PS.transformDirection(jx).toVar(`refractVector`),LS=new Dc,RS=class extends zb{static get type(){return`CubeTextureNode`}constructor(e,t=null,n=null,r=null){super(e,t,n,r),this.isCubeTextureNode=!0}getInputType(){return this.value.isDepthTexture===!0?`cubeDepthTexture`:`cubeTexture`}getDefaultUV(){let e=this.value;return e.mapping===301?FS:e.mapping===302?IS:(p(`CubeTextureNode: Mapping "%s" not supported.`,e.mapping),K(0,0,0))}setUpdateMatrix(){}setupUV(e,t){let n=this.value;return n.isDepthTexture===!0?e.renderer.coordinateSystem===2001?K(t.x,t.y.negate(),t.z):t:(t=MS.mul(t),(e.renderer.coordinateSystem===2001||!n.isRenderTargetTexture)&&(t=K(t.x.negate(),t.yz)),t)}generateUV(e,t){return t.build(e,this.sampler===!0?`vec3`:`ivec3`)}},zS=ng(RS).setParameterLength(1,4).setName(`cubeTexture`),BS=(e=LS,t=null,n=null,r=null)=>{let i;return e&&e.isCubeTextureNode===!0?(i=Qh(e.clone()),i.referenceNode=e,t!==null&&(i.uvNode=Qh(t)),n!==null&&(i.levelNode=Qh(n)),r!==null&&(i.biasNode=Qh(r))):i=zS(e,t,n,r),i},VS=(e=LS)=>zS(e),HS=class extends dh{static get type(){return`ReferenceNode`}constructor(e,t,n=null,r=null){super(),this.property=e,this.uniformType=t,this.object=n,this.count=r,this.properties=e.split(`.`),this.reference=n,this.node=null,this.group=null,this.name=null,this.updateType=nh.OBJECT}element(e){return new Uy(this,Qh(e))}setGroup(e){return this.group=e,this}setName(e){return this.name=e,this}label(e){return f(`TSL: "label()" has been deprecated. Use "setName()" instead.`),this.setName(e)}setNodeType(e){let t=null;this.count===null?Array.isArray(this.getValueFromReference())?(t=Zb(null,e),t.updateType=nh.OBJECT):t=e===`texture`?Vb(null):e===`cubeTexture`?BS(null):v_(null,e):t=Jb(null,e,this.count),this.group!==null&&t.setGroup(this.group),this.name!==null&&t.setName(this.name),this.node=t}generateNodeType(e){return this.node===null&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){let{properties:t}=this,n=e[t[0]];for(let e=1;enew HS(e,t,n),WS=(e,t,n,r)=>new HS(e,t,r,n),GS=class extends HS{static get type(){return`MaterialReferenceNode`}constructor(e,t,n=null){super(e,t,n),this.material=n,this.isMaterialReferenceNode=!0}updateReference(e){return this.reference=this.material===null?e.material:this.material,this.reference}},KS=(e,t,n=null)=>new GS(e,t,n),qS=Mb(),JS=lS.dFdx(),YS=lS.dFdy(),XS=qS.dFdx(),ZS=qS.dFdy(),QS=xS,$S=YS.cross(QS),eC=QS.cross(JS),tC=$S.mul(XS.x).add(eC.mul(ZS.x)),nC=$S.mul(XS.y).add(eC.mul(ZS.y)),rC=tC.dot(tC).max(nC.dot(nC)),iC=rC.equal(0).select(0,rC.inverseSqrt()),aC=tC.mul(iC).toVar(`tangentViewFrame`),oC=nC.mul(iC).toVar(`bitangentViewFrame`),sC=jb(`tangent`,`vec4`),cC=sC.xyz.toVar(`tangentLocal`),lC=V(e=>{let t;return t=e.subBuildFn===`VERTEX`||e.geometry.hasAttribute(`tangent`)?$x.mul(bg(cC,0)).xyz.toVarying(`v_tangentView`).normalize():aC,e.isFlatShading()!==!0&&(t=mS(t)),t},`vec3`).once([`NORMAL`,`VERTEX`])().toVar(`tangentView`),uC=lC.transformDirection(jx).toVarying(`v_tangentWorld`).normalize().toVar(`tangentWorld`),dC=V(([e,t],n)=>{let r=e.mul(sC.w).xyz;return n.subBuildFn===`NORMAL`&&n.isFlatShading()!==!0&&(r=r.toVarying(t)),r}).once([`NORMAL`]),fC=dC(gS.cross(sC),`v_bitangentGeometry`).normalize().toVar(`bitangentGeometry`),pC=dC(_S.cross(cC),`v_bitangentLocal`).normalize().toVar(`bitangentLocal`),mC=V(e=>{let t;return t=e.subBuildFn===`VERTEX`||e.geometry.hasAttribute(`tangent`)?dC(xS.cross(lC),`v_bitangentView`).normalize():oC,e.isFlatShading()!==!0&&(t=mS(t)),t},`vec3`).once([`NORMAL`,`VERTEX`])().toVar(`bitangentView`),hC=dC(SS.cross(uC),`v_bitangentWorld`).normalize().toVar(`bitangentWorld`),gC=Tg(lC,mC,xS).toVar(`TBNViewMatrix`),_C=uS.mul(gC),vC=(e,t)=>e.sub(_C.mul(t)),yC=V(()=>{let e=Jg.cross(uS);return e=e.cross(Jg).normalize(),e=sy(e,xS,Kg.mul(Ig.oneMinus()).oneMinus().pow2().pow2()).normalize(),e}).once()(),bC=e=>Qh(e).mul(.5).add(.5),xC=e=>Qh(e).mul(2).sub(1),SC=e=>K(e,fv(ly(U(1).sub(Xv(e,e))))),CC=e=>(m(`TSL: "directionToColor()" has been renamed to "packNormalToRGB()".`),bC(e)),wC=e=>(m(`TSL: "colorToDirection()" has been renamed to "unpackRGBToNormal()".`),xC(e)),TC=class extends mh{static get type(){return`NormalMapNode`}constructor(e,t=null){super(`vec3`),this.node=e,this.scaleNode=t,this.normalMapType=0,this.unpackNormalMode=``}setup(e){let{normalMapType:t,scaleNode:n,unpackNormalMode:r}=this,i=this.node.mul(2).sub(1);if(t===0?r===`rg`?i=SC(i.xy):r===`ga`?i=SC(i.yw):r!==``&&p(`THREE.NodeMaterial: Unexpected unpack normal mode: ${r}`):r!==``&&p(`THREE.NodeMaterial: Normal map type '${t}' is not compatible with unpack normal mode '${r}'`),n!==null){let t=n;e.isFlatShading()===!0&&(t=mS(t)),i=K(i.xy.mul(t),i.z)}let a=null;return t===1?a=TS(i):t===0?a=gC.mul(i).normalize():(p(`NodeMaterial: Unsupported normal map type: ${t}`),a=xS),a}},EC=ng(TC).setParameterLength(1,2),DC=V(({textureNode:e,bumpScale:t})=>{let n=t=>e.isolate().context({getUV:e=>t(e.uvNode||Mb()),forceUVContext:!0}),r=U(n(e=>e));return pg(U(n(e=>e.add(e.dFdx()))).sub(r),U(n(e=>e.add(e.dFdy()))).sub(r)).mul(t)}),OC=V(e=>{let{surf_pos:t,surf_norm:n,dHdxy:r}=e,i=t.dFdx().normalize(),a=t.dFdy().normalize(),o=n,s=a.cross(o),c=o.cross(i),l=i.dot(s).mul(pS),u=l.sign().mul(r.x.mul(s).add(r.y.mul(c)));return l.abs().mul(n).sub(u).normalize()}),kC=class extends mh{static get type(){return`BumpMapNode`}constructor(e,t=null){super(`vec3`),this.textureNode=e,this.scaleNode=t}setup(e){if(e.material.wireframe===!0)return xS;let t=this.scaleNode===null?1:this.scaleNode,n=DC({textureNode:this.textureNode,bumpScale:t});return OC({surf_pos:lS,surf_norm:xS,dHdxy:n})}},AC=ng(kC).setParameterLength(1,2),jC=new Map,J=class e extends dh{static get type(){return`MaterialNode`}constructor(e){super(),this.scope=e}getCache(e,t){let n=jC.get(e);return n===void 0&&(n=KS(e,t),jC.set(e,n)),n}getFloat(e){return this.getCache(e,`float`)}getColor(e){return this.getCache(e,`color`)}getTexture(e){return this.getCache(e===`map`?`map`:e+`Map`,`texture`)}setup(t){let n=t.context.material,r=this.scope,i=null;if(r===e.COLOR){let e=n.color===void 0?K():this.getColor(r);i=n.map&&n.map.isTexture===!0?e.mul(this.getTexture(`map`)):e}else if(r===e.OPACITY){let e=this.getFloat(r);i=n.alphaMap&&n.alphaMap.isTexture===!0?e.mul(this.getTexture(`alpha`)):e}else if(r===e.SPECULAR_STRENGTH)i=n.specularMap&&n.specularMap.isTexture===!0?this.getTexture(`specular`).r:U(1);else if(r===e.SPECULAR_INTENSITY){let e=this.getFloat(r);i=n.specularIntensityMap&&n.specularIntensityMap.isTexture===!0?e.mul(this.getTexture(r).a):e}else if(r===e.SPECULAR_COLOR){let e=this.getColor(r);i=n.specularColorMap&&n.specularColorMap.isTexture===!0?e.mul(this.getTexture(r).rgb):e}else if(r===e.ROUGHNESS){let e=this.getFloat(r);i=n.roughnessMap&&n.roughnessMap.isTexture===!0?e.mul(this.getTexture(r).g):e}else if(r===e.METALNESS){let e=this.getFloat(r);i=n.metalnessMap&&n.metalnessMap.isTexture===!0?e.mul(this.getTexture(r).b):e}else if(r===e.EMISSIVE){let e=this.getFloat(`emissiveIntensity`),t=this.getColor(r).mul(e);i=n.emissiveMap&&n.emissiveMap.isTexture===!0?t.mul(this.getTexture(r)):t}else if(r===e.NORMAL)n.normalMap?(i=EC(this.getTexture(`normal`),this.getCache(`normalScale`,`vec2`)),i.normalMapType=n.normalMapType,(n.normalMap.format==1030||n.normalMap.format==36285||n.normalMap.format==37490)&&(i.unpackNormalMode=`rg`)):i=n.bumpMap?AC(this.getTexture(`bump`).r,this.getFloat(`bumpScale`)):xS;else if(r===e.CLEARCOAT){let e=this.getFloat(r);i=n.clearcoatMap&&n.clearcoatMap.isTexture===!0?e.mul(this.getTexture(r).r):e}else if(r===e.CLEARCOAT_ROUGHNESS){let e=this.getFloat(r);i=n.clearcoatRoughnessMap&&n.clearcoatRoughnessMap.isTexture===!0?e.mul(this.getTexture(r).r):e}else if(r===e.CLEARCOAT_NORMAL)i=n.clearcoatNormalMap?EC(this.getTexture(r),this.getCache(r+`Scale`,`vec2`)):xS;else if(r===e.SHEEN){let e=this.getColor(`sheenColor`).mul(this.getFloat(`sheen`));i=n.sheenColorMap&&n.sheenColorMap.isTexture===!0?e.mul(this.getTexture(`sheenColor`).rgb):e}else if(r===e.SHEEN_ROUGHNESS){let e=this.getFloat(r);i=n.sheenRoughnessMap&&n.sheenRoughnessMap.isTexture===!0?e.mul(this.getTexture(r).a):e,i=i.clamp(1e-4,1)}else if(r===e.ANISOTROPY){if(n.anisotropyMap&&n.anisotropyMap.isTexture===!0){let e=this.getTexture(r);i=wg(gw.x,gw.y,gw.y.negate(),gw.x).mul(e.rg.mul(2).sub(pg(1)).normalize().mul(e.b))}else i=gw}else if(r===e.IRIDESCENCE_THICKNESS){let e=US(`1`,`float`,n.iridescenceThicknessRange);if(n.iridescenceThicknessMap){let t=US(`0`,`float`,n.iridescenceThicknessRange);i=e.sub(t).mul(this.getTexture(r).g).add(t)}else i=e}else if(r===e.TRANSMISSION){let e=this.getFloat(r);i=n.transmissionMap?e.mul(this.getTexture(r).r):e}else if(r===e.THICKNESS){let e=this.getFloat(r);i=n.thicknessMap?e.mul(this.getTexture(r).g):e}else if(r===e.IOR)i=this.getFloat(r);else if(r===e.LIGHT_MAP)i=n.lightMap?this.getTexture(r).rgb.mul(this.getFloat(`lightMapIntensity`)):K(0);else if(r===e.AO)i=n.aoMap?this.getTexture(r).r.sub(1).mul(this.getFloat(`aoMapIntensity`)).add(1):U(1);else if(r===e.LINE_DASH_OFFSET)i=n.dashOffset?this.getFloat(r):U(0);else{let e=this.getNodeType(t);i=this.getCache(r,e)}return i}},J.ALPHA_TEST=`alphaTest`,J.COLOR=`color`,J.OPACITY=`opacity`,J.SHININESS=`shininess`,J.SPECULAR=`specular`,J.SPECULAR_STRENGTH=`specularStrength`,J.SPECULAR_INTENSITY=`specularIntensity`,J.SPECULAR_COLOR=`specularColor`,J.REFLECTIVITY=`reflectivity`,J.ROUGHNESS=`roughness`,J.METALNESS=`metalness`,J.NORMAL=`normal`,J.CLEARCOAT=`clearcoat`,J.CLEARCOAT_ROUGHNESS=`clearcoatRoughness`,J.CLEARCOAT_NORMAL=`clearcoatNormal`,J.EMISSIVE=`emissive`,J.ROTATION=`rotation`,J.SHEEN=`sheen`,J.SHEEN_ROUGHNESS=`sheenRoughness`,J.ANISOTROPY=`anisotropy`,J.IRIDESCENCE=`iridescence`,J.IRIDESCENCE_IOR=`iridescenceIOR`,J.IRIDESCENCE_THICKNESS=`iridescenceThickness`,J.IOR=`ior`,J.TRANSMISSION=`transmission`,J.THICKNESS=`thickness`,J.ATTENUATION_DISTANCE=`attenuationDistance`,J.ATTENUATION_COLOR=`attenuationColor`,J.LINE_SCALE=`scale`,J.LINE_DASH_SIZE=`dashSize`,J.LINE_GAP_SIZE=`gapSize`,J.LINE_WIDTH=`linewidth`,J.LINE_DASH_OFFSET=`dashOffset`,J.POINT_SIZE=`size`,J.DISPERSION=`dispersion`,J.RETROREFLECTIVITY=`retroreflectivity`,J.LIGHT_MAP=`light`,J.AO=`ao`,MC=rg(J,J.ALPHA_TEST),NC=rg(J,J.COLOR),PC=rg(J,J.SHININESS),FC=rg(J,J.EMISSIVE),IC=rg(J,J.OPACITY),LC=rg(J,J.SPECULAR),RC=rg(J,J.SPECULAR_INTENSITY),zC=rg(J,J.SPECULAR_COLOR),BC=rg(J,J.SPECULAR_STRENGTH),VC=rg(J,J.REFLECTIVITY),HC=rg(J,J.ROUGHNESS),UC=rg(J,J.METALNESS),WC=rg(J,J.NORMAL),GC=rg(J,J.CLEARCOAT),KC=rg(J,J.CLEARCOAT_ROUGHNESS),qC=rg(J,J.CLEARCOAT_NORMAL),JC=rg(J,J.ROTATION),YC=rg(J,J.SHEEN),XC=rg(J,J.SHEEN_ROUGHNESS),ZC=rg(J,J.ANISOTROPY),QC=rg(J,J.IRIDESCENCE),$C=rg(J,J.IRIDESCENCE_IOR),ew=rg(J,J.IRIDESCENCE_THICKNESS),tw=rg(J,J.TRANSMISSION),nw=rg(J,J.THICKNESS),rw=rg(J,J.IOR),iw=rg(J,J.ATTENUATION_DISTANCE),aw=rg(J,J.ATTENUATION_COLOR),ow=rg(J,J.LINE_SCALE),sw=rg(J,J.LINE_DASH_SIZE),cw=rg(J,J.LINE_GAP_SIZE),lw=rg(J,J.LINE_WIDTH),uw=rg(J,J.LINE_DASH_OFFSET),dw=rg(J,J.POINT_SIZE),fw=rg(J,J.DISPERSION),pw=rg(J,J.RETROREFLECTIVITY),mw=rg(J,J.LIGHT_MAP),hw=rg(J,J.AO),gw=v_(new N).onReference(function(e){return e.material}).onRenderUpdate(function({material:e}){this.value.set(e.anisotropy*Math.cos(e.anisotropyRotation),e.anisotropy*Math.sin(e.anisotropyRotation))}),_w=V(e=>e.context.setupModelViewProjection(),`vec4`).once()().toVarying(`v_modelViewProjection`),vw=class e extends dh{static get type(){return`EventNode`}constructor(t,n){super(`void`),this.eventType=t,this.callback=n,t===e.OBJECT?this.updateType=nh.OBJECT:t===e.MATERIAL?this.updateType=nh.RENDER:t===e.FRAME?this.updateType=nh.FRAME:t===e.AFTER_OBJECT?this.updateAfterType=nh.OBJECT:t===e.BEFORE_OBJECT?this.updateBeforeType=nh.OBJECT:t===e.BEFORE_MATERIAL?this.updateBeforeType=nh.RENDER:t===e.BEFORE_FRAME&&(this.updateBeforeType=nh.FRAME)}setup(t){let{eventType:n,callback:r}=this;if(n===e.BEFORE_RENDER_PIPELINE){let e=t.context.onBeforePipelineCallbacks;e&&e.push(r)}else if(n===e.AFTER_RENDER_PIPELINE){let e=t.context.onAfterPipelineCallbacks;e&&e.push(r)}return super.setup(t)}update(e){this.callback(e)}updateBefore(e){this.callback(e)}updateAfter(e){this.callback(e)}},vw.OBJECT=`object`,vw.MATERIAL=`material`,vw.FRAME=`frame`,vw.AFTER_OBJECT=`afterObject`,vw.BEFORE_OBJECT=`beforeObject`,vw.BEFORE_MATERIAL=`beforeMaterial`,vw.BEFORE_FRAME=`beforeFrame`,vw.BEFORE_RENDER_PIPELINE=`beforeRenderPipeline`,vw.AFTER_RENDER_PIPELINE=`afterRenderPipeline`,yw=(e,t)=>new vw(e,t).toStack(),bw=e=>yw(vw.OBJECT,e),xw=e=>yw(vw.MATERIAL,e),Sw=e=>yw(vw.FRAME,e),Cw=e=>yw(vw.AFTER_OBJECT,e),ww=e=>yw(vw.BEFORE_OBJECT,e),Tw=e=>yw(vw.BEFORE_MATERIAL,e),Ew=e=>yw(vw.BEFORE_FRAME,e),Dw=e=>yw(vw.BEFORE_RENDER_PIPELINE,e),Ow=e=>yw(vw.AFTER_RENDER_PIPELINE,e),kw=class extends fh{static get type(){return`StorageArrayElementNode`}constructor(e,t){super(e,t),this.isStorageArrayElementNode=!0}set storageBufferNode(e){this.node=e}get storageBufferNode(){return this.node}getMemberType(e,t){let n=this.storageBufferNode.structTypeNode;return n?n.getMemberType(e,t):`void`}setup(e){return e.isAvailable(`storageBuffer`)===!1&&this.node.isPBO===!0&&e.setupPBO(this.node),super.setup(e)}generate(e,t){let n,r=e.isContextAssign();if(n=e.isAvailable(`storageBuffer`)===!1?this.node.isPBO===!0&&r!==!0&&(this.node.value.isInstancedBufferAttribute||e.shaderStage!==`compute`)?e.generatePBO(this):this.node.build(e):super.generate(e),r!==!0){let r=this.getNodeType(e);n=e.format(n,r,t)}return n}},Aw=ng(kw).setParameterLength(2),jw=class extends qb{static get type(){return`StorageBufferNode`}constructor(e,t=null,n=0){let r,i=null;t&&t.isStructTypeNode?(r=`struct`,i=t,(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)&&(n=e.count)):t===null&&(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)?(r=Jf(e.itemSize),n=e.count):r=t,super(e,r,n),this.isStorageBufferNode=!0,this.structTypeNode=i,this.access=ih.READ_WRITE,this.isAtomic=!1,this.isPBO=!1,this._attribute=null,this._varying=null,this.global=!0,e.isStorageBufferAttribute!==!0&&e.isStorageInstancedBufferAttribute!==!0&&(e.isInstancedBufferAttribute?e.isStorageInstancedBufferAttribute=!0:e.isStorageBufferAttribute=!0)}getHash(e){let t;if(this.bufferCount===0){let n=e.globalCache.getData(this.value);n===void 0&&(n={node:this},e.globalCache.setData(this.value,n)),t=n.node.id}else t=this.id;return String(t)}getInputType(){return this.value.isIndirectStorageBufferAttribute?`indirectStorageBuffer`:`storageBuffer`}element(e){return Aw(this,e)}setPBO(e){return this.isPBO=e,this}getPBO(){return this.isPBO}setAccess(e){return this.access=e,this}toReadOnly(){return this.setAccess(ih.READ_ONLY)}setAtomic(e){return this.isAtomic=e,this}toAtomic(){return this.setAtomic(!0)}getAttributeData(){return this._attribute===null&&(this._attribute=$y(this.value),this._varying=Ny(this._attribute)),{attribute:this._attribute,varying:this._varying}}generateNodeType(e){if(this.structTypeNode!==null)return this.structTypeNode.getNodeType(e);if(e.isAvailable(`storageBuffer`)||e.isAvailable(`indirectStorageBuffer`))return super.generateNodeType(e);let{attribute:t}=this.getAttributeData();return t.getNodeType(e)}getMemberType(e,t){return this.structTypeNode===null?`void`:this.structTypeNode.getMemberType(e,t)}generate(e){if(this.structTypeNode!==null&&this.structTypeNode.build(e),e.isAvailable(`storageBuffer`)||e.isAvailable(`indirectStorageBuffer`))return super.generate(e);let{attribute:t,varying:n}=this.getAttributeData(),r=n.build(e);return e.registerTransform(r,t),r}},Mw=(e,t=null,n=0)=>new jw(e,t,n),Nw=new WeakMap,Pw=new WeakMap,Fw=new WeakMap,Iw=Mg(`vec3`,`vInstanceColor`),Lw=V(([e,t=null],n)=>{let r=e.isStorageInstancedBufferAttribute===!0,i=t&&t.isStorageInstancedBufferAttribute===!0,a=Sp(n,e),o=null;r||Math.max(e.count,1)*16*4>n.getUniformBufferLimit()&&(o=Nw.get(e));let s=null,c=null;if(t){if(i)s=Mw(t,`vec3`,Math.max(t.count,1)).element(ab);else{let e=Pw.get(t);e||(e=new Ds(t.array,3),Pw.set(t,e)),c=e;let n=t.usage===35048?nb:tb;s=K(n(e,`vec3`,3,0))}}(o!==null||c!==null)&&Ew(()=>{o!==null&&o.version!==e.version&&(o.clearUpdateRanges(),o.updateRanges.push(...e.updateRanges),e.clearUpdateRanges(),o.version=e.version),t&&c!==null&&c.version!==t.version&&(c.clearUpdateRanges(),c.updateRanges.push(...t.updateRanges),t.clearUpdateRanges(),c.version=t.version)});let l=a.mul(aS).xyz;if(aS.assign(l),n.needsPreviousData()){let t=n.object;Cw(({object:t})=>{let{previousInstanceMatrix:n}=Fw.get(t);n.array.set(e.array),n.version=e.version;let r=Nw.get(n);r!==void 0&&(r.version=e.version)});let r=Cp(t,e,n);oS.assign(r.mul(oS).xyz)}if(n.hasGeometryAttribute(`normal`)){let e=wS(_S,a);_S.assign(e)}s!==null&&Iw.assign(s)},`void`),Rw=V(([e])=>{let{instanceMatrix:t,instanceColor:n}=e;Lw(t,n)},`void`),zw=new WeakMap,Bw=V(([e,t])=>{let n=W(Pb(Ub(e),0).x).toConst(),r=W(t),i=r.mod(n).toConst(),a=r.div(n).toConst();return Ub(e,mg(i,a))}),Vw=V(([e,t])=>{let n=W(Pb(Ub(e),0).x).toConst(),r=W(t).mod(n).toConst(),i=W(t).div(n).toConst();return Ub(e,mg(r,i)).x}),Hw=Mg(`vec4`,`vBatchColor`),Uw=Mg(`uint`,`vBatchIndirectId`),Ww=V(([e],t)=>{let n=t.getDrawIndex()===null?ab:lb,r=Vw(e._indirectTexture,W(n));Uw.assign(r);let i=wp(e._matricesTexture,r),a=e._colorsTexture;if(a!==null){let e=Bw(a,r);Hw.assign(e)}let o=Tg(i);if(aS.assign(i.mul(aS)),t.needsPreviousData()){Cw(({object:e})=>{let t=zw.get(e);t.previousMatricesTexture.image.data.set(e._matricesTexture.image.data),t.previousMatricesTexture.needsUpdate=!0});let t=Tp(e,r);oS.assign(t.mul(oS).xyz)}let s=_S.div(K(o[0].dot(o[0]),o[1].dot(o[1]),o[2].dot(o[2]))),c=o.mul(s).xyz;_S.assign(c),t.hasGeometryAttribute(`tangent`)&&cC.mulAssign(o)},`void`),Gw=new WeakMap,Kw=new WeakMap,qw=V(([e],t)=>{let n=jb(`skinIndex`,`uvec4`),r=jb(`skinWeight`,`vec4`),i=US(`bindMatrix`,`mat4`),a=US(`bindMatrixInverse`,`mat4`),o=Dp(t,e.skeleton);if(bw(({object:e,frameId:t})=>{let n=e.skeleton;if(Gw.get(n)!==t){Gw.set(n,t);let e=Kw.get(n);e!==void 0&&(e.previousBoneMatrices.set(n.boneMatrices),e.previousBoneTexture!==null&&(e.previousBoneTexture.needsUpdate=!0)),n.update()}}),t.needsPreviousData()){let o=Ap(t,e,i,a,n,r);oS.assign(o)}let s=Op(o,aS,i,a,n,r);if(aS.assign(s),t.hasGeometryAttribute(`normal`)){let{skinNormal:e,skinTangent:s}=kp(o,_S,cC,i,a,n,r);_S.assign(e),t.hasGeometryAttribute(`tangent`)&&cC.assign(s)}},`void`),Jw=V(([e,t=null],n)=>{let r=Mw(new Ds(e.geometry.getAttribute(`position`).array,3),`vec3`).setPBO(!0).toReadOnly().element(ab).toVar(),i=Mw(new Ds(new Uint32Array(e.geometry.getAttribute(`skinIndex`).array),4),`uvec4`).setPBO(!0).toReadOnly().element(ab).toVar(),a=Mw(new Ds(e.geometry.getAttribute(`skinWeight`).array,4),`vec4`).setPBO(!0).toReadOnly().element(ab).toVar(),o=v_(e.bindMatrix,`mat4`),s=v_(e.bindMatrixInverse,`mat4`),c=Jb(e.skeleton.boneMatrices,`mat4`,e.skeleton.bones.length),l=e.skeleton;if(bw(({frameId:e})=>{if(Gw.get(l)!==e){Gw.set(l,e);let t=Kw.get(l);t!==void 0&&(t.previousBoneMatrices.set(l.boneMatrices),t.previousBoneTexture!==null&&(t.previousBoneTexture.needsUpdate=!0)),l.update()}}),n.needsPreviousData()){let t=Ap(n,e,o,s,i,a);oS.assign(t)}let u=Op(c,r,o,s,i,a);if(t!==null&&t.assign(u),n.hasGeometryAttribute(`normal`)){let{skinNormal:e,skinTangent:t}=kp(c,_S,cC,o,s,i,a);_S.assign(e),n.hasGeometryAttribute(`tangent`)&&cC.assign(t)}return u}),Yw=class extends dh{static get type(){return`LoopNode`}constructor(e=[]){super(`void`),this.params=e}getVarName(e){return String.fromCharCode(105+e)}getProperties(e){let t=e.getNodeProperties(this);if(t.stackNode!==void 0)return t;let n={},r=this._getInternalParams();for(let e=0,t=r.length-1;e=`):s!==void 0&&o===void 0&&(o=`0`,u=`<`),u===void 0&&(u=Number(o)>Number(s)?`>=`:`<`));let f;if(a)f=`while ( ${s} )`;else{let n={start:o,end:s},r=n.start,i=n.end,a,m=()=>u.includes(`<`)?`+=`:`-=`;if(d!=null)switch(typeof d){case`function`:a=e.flowStagesNode(t.updateNode,`void`).code.replace(/\t|;/g,``);break;case`number`:a=c+` `+m()+` `+e.generateConst(l,d);break;case`string`:a=c+` `+d;break;default:d.isNode?a=c+` `+m()+` `+d.build(e):(p(`TSL: 'Loop( { update: ... } )' is not a function, string or number.`,this.stackTrace),a=`break /* invalid update */`)}else d=l===`int`||l===`uint`?u.includes(`<`)?`++`:`--`:m()+` 1.`,a=c+` `+d;f=`for ( ${e.getVar(l,c)+` = `+r}; ${c+` `+u+` `+i}; ${a} )`}e.addFlowCode((r===0?` `:``)+e.tab+f+` { `).addFlowTab()}let i=r.build(e,`void`);t.returnsNode.build(e,`void`),e.removeFlowTab().addFlowCode(` `+e.tab+i);for(let t=0,r=n.length-1;tnew Yw(tg(e,`int`)).toStack(),Zw=()=>yb(`continue`).toStack(),Qw=()=>yb(`break`).toStack(),$w=new WeakMap,eT=new Mi,tT=new WeakMap,nT=V(({bufferMap:e,influence:t,stride:n,width:r,depth:i,offset:a})=>{let o=W(ib).mul(n).add(a),s=o.div(r),c=o.sub(s.mul(r));return Ub(e,mg(c,s)).depth(i).xyz.mul(t)}),rT=V(([e])=>{let{geometry:t}=e,n=t.morphAttributes.position!==void 0,r=t.hasAttribute(`normal`)&&t.morphAttributes.normal!==void 0,i=t.morphAttributes.position||t.morphAttributes.normal||t.morphAttributes.color,a=i===void 0?0:i.length;if(a===0)return;let o=tT.get(e);(o===void 0||o.count!==a)&&(o={base:v_(1),influences:e.morphTargetInfluences?Zb(e.morphTargetInfluences,`float`):null,count:a},tT.set(e,o));let{base:s,influences:c}=o,{texture:l,stride:u,size:d}=jp(t);n===!0&&aS.mulAssign(s),r===!0&&_S.mulAssign(s);let f=W(d.width);Xw(a,({i:t})=>{let i=U(0).toVar();e.count>1&&e.morphTexture!==null&&e.morphTexture!==void 0?i.assign(Ub(e.morphTexture,mg(W(t).add(1),W(ab))).r):i.assign(c.element(t).toVar()),lg(i.notEqual(0),()=>{n===!0&&aS.addAssign(nT({bufferMap:l,influence:i,stride:u,width:f,depth:t,offset:W(0)})),r===!0&&_S.addAssign(nT({bufferMap:l,influence:i,stride:u,width:f,depth:t,offset:W(1)}))})}),bw(({object:e})=>{let{base:t,influences:n}=o;t.value=e.geometry.morphTargetsRelative?1:1-e.morphTargetInfluences.reduce((e,t)=>e+t,0),n&&(n.array=e.morphTargetInfluences,n.update())})},`void`),iT=class extends dh{static get type(){return`LightingNode`}constructor(){super(`vec3`),this.isLightingNode=!0}},aT=class extends iT{static get type(){return`AONode`}constructor(e=null){super(),this.aoNode=e}setup(e){e.context.ambientOcclusion.mulAssign(this.aoNode)}},oT=class extends xy{static get type(){return`LightingContextNode`}constructor(e,t=null,n=[],r=null,i=null){super(e),this.lightingModel=t,this.materialLightings=n,this.backdropNode=r,this.backdropAlphaNode=i,this._value=null}getContext(){let{materialLightings:e,backdropNode:t,backdropAlphaNode:n}=this,r={directDiffuse:K().toVar(`directDiffuse`),directSpecular:K().toVar(`directSpecular`),indirectDiffuse:K().toVar(`indirectDiffuse`),indirectSpecular:K().toVar(`indirectSpecular`)};return{radiance:K().toVar(`radiance`),irradiance:K().toVar(`irradiance`),iblIrradiance:K().toVar(`iblIrradiance`),ambientOcclusion:U(1).toVar(`ambientOcclusion`),reflectedLight:r,materialLightings:e,backdrop:t,backdropAlpha:n}}setup(e){return this.value=this._value||=this.getContext(),this.value.lightingModel=this.lightingModel||e.context.lightingModel,super.setup(e)}},sT=ng(oT),cT=class extends iT{static get type(){return`IrradianceNode`}constructor(e){super(),this.node=e}setup(e){e.context.irradiance.addAssign(this.node)}},lT=new N,uT=class extends zb{static get type(){return`ViewportTextureNode`}constructor(e=ix,t=null,n=null){let r=null;n===null?(r=new Cc,r.minFilter=cn,n=r):r=n,super(n,e,t),this.generateMipmaps=!1,this.defaultFramebuffer=r,this.isOutputTextureNode=!0,this.updateBeforeType=nh.RENDER,this._cacheTextures=new WeakMap}getTextureForReference(e=null){let t,n;if(this.referenceNode?(t=this.referenceNode.defaultFramebuffer,n=this.referenceNode._cacheTextures):(t=this.defaultFramebuffer,n=this._cacheTextures),e===null)return t;if(n.has(e)===!1){let r=t.clone();n.set(e,r)}return n.get(e)}updateReference(e){let t=e.renderer,n=t.getRenderTarget(),r=t.getCanvasTarget(),i=n||r;return this.value=this.getTextureForReference(i),this.value}updateBefore(e){let t=e.renderer,n=t.getRenderTarget(),r=t.getCanvasTarget(),i=n||r;i===null?t.getDrawingBufferSize(lT):i.getDrawingBufferSize?i.getDrawingBufferSize(lT):lT.set(i.width,i.height);let a=this.getTextureForReference(i);(a.image.width!==lT.width||a.image.height!==lT.height)&&(a.image.width=lT.width,a.image.height=lT.height,a.needsUpdate=!0);let o=a.generateMipmaps;a.generateMipmaps=this.generateMipmaps,t.copyFramebufferToTexture(a),a.generateMipmaps=o}clone(){let e=new this.constructor(this.uvNode,this.levelNode,this.value);return e.generateMipmaps=this.generateMipmaps,e}},dT=ng(uT).setParameterLength(0,3),fT=ng(uT,null,null,{generateMipmaps:!0}).setParameterLength(0,3),pT=fT(),mT=(e=ix,t=null)=>pT.sample(e,t),hT=null,gT=class extends uT{static get type(){return`ViewportDepthTextureNode`}constructor(e=ix,t=null,n=null){n===null&&(hT===null&&(hT=new Ac),n=hT),super(e,t,n)}},_T=ng(gT).setParameterLength(0,3),vT=class e extends dh{static get type(){return`ViewportDepthNode`}constructor(e,t=null){super(`float`),this.scope=e,this.valueNode=t,this.isViewportDepthNode=!0}generate(t){let{scope:n}=this;return n===e.DEPTH_BASE?t.getFragDepth():super.generate(t)}setup({camera:t}){let{scope:n}=this,r=this.valueNode,i=null;if(n===e.DEPTH_BASE)r!==null&&(i=DT().assign(r));else if(n===e.DEPTH)i=t.isPerspectiveCamera?ST(lS.z,Ex,Dx):yT(lS.z,Ex,Dx);else if(n===e.LINEAR_DEPTH){if(r!==null){if(t.isPerspectiveCamera){let e=wT(r,Ex,Dx);i=yT(e,Ex,Dx)}else i=r}else i=yT(lS.z,Ex,Dx)}return i}},vT.DEPTH_BASE=`depthBase`,vT.DEPTH=`depth`,vT.LINEAR_DEPTH=`linearDepth`,yT=(e,t,n)=>e.add(t).div(t.sub(n)),bT=(e,t,n)=>e.add(n).div(n.sub(t)),xT=V(([e,t,n],r)=>r.renderer.reversedDepthBuffer===!0?n.sub(t).mul(e).sub(n):t.sub(n).mul(e).sub(t)),ST=(e,t,n)=>t.add(e).mul(n).div(n.sub(t).mul(e)),CT=(e,t,n)=>t.mul(e.add(n)).div(e.mul(t.sub(n))),wT=V(([e,t,n],r)=>r.renderer.reversedDepthBuffer===!0?t.mul(n).div(t.sub(n).mul(e).sub(t)):t.mul(n).div(n.sub(t).mul(e).sub(n))),TT=(e,t,n)=>{t=t.max(1e-6).toVar();let r=dv(e.negate().div(t)),i=dv(n.div(t));return r.div(i)},ET=(e,t,n)=>{let r=e.mul(uv(n.div(t)));return U(Math.E).pow(r).mul(t).negate()},DT=ng(vT,vT.DEPTH_BASE),OT=rg(vT,vT.DEPTH),kT=ng(vT,vT.LINEAR_DEPTH).setParameterLength(0,1),AT=kT(_T()),OT.assign=e=>DT(e),jT=class e extends dh{static get type(){return`ClippingNode`}constructor(t=e.DEFAULT){super(),this.scope=t}setup(t){super.setup(t);let{intersectionPlanes:n,unionPlanes:r}=t.clippingContext;return this.hardwareClipping=t.hardwareClipping,this.scope===e.ALPHA_TO_COVERAGE?this.setupAlphaToCoverage(n,r):this.scope===e.HARDWARE?this.setupHardwareClipping(r,t):this.setupDefault(n,r)}setupAlphaToCoverage(e,t){return V(()=>{let n=U().toVar(`distanceToPlane`),r=U().toVar(`distanceToGradient`),i=U(1).toVar(`clipOpacity`),a=t.length;if(this.hardwareClipping===!1&&a>0){let e=Zb(t).setGroup(h_);Xw(a,({i:t})=>{let a=e.element(t);n.assign(lS.dot(a.xyz).negate().add(a.w)),r.assign(n.fwidth().div(2)),i.mulAssign(dy(r.negate(),r,n))})}let o=e.length;if(o>0){let t=Zb(e).setGroup(h_),a=U(1).toVar(`intersectionClipOpacity`);Xw(o,({i:e})=>{let i=t.element(e);n.assign(lS.dot(i.xyz).negate().add(i.w)),r.assign(n.fwidth().div(2)),a.mulAssign(dy(r.negate(),r,n).oneMinus())}),i.mulAssign(a.oneMinus())}Ng.a.mulAssign(i),Ng.a.equal(0).discard()})()}setupDefault(e,t){return V(()=>{let n=t.length;if(this.hardwareClipping===!1&&n>0){let e=Zb(t).setGroup(h_);Xw(n,({i:t})=>{let n=e.element(t);lS.dot(n.xyz).greaterThan(n.w).discard()})}let r=e.length;if(r>0){let t=Zb(e).setGroup(h_),n=fg(!0).toVar(`clipped`);Xw(r,({i:e})=>{let r=t.element(e);n.assign(lS.dot(r.xyz).greaterThan(r.w).and(n))}),n.discard()}})()}setupHardwareClipping(e,t){let n=e.length;return t.enableHardwareClipping(n),V(()=>{let r=Zb(e).setGroup(h_),i=$b(t.getClipDistance());Xw(n,({i:e})=>{let t=r.element(e),n=lS.dot(t.xyz).sub(t.w).negate();i.element(e).assign(n)})})()}},jT.ALPHA_TO_COVERAGE=`alphaToCoverage`,jT.DEFAULT=`default`,jT.HARDWARE=`hardware`,MT=()=>new jT,NT=()=>new jT(jT.ALPHA_TO_COVERAGE),PT=()=>new jT(jT.HARDWARE),FT=.05,IT=V(([e])=>_v(k_(1e4,vv(k_(17,e.x).add(k_(.1,e.y)))).mul(D_(.1,Av(vv(k_(13,e.y).add(e.x))))))),LT=V(([e])=>IT(pg(IT(e.xy),e.z))),RT=V(([e])=>{let t=Gv(Mv(Fv(e.xyz)),Mv(Iv(e.xyz))),n=U(1).div(U(FT).mul(t)).toVar(`pixScale`),r=pg(lv(mv(dv(n))),lv(hv(dv(n)))),i=pg(LT(mv(r.x.mul(e.xyz))),LT(mv(r.y.mul(e.xyz)))),a=_v(dv(n)),o=D_(k_(a.oneMinus(),i.x),k_(a,i.y)),s=Wv(a,a.oneMinus()),c=K(o.mul(o).div(k_(2,s).mul(O_(1,s))),o.sub(k_(.5,s)).div(O_(1,s)),O_(1,O_(1,o).mul(O_(1,o)).div(k_(2,s).mul(O_(1,s))))),l=o.lessThan(s.oneMinus()).select(o.lessThan(s).select(c.x,c.y),c.z);return cy(l,1e-6,1)}).setLayout({name:`getAlphaHashThreshold`,type:`float`,inputs:[{name:`position`,type:`vec3`}]}),zT=class extends Ab{static get type(){return`VertexColorNode`}constructor(e){super(null,`vec4`),this.isVertexColorNode=!0,this.index=e}getAttributeName(){let e=this.index;return`color`+(e>0?e:``)}generate(e){let t=this.getAttributeName(e),n=e.hasGeometryAttribute(t),r;return r=n===!0?super.generate(e):e.generateConst(this.nodeType,new Mi(1,1,1,1)),r}serialize(e){super.serialize(e),e.index=this.index}deserialize(e){super.deserialize(e),this.index=e.index}},BT=(e=0)=>new zT(e),VT=class extends Ao{static get type(){return`NodeMaterial`}get type(){return this.constructor.type}set type(e){}constructor(){super(),this.isNodeMaterial=!0,this.fog=!0,this.lights=!1,this.lightsNode=null,this.envNode=null,this.aoNode=null,this.colorNode=null,this.normalNode=null,this.opacityNode=null,this.backdropNode=null,this.backdropAlphaNode=null,this.alphaTestNode=null,this.maskNode=null,this.maskShadowNode=null,this.positionNode=null,this.geometryNode=null,this.depthNode=null,this.receivedShadowPositionNode=null,this.castShadowPositionNode=null,this.receivedShadowNode=null,this.castShadowNode=null,this.outputNode=null,this.mrtNode=null,this.fragmentNode=null,this.vertexNode=null,this.contextNode=null}_getNodeChildren(){let e=[];for(let t of Object.getOwnPropertyNames(this)){if(t.startsWith(`_`)===!0)continue;let n=this[t];n&&n.isNode===!0&&e.push({property:t,childNode:n})}return e}customProgramCacheKey(){let e=[];for(let{property:t,childNode:n}of this._getNodeChildren())e.push(Ym(t.slice(0,-4)),n.getCacheKey());return this.type+Xm(e)}build(e){this.setup(e)}setupObserver(e){return new Km(e)}setup(e){e.context.setupNormal=()=>jy(this.setupNormal(e),`NORMAL`,`vec3`),e.context.setupPositionView=()=>this.setupPositionView(e),e.context.setupModelViewProjection=()=>this.setupModelViewProjection(e);let t=e.renderer,n=t.getRenderTarget();e.addStack();let r=this.setupVertex(e),i=jy(this.vertexNode||r,`VERTEX`);e.context.clipSpace=i,e.stack.outputNode=i,this.setupHardwareClipping(e),this.geometryNode!==null&&(e.stack.outputNode=e.stack.outputNode.bypass(this.geometryNode)),e.addFlow(`vertex`,e.removeStack()),e.addStack();let a,o=this.setupClipping(e);if((this.depthWrite===!0||this.depthTest===!0)&&(n===null?t.depth===!0&&this.setupDepth(e):n.depthBuffer===!0&&this.setupDepth(e)),this.fragmentNode===null){this.setupDiffuseColor(e),this.setupAmbientOcclusion(e),this.setupVariants(e);let r=this.setupLighting(e);o!==null&&e.stack.addToStack(o);let i=bg(r,Ng.a).max(0);a=this.setupOutput(e,i),$g.assign(a);let s=this.outputNode!==null;if(s&&(a=this.outputNode),e.context.getOutput&&(a=e.context.getOutput(a,e)),n!==null){let e=t.getMRT(),n=this.mrtNode;e===null?n!==null&&(a=n):(s&&$g.assign(a),a=e,n!==null&&(a=e.merge(n)))}}else{let t=this.fragmentNode;t.isOutputStructNode!==!0&&(t=t.convert(e.getOutputType())),a=this.setupOutput(e,t)}e.stack.outputNode=a,e.addFlow(`fragment`,e.removeStack()),e.observer=this.setupObserver(e)}setupClipping(e){if(e.clippingContext===null)return null;let{unionPlanes:t,intersectionPlanes:n}=e.clippingContext,r=null;if(t.length>0||n.length>0){let t=e.renderer.currentSamples;this.alphaToCoverage&&t>1?r=NT():e.stack.addToStack(MT())}return r}setupHardwareClipping(e){if(e.hardwareClipping=!1,e.clippingContext===null)return;let t=e.clippingContext.unionPlanes.length;t>0&&t<=8&&e.isAvailable(`clipDistance`)&&(e.stack.addToStack(PT()),e.hardwareClipping=!0)}setupDepth(e){let{renderer:t,camera:n}=e,r=this.depthNode;if(r===null){let e=t.getMRT();e&&e.has(`depth`)?r=e.get(`depth`):t.logarithmicDepthBuffer===!0&&(r=n.isPerspectiveCamera?TT(lS.z,Ex,Dx):yT(lS.z,Ex,Dx))}r!==null&&OT.assign(r).toStack()}setupPositionView(){return $x.mul(aS).xyz}setupModelViewProjection(){return Ox.mul(lS)}setupVertex(e){return e.addStack(),this.setupPosition(e),e.context.position=e.removeStack(),_w}setupPosition(e){let{object:t,geometry:n}=e;if((n.morphAttributes.position||n.morphAttributes.normal||n.morphAttributes.color)&&rT(t),t.isSkinnedMesh===!0&&qw(t),this.displacementMap){let e=KS(`displacementMap`,`texture`),t=KS(`displacementScale`,`float`),n=KS(`displacementBias`,`float`);aS.addAssign(_S.normalize().mul(e.x.mul(t).add(n)))}return t.isBatchedMesh&&Ww(t),t.isInstancedMesh&&t.instanceMatrix&&t.instanceMatrix.isInstancedBufferAttribute===!0&&Rw(t),this.positionNode!==null&&aS.assign(jy(this.positionNode,`POSITION`,`vec3`)),aS}setupDiffuseColor(e){let{object:t,geometry:n}=e;this.maskNode!==null&&fg(this.maskNode).not().discard();let r=this.colorNode?bg(this.colorNode):NC;this.vertexColors===!0&&n.hasAttribute(`color`)&&(r=r.mul(BT())),t.instanceColor&&(r=Iw.mul(r)),t.isBatchedMesh&&t._colorsTexture&&(r=Hw.mul(r)),Ng.assign(r);let i=this.opacityNode?U(this.opacityNode):IC;Ng.a.assign(Ng.a.mul(i));let a=null;(this.alphaTestNode!==null||this.alphaTest>0)&&(a=this.alphaTestNode===null?MC:U(this.alphaTestNode),this.alphaToCoverage===!0?(Ng.a=dy(a,a.add(Bv(Ng.a)),Ng.a),Ng.a.lessThanEqual(0).discard()):Ng.a.lessThanEqual(a).discard()),this.alphaHash===!0&&Ng.a.lessThan(RT(aS)).discard(),e.isOpaque()&&Ng.a.assign(1)}setupVariants(){}setupOutgoingLight(){return this.lights===!0?K(0):Ng.rgb}setupNormal(){return this.normalNode?K(this.normalNode):WC}setupEnvironment(){let e=null;return this.envNode?e=this.envNode:this.envMap&&(e=this.envMap.isCubeTexture?KS(`envMap`,`cubeTexture`):KS(`envMap`,`texture`)),e}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new cT(mw)),t}setupMaterialLightings(e){let t=[],n=this.setupEnvironment(e);n&&n.isLightingNode&&t.push(n);let r=this.setupLightMap(e);if(r&&r.isLightingNode&&t.push(r),e.context.ambientOcclusion&&t.push(new aT(e.context.ambientOcclusion)),e.context.getGI){let n=e.context.getGI(null,e);n!==null&&t.push(new cT(n))}return t}setupAmbientOcclusion(e){let t=this.aoNode;t===null&&e.material.aoMap&&(t=hw),e.context.getAO&&(t=e.context.getAO(t,e)),t!==null&&(u_.assign(t),e.context.ambientOcclusion=u_)}setupLightingModel(){}setupLighting(e){let{material:t}=e,{backdropNode:n,backdropAlphaNode:r,emissiveNode:i}=this,a=this.lights===!0&&e.renderer.lighting.enabled,o=a||this.lightsNode!==null,s=a?this.setupMaterialLightings(e):[],c=o?this.lightsNode||e.lightsNode:null,l=this.setupOutgoingLight(e);if(c&&(s.length>0||c.getScope().hasLights)){let t=this.setupLightingModel(e)||null;l=sT(c,t,s,n,r)}else n!==null&&(l=K(r===null?n:sy(l,n,r)));return(i&&i.isNode===!0||t.emissive&&t.emissive.isColor===!0)&&(Fg.assign(K(i||FC)),l=l.add(Fg)),l}setupFog(e,t){let n=e.fogNode;return n&&($g.assign(t),t=bg(n.toVar())),t}setupPremultipliedAlpha(e,t){return Sb(t)}setupOutput(e,t){return this.fog===!0&&(t=this.setupFog(e,t)),this.premultipliedAlpha===!0&&(t=this.setupPremultipliedAlpha(e,t)),t}setDefaultValues(e){for(let t in e){let n=e[t];this[t]===void 0&&(this[t]=n,n&&n.clone&&(this[t]=n.clone()))}let t=Object.getOwnPropertyDescriptors(e.constructor.prototype);for(let e in t)Object.getOwnPropertyDescriptor(this.constructor.prototype,e)===void 0&&t[e].get!==void 0&&Object.defineProperty(this.constructor.prototype,e,t[e])}toJSON(e){let t=e===void 0||typeof e==`string`;t&&(e={textures:{},images:{},nodes:{}});let n=Ao.prototype.toJSON.call(this,e);n.inputNodes={};for(let{property:t,childNode:r}of this._getNodeChildren())n.inputNodes[t]=r.toJSON(e).uuid;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),a=r(e.nodes);t.length>0&&(n.textures=t),i.length>0&&(n.images=i),a.length>0&&(n.nodes=a)}return n}copy(e){let t=Object.getOwnPropertyDescriptors(this.constructor.prototype);for(let n in t)if(t[n].set!==void 0&&e[n]!==void 0){let t=e[n];this[n]&&this[n].copy!==void 0?this[n].copy(t):this[n]=t}for(let t in this)if(!/^(?:is[A-Z]|_)|^(?:id|uuid|version|type|userData|clippingPlanes)$/.test(t)&&this[t]!==void 0&&e[t]!==void 0){let n=e[t];this[t]&&this[t].copy!==void 0?this[t].copy(n):this[t]=n}return this.clippingPlanes=e.clippingPlanes?e.clippingPlanes.map(e=>e.clone()):null,this.userData=JSON.parse(JSON.stringify(e.userData)),this}},HT=new nc,UT=class extends VT{static get type(){return`LineBasicNodeMaterial`}constructor(e){super(),this.isLineBasicNodeMaterial=!0,this.setDefaultValues(HT),this.setValues(e)}},WT=new Hl,GT=class extends VT{static get type(){return`LineDashedNodeMaterial`}constructor(e){super(),this.isLineDashedNodeMaterial=!0,this.setDefaultValues(WT),this.dashOffset=0,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setValues(e)}setupVariants(){let e=this.offsetNode?U(this.offsetNode):uw,t=this.dashScaleNode?U(this.dashScaleNode):ow,n=this.dashSizeNode?U(this.dashSizeNode):sw,r=this.gapSizeNode?U(this.gapSizeNode):cw;e_.assign(n),t_.assign(r);let i=Ny(jb(`lineDistance`).mul(t));(e?i.add(e):i).mod(e_.add(t_)).greaterThan(e_).discard()}},KT=new Hl,qT=Mg(`vec3`,`worldStart`),JT=Mg(`vec3`,`worldEnd`),YT=Mg(`float`,`lineDistance`),XT=Mg(`vec4`,`worldPos`),ZT=V(({start:e,end:t})=>{let n=Ox.element(2).element(2),r=Ox.element(3).element(2);return n.greaterThan(0).select(r.negate().div(n.add(1)),r.mul(-.5).div(n)).sub(e.z).div(t.z.sub(e.z))},{start:`vec4`,end:`vec4`,return:`float`}),QT=V(({p1:e,p2:t,p3:n,p4:r})=>{let i=e.sub(n),a=r.sub(n),o=t.sub(e),s=i.dot(a),c=a.dot(o),l=i.dot(o),u=a.dot(a),d=o.dot(o).mul(u).sub(c.mul(c)),f=s.mul(c).sub(l.mul(u)).div(d).clamp(),p=s.add(c.mul(f)).div(u).clamp();return pg(f,p)},{p1:`vec3`,p2:`vec3`,p3:`vec3`,p4:`vec3`,return:`vec2`}),$T=V(({material:e})=>{let t=e._useDash,n=e._useWorldUnits,r=jb(`instanceStart`),i=jb(`instanceEnd`),a=bg($x.mul(bg(r,1))).toVar(`start`),o=bg($x.mul(bg(i,1))).toVar(`end`),s,c;t&&(s=U(jb(`instanceDistanceStart`)).toVar(`distanceStart`),c=U(jb(`instanceDistanceEnd`)).toVar(`distanceEnd`)),n&&(qT.assign(a.xyz),JT.assign(o.xyz));let l=sx.z.div(sx.w),u=Ox.element(2).element(3).equal(-1);if(lg(u,()=>{lg(a.z.lessThan(0).and(o.z.greaterThan(0)),()=>{let e=ZT({start:a,end:o});o.assign(bg(sy(a.xyz,o.xyz,e),o.w)),t&&c.assign(sy(s,c,e))}).ElseIf(o.z.lessThan(0).and(a.z.greaterThanEqual(0)),()=>{let e=ZT({start:o,end:a});a.assign(bg(sy(o.xyz,a.xyz,e),a.w)),t&&s.assign(sy(c,s,e))})}),t){let t=e.dashScaleNode?U(e.dashScaleNode):ow,n=e.offsetNode?U(e.offsetNode):uw,r=iS.y.lessThan(.5).select(t.mul(s),t.mul(c));r=r.add(n),YT.assign(r)}let d=Ox.mul(a),f=Ox.mul(o),p=d.xyz.div(d.w),m=f.xyz.div(f.w),h=m.xy.sub(p.xy).toVar();h.x.assign(h.x.mul(l)),h.assign(h.normalize());let g=bg().toVar();if(n){let e=o.xyz.sub(a.xyz).normalize(),n=sy(a.xyz,o.xyz,.5).normalize(),r=e.cross(n).normalize(),i=e.cross(r);XT.assign(iS.y.lessThan(.5).select(a,o));let s=lw.mul(.5);XT.addAssign(bg(iS.x.lessThan(0).select(r.mul(s),r.mul(s).negate()),0)),t||(XT.addAssign(bg(iS.y.lessThan(.5).select(e.mul(s).negate(),e.mul(s)),0)),XT.addAssign(bg(i.mul(s),0)),lg(iS.y.greaterThan(1).or(iS.y.lessThan(0)),()=>{XT.subAssign(bg(i.mul(2).mul(s),0))})),g.assign(Ox.mul(XT));let c=K().toVar();c.assign(iS.y.lessThan(.5).select(p,m)),g.z.assign(c.z.mul(g.w))}else{let e=pg(h.y,h.x.negate()).toVar(`offset`);h.x.assign(h.x.div(l)),e.x.assign(e.x.div(l)),e.assign(iS.x.lessThan(0).select(e.negate(),e)),lg(iS.y.lessThan(0),()=>{e.assign(e.sub(h))}).ElseIf(iS.y.greaterThan(1),()=>{e.assign(e.add(h))}),e.assign(e.mul(lw)),e.assign(e.div(sx.w.div(rx))),g.assign(iS.y.lessThan(.5).select(d,f)),e.assign(e.mul(g.w)),g.assign(g.add(bg(e,0,0)))}return g})(),eE=V(({material:e,renderer:t})=>{let n=e._useAlphaToCoverage,r=e._useDash,i=e._useWorldUnits,a=Mb();if(r){let t=e.dashSizeNode?U(e.dashSizeNode):sw,n=e.gapSizeNode?U(e.gapSizeNode):cw;e_.assign(t),t_.assign(n),a.y.lessThan(-1).or(a.y.greaterThan(1)).discard(),YT.mod(e_.add(t_)).greaterThan(e_).discard()}let o=U(1).toVar(`alpha`);if(i){let e=XT.xyz.normalize().mul(1e5),i=JT.sub(qT),a=QT({p1:qT,p2:JT,p3:K(0,0,0),p4:e}),s=qT.add(i.mul(a.x)),c=e.mul(a.y),l=s.sub(c).length().div(lw);if(!r){if(n&&t.currentSamples>0){let e=l.fwidth();o.assign(dy(e.negate().add(.5),e.add(.5),l).oneMinus())}else l.greaterThan(.5).discard()}}else if(n&&t.currentSamples>0){let e=a.x,t=a.y.greaterThan(0).select(a.y.sub(1),a.y.add(1)),n=e.mul(e).add(t.mul(t)),r=U(n.fwidth()).toVar(`dlen`);lg(a.y.abs().greaterThan(1),()=>{o.assign(dy(r.oneMinus(),r.add(1),n).oneMinus())})}else lg(a.y.abs().greaterThan(1),()=>{let e=a.x,t=a.y.greaterThan(0).select(a.y.sub(1),a.y.add(1));e.mul(e).add(t.mul(t)).greaterThan(1).discard()});return o})(),tE=class extends VT{static get type(){return`Line2NodeMaterial`}constructor(e={}){super(),this.isLine2NodeMaterial=!0,this.setDefaultValues(KT),this.vertexColors=e.vertexColors,this.dashOffset=0,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.blending=0,this._useDash=e.dashed,this._useAlphaToCoverage=!0,this._useWorldUnits=!1,this.setValues(e)}setupDiffuseColor(e){if(super.setupDiffuseColor(e),Ng.a.mulAssign(eE),this.vertexColors===!0&&e.geometry.hasAttribute(`instanceColorStart`)){let e=jb(`instanceColorStart`),t=jb(`instanceColorEnd`),n=iS.y.lessThan(.5).select(e,t);Ng.rgb.mulAssign(n)}this.transparent&&Ng.rgb.assign(Ng.rgb.mul(Ng.a).add(mT().rgb.mul(Ng.a.oneMinus())))}setupPosition(e){let t=Qx.mul(jx).mul(kx).mul($T);return aS.assign(t.xyz.div(t.w)),e.needsPreviousData()&&oS.assign(aS),super.setupPosition(e)}get lineColorNode(){return this.colorNode}set lineColorNode(e){m(`Line2NodeMaterial: "lineColorNode" has been deprecated. Use "colorNode" instead.`),this.colorNode=e}get worldUnits(){return this._useWorldUnits}set worldUnits(e){this._useWorldUnits!==e&&(this._useWorldUnits=e,this.needsUpdate=!0)}get dashed(){return this._useDash}set dashed(e){this._useDash!==e&&(this._useDash=e,this.needsUpdate=!0)}get alphaToCoverage(){return this._useAlphaToCoverage}set alphaToCoverage(e){this._useAlphaToCoverage!==e&&(this._useAlphaToCoverage=e,this.needsUpdate=!0)}},nE=new Ll,rE=class extends VT{static get type(){return`MeshNormalNodeMaterial`}constructor(e){super(),this.isMeshNormalNodeMaterial=!0,this.setDefaultValues(nE),this.setValues(e)}setupDiffuseColor(){let e=this.opacityNode?U(this.opacityNode):IC;Ng.assign(Vy(bg(bC(xS),e),Mr))}},iE=V(([e=cS])=>{let t=e.z.atan(e.x).mul(1/(Math.PI*2)).add(.5),n=e.y.clamp(-1,1).asin().mul(1/Math.PI).add(.5);return pg(t,n)}),aE=V(([e=Mb()])=>{let t=e.x.sub(.5).mul(Math.PI*2),n=e.y.sub(.5).mul(Math.PI),r=n.cos(),i=r.mul(t.cos()),a=n.sin(),o=r.mul(t.sin());return K(i,a,o)}),oE=class extends Ni{constructor(e=1,t={}){super(e,e,t),this.isCubeRenderTarget=!0;let n={width:e,height:e,depth:1},r=[n,n,n,n,n,n];this.texture=new Dc(r),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){let n=t.minFilter,r=t.generateMipmaps;t.generateMipmaps=!0,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 i=new Nc(5,5,5),a=iE(cS),o=new VT;o.colorNode=Vb(t,a,0),o.side=1,o.blending=0;let s=new z(i,o),c=new ba;c.add(s),t.minFilter===1008&&(t.minFilter=an);let l=new ud(1,10,this),u=e.getMRT();return e.setMRT(null),l.update(e,c),e.setMRT(u),t.minFilter=n,t.generateMipmaps=r,s.geometry.dispose(),s.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)}},sE=new WeakMap,cE=class extends mh{static get type(){return`CubeMapNode`}constructor(e){super(`vec3`),this.envNode=e,this._cubeTexture=null,this._cubeTextureNode=BS(null);let t=new Dc;t.isRenderTargetTexture=!0,this._defaultTexture=t,this.updateBeforeType=nh.RENDER}updateBefore(e){let{renderer:t,material:n}=e,r=this.envNode;if(r.isTextureNode||r.isMaterialReferenceNode){let e=r.isTextureNode?r.value:n[r.property];if(e&&e.isTexture){let n=e.mapping;if(n===303||n===304){if(sE.has(e)){let t=sE.get(e);Pp(t,e.mapping),this._cubeTexture=t}else{let n=e.image;if(Mp(n)){let r=new oE(n.height);r.fromEquirectangularTexture(t,e),Pp(r.texture,e.mapping),this._cubeTexture=r.texture,sE.set(e,r.texture),e.addEventListener(`dispose`,Np)}else this._cubeTexture=this._defaultTexture}this._cubeTextureNode.value=this._cubeTexture}else this._cubeTextureNode=this.envNode}}}setup(e){return this.updateBefore(e),this._cubeTextureNode}},lE=ng(cE).setParameterLength(1),uE=class extends iT{static get type(){return`BasicEnvironmentNode`}constructor(e=null){super(),this.envNode=e}setup(e){e.context.environment=lE(this.envNode)}},dE=class extends iT{static get type(){return`BasicLightMapNode`}constructor(e=null){super(),this.lightMapNode=e}setup(e){let t=U(1/Math.PI);e.context.irradianceLightMap=this.lightMapNode.mul(t)}},fE=class{start(e){e.lightsNode.setupLights(e,e.lightsNode.getLightNodes(e)),this.indirect(e)}finish(){}direct(){}directRectArea(){}indirect(){}ambientOcclusion(){}},pE=class extends fE{constructor(){super()}indirect({context:e}){let t=e.ambientOcclusion,n=e.reflectedLight,r=e.irradianceLightMap;n.indirectDiffuse.assign(bg(0)),r?n.indirectDiffuse.addAssign(r):n.indirectDiffuse.addAssign(bg(1,1,1,0)),n.indirectDiffuse.mulAssign(t),n.indirectDiffuse.mulAssign(Ng.rgb)}finish(e){let{material:t,context:n}=e,r=n.outgoingLight,i=e.context.environment;if(i)switch(t.combine){case 0:r.rgb.assign(sy(r.rgb,r.rgb.mul(i.rgb),BC.mul(VC)));break;case 1:r.rgb.assign(sy(r.rgb,i.rgb,BC.mul(VC)));break;case 2:r.rgb.addAssign(i.rgb.mul(BC.mul(VC)));break;default:f(`BasicLightingModel: Unsupported .combine value:`,t.combine)}}},mE=new es,Y=class extends VT{static get type(){return`MeshBasicNodeMaterial`}constructor(e){super(),this.isMeshBasicNodeMaterial=!0,this.lights=!0,this.setDefaultValues(mE),this.setValues(e)}setupNormal(){return mS(yS)}setupEnvironment(e){let t=super.setupEnvironment(e);return t?new uE(t):null}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new dE(mw)),t}setupOutgoingLight(){return Ng.rgb}setupLightingModel(){return new pE}},hE=V(({f0:e,f90:t,dotVH:n})=>{let r=n.mul(-5.55473).sub(6.98316).mul(n).exp2();return e.mul(r.oneMinus()).add(t.mul(r))}),gE=V(e=>e.diffuseColor.mul(1/Math.PI)),_E=()=>U(.25),vE=V(({dotNH:e})=>Qg.mul(U(.5)).add(1).mul(U(1/Math.PI)).mul(e.pow(Qg))),yE=V(({lightDirection:e})=>{let t=e.add(uS).normalize(),n=xS.dot(t).clamp(),r=uS.dot(t).clamp(),i=hE({f0:Yg,f90:1,dotVH:r}),a=_E(),o=vE({dotNH:n});return i.mul(a).mul(o)}),bE=class extends pE{constructor(e=!0){super(),this.specular=e}direct({lightDirection:e,lightColor:t,reflectedLight:n}){let r=xS.dot(e).clamp().mul(t);n.directDiffuse.addAssign(r.mul(gE({diffuseColor:Ng.rgb}))),this.specular===!0&&n.directSpecular.addAssign(r.mul(yE({lightDirection:e})).mul(BC))}indirect(e){let{ambientOcclusion:t,irradiance:n,reflectedLight:r}=e.context;r.indirectDiffuse.addAssign(n.mul(gE({diffuseColor:Ng}))),r.indirectDiffuse.mulAssign(t)}},xE=new Rl,SE=class extends VT{static get type(){return`MeshLambertNodeMaterial`}constructor(e){super(),this.isMeshLambertNodeMaterial=!0,this.lights=!0,this.setDefaultValues(xE),this.setValues(e)}setupEnvironment(e){let t=super.setupEnvironment(e);return t?new uE(t):null}setupLightingModel(){return new bE(!1)}},CE=new Fl,wE=class extends VT{static get type(){return`MeshPhongNodeMaterial`}constructor(e){super(),this.isMeshPhongNodeMaterial=!0,this.lights=!0,this.shininessNode=null,this.specularNode=null,this.setDefaultValues(CE),this.setValues(e)}setupEnvironment(e){let t=super.setupEnvironment(e);return t?new uE(t):null}setupLightingModel(){return new bE}setupVariants(){let e=(this.shininessNode?U(this.shininessNode):PC).max(1e-4);Qg.assign(e);let t=this.specularNode||LC;Yg.assign(t)}},TE=V(e=>{if(e.geometry.hasAttribute(`normal`)===!1)return U(0);let t=yS.dFdx().abs().max(yS.dFdy().abs());return t.x.max(t.y).max(t.z)}),EE=V(e=>{let{roughness:t}=e,n=TE(),r=t.max(.0525);return r=r.add(n),r=r.min(1),r}),DE=V(({alpha:e,dotNL:t,dotNV:n})=>{let r=e.pow2(),i=t.mul(r.add(r.oneMinus().mul(n.pow2())).sqrt()),a=n.mul(r.add(r.oneMinus().mul(t.pow2())).sqrt());return A_(.5,i.add(a).max(Q_))}).setLayout({name:`V_GGX_SmithCorrelated`,type:`float`,inputs:[{name:`alpha`,type:`float`},{name:`dotNL`,type:`float`},{name:`dotNV`,type:`float`}]}),OE=V(({alphaT:e,alphaB:t,dotTV:n,dotBV:r,dotTL:i,dotBL:a,dotNV:o,dotNL:s})=>{let c=s.mul(K(e.mul(n),t.mul(r),o).length()),l=o.mul(K(e.mul(i),t.mul(a),s).length());return A_(.5,c.add(l).max(Q_))}).setLayout({name:`V_GGX_SmithCorrelated_Anisotropic`,type:`float`,inputs:[{name:`alphaT`,type:`float`,qualifier:`in`},{name:`alphaB`,type:`float`,qualifier:`in`},{name:`dotTV`,type:`float`,qualifier:`in`},{name:`dotBV`,type:`float`,qualifier:`in`},{name:`dotTL`,type:`float`,qualifier:`in`},{name:`dotBL`,type:`float`,qualifier:`in`},{name:`dotNV`,type:`float`,qualifier:`in`},{name:`dotNL`,type:`float`,qualifier:`in`}]}),kE=V(({alpha:e,dotNH:t})=>{let n=e.pow2(),r=t.pow2().mul(n.oneMinus()).oneMinus();return n.div(r.pow2()).mul(1/Math.PI)}).setLayout({name:`D_GGX`,type:`float`,inputs:[{name:`alpha`,type:`float`},{name:`dotNH`,type:`float`}]}),AE=U(1/Math.PI),jE=V(({alphaT:e,alphaB:t,dotNH:n,dotTH:r,dotBH:i})=>{let a=e.mul(t),o=K(t.mul(r),e.mul(i),a.mul(n)),s=o.dot(o),c=a.div(s);return AE.mul(a.mul(c.pow2()))}).setLayout({name:`D_GGX_Anisotropic`,type:`float`,inputs:[{name:`alphaT`,type:`float`,qualifier:`in`},{name:`alphaB`,type:`float`,qualifier:`in`},{name:`dotNH`,type:`float`,qualifier:`in`},{name:`dotTH`,type:`float`,qualifier:`in`},{name:`dotBH`,type:`float`,qualifier:`in`}]}),ME=V(({lightDirection:e,f0:t,f90:n,roughness:r,f:i,normalView:a=xS,viewDirection:o=uS,USE_IRIDESCENCE:s,USE_ANISOTROPY:c})=>{let l=r.pow2(),u=e.add(o).normalize(),d=a.dot(e).clamp(),f=a.dot(o).clamp(),p=a.dot(u).clamp(),m=o.dot(u).clamp(),h=hE({f0:t,f90:n,dotVH:m}),g,_;if(lp(s)&&(h=Hg.mix(h,i)),lp(c)){let t=qg.dot(e),n=qg.dot(o),r=qg.dot(u),i=Jg.dot(e),a=Jg.dot(o),s=Jg.dot(u);g=OE({alphaT:Gg,alphaB:l,dotTV:n,dotBV:a,dotTL:t,dotBL:i,dotNV:f,dotNL:d}),_=jE({alphaT:Gg,alphaB:l,dotNH:p,dotTH:r,dotBH:s})}else g=DE({alpha:l,dotNL:d,dotNV:f}),_=kE({alpha:l,dotNH:p});return h.mul(g).mul(_)}),NE=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]),PE=null,FE=V(({roughness:e,dotNV:t})=>{PE===null&&(PE=new Cs(NE,16,16,An,_n),PE.name=`DFG_LUT`,PE.minFilter=an,PE.magFilter=an,PE.wrapS=Zt,PE.wrapT=Zt,PE.generateMipmaps=!1,PE.needsUpdate=!0);let n=pg(e,t);return Vb(PE,n).rg}),IE=V(e=>{let{dotNV:t,specularColor:n,specularF90:r,roughness:i}=e,a=FE({dotNV:t,roughness:i});return n.mul(a.x).add(r.mul(a.y))}),LE=V(({f:e,f90:t,dotVH:n})=>{let r=n.oneMinus().saturate(),i=r.mul(r),a=r.mul(i,i).clamp(0,.9999);return e.sub(K(t).mul(a)).div(a.oneMinus())}).setLayout({name:`Schlick_to_F0`,type:`vec3`,inputs:[{name:`f`,type:`vec3`},{name:`f90`,type:`float`},{name:`dotVH`,type:`float`}]}),RE=V(({roughness:e,dotNH:t})=>{let n=e.pow2(),r=U(1).div(n),i=t.pow2().oneMinus().max(.0078125);return U(2).add(r).mul(i.pow(r.mul(.5))).div(2*Math.PI)}).setLayout({name:`D_Charlie`,type:`float`,inputs:[{name:`roughness`,type:`float`},{name:`dotNH`,type:`float`}]}),zE=V(({dotNV:e,dotNL:t})=>U(1).div(U(4).mul(t.add(e).sub(t.mul(e)))).clamp()).setLayout({name:`V_Neubelt`,type:`float`,inputs:[{name:`dotNV`,type:`float`},{name:`dotNL`,type:`float`}]}),BE=V(({lightDirection:e})=>{let t=e.add(uS).normalize(),n=xS.dot(e).clamp(),r=xS.dot(uS).clamp(),i=xS.dot(t).clamp(),a=RE({roughness:Vg,dotNH:i}),o=zE({dotNV:r,dotNL:n});return Bg.mul(a).mul(o)}),VE=V(({N:e,V:t,roughness:n})=>{let r=e.dot(t).saturate(),i=pg(n,r.oneMinus().sqrt());return i.assign(i.mul(.984375).add(.0078125)),i}).setLayout({name:`LTC_Uv`,type:`vec2`,inputs:[{name:`N`,type:`vec3`},{name:`V`,type:`vec3`},{name:`roughness`,type:`float`}]}),HE=V(({f:e})=>{let t=e.length();return Gv(t.mul(t).add(e.z).div(t.add(1)),0)}).setLayout({name:`LTC_ClippedSphereFormFactor`,type:`float`,inputs:[{name:`f`,type:`vec3`}]}),UE=V(({v1:e,v2:t})=>{let n=e.dot(t),r=n.abs().toVar(),i=r.mul(.0145206).add(.4965155).mul(r).add(.8543985).toVar(),a=r.add(4.1616724).mul(r).add(3.417594).toVar(),o=i.div(a),s=n.greaterThan(0).select(o,Gv(n.mul(n).oneMinus(),1e-7).inverseSqrt().mul(.5).sub(o));return e.cross(t).mul(s)}).setLayout({name:`LTC_EdgeVectorFormFactor`,type:`vec3`,inputs:[{name:`v1`,type:`vec3`},{name:`v2`,type:`vec3`}]}),WE=V(({N:e,V:t,P:n,mInv:r,p0:i,p1:a,p2:o,p3:s})=>{let c=a.sub(i).toVar(),l=s.sub(i).toVar(),u=c.cross(l),d=K().toVar();return lg(u.dot(n.sub(i)).greaterThanEqual(0),()=>{let c=t.sub(e.mul(t.dot(e))).normalize(),l=e.cross(c).negate(),u=r.mul(Tg(c,l,e).transpose()).toVar(),f=u.mul(i.sub(n)).normalize().toVar(),p=u.mul(a.sub(n)).normalize().toVar(),m=u.mul(o.sub(n)).normalize().toVar(),h=u.mul(s.sub(n)).normalize().toVar(),g=K(0).toVar();g.addAssign(UE({v1:f,v2:p})),g.addAssign(UE({v1:p,v2:m})),g.addAssign(UE({v1:m,v2:h})),g.addAssign(UE({v1:h,v2:f})),d.assign(K(HE({f:g})))}),d}).setLayout({name:`LTC_Evaluate`,type:`vec3`,inputs:[{name:`N`,type:`vec3`},{name:`V`,type:`vec3`},{name:`P`,type:`vec3`},{name:`mInv`,type:`mat3`},{name:`p0`,type:`vec3`},{name:`p1`,type:`vec3`},{name:`p2`,type:`vec3`},{name:`p3`,type:`vec3`}]}),GE=V(({P:e,p0:t,p1:n,p2:r,p3:i})=>{let a=n.sub(t).toVar(),o=i.sub(t).toVar(),s=a.cross(o),c=K().toVar();return lg(s.dot(e.sub(t)).greaterThanEqual(0),()=>{let a=t.sub(e).normalize().toVar(),o=n.sub(e).normalize().toVar(),s=r.sub(e).normalize().toVar(),l=i.sub(e).normalize().toVar(),u=K(0).toVar();u.addAssign(UE({v1:a,v2:o})),u.addAssign(UE({v1:o,v2:s})),u.addAssign(UE({v1:s,v2:l})),u.addAssign(UE({v1:l,v2:a})),c.assign(K(HE({f:u.abs()})))}),c}).setLayout({name:`LTC_Evaluate_Volume`,type:`vec3`,inputs:[{name:`P`,type:`vec3`},{name:`p0`,type:`vec3`},{name:`p1`,type:`vec3`},{name:`p2`,type:`vec3`},{name:`p3`,type:`vec3`}]}),KE=1/6,qE=e=>k_(KE,k_(e,k_(e,e.negate().add(3)).sub(3)).add(1)),JE=e=>k_(KE,k_(e,k_(e,k_(3,e).sub(6))).add(4)),YE=e=>k_(KE,k_(e,k_(e,k_(-3,e).add(3)).add(3)).add(1)),XE=e=>k_(KE,Qv(e,3)),ZE=e=>qE(e).add(JE(e)),QE=e=>YE(e).add(XE(e)),$E=e=>D_(-1,JE(e).div(qE(e).add(JE(e)))),eD=e=>D_(1,XE(e).div(YE(e).add(XE(e)))),tD=(e,t,n)=>{let r=e.uvNode,i=k_(r,t.zw).add(.5),a=mv(i),o=_v(i),s=ZE(o.x),c=QE(o.x),l=$E(o.x),u=eD(o.x),d=$E(o.y),f=eD(o.y),p=pg(a.x.add(l),a.y.add(d)).sub(.5).mul(t.xy),m=pg(a.x.add(u),a.y.add(d)).sub(.5).mul(t.xy),h=pg(a.x.add(l),a.y.add(f)).sub(.5).mul(t.xy),g=pg(a.x.add(u),a.y.add(f)).sub(.5).mul(t.xy),_=ZE(o.y).mul(D_(s.mul(e.sample(p).level(n)),c.mul(e.sample(m).level(n)))),v=QE(o.y).mul(D_(s.mul(e.sample(h).level(n)),c.mul(e.sample(g).level(n))));return _.add(v)},nD=V(([e,t])=>{let n=pg(e.size(W(t))),r=pg(e.size(W(t.add(1)))),i=A_(1,n),a=A_(1,r),o=tD(e,bg(i,n),mv(t)),s=tD(e,bg(a,r),hv(t));return _v(t).mix(o,s)}),rD=V(([e,t])=>{let n=t.mul(Ib(e));return nD(e,n)}),iD=V(([e,t,n,r,i])=>{let a=K(uy(t.negate(),gv(e),A_(1,r))),o=K(Mv(i[0].xyz),Mv(i[1].xyz),Mv(i[2].xyz));return gv(a).mul(n.mul(o))}).setLayout({name:`getVolumeTransmissionRay`,type:`vec3`,inputs:[{name:`n`,type:`vec3`},{name:`v`,type:`vec3`},{name:`thickness`,type:`float`},{name:`ior`,type:`float`},{name:`modelMatrix`,type:`mat4`}]}),aD=V(([e,t])=>e.mul(cy(t.mul(2).sub(2),0,1))).setLayout({name:`applyIorToRoughness`,type:`float`,inputs:[{name:`roughness`,type:`float`},{name:`ior`,type:`float`}]}),oD=fT(),sD=mT(),cD=V(([e,t,n],{material:r})=>{let i=(r.side===1?oD:sD).sample(e.mul(Px.zw).add(Px.xy).div(ax)),a=dv(Px.z).mul(aD(t,n));return nD(i,a)}),lD=V(([e,t,n])=>(lg(n.notEqual(0),()=>{let r=uv(t).negate().div(n);return cv(r.negate().mul(e))}),K(1))).setLayout({name:`volumeAttenuation`,type:`vec3`,inputs:[{name:`transmissionDistance`,type:`float`},{name:`attenuationColor`,type:`vec3`},{name:`attenuationDistance`,type:`float`}]}),uD=V(([e,t,n,r,i,a,o,s,c,l,u,d,f,p,m])=>{let h,g;if(m){h=bg().toVar(),g=K().toVar();let i=u.sub(1).mul(m.mul(.025)),a=K(u.sub(i),u,u.add(i));Xw({start:0,end:3},({i})=>{let u=a.element(i),m=iD(e,t,d,u,s),_=o.add(m),v=l.mul(c.mul(bg(_,1))),y=pg(v.xy.div(v.w)).toVar();y.addAssign(1),y.divAssign(2),y.assign(pg(y.x,y.y.oneMinus()));let b=cD(y,n,u);h.element(i).assign(b.element(i)),h.a.addAssign(b.a),g.element(i).assign(r.element(i).mul(lD(Mv(m),f,p).element(i)))}),h.a.divAssign(3)}else{let i=iD(e,t,d,u,s),a=o.add(i),m=l.mul(c.mul(bg(a,1))),_=pg(m.xy.div(m.w)).toVar();_.addAssign(1),_.divAssign(2),_.assign(pg(_.x,_.y.oneMinus())),h=cD(_,n,u),g=r.mul(lD(Mv(i),f,p))}let _=g.rgb.mul(h.rgb),v=e.dot(t).clamp(),y=K(IE({dotNV:v,specularColor:i,specularF90:a,roughness:n})),b=g.r.add(g.g,g.b).div(3);return bg(y.oneMinus().mul(_),h.a.oneMinus().mul(b).oneMinus())}),dD=Tg(3.2404542,-1.5371385,-.4985314,-.969266,1.8760108,.041556,.0556434,-.2040259,1.0572252),fD=e=>{let t=e.sqrt();return K(1).add(t).div(K(1).sub(t))},pD=(e,t)=>e.sub(t).div(e.add(t)).pow2(),mD=(e,t)=>{let n=e.mul(2*Math.PI*1e-9),r=K(54856e-17,44201e-17,52481e-17),i=K(1681e3,1795300,2208400),a=K(43278e5,93046e5,66121e5),o=U(9747e-17*Math.sqrt(2*Math.PI*45282e5)).mul(n.mul(2239900).add(t.x).cos()).mul(n.pow2().mul(-45282e5).exp()),s=r.mul(a.mul(2*Math.PI).sqrt()).mul(i.mul(n).add(t).cos()).mul(n.pow2().negate().mul(a).exp());return s=K(s.x.add(o),s.y,s.z).div(1.0685e-7),dD.mul(s)},hD=V(({outsideIOR:e,eta2:t,cosTheta1:n,thinFilmThickness:r,baseF0:i})=>{let a=sy(e,t,dy(0,.03,r)),o=e.div(a).pow2().mul(n.pow2().oneMinus()).oneMinus();lg(o.lessThan(0),()=>K(1));let s=o.sqrt(),c=pD(a,e),l=hE({f0:c,f90:1,dotVH:n}),u=l.oneMinus(),d=a.lessThan(e).select(Math.PI,0),f=U(Math.PI).sub(d),p=fD(i.clamp(0,.9999)),m=pD(p,a.toVec3()),h=hE({f0:m,f90:1,dotVH:s}),g=K(p.x.lessThan(a).select(Math.PI,0),p.y.lessThan(a).select(Math.PI,0),p.z.lessThan(a).select(Math.PI,0)),_=a.mul(r,s,2),v=K(f).add(g),y=l.mul(h).clamp(1e-5,.9999),b=y.sqrt(),x=u.pow2().mul(h).div(K(1).sub(y)),S=l.add(x).toVar(),C=x.sub(u).toVar();return Xw({start:1,end:2,condition:`<=`,name:`m`},({m:e})=>{C.mulAssign(b);let t=mD(U(e).mul(_),U(e).mul(v)).mul(2);S.addAssign(C.mul(t))}),S.max(K(0))}).setLayout({name:`evalIridescence`,type:`vec3`,inputs:[{name:`outsideIOR`,type:`float`},{name:`eta2`,type:`float`},{name:`cosTheta1`,type:`float`},{name:`thinFilmThickness`,type:`float`},{name:`baseF0`,type:`vec3`}]}),gD=V(({normal:e,viewDir:t,roughness:n})=>{let r=e.dot(t).saturate(),i=n.mul(n),a=n.add(.1).reciprocal(),o=U(-1.9362).add(n.mul(1.0678)).add(i.mul(.4573)).sub(a.mul(.8469)),s=U(-.6014).add(n.mul(.5538)).sub(i.mul(.467)).sub(a.mul(.1255));return o.mul(r).add(s).exp().saturate()}),_D=K(.04),vD=U(1),yD=class extends fE{constructor(e=!1,t=!1,n=!1,r=!1,i=!1,a=!1,o=!1){super(),this.clearcoat=e,this.sheen=t,this.iridescence=n,this.anisotropy=r,this.transmission=i,this.dispersion=a,this.retroreflection=o,this.clearcoatRadiance=null,this.clearcoatSpecularDirect=null,this.clearcoatSpecularIndirect=null,this.sheenSpecularDirect=null,this.sheenSpecularIndirect=null,this.iridescenceFresnel=null,this.iridescenceF0Dielectric=null,this.iridescenceF0Metallic=null,this.dfg=null,this.multiScatteringCompensation=null}start(e){if(this.clearcoat===!0&&(this.clearcoatRadiance=K().toVar(`clearcoatRadiance`),this.clearcoatSpecularDirect=K().toVar(`clearcoatSpecularDirect`),this.clearcoatSpecularIndirect=K().toVar(`clearcoatSpecularIndirect`)),this.sheen===!0&&(this.sheenSpecularDirect=K().toVar(`sheenSpecularDirect`),this.sheenSpecularIndirect=K().toVar(`sheenSpecularIndirect`)),this.iridescence===!0){let e=xS.dot(uS).clamp(),t=hD({outsideIOR:U(1),eta2:Ug,cosTheta1:e,thinFilmThickness:Wg,baseF0:Yg}),n=hD({outsideIOR:U(1),eta2:Ug,cosTheta1:e,thinFilmThickness:Wg,baseF0:Ng.rgb});this.iridescenceFresnel=sy(t,n,Lg),this.iridescenceF0Dielectric=LE({f:t,f90:1,dotVH:e}),this.iridescenceF0Metallic=LE({f:n,f90:1,dotVH:e})}if(this.transmission===!0){let t=sS,n=Nx.sub(sS).normalize(),r=SS,i=e.context;i.backdrop=uD(r,n,Ig,Pg,Xg,Zg,t,Kx,Ax,Ox,r_,a_,s_,o_,this.dispersion?c_:null),i.backdropAlpha=i_,Ng.a.mulAssign(sy(1,i.backdrop.a,i_))}let t=xS.dot(uS).clamp();this.dfg=FE({roughness:Ig,dotNV:t}).toConst(`dfg`);let n=this.dfg.x.add(this.dfg.y);this.multiScatteringCompensation=Xg.mul(n.reciprocal().sub(1)).add(1).toConst(`multiScatteringCompensation`),super.start(e)}computeMultiscattering(e,t,n,r,i=null){let a=this.dfg,o=i?Hg.mix(r,i):r,s=o.mul(a.x).add(n.mul(a.y)),c=a.x.add(a.y).oneMinus(),l=o.add(o.oneMinus().mul(.047619)),u=s.mul(l).div(c.mul(l).oneMinus());e.addAssign(s),t.addAssign(u.mul(c))}direct({lightDirection:e,lightColor:t,reflectedLight:n}){let r=xS.dot(e).clamp().mul(t).toVar();if(this.sheen===!0){this.sheenSpecularDirect.addAssign(r.mul(BE({lightDirection:e})));let t=gD({normal:xS,viewDir:uS,roughness:Vg}),n=gD({normal:xS,viewDir:e,roughness:Vg}),i=Bg.r.max(Bg.g).max(Bg.b).mul(t.max(n)).oneMinus();r.mulAssign(i)}if(this.clearcoat===!0){let n=CS.dot(e).clamp().mul(t);this.clearcoatSpecularDirect.addAssign(n.mul(ME({lightDirection:e,f0:_D,f90:vD,roughness:zg,normalView:CS})))}let i=e.add(uS).normalize(),a=uS.dot(i).clamp(),o=hE({f0:Yg,f90:Zg,dotVH:a}),s=ME({lightDirection:e,f0:Xg,f90:1,roughness:Ig,f:this.iridescenceFresnel,USE_IRIDESCENCE:this.iridescence,USE_ANISOTROPY:this.anisotropy});if(this.retroreflection===!0){let t=uS.negate().reflect(xS),n=e.add(t).normalize(),r=t.dot(n).clamp(),i=hE({f0:Yg,f90:Zg,dotVH:r}),a=ME({lightDirection:e,viewDirection:t,f0:Xg,f90:1,roughness:Ig,f:this.iridescenceFresnel,USE_IRIDESCENCE:this.iridescence,USE_ANISOTROPY:this.anisotropy});o=sy(o,i,l_.clamp()),s=sy(s,a,l_.clamp())}n.directDiffuse.addAssign(r.mul(gE({diffuseColor:Pg})).mul(o.oneMinus())),n.directSpecular.addAssign(r.mul(s).mul(this.multiScatteringCompensation))}directRectArea({lightColor:e,lightPosition:t,halfWidth:n,halfHeight:r,reflectedLight:i,ltc_1:a,ltc_2:o}){let s=t.add(n).sub(r),c=t.sub(n).sub(r),l=t.sub(n).add(r),u=t.add(n).add(r),d=xS,f=uS,p=lS.toVar(),m=VE({N:d,V:f,roughness:Ig}),h=a.sample(m).toVar(),g=o.sample(m).toVar(),_=Tg(K(h.x,0,h.y),K(0,1,0),K(h.z,0,h.w)).toVar(),v=Xg.mul(g.x).add(Zg.sub(Xg).mul(g.y)).toVar();if(i.directSpecular.addAssign(e.mul(v).mul(WE({N:d,V:f,P:p,mInv:_,p0:s,p1:c,p2:l,p3:u}))),i.directDiffuse.addAssign(e.mul(Pg).mul(WE({N:d,V:f,P:p,mInv:Tg(1,0,0,0,1,0,0,0,1),p0:s,p1:c,p2:l,p3:u}))),this.clearcoat===!0){let t=CS,n=VE({N:t,V:f,roughness:zg}),r=a.sample(n),i=o.sample(n),d=Tg(K(r.x,0,r.y),K(0,1,0),K(r.z,0,r.w)),m=_D.mul(i.x).add(vD.sub(_D).mul(i.y));this.clearcoatSpecularDirect.addAssign(e.mul(m).mul(WE({N:t,V:f,P:p,mInv:d,p0:s,p1:c,p2:l,p3:u})))}}indirect(e){this.indirectDiffuse(e),this.indirectSpecular(e),this.ambientOcclusion(e)}indirectDiffuse(e){let{irradiance:t,reflectedLight:n}=e.context,r=K().toVar(),i=K().toVar();this.computeMultiscattering(r,i,Zg,Yg,this.iridescenceF0Dielectric);let a=t.mul(gE({diffuseColor:Pg})).mul(r.add(i).oneMinus()).toVar();if(this.sheen===!0){let e=gD({normal:xS,viewDir:uS,roughness:Vg});this.sheenSpecularIndirect.addAssign(t.mul(Bg,e,1/Math.PI));let n=Bg.r.max(Bg.g).max(Bg.b).mul(e).oneMinus();a.mulAssign(n)}n.indirectDiffuse.addAssign(a)}indirectSpecular(e){let{radiance:t,iblIrradiance:n,reflectedLight:r}=e.context;if(this.sheen===!0&&this.sheenSpecularIndirect.addAssign(n.mul(Bg,gD({normal:xS,viewDir:uS,roughness:Vg}),1/Math.PI)),this.clearcoat===!0){let e=CS.dot(uS).clamp(),t=IE({dotNV:e,specularColor:_D,specularF90:vD,roughness:zg});this.clearcoatSpecularIndirect.addAssign(this.clearcoatRadiance.mul(t))}let i=K().toVar(`singleScatteringDielectric`),a=K().toVar(`multiScatteringDielectric`),o=K().toVar(`singleScatteringMetallic`),s=K().toVar(`multiScatteringMetallic`);this.computeMultiscattering(i,a,Zg,Yg,this.iridescenceF0Dielectric),this.computeMultiscattering(o,s,Zg,Ng.rgb,this.iridescenceF0Metallic);let c=sy(i,o,Lg),l=sy(a,s,Lg),u=i.add(a),d=Pg.mul(u.oneMinus()),f=n.mul(1/Math.PI),p=t.mul(c).add(l.mul(f)).toVar(),m=d.mul(f).toVar();if(this.sheen===!0){let e=gD({normal:xS,viewDir:uS,roughness:Vg}),t=Bg.r.max(Bg.g).max(Bg.b).mul(e).oneMinus();p.mulAssign(t),m.mulAssign(t)}r.indirectSpecular.addAssign(p),r.indirectDiffuse.addAssign(m)}ambientOcclusion(e){let{ambientOcclusion:t,reflectedLight:n}=e.context,r=xS.dot(uS).clamp().add(t),i=Ig.mul(-16).oneMinus().negate().exp2(),a=t.sub(r.pow(i).oneMinus()).clamp();this.clearcoat===!0&&this.clearcoatSpecularIndirect.mulAssign(t),this.sheen===!0&&this.sheenSpecularIndirect.mulAssign(t),n.indirectDiffuse.mulAssign(t),n.indirectSpecular.mulAssign(a)}finish({context:e}){let{outgoingLight:t}=e;if(this.clearcoat===!0){let e=CS.dot(uS).clamp(),n=hE({dotVH:e,f0:_D,f90:vD}),r=t.mul(Rg.mul(n).oneMinus()).add(this.clearcoatSpecularDirect.add(this.clearcoatSpecularIndirect).mul(Rg));t.assign(r)}if(this.sheen===!0){let e=t.add(this.sheenSpecularDirect,this.sheenSpecularIndirect);t.assign(e)}}},bD=2.399963229728653,xD=U(1),SD=U(-2),CD=U(.8),wD=U(-1),TD=U(.4),ED=U(2),DD=U(.305),OD=U(3),kD=U(.21),AD=U(4),jD=U(4),MD=U(16),ND=V(([e])=>{let t=K(Av(e)).toVar(),n=U(-1).toVar();return lg(t.x.greaterThan(t.z),()=>{lg(t.x.greaterThan(t.y),()=>{n.assign(by(e.x.greaterThan(0),0,3))}).Else(()=>{n.assign(by(e.y.greaterThan(0),1,4))})}).Else(()=>{lg(t.z.greaterThan(t.y),()=>{n.assign(by(e.z.greaterThan(0),2,5))}).Else(()=>{n.assign(by(e.y.greaterThan(0),1,4))})}),n}).setLayout({name:`getFace`,type:`float`,inputs:[{name:`direction`,type:`vec3`}]}),PD=V(([e,t])=>{let n=pg().toVar();return lg(t.equal(0),()=>{n.assign(pg(e.z,e.y).div(Av(e.x)))}).ElseIf(t.equal(1),()=>{n.assign(pg(e.x.negate(),e.z.negate()).div(Av(e.y)))}).ElseIf(t.equal(2),()=>{n.assign(pg(e.x.negate(),e.y).div(Av(e.z)))}).ElseIf(t.equal(3),()=>{n.assign(pg(e.z.negate(),e.y).div(Av(e.x)))}).ElseIf(t.equal(4),()=>{n.assign(pg(e.x.negate(),e.z).div(Av(e.y)))}).Else(()=>{n.assign(pg(e.x,e.y).div(Av(e.z)))}),k_(.5,n.add(1))}).setLayout({name:`getUV`,type:`vec2`,inputs:[{name:`direction`,type:`vec3`},{name:`face`,type:`float`}]}),FD=V(([e])=>{let t=U(0).toVar();return lg(e.greaterThanEqual(CD),()=>{t.assign(xD.sub(e).mul(wD.sub(SD)).div(xD.sub(CD)).add(SD))}).ElseIf(e.greaterThanEqual(TD),()=>{t.assign(CD.sub(e).mul(ED.sub(wD)).div(CD.sub(TD)).add(wD))}).ElseIf(e.greaterThanEqual(DD),()=>{t.assign(TD.sub(e).mul(OD.sub(ED)).div(TD.sub(DD)).add(ED))}).ElseIf(e.greaterThanEqual(kD),()=>{t.assign(DD.sub(e).mul(AD.sub(OD)).div(DD.sub(kD)).add(OD))}).Else(()=>{t.assign(U(-2).mul(dv(k_(1.16,e))))}),t}).setLayout({name:`roughnessToMip`,type:`float`,inputs:[{name:`roughness`,type:`float`}]}),ID=V(([e,t,n,r,i,a])=>{let o=U(n),s=K(t),c=cy(FD(o),SD,a),l=_v(c),u=mv(c),d=K(LD(e,s,u,r,i,a)).toVar();return lg(l.notEqual(0),()=>{let t=K(LD(e,s,u.add(1),r,i,a)).toVar();d.assign(sy(d,t,l))}),d}),LD=V(([e,t,n,r,i,a])=>{let o=U(n).toVar(),s=K(t),c=U(ND(s)).toVar(),l=U(Gv(jD.sub(o),0)).toVar();o.assign(Gv(o,jD));let u=U(lv(o)).toVar(),d=pg(PD(s,c).mul(u.sub(2)).add(1)).toVar();return lg(c.greaterThan(2),()=>{d.y.addAssign(u),c.subAssign(3)}),d.x.addAssign(c.mul(u)),d.x.addAssign(l.mul(k_(3,MD))),d.y.addAssign(k_(4,lv(a).sub(u))),d.x.mulAssign(r),d.y.mulAssign(i),e.sample(d).grad(pg(),pg())}),RD=V(({SAMPLES:e,sigma:t,outputDirection:n,mipInt:r,envMap:i,CUBEUV_TEXEL_WIDTH:a,CUBEUV_TEXEL_HEIGHT:o,CUBEUV_MAX_MIP:s})=>{let c=K(0).toVar();return lg(t.equal(0),()=>{c.assign(LD(i,n,r,a,o,s))}).Else(()=>{let l=by(Av(n.z).lessThan(.999),K(0,0,1),K(1,0,0)),u=gv(Zv(l,n)).toVar(),d=Zv(n,u).toVar(),f=Wv(t.mul(3),Math.PI),p=cv(f.mul(f).mul(-.5).div(t.mul(t))).oneMinus().toVar(),m=U(0).toVar();Xw({start:W(0),end:e},({i:l})=>{let f=U(l).add(.5).div(U(e)),h=t.mul(fv(uv(f.mul(p).oneMinus()).mul(-2))).toVar(),g=U(l).mul(bD).toVar(),_=u.mul(bv(g)).add(d.mul(vv(g))),v=n.mul(bv(h)).add(_.mul(vv(h))),y=vv(h).div(h).toVar();c.addAssign(LD(i,v,r,a,o,s).mul(y)),m.addAssign(y)}),c.divAssign(m)}),bg(c,1)}),zD=V(([e])=>{let t=G(e).toVar();return t.assign(t.shiftLeft(G(16)).bitOr(t.shiftRight(G(16)))),t.assign(t.bitAnd(G(1431655765)).shiftLeft(G(1)).bitOr(t.bitAnd(G(2863311530)).shiftRight(G(1)))),t.assign(t.bitAnd(G(858993459)).shiftLeft(G(2)).bitOr(t.bitAnd(G(3435973836)).shiftRight(G(2)))),t.assign(t.bitAnd(G(252645135)).shiftLeft(G(4)).bitOr(t.bitAnd(G(4042322160)).shiftRight(G(4)))),t.assign(t.bitAnd(G(16711935)).shiftLeft(G(8)).bitOr(t.bitAnd(G(4278255360)).shiftRight(G(8)))),U(t).mul(23283064365386963e-26)}),BD=V(([e,t])=>pg(U(e).div(U(t)),zD(e))),VD=V(([e,t,n])=>{let r=n.mul(n).toConst(),i=K(1,0,0).toConst(),a=Zv(t,i).toConst(),o=fv(e.x).toConst(),s=k_(2,3.14159265359).mul(e.y).toConst(),c=o.mul(bv(s)).toConst(),l=o.mul(vv(s)).toVar(),u=k_(.5,t.z.add(1)).toConst();l.assign(u.oneMinus().mul(fv(c.mul(c).oneMinus())).add(u.mul(l)));let d=i.mul(c).add(a.mul(l)).add(t.mul(fv(Gv(0,c.mul(c).add(l.mul(l)).oneMinus()))));return gv(K(r.mul(d.x),r.mul(d.y),Gv(0,d.z)))}),HD=V(({roughness:e,mipInt:t,envMap:n,N_immutable:r,GGX_SAMPLES:i,CUBEUV_TEXEL_WIDTH:a,CUBEUV_TEXEL_HEIGHT:o,CUBEUV_MAX_MIP:s})=>{let c=K(r).toVar(),l=K(0).toVar(),u=U(0).toVar();return lg(e.lessThan(.001),()=>{l.assign(LD(n,c,t,a,o,s))}).Else(()=>{let r=by(Av(c.z).lessThan(.999),K(0,0,1),K(1,0,0)),d=gv(Zv(r,c)).toVar(),f=Zv(c,d).toVar();Xw({start:G(0),end:i},({i:r})=>{let p=BD(r,i),m=VD(p,K(0,0,1),e),h=gv(d.mul(m.x).add(f.mul(m.y)).add(c.mul(m.z))),g=gv(h.mul(Xv(c,h).mul(2)).sub(c)),_=Gv(Xv(c,g),0);lg(_.greaterThan(0),()=>{let e=LD(n,g,t,a,o,s);l.addAssign(e.mul(_)),u.addAssign(_)})}),lg(u.greaterThan(0),()=>{l.assign(l.div(u))})}),bg(l,1)}),UD=4,WD=6,GD=20,KD=256,qD=new Iu(-1,1,1,-1,0,1),JD=new ju(90,1),YD=new L,XD=null,ZD=0,QD=0,$D=new P,eO=new P,tO=new WeakMap,nO=[3,1,5,0,4,2],rO=jb(`outputDirection`).normalize(),iO=class{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._sizeLods=[],this._lodMeshes=[],this._blurMaterial=null,this._ggxMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._backgroundBox=null}get _hasInitialized(){return this._renderer.hasInitialized()}fromScene(e,t=0,n=.1,r=100,i={}){let{size:a=256,position:o=$D,renderTarget:s=null}=i;if(this._setSize(a),this._hasInitialized===!1)throw Error(`THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Use "await renderer.init();" before using this method.`);XD=this._renderer.getRenderTarget(),ZD=this._renderer.getActiveCubeFace(),QD=this._renderer.getActiveMipmapLevel();let c=s||this._allocateTarget(!0);return this._init(c),this._sceneToCubeUV(e,n,r,c,o),t>0&&this._blur(c,0,0,t),this._applyPMREM(c),this._cleanup(c),c}async fromSceneAsync(e,t=0,n=.1,r=100,i={}){return m(`PMREMGenerator: ".fromSceneAsync()" is deprecated. Use "await renderer.init()" instead.`),await this._renderer.init(),this.fromScene(e,t,n,r,i)}fromEquirectangular(e,t=null){if(this._hasInitialized===!1)throw Error(`THREE.PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Use "await renderer.init();" before using this method.`);return this._fromTexture(e,t)}async fromEquirectangularAsync(e,t=null){return m(`PMREMGenerator: ".fromEquirectangularAsync()" is deprecated. Use "await renderer.init()" instead.`),await this._renderer.init(),this._fromTexture(e,t)}fromCubemap(e,t=null){if(this._hasInitialized===!1)throw Error(`THREE.PMREMGenerator: .fromCubemap() called before the backend is initialized. Use "await renderer.init();" before using this method.`);return this._fromTexture(e,t)}async fromCubemapAsync(e,t=null){return m(`PMREMGenerator: ".fromCubemapAsync()" is deprecated. Use "await renderer.init()" instead.`),await this._renderer.init(),this._fromTexture(e,t)}async compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=Bp(),await this._compileMaterial(this._cubemapMaterial))}async compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=Vp(),await 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())}_setSizeFromTexture(e){e.mapping===301||e.mapping===302?this._setSize(e.image.length===0?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4)}_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.render(e,a)}c.autoClear=l,e.background=p}_textureToCubeUV(e,t){let n=this._renderer,r=e.mapping===301||e.mapping===302;r?this._cubemapMaterial===null&&(this._cubemapMaterial=Bp(e)):this._equirectMaterial===null&&(this._equirectMaterial=Vp(e));let i=r?this._cubemapMaterial:this._equirectMaterial;i.fragmentNode.value=e;let a=this._lodMeshes[0];a.material=i;let o=this._cubeSize;this._setViewport(t,0,0,3*o,2*o),n.setRenderTarget(t),n.render(a,qD)}_applyPMREM(e){let t=this._renderer,n=t.autoClear;t.autoClear=!1;let r=this._lodMeshes.length;for(let t=1;td-UD?n-d+UD:0),m=4*(this._cubeSize-f);e.texture.frame=(e.texture.frame||0)+1,s.envMap.value=e.texture,s.roughness.value=u,s.mipInt.value=d-t,this._setViewport(i,p,m,3*f,2*f),r.setRenderTarget(i),r.render(o,qD),i.texture.frame=(i.texture.frame||0)+1,s.envMap.value=i.texture,s.roughness.value=0,s.mipInt.value=d-n,this._setViewport(e,p,m,3*f,2*f),r.setRenderTarget(e),r.render(o,qD)}_blur(e,t,n,r){let i=this._pingPongRenderTarget,a=Math.min(r,Math.PI)/Math.SQRT2;this._blurPass(e,i,t,n,a),this._blurPass(i,e,n,n,a)}_blurPass(e,t,n,r,i){let a=this._renderer,o=this._blurMaterial,s=this._lodMeshes[r];s.material=o;let c=tO.get(o);e.texture.frame=(e.texture.frame||0)+1,c.envMap.value=e.texture,c.sigma.value=i,c.mipInt.value=this._lodMax-n;let l=this._sizeLods[r],u=3*l*(r>this._lodMax-UD?r-this._lodMax+UD:0),d=4*(this._cubeSize-l);this._setViewport(t,u,d,3*l,2*l),a.setRenderTarget(t),a.render(s,qD)}_setViewport(e,t,n,r,i){this._renderer.isWebGLRenderer?(e.viewport.set(t,e.height-i-n,r,i),e.scissor.set(t,e.height-i-n,r,i)):(e.viewport.set(t,n,r,i),e.scissor.set(t,n,r,i))}},aO=new WeakMap,oO=class extends mh{static get type(){return`PMREMNode`}constructor(e,t=null,n=null){super(`vec3`),this._value=e,this._pmrem=null,this.uvNode=t,this.levelNode=n,this._generator=null;let r=new ji;r.isRenderTargetTexture=!0,this._texture=Vb(r),this._width=v_(0),this._height=v_(0),this._maxMip=v_(0),this.updateBeforeType=nh.RENDER}set value(e){this._value=e,this._pmrem=null}get value(){return this._value}updateFromTexture(e){let t=Hp(e.image.height);this._texture.value=e,this._width.value=t.texelWidth,this._height.value=t.texelHeight,this._maxMip.value=t.maxMip}updateBefore(e){let t=this._pmrem,n=t?t.pmremVersion:-1,r=this._value;n!==r.pmremVersion&&(t=r.isPMREMTexture===!0||r.mapping===306?r:Up(r,e.renderer,this._generator),t!==null&&(this._pmrem=t,this.updateFromTexture(t)))}setup(e){this._generator===null&&(this._generator=new iO(e.renderer)),this.updateBefore(e);let t=this.uvNode;t===null&&e.context.getUV&&(t=e.context.getUV(this,e)),t=this._pmrem===null||this._pmrem.isRenderTargetTexture?MS.mul(K(t.x,t.y.negate(),t.z)):MS.mul(t);let n=this.levelNode;return n===null&&e.context.getTextureLevel&&(n=e.context.getTextureLevel(this)),ID(this._texture,t,n,this._width,this._height,this._maxMip)}dispose(){super.dispose(),this._generator!==null&&this._generator.dispose()}},sO=ng(oO).setParameterLength(1,3),cO=new WeakMap,lO=class extends iT{static get type(){return`EnvironmentNode`}constructor(e=null){super(),this.envNode=e}setup(e){let{material:t}=e,n=this.envNode;if(n.isTextureNode||n.isMaterialReferenceNode){let r=n.isTextureNode?n.value:t[n.property],i=this._getPMREMNodeCache(e.renderer),a=i.get(r);a===void 0&&(a=sO(r),i.set(r,a)),n=a}let r=t.useAnisotropy===!0||t.anisotropy>0?yC:xS,i=mb(n.context(uO(Ig,r)).mul(jS));if(t.useRetroreflection===!0||t.retroreflectivity>0){let e=mb(n.context(dO(Ig,r)).mul(jS));i=l_.clamp().mix(i,e)}let a=n.context(fO(SS)).mul(Math.PI).mul(jS),o=mb(a);e.context.radiance.addAssign(i),e.context.iblIrradiance.addAssign(o);let s=e.context.lightingModel.clearcoatRadiance;if(s){let e=n.context(uO(zg,CS)).mul(jS),t=mb(e);s.addAssign(t)}}_getPMREMNodeCache(e){let t=cO.get(e);return t===void 0&&(t=new WeakMap,cO.set(e,t)),t}},uO=(e,t)=>{let n=null;return{getUV:()=>(n===null&&(n=uS.negate().reflect(t),n=ty(e).mix(n,t).normalize(),n=n.transformDirection(jx)),n),getTextureLevel:()=>e}},dO=(e,t)=>{let n=null;return{getUV:()=>(n===null&&(n=ty(e).mix(uS,t).normalize(),n=n.transformDirection(jx)),n),getTextureLevel:()=>e}},fO=e=>({getUV:()=>e,getTextureLevel:()=>U(1)}),pO=new Nl,mO=class extends VT{static get type(){return`MeshStandardNodeMaterial`}constructor(e){super(),this.isMeshStandardNodeMaterial=!0,this.lights=!0,this.emissiveNode=null,this.metalnessNode=null,this.roughnessNode=null,this.setDefaultValues(pO),this.setValues(e)}setupEnvironment(e){let t=super.setupEnvironment(e);return t===null&&e.environmentNode&&(t=e.environmentNode),t?new lO(t):null}setupLightingModel(){return new yD}setupSpecular(){let e=sy(K(.04),Ng.rgb,Lg);Yg.assign(K(.04)),Xg.assign(e),Zg.assign(1)}setupVariants(){let e=this.metalnessNode?U(this.metalnessNode):UC;Lg.assign(e);let t=this.roughnessNode?U(this.roughnessNode):HC;t=EE({roughness:t}),Ig.assign(t),this.setupSpecular(),Pg.assign(Ng.rgb.mul(e.oneMinus()))}},hO=new Pl,gO=class extends mO{static get type(){return`MeshPhysicalNodeMaterial`}constructor(e){super(),this.isMeshPhysicalNodeMaterial=!0,this.clearcoatNode=null,this.clearcoatRoughnessNode=null,this.clearcoatNormalNode=null,this.sheenNode=null,this.sheenRoughnessNode=null,this.iridescenceNode=null,this.iridescenceIORNode=null,this.iridescenceThicknessNode=null,this.specularIntensityNode=null,this.specularColorNode=null,this.iorNode=null,this.transmissionNode=null,this.thicknessNode=null,this.attenuationDistanceNode=null,this.attenuationColorNode=null,this.dispersionNode=null,this.retroreflectivityNode=null,this.anisotropyNode=null,this.setDefaultValues(hO),this.setValues(e)}get useClearcoat(){return this.clearcoat>0||this.clearcoatNode!==null}get useIridescence(){return this.iridescence>0||this.iridescenceNode!==null}get useSheen(){return this.sheen>0||this.sheenNode!==null}get useAnisotropy(){return this.anisotropy>0||this.anisotropyNode!==null}get useTransmission(){return this.transmission>0||this.transmissionNode!==null}get useDispersion(){return this.dispersion>0||this.dispersionNode!==null}get useRetroreflection(){return this.retroreflectivity>0||this.retroreflectivityNode!==null}setupSpecular(){let e=this.iorNode?U(this.iorNode):rw,t=this.specularColorNode?K(this.specularColorNode):zC,n=this.specularIntensityNode?U(this.specularIntensityNode):RC;r_.assign(e),Yg.assign(Wv($v(r_.sub(1).div(r_.add(1))).mul(t),K(1)).mul(n)),Xg.assign(sy(Yg,Ng.rgb,Lg)),Zg.assign(sy(n,1,Lg))}setupLightingModel(){return new yD(this.useClearcoat,this.useSheen,this.useIridescence,this.useAnisotropy,this.useTransmission,this.useDispersion,this.useRetroreflection)}setupVariants(e){if(super.setupVariants(e),this.useClearcoat){let e=this.clearcoatNode?U(this.clearcoatNode):GC,t=this.clearcoatRoughnessNode?U(this.clearcoatRoughnessNode):KC;Rg.assign(e),zg.assign(EE({roughness:t}))}if(this.useSheen){let e=this.sheenNode?K(this.sheenNode):YC,t=this.sheenRoughnessNode?U(this.sheenRoughnessNode):XC;Bg.assign(e),Vg.assign(t)}if(this.useRetroreflection){let e=this.retroreflectivityNode?U(this.retroreflectivityNode):pw;l_.assign(e)}if(this.useIridescence){let e=this.iridescenceNode?U(this.iridescenceNode):QC,t=this.iridescenceIORNode?U(this.iridescenceIORNode):$C,n=this.iridescenceThicknessNode?U(this.iridescenceThicknessNode):ew;Hg.assign(e),Ug.assign(t),Wg.assign(n)}if(this.useAnisotropy){let e=(this.anisotropyNode?pg(this.anisotropyNode):ZC).toVar();Kg.assign(e.length()),lg(Kg.equal(0),()=>{e.assign(pg(1,0))}).Else(()=>{e.divAssign(pg(Kg)),Kg.assign(Kg.saturate())}),Gg.assign(Kg.pow2().mix(Ig.pow2(),1)),qg.assign(gC[0].mul(e.x).add(gC[1].mul(e.y))),Jg.assign(gC[1].mul(e.x).sub(gC[0].mul(e.y)))}if(this.useTransmission){let e=this.transmissionNode?U(this.transmissionNode):tw,t=this.thicknessNode?U(this.thicknessNode):nw,n=this.attenuationDistanceNode?U(this.attenuationDistanceNode):iw,r=this.attenuationColorNode?K(this.attenuationColorNode):aw;if(i_.assign(e),a_.assign(t),o_.assign(n),s_.assign(r),this.useDispersion){let e=this.dispersionNode?U(this.dispersionNode):fw;c_.assign(e)}}}setupClearcoatNormal(){return this.clearcoatNormalNode?K(this.clearcoatNormalNode):qC}setup(e){e.context.setupClearcoatNormal=()=>jy(this.setupClearcoatNormal(e),`NORMAL`,`vec3`),super.setup(e)}},_O=class extends yD{constructor(e=!1,t=!1,n=!1,r=!1,i=!1,a=!1,o=!1){super(e,t,n,r,i,a),this.useSSS=o}direct({lightDirection:e,lightColor:t,reflectedLight:n},r){if(this.useSSS===!0){let{thicknessColorNode:i,thicknessDistortionNode:a,thicknessAmbientNode:o,thicknessAttenuationNode:s,thicknessPowerNode:c,thicknessScaleNode:l}=r.material,u=e.add(xS.mul(a)).normalize(),d=U(uS.dot(u.negate()).saturate().pow(c).mul(l)),f=K(d.add(o).mul(i));n.directDiffuse.addAssign(f.mul(s.mul(t)))}super.direct({lightDirection:e,lightColor:t,reflectedLight:n},r)}},vO=class extends gO{static get type(){return`MeshSSSNodeMaterial`}constructor(e){super(e),this.thicknessColorNode=null,this.thicknessDistortionNode=U(.1),this.thicknessAmbientNode=U(0),this.thicknessAttenuationNode=U(.1),this.thicknessPowerNode=U(2),this.thicknessScaleNode=U(10)}get useSSS(){return this.thicknessColorNode!==null}setupLightingModel(){return new _O(this.useClearcoat,this.useSheen,this.useIridescence,this.useAnisotropy,this.useTransmission,this.useDispersion,this.useSSS)}},yO=V(({normal:e,lightDirection:t,builder:n})=>{let r=e.dot(t),i=pg(r.mul(.5).add(.5),0);if(n.material.gradientMap){let e=KS(`gradientMap`,`texture`).context({getUV:()=>i});return K(e.r)}{let e=i.fwidth().mul(.5);return sy(K(.7),K(1),dy(U(.7).sub(e.x),U(.7).add(e.x),i.x))}}),bO=class extends fE{direct({lightDirection:e,lightColor:t,reflectedLight:n},r){let i=yO({normal:xS,lightDirection:e,builder:r}).mul(t);n.directDiffuse.addAssign(i.mul(gE({diffuseColor:Ng.rgb})))}indirect(e){let{ambientOcclusion:t,irradiance:n,reflectedLight:r}=e.context;r.indirectDiffuse.addAssign(n.mul(gE({diffuseColor:Ng}))),r.indirectDiffuse.mulAssign(t)}},xO=new Il,SO=class extends VT{static get type(){return`MeshToonNodeMaterial`}constructor(e){super(),this.isMeshToonNodeMaterial=!0,this.lights=!0,this.setDefaultValues(xO),this.setValues(e)}setupLightingModel(){return new bO}},CO=V(()=>{let e=K(uS.z,0,uS.x.negate()).normalize(),t=uS.cross(e);return pg(e.dot(xS),t.dot(xS)).mul(.495).add(.5)}).once([`NORMAL`,`VERTEX`])().toVar(`matcapUV`),wO=new Vl,TO=class extends VT{static get type(){return`MeshMatcapNodeMaterial`}constructor(e){super(),this.isMeshMatcapNodeMaterial=!0,this.setDefaultValues(wO),this.setValues(e)}setupVariants(e){let t=CO,n;n=e.material.matcap?KS(`matcap`,`texture`).context({getUV:()=>t}):K(sy(.2,.8,t.y)),Ng.rgb.mulAssign(n.rgb)}},EO=class extends mh{static get type(){return`RotateNode`}constructor(e,t,n=`XYZ`){super(),this.positionNode=e,this.rotationNode=t,this._order=n}customCacheKey(){return Ym(this._order)}setOrder(e){return this._order=e,this}getOrder(){return this._order}generateNodeType(e){return this.positionNode.getNodeType(e)}setup(e){let{rotationNode:t,positionNode:n}=this;if(this.getNodeType(e)===`vec2`){let e=t.cos(),r=t.sin();return wg(e,r,r.negate(),e).mul(n)}{let e=t,r=this._order,i={X:Eg(bg(1,0,0,0),bg(0,bv(e.x),vv(e.x),0),bg(0,vv(e.x).negate(),bv(e.x),0),bg(0,0,0,1)),Y:Eg(bg(bv(e.y),0,vv(e.y).negate(),0),bg(0,1,0,0),bg(vv(e.y),0,bv(e.y),0),bg(0,0,0,1)),Z:Eg(bg(bv(e.z),vv(e.z),0,0),bg(vv(e.z).negate(),bv(e.z),0,0),bg(0,0,1,0),bg(0,0,0,1))};return i[r.charAt(0)].mul(i[r.charAt(1)]).mul(i[r.charAt(2)]).mul(bg(n,1)).xyz}}serialize(e){super.serialize(e),e.order=this._order}deserialize(e){super.deserialize(e),this._order=e.order}},DO=ng(EO).setParameterLength(2,3),OO=new jo,kO=class extends VT{static get type(){return`SpriteNodeMaterial`}constructor(e){super(),this.isSpriteNodeMaterial=!0,this._useSizeAttenuation=!0,this.positionNode=null,this.rotationNode=null,this.scaleNode=null,this.transparent=!0,this.setDefaultValues(OO),this.setValues(e)}setupPositionView(e){let{object:t,camera:n}=e,{positionNode:r,rotationNode:i,scaleNode:a,sizeAttenuation:o}=this,s=$x.mul(K(r||0)),c=pg(Kx[0].xyz.length(),Kx[1].xyz.length());a!==null&&(c=c.mul(pg(a))),n.isPerspectiveCamera&&o===!1&&(c=c.mul(s.z.negate()));let l=iS.xy;if(t.center&&t.center.isVector2===!0){let e=Gy(`center`,`vec2`,t);l=l.sub(e.sub(.5))}l=l.mul(c);let u=U(i||JC),d=DO(l,u);return bg(s.xy.add(d),s.zw)}get sizeAttenuation(){return this._useSizeAttenuation}set sizeAttenuation(e){this._useSizeAttenuation!==e&&(this._useSizeAttenuation=e,this.needsUpdate=!0)}},AO=new hc,jO=new N,MO=class extends kO{static get type(){return`PointsNodeMaterial`}constructor(e){super(),this.sizeNode=null,this.isPointsNodeMaterial=!0,this.setDefaultValues(AO),this.setValues(e)}setupPositionView(){let{positionNode:e}=this;return $x.mul(K(e||aS)).xyz}setupVertexSprite(e){let{material:t,camera:n}=e,{rotationNode:r,scaleNode:i,sizeNode:a,sizeAttenuation:o}=this,s=super.setupVertex(e);if(t.isNodeMaterial!==!0)return s;let c=a===null?dw:pg(a);c=c.mul(rx),n.isPerspectiveCamera&&o===!0&&(c=c.mul(NO.div(lS.z.negate()))),i&&i.isNode&&(c=c.mul(pg(i)));let l=iS.xy;if(r&&r.isNode){let e=U(r);l=DO(l,e)}return l=l.mul(c),l=l.div(cx.div(2)),l=l.mul(s.w),s=s.add(bg(l,0,0)),s}setupVertex(e){return e.object.isPoints?super.setupVertex(e):this.setupVertexSprite(e)}get alphaToCoverage(){return this._useAlphaToCoverage}set alphaToCoverage(e){this._useAlphaToCoverage!==e&&(this._useAlphaToCoverage=e,this.needsUpdate=!0)}},NO=v_(1).setGroup(h_).onRenderUpdate(function({renderer:e}){let t=e.getSize(jO);this.value=.5*t.y}),PO=class extends fE{constructor(){super(),this.shadowNode=U(1).toVar(`shadowMask`)}direct({lightNode:e}){e.shadowNode!==null&&this.shadowNode.mulAssign(e.shadowNode)}finish({context:e}){Ng.a.mulAssign(this.shadowNode.oneMinus()),e.outgoingLight.rgb.assign(Ng.rgb)}},FO=new Ol,IO=class extends VT{static get type(){return`ShadowNodeMaterial`}constructor(e){super(),this.isShadowNodeMaterial=!0,this.lights=!0,this.transparent=!0,this.setDefaultValues(FO),this.setValues(e)}setupLightingModel(){return new PO}},LO=jg(`vec3`),RO=jg(`vec3`),zO=jg(`vec3`),BO=class extends fE{constructor(){super()}start(e){let{material:t}=e,n=jg(`vec3`),r=jg(`vec3`),i=jg(`bool`);lg(Nx.sub(sS).length().greaterThan(Xx.mul(2)),()=>{n.assign(Nx),r.assign(sS),i.assign(!0)}).Else(()=>{n.assign(sS),r.assign(Nx),i.assign(!1)});let a=r.sub(n),o=v_(`int`).onRenderUpdate(({material:e})=>e.steps),s=a.length().div(o).toVar(),c=a.normalize().toVar(),l=U(0).toVar(),u=K(1).toVar();t.offsetNode&&l.addAssign(t.offsetNode.mul(s)),Xw(o,()=>{let r=n.add(c.mul(l)),a=Ax.mul(bg(r,1)).xyz;t.depthNode!==null&&(RO.assign(kT(ST(a.z,Ex,Dx))),e.context.sceneDepthNode=kT(t.depthNode).toVar()),e.context.positionWorld=r,e.context.shadowPositionWorld=r,e.context.positionView=a,LO.assign(0);let o,d;t.scatteringNode&&(o=t.scatteringNode({positionRay:r})),t.scatteringEmissiveNode&&(d=t.scatteringEmissiveNode({positionRay:r})),super.start(e),o&&LO.mulAssign(o);let f=LO.mul(.01).toVar();d&&f.addAssign(d.mul(.01));let p=LO.mul(.01).negate().mul(s).exp();lg(i,()=>{zO.addAssign(f.mul(u).mul(s))}).Else(()=>{zO.assign(zO.mul(p).add(f.mul(s)))}),u.mulAssign(p),l.addAssign(s)})}scatteringLight(e,t){let n=t.context.sceneDepthNode;n?lg(n.greaterThanEqual(RO),()=>{LO.addAssign(e)}):LO.addAssign(e)}direct({lightNode:e,lightColor:t},n){if(e.isAnalyticLightNode!==!0||e.light.distance===void 0)return;let r=t.xyz.toVar();e.shadowNode!==null&&r.mulAssign(e.shadowNode),this.scatteringLight(r,n)}directRectArea({lightColor:e,lightPosition:t,halfWidth:n,halfHeight:r},i){let a=t.add(n).sub(r),o=t.sub(n).sub(r),s=t.sub(n).add(r),c=t.add(n).add(r),l=i.context.positionView,u=e.xyz.mul(GE({P:l,p0:a,p1:o,p2:s,p3:c})).pow(1.5);this.scatteringLight(u,i)}finish(e){e.context.outgoingLight.assign(zO)}},VO=class extends VT{static get type(){return`VolumeNodeMaterial`}constructor(e){super(),this.isVolumeNodeMaterial=!0,this.steps=25,this.offsetNode=null,this.scatteringNode=null,this.lights=!0,this.transparent=!0,this.side=1,this.depthTest=!1,this.depthWrite=!1,this.setValues(e)}setupLightingModel(){return new BO}},HO=class{constructor(e,t,n){this.renderer=e,this.nodes=t,this.info=n,this._context=typeof self<`u`?self:null,this._animationLoop=null,this._requestId=null}start(){let e=(t,n)=>{this._requestId=this._context.requestAnimationFrame(e),this.renderer._inspector.isRunning&&this.renderer._inspector.finish(),this.info.autoReset===!0&&this.info.reset(),this.nodes.nodeFrame.update(),this.info.frame=this.nodes.nodeFrame.frameId,this.renderer._inspector.begin(),this._animationLoop!==null&&this._animationLoop(t,n)};e()}stop(){this.renderer._inspector.isRunning&&this.renderer._inspector.finish(),this._context!==null&&this._context.cancelAnimationFrame(this._requestId),this._requestId=null}getAnimationLoop(){return this._animationLoop}setAnimationLoop(e){this._animationLoop=e}getContext(){return this._context}setContext(e){this._context=e}dispose(){this.stop()}},UO=class{constructor(){this.weakMaps={}}_getWeakMap(e){let t=e.length,n=this.weakMaps[t];return n===void 0&&(n=new WeakMap,this.weakMaps[t]=n),n}get(e){let t=this._getWeakMap(e);for(let n=0;n{this.dispose()},this.onGeometryDispose=()=>{this.attributes=null,this.attributesId=null},this.onObjectDispose=()=>{this.dispose()},this.object.addEventListener(`dispose`,this.onObjectDispose),this.material.addEventListener(`dispose`,this.onMaterialDispose),this.geometry.addEventListener(`dispose`,this.onGeometryDispose),this._sourceMaterial!==null&&this._sourceMaterial.addEventListener(`dispose`,this.onMaterialDispose)}updateClipping(e){this.clippingContext=e}get clippingNeedsUpdate(){return this.clippingContext===null||this.clippingContext.cacheKey===this.clippingContextCacheKey?!1:(this.clippingContextCacheKey=this.clippingContext.cacheKey,!0)}get hardwareClippingPlanes(){return this.getNodeBuilderState().hardwareClipping===!0?this.clippingContext.unionClippingCount:0}getNodeBuilderState(){return this._nodeBuilderState||=this._nodes.getForRender(this)}getMonitor(){return this._monitor||=this.getNodeBuilderState().observer}getBindings(){return this._bindings||=this.getNodeBuilderState().createBindings()}getBindingGroup(e){for(let t of this.getBindings())if(t.name===e)return t}getIndex(){return this._geometries.getIndex(this)}getIndirect(){return this._geometries.getIndirect(this)}getIndirectOffset(){return this._geometries.getIndirectOffset(this)}getChainArray(){return[this.object,this.material,this.context,this.lightsNode]}setGeometry(e){this.geometry=e,this.attributes=null,this.attributesId=null}getAttributes(){if(this.attributes!==null)return this.attributes;let e=this.getNodeBuilderState().nodeAttributes,t=this.geometry,n=[],r=new Set,i={};for(let a of e){let e;if(a.node&&a.node.attribute?e=a.node.attribute:(e=t.getAttribute(a.name),e!==void 0&&(e.isInterleavedBufferAttribute?i[a.name]=e.data.uuid:i[a.name]=e.id)),e===void 0)continue;n.push(e);let o=e.isInterleavedBufferAttribute?e.data:e;r.add(o)}return this.attributes=n,this.attributesId=i,this.vertexBuffers=Array.from(r.values()),n}getVertexBuffers(){return this.vertexBuffers===null&&this.getAttributes(),this.vertexBuffers}getDrawParameters(){let{object:e,material:t,geometry:n,group:r,drawRange:i}=this,a=this.drawParams||={vertexCount:0,firstVertex:0,instanceCount:0,firstInstance:0},o=this.getIndex(),s=o!==null,c=1;if(n.isInstancedBufferGeometry===!0?c=n.instanceCount:e.count!==void 0&&(c=Math.max(0,e.count)),c===0)return null;if(a.instanceCount=c,e.isBatchedMesh===!0)return a;let l=1;t.wireframe===!0&&!e.isPoints&&!e.isLineSegments&&!e.isLine&&!e.isLineLoop&&(l=2);let u=i.start*l,d=(i.start+i.count)*l;r!==null&&(u=Math.max(u,r.start*l),d=Math.min(d,(r.start+r.count)*l));let f=n.attributes.position,p=1/0;s?p=o.count:f!=null&&(p=f.count),u=Math.max(u,0),d=Math.min(d,p);let m=d-u;return m<0||m===1/0?null:(a.vertexCount=m,a.firstVertex=u,a)}getGeometryCacheKey(){let{geometry:e}=this,t=``;for(let n of Object.keys(e.attributes).sort()){let r=e.attributes[n];t+=n+`,`,r.data&&(t+=r.data.stride+`,`),r.offset&&(t+=r.offset+`,`),r.itemSize&&(t+=r.itemSize+`,`),r.normalized&&(t+=`n,`)}for(let n of Object.keys(e.morphAttributes).sort()){let r=e.morphAttributes[n];t+=`morph-`+n+`,`;for(let e=0,n=r.length;e1)&&(r+=e.uuid+`,`),r+=this.context.id+`,`,r+=e.receiveShadow+`,`,Ym(r)}get needsGeometryUpdate(){if(this.geometry.id!==this.object.geometry.id)return!0;if(this.attributes!==null){let e=this.attributesId;for(let t in e){let n=this.geometry.getAttribute(t);if(n===void 0)return!0;let r=n.isInterleavedBufferAttribute?n.data.uuid:n.id;if(e[t]!==r)return!0}}return!1}get needsUpdate(){return this.initialNodesCacheKey!==this.getDynamicCacheKey()||this.clippingNeedsUpdate}getDynamicCacheKey(){let e=0;return this.material.isShadowPassMaterial!==!0&&(e=this._nodes.getCacheKey(this.scene,this.lightsNode)),this.camera.isArrayCamera&&(e=Zm(e,this.camera.cameras.length)),this.object.receiveShadow&&(e=Zm(e,1)),e=Zm(e,this.renderer.contextNode.id,this.renderer.contextNode.version),e}getCacheKey(){return this.getMaterialCacheKey()+this.getDynamicCacheKey()}dispose(){this.object.removeEventListener(`dispose`,this.onObjectDispose),this.material.removeEventListener(`dispose`,this.onMaterialDispose),this.geometry.removeEventListener(`dispose`,this.onGeometryDispose),this._sourceMaterial!==null&&this._sourceMaterial.removeEventListener(`dispose`,this.onMaterialDispose),this.onDispose()}},qO=[],JO=class{constructor(e,t,n,r,i,a){this.renderer=e,this.nodes=t,this.geometries=n,this.pipelines=r,this.bindings=i,this.info=a,this._chainMaps={},this._renderObjects=new Set}get(e,t,n,r,i,a,o,s){let c=this.getChainMap(s);qO[0]=e,qO[1]=t,qO[2]=a,qO[3]=i;let l=c.get(qO);return l===void 0?(l=this.createRenderObject(this.nodes,this.geometries,this.renderer,e,t,n,r,i,a,o,s),c.set(qO,l)):(l.camera=r,l.updateClipping(o),l.needsGeometryUpdate&&l.setGeometry(e.geometry),(l.version!==t.version||l.needsUpdate)&&(l.initialCacheKey===l.getCacheKey()?l.version=t.version:(l.dispose(),l=this.get(e,t,n,r,i,a,o,s)))),qO[0]=null,qO[1]=null,qO[2]=null,qO[3]=null,l}getChainMap(e=`default`){return this._chainMaps[e]||(this._chainMaps[e]=new UO)}dispose(){for(let e of this._renderObjects)e.dispose();this._renderObjects.clear(),this._chainMaps={}}createRenderObject(e,t,n,r,i,a,o,s,c,l,u){let d=this.getChainMap(u),f=new KO(e,t,n,r,i,a,o,s,c,l);return f.onDispose=()=>{this.pipelines.delete(f),this.bindings.deleteForRender(f),this.nodes.delete(f),d.delete(f.getChainArray()),this._renderObjects.delete(f)},this._renderObjects.add(f),f}},YO=class{constructor(){this.data=new WeakMap}get(e){let t=this.data.get(e);return t===void 0&&(t={},this.data.set(e,t)),t}delete(e){let t=null;return this.data.has(e)&&(t=this.data.get(e),this.data.delete(e)),t}has(e){return this.data.has(e)}dispose(){this.data=new WeakMap}},XO={VERTEX:1,INDEX:2,STORAGE:3,INDIRECT:4},ZO=16,QO=class extends YO{constructor(e,t){super(),this.backend=e,this.info=t}delete(e){let t=super.delete(e);return t!==null&&(this.backend.destroyAttribute(e),this.info.destroyAttribute(e)),t}update(e,t){let n=this.get(e);if(n.version===void 0)t===XO.VERTEX?(this.backend.createAttribute(e),this.info.createAttribute(e)):t===XO.INDEX?(this.backend.createIndexAttribute(e),this.info.createIndexAttribute(e)):t===XO.STORAGE?(this.backend.createStorageAttribute(e),this.info.createStorageAttribute(e)):t===XO.INDIRECT&&(this.backend.createIndirectStorageAttribute(e),this.info.createIndirectStorageAttribute(e)),n.version=this._getBufferAttribute(e).version;else{let t=this._getBufferAttribute(e);(n.version{this.info.memory.geometries--;let n=t.index;n!==null&&this.attributes.delete(n);for(let e of Object.values(t.attributes))this.attributes.delete(e);let i=this.wireframes.get(t);i!==void 0&&this.attributes.delete(i);let a=new Set(Object.values(e.geometry.attributes));for(let t of e.getAttributes())a.has(t)===!1&&this.attributes.delete(t);t.removeEventListener(`dispose`,r),this._geometryDisposeListeners.delete(t),this.delete(t)};t.addEventListener(`dispose`,r),this._geometryDisposeListeners.set(t,r)}updateAttributes(e){let t=e.getAttributes();for(let e of t)e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute?this.updateAttribute(e,XO.STORAGE):this.updateAttribute(e,XO.VERTEX);let n=this.getIndex(e);n!==null&&this.updateAttribute(n,XO.INDEX);let r=e.geometry.indirect;r!==null&&this.updateAttribute(r,XO.INDIRECT)}updateAttribute(e,t){let n=this.info.render.calls;e.isInterleavedBufferAttribute?this.attributeCall.get(e)===void 0?(this.attributes.update(e,t),this.attributeCall.set(e,n)):this.attributeCall.get(e.data)!==n&&(this.attributes.update(e,t),this.attributeCall.set(e.data,n),this.attributeCall.set(e,n)):this.attributeCall.get(e)!==n&&(this.attributes.update(e,t),this.attributeCall.set(e,n))}getIndirect(e){return e.geometry.indirect}getIndirectOffset(e){return e.geometry.indirectOffset}getIndex(e){let{geometry:t,material:n}=e,r=t.index;if(n.wireframe===!0){let e=this.wireframes,n=e.get(t);n===void 0?(n=Xp(t),e.set(t,n)):(n.version!==Jp(t)||n.__id!==Yp(t))&&(this.attributes.delete(n),n=Xp(t),e.set(t,n)),r=n}return r}dispose(){for(let[e,t]of this._geometryDisposeListeners.entries())e.removeEventListener(`dispose`,t);this._geometryDisposeListeners.clear()}},ek=class{constructor(){this.autoReset=!0,this.frame=0,this.calls=0,this.render={calls:0,frameCalls:0,drawCalls:0,triangles:0,points:0,lines:0,timestamp:0},this.compute={calls:0,frameCalls:0,timestamp:0},this.memory={attributes:0,attributesSize:0,geometries:0,indexAttributes:0,indexAttributesSize:0,indirectStorageAttributes:0,indirectStorageAttributesSize:0,programs:0,programsSize:0,readbackBuffers:0,readbackBuffersSize:0,renderTargets:0,storageAttributes:0,storageAttributesSize:0,textures:0,texturesSize:0,uniformBuffers:0,uniformBuffersSize:0,total:0},this.memoryMap=new WeakMap}update(e,t,n){this.render.drawCalls++,e.isMesh||e.isSprite?this.render.triangles+=t/3*n:e.isPoints?this.render.points+=n*t:e.isLineSegments?this.render.lines+=t/2*n:e.isLine?this.render.lines+=n*(t-1):p(`WebGPUInfo: Unknown object type.`)}reset(){this.render.drawCalls=0,this.render.frameCalls=0,this.compute.frameCalls=0,this.render.triangles=0,this.render.points=0,this.render.lines=0}dispose(){this.reset(),this.calls=0,this.render.calls=0,this.compute.calls=0,this.render.timestamp=0,this.compute.timestamp=0;for(let e in this.memory)this.memory[e]=0;this.memoryMap=new WeakMap}createTexture(e){let t=this._getTextureMemorySize(e);this.memoryMap.set(e,t),this.memory.textures++,this.memory.total+=t,this.memory.texturesSize+=t}destroyTexture(e){let t=this.memoryMap.get(e)||0;this.memoryMap.delete(e),this.memory.textures--,this.memory.total-=t,this.memory.texturesSize-=t}_createAttribute(e,t){let n=this._getAttributeMemorySize(e);this.memoryMap.set(e,{size:n,type:t}),this.memory[t]++,this.memory.total+=n,this.memory[t+`Size`]+=n}createAttribute(e){this._createAttribute(e,`attributes`)}createIndexAttribute(e){this._createAttribute(e,`indexAttributes`)}createStorageAttribute(e){this._createAttribute(e,`storageAttributes`)}createIndirectStorageAttribute(e){this._createAttribute(e,`indirectStorageAttributes`)}destroyAttribute(e){let t=this.memoryMap.get(e);t&&(this.memoryMap.delete(e),this.memory[t.type]--,this.memory.total-=t.size,this.memory[t.type+`Size`]-=t.size)}createReadbackBuffer(e){let t=e.maxByteLength;this.memoryMap.set(e,{size:t,type:`readbackBuffers`}),this.memory.readbackBuffers++,this.memory.total+=t,this.memory.readbackBuffersSize+=t}destroyReadbackBuffer(e){let{size:t}=this.memoryMap.get(e);this.memoryMap.delete(e),this.memory.readbackBuffers--,this.memory.total-=t,this.memory.readbackBuffersSize-=t}createUniformBuffer(e){let t=e.byteLength;this.memoryMap.set(e,{size:t,type:`uniformBuffers`}),this.memory.uniformBuffers++,this.memory.total+=t,this.memory.uniformBuffersSize+=t}destroyUniformBuffer(e){let t=this.memoryMap.get(e);t&&(this.memoryMap.delete(e),this.memory.uniformBuffers--,this.memory.total-=t.size,this.memory.uniformBuffersSize-=t.size)}createProgram(e){let t=e.code.length;this.memoryMap.set(e,t),this.memory.programs++,this.memory.total+=t,this.memory.programsSize+=t}destroyProgram(e){let t=this.memoryMap.get(e)||0;this.memoryMap.delete(e),this.memory.programs--,this.memory.total-=t,this.memory.programsSize-=t}_getTextureMemorySize(e){if(e.isCompressedTexture)return 1;let t=1;e.type===1010||e.type===1009?t=1:e.type===1011||e.type===1012||e.type===1016?t=2:(e.type===1013||e.type===1014||e.type===1015)&&(t=4);let n=4;e.format===1021||e.format===1028||e.format===1029||e.format===1026||e.format===1027?n=1:e.format===1030||e.format===1031?n=2:(e.format===1022||e.format===1032)&&(n=3);let r=t*n;e.type===1017||e.type===1018?r=2:(e.type===1020||e.type===35902||e.type===35899)&&(r=4);let i=e.width||1,a=e.height||1,o=e.isCubeTexture?6:e.depth||1,s=i*a*o*r,c=e.mipmaps;if(c&&c.length>0){let e=0;for(let t=0;t>t),c=n.height||Math.max(1,a>>t);e+=s*c*o*r}}s+=e}else e.generateMipmaps&&(s*=1.333);return Math.round(s)}_getAttributeMemorySize(e){return e.isInterleavedBufferAttribute&&(e=e.data),e.array?e.array.byteLength:e.count&&e.itemSize?e.count*e.itemSize*4:0}},tk=class{constructor(e){this.cacheKey=e,this.usedTimes=0}},nk=class extends tk{constructor(e,t,n){super(e),this.vertexProgram=t,this.fragmentProgram=n}},rk=class extends tk{constructor(e,t){super(e),this.computeProgram=t,this.isComputePipeline=!0}},ik=0,ak=class{constructor(e,t,n,r=null,i=null){this.id=ik++,this.code=e,this.stage=t,this.name=n,this.transforms=r,this.attributes=i,this.usedTimes=0}},ok=class extends YO{constructor(e,t,n){super(),this.backend=e,this.nodes=t,this.info=n,this.bindings=null,this.caches=new Map,this.programs={vertex:new Map,fragment:new Map,compute:new Map}}getForCompute(e,t,n=null){let{backend:r}=this,i=this.get(e);if(this._needsComputeUpdate(e)){let a=i.pipeline;a&&(a.usedTimes--,a.computeProgram.usedTimes--);let o=this.nodes.getForCompute(e),s=this.programs.compute.get(o.computeShader);s===void 0&&(a&&a.computeProgram.usedTimes===0&&this._releaseProgram(a.computeProgram),s=new ak(o.computeShader,`compute`,e.name,o.transforms,o.nodeAttributes),this.programs.compute.set(o.computeShader,s),r.createProgram(s),this.info.createProgram(s));let c=this._getComputeCacheKey(e,s),l=this.caches.get(c);l===void 0&&(a&&a.usedTimes===0&&this._releasePipeline(a),l=this._getComputePipeline(e,s,c,t,n)),l.usedTimes++,s.usedTimes++,i.version=e.version,i.pipeline=l}return i.pipeline}getForRender(e,t=null){let{backend:n}=this,r=this.get(e);if(this._needsRenderUpdate(e)){let i=r.pipeline;i&&(i.usedTimes--,i.vertexProgram.usedTimes--,i.fragmentProgram.usedTimes--);let a=e.getNodeBuilderState(),o=e.material?e.material.name:``,s=this.programs.vertex.get(a.vertexShader);s===void 0&&(i&&i.vertexProgram.usedTimes===0&&this._releaseProgram(i.vertexProgram),s=new ak(a.vertexShader,`vertex`,o),this.programs.vertex.set(a.vertexShader,s),n.createProgram(s),this.info.createProgram(s));let c=this.programs.fragment.get(a.fragmentShader);c===void 0&&(i&&i.fragmentProgram.usedTimes===0&&this._releaseProgram(i.fragmentProgram),c=new ak(a.fragmentShader,`fragment`,o),this.programs.fragment.set(a.fragmentShader,c),n.createProgram(c),this.info.createProgram(c));let l=this._getRenderCacheKey(e,s,c),u=this.caches.get(l);u===void 0?(i&&i.usedTimes===0&&this._releasePipeline(i),u=this._getRenderPipeline(e,s,c,l,t)):e.pipeline=u,u.usedTimes++,s.usedTimes++,c.usedTimes++,r.pipeline=u}return r.pipeline}isReady(e){let t=this.get(e).pipeline;if(t===void 0)return!1;let n=this.backend.get(t);return n.pipeline!==void 0&&n.pipeline!==null}delete(e){let t=this.get(e).pipeline;return t&&(t.usedTimes--,t.usedTimes===0&&this._releasePipeline(t),t.isComputePipeline?(t.computeProgram.usedTimes--,t.computeProgram.usedTimes===0&&this._releaseProgram(t.computeProgram)):(t.fragmentProgram.usedTimes--,t.vertexProgram.usedTimes--,t.vertexProgram.usedTimes===0&&this._releaseProgram(t.vertexProgram),t.fragmentProgram.usedTimes===0&&this._releaseProgram(t.fragmentProgram))),super.delete(e)}dispose(){super.dispose(),this.caches=new Map,this.programs={vertex:new Map,fragment:new Map,compute:new Map}}updateForRender(e){this.getForRender(e)}_getComputePipeline(e,t,n,r,i){n||=this._getComputeCacheKey(e,t);let a=this.caches.get(n);return a===void 0&&(a=new rk(n,t),this.caches.set(n,a),this.backend.createComputePipeline(a,r,i)),a}_getRenderPipeline(e,t,n,r,i){r||=this._getRenderCacheKey(e,t,n);let a=this.caches.get(r);return a===void 0&&(a=new nk(r,t,n),this.caches.set(r,a),e.pipeline=a,this.backend.createRenderPipeline(e,i)),a}_getComputeCacheKey(e,t){return e.id+`,`+t.id}_getRenderCacheKey(e,t,n){return t.id+`,`+n.id+`,`+this.backend.getRenderCacheKey(e)}_releasePipeline(e){this.caches.delete(e.cacheKey)}_releaseProgram(e){let t=e.code,n=e.stage;this.programs[n].delete(t),this.info.destroyProgram(e)}_needsComputeUpdate(e){let t=this.get(e);return t.pipeline===void 0||t.version!==e.version}_needsRenderUpdate(e){return this.get(e).pipeline===void 0||this.backend.needsRenderUpdate(e)}},sk=class extends YO{constructor(e,t,n,r,i,a){super(),this.backend=e,this.textures=n,this.pipelines=i,this.attributes=r,this.nodes=t,this.info=a,this.pipelines.bindings=this}getForRender(e){let t=e.getBindings(),n=this.get(e);return n.initialized!==!0&&(this._createBindings(t),n.initialized=!0),t}getForCompute(e){let t=this.nodes.getForCompute(e).bindings,n=this.get(e);return(n.initialized!==!0||n.bindings!==t)&&(n.bindings!==void 0&&this._destroyBindings(n.bindings),this._createBindings(t),n.initialized=!0,n.bindings=t),t}updateForCompute(e){this._updateBindings(this.getForCompute(e))}updateForRender(e){this._updateBindings(this.getForRender(e))}updateSharedForRender(e){let t=this.getForRender(e);for(let e of t)for(let t of e.bindings)if((t.isNodeUniformsGroup===!0||t.isNodeUniformBuffer===!0)&&t.groupNode.shared===!0){if(this.nodes.updateGroup(t)===!1)continue;t.update()&&this.backend.updateBinding(t),t.updateRanges.length>0&&t.clearUpdateRanges()}}deleteForCompute(e){let t=this.get(e).bindings||this.nodes.getForCompute(e).bindings;this._destroyBindings(t),this.delete(e)}deleteForRender(e){let t=e.getBindings();this._destroyBindings(t),this.delete(e)}_createBindings(e){for(let t of e){let n=this.get(t);if(n.bindGroup===void 0){for(let e of t.bindings)if(e.isUniformBuffer)this.backend.createUniformBuffer(e),this.info.createUniformBuffer(e);else if(e.isSampledTexture)this.textures.updateTexture(e.texture);else if(e.isSampler)this.textures.updateSampler(e);else if(e.isStorageBuffer){let t=e.attribute,n=t.isIndirectStorageBufferAttribute?XO.INDIRECT:XO.STORAGE;this.attributes.update(t,n)}this.backend.createBindings(t,e,``),n.bindGroup=t,n.usedTimes=1}else n.usedTimes++}}_destroyBindings(e){for(let t of e){let e=this.get(t);if(e.usedTimes--,e.usedTimes===0){for(let e of t.bindings)if(e.isUniformBuffer)this.backend.destroyUniformBuffer(e),this.info.destroyUniformBuffer(e),e.release();else if(e.isSampler){if(e.isSampledTexture!==!0)this.backend.destroySampler(e);else if(e.texture!==null){let n=this.textures.get(e.texture);n.bindGroups!==void 0&&n.bindGroups.delete(t)}e.release()}this.backend.deleteBindGroupData(t),this.delete(t)}}}_updateBindings(e){for(let t of e)this._update(t,e)}_update(e,t){let{backend:n}=this,r=!1,i=!0,a=``,o=0;for(let t of e.bindings)if(this.nodes.updateGroup(t)!==!1){if(t.isStorageBuffer){let e=t.attribute,i=e.isIndirectStorageBufferAttribute?XO.INDIRECT:XO.STORAGE,o=n.get(t);this.attributes.update(e,i),o.attribute!==e&&(o.attribute=e,r=!0),a+=e.id+`,`}if(t.isUniformBuffer)t.update()&&n.updateBinding(t);else if(t.isSampledTexture){let s=t.update(),c=t.texture,l=this.textures.get(c);if(s&&(this.textures.updateTexture(c),t.generation!==l.generation&&(t.generation=l.generation,r=!0),l.bindGroups.add(e)),n.get(c).externalTexture!==void 0||l.isDefaultTexture?i=!1:(a+=c.id+`,`,o+=c.version),c.isStorageTexture===!0&&c.mipmapsAutoUpdate===!0){let e=this.get(c);t.store===!0?e.needsMipmap=!0:this.textures.needsMipmaps(c)&&e.needsMipmap===!0&&(this.backend.generateMipmaps(c),e.needsMipmap=!1)}}else if(t.isSampler&&t.update()){let e=this.textures.updateSampler(t);t.samplerKey!==e&&(t.samplerKey=e,r=!0)}t.isBuffer&&t.updateRanges.length>0&&t.clearUpdateRanges()}r===!0&&this.backend.updateBindings(e,t,i?a:``,o)}},ck=Object.freeze([]),lk=class{constructor(e,t,n){this.renderItems=[],this.renderItemsIndex=0,this.opaque=[],this.transparentDoublePass=[],this.transparent=[],this.bundles=[],this.lighting=e,this.lightsNode=e.getNode(t),this.lightsArray=[],this.scene=t,this.camera=n,this.occlusionQueryCount=0,this.frameId=-1,this._lastOcclusionObject=null}begin(){return this.renderItemsIndex=0,this.opaque.length=0,this.transparentDoublePass.length=0,this.transparent.length=0,this.bundles.length=0,this.lightsArray.length=0,this.occlusionQueryCount=0,this}getNextRenderItem(e,t,n,r,i,a,o){let s=this.renderItems[this.renderItemsIndex];return s===void 0?(s={id:e.id,object:e,geometry:t,material:n,groupOrder:r,renderOrder:e.renderOrder,z:i,group:a,clippingContext:o},this.renderItems[this.renderItemsIndex]=s):(s.id=e.id,s.object=e,s.geometry=t,s.material=n,s.groupOrder=r,s.renderOrder=e.renderOrder,s.z=i,s.group=a,s.clippingContext=o),this.renderItemsIndex++,s}push(e,t,n,r,i,a,o){this.camera.reversedDepth===!0&&(i=-i);let s=this.getNextRenderItem(e,t,n,r,i,a,o);e.occlusionTest===!0&&this._lastOcclusionObject!==e&&(this.occlusionQueryCount++,this._lastOcclusionObject=e),n.transparent===!0||n.transmission>0||n.transmissionNode&&n.transmissionNode.isNode||n.backdropNode&&n.backdropNode.isNode?($p(n)&&this.transparentDoublePass.push(s),this.transparent.push(s)):this.opaque.push(s)}unshift(e,t,n,r,i,a,o){let s=this.getNextRenderItem(e,t,n,r,i,a,o);n.transparent===!0||n.transmission>0||n.transmissionNode&&n.transmissionNode.isNode||n.backdropNode&&n.backdropNode.isNode?($p(n)&&this.transparentDoublePass.unshift(s),this.transparent.unshift(s)):this.opaque.unshift(s)}pushBundle(e){this.bundles.push(e)}pushLight(e){this.lightsArray.push(e)}sort(e,t){this.opaque.length>1&&this.opaque.sort(e||Zp),this.transparentDoublePass.length>1&&this.transparentDoublePass.sort(t||Qp),this.transparent.length>1&&this.transparent.sort(t||Qp)}finish(){this.lightsNode.setLights(this.lighting.enabled?this.lightsArray:ck);for(let e=this.renderItemsIndex,t=this.renderItems.length;e10&&(t.clear(),this._activeLists.delete(t))}}dispose(){this.lists=new UO,this._activeLists.clear(),this._frameId=-1}},fk=0,pk=class{constructor(){this.id=fk++,this.mrt=null,this.color=!0,this.clearColor=!0,this.clearColorValue={r:0,g:0,b:0,a:1},this.depth=!0,this.clearDepth=!0,this.clearDepthValue=1,this.stencil=!1,this.clearStencil=!0,this.clearStencilValue=1,this.viewport=!1,this.viewportValue=new Mi,this.scissor=!1,this.scissorValue=new Mi,this.renderTarget=null,this.textures=null,this.depthTexture=null,this.activeCubeFace=0,this.activeMipmapLevel=0,this.sampleCount=1,this.width=0,this.height=0,this.occlusionQueryCount=0,this.clippingContext=null,this.camera=null,this.fullscreenPass=!1,this.isRenderContext=!0}getCacheKey(){return tm(this)}},mk=class{constructor(e){this.renderer=e,this._renderContexts={}}get(e=null,t=null,n=0){let r;if(e===null)r=`default`;else{let t=e.texture.format,n=e.texture.type;r=`${e.textures.length}:${t}:${n}:${e.samples}:${e.depthBuffer}:${e.stencilBuffer}`}let i=t===null?`default`:t.id,a=r+`-`+i+`-`+n,o=this._renderContexts[a];return o===void 0&&(o=new pk,o.mrt=t,this._renderContexts[a]=o),e!==null&&(o.sampleCount=e.samples===0?1:e.samples),o.clearDepthValue=this.renderer.getClearDepth(),o.clearStencilValue=this.renderer.getClearStencil(),o}dispose(){this._renderContexts={}}},hk=new P,gk=class extends YO{constructor(e,t,n){super(),this.renderer=e,this.backend=t,this.info=n,this._htmlTextures=new Set}updateRenderTarget(e,t=0){let n=this.get(e),r=e.samples===0?1:e.samples,i=n.depthTextureMips||={},a=e.textures,o=this.getSize(a[0]),s=o.width>>t,c=o.height>>t,l=e.depthTexture||i[t],u=e.depthBuffer===!0||e.stencilBuffer===!0,d=!1,f=l!==void 0&&l.image!==void 0&&l.image.depth>1,p=o.depth>1&&(e.useArrayDepthTexture||e.multiview||f);l===void 0&&u&&(l=new Ac,l.format=e.stencilBuffer?Dn:En,l.type=e.stencilBuffer?bn:hn,l.image.width=s,l.image.height=c,l.image.depth=o.depth,l.renderTarget=e,i[t]=l),l&&(l.isArrayTexture=p),(n.width!==o.width||o.height!==n.height)&&(d=!0,l&&l.renderTarget===e&&(l.needsUpdate=!0,l.image.width=s,l.image.height=c,l.image.depth=p?o.depth:1)),n.width=o.width,n.height=o.height,n.textures=a,n.depthTexture=l||null,n.depth=e.depthBuffer,n.stencil=e.stencilBuffer,n.renderTarget=e,n.sampleCount!==r&&(d=!0,l&&l.renderTarget===e&&(l.needsUpdate=!0),n.sampleCount=r);let m={sampleCount:r};if(e.isXRRenderTarget!==!0){for(let e=0;e{this._destroyRenderTarget(e)},e.addEventListener(`dispose`,n.onDispose))}updateTexture(e,t={}){let n=this.get(e);if(n.initialized===!0&&n.version===e.version)return;let r=e.isRenderTargetTexture||e.isDepthTexture||e.isFramebufferTexture,i=this.backend;if(r&&n.initialized===!0&&i.destroyTexture(e),e.isFramebufferTexture){let t=this.renderer.getRenderTarget();e.type=t?t.texture.type:un}if(e.isHTMLTexture&&e.image){let t=this.renderer.domElement;if(`requestPaint`in t){if(t.hasAttribute(`layoutsubtree`)||t.setAttribute(`layoutsubtree`,`true`),e.image.parentNode!==t&&t.appendChild(e.image),this._htmlTextures.size===0){let e=this._htmlTextures;t.onpaint=t=>{let n=t&&t.changedElements;for(let t of e)(!n||n.includes(t.image))&&(t.needsUpdate=!0)}}this._htmlTextures.add(e)}}let{width:a,height:o,depth:s}=this.getSize(e);if(t.width=a,t.height=o,t.depth=s,t.needsMipmaps=this.needsMipmaps(e),t.levels=t.needsMipmaps?this.getMipLevels(e,a,o):1,e.isCubeTexture&&e.mipmaps.length>0&&t.levels++,r||e.isStorageTexture===!0||e.isExternalTexture===!0)i.createTexture(e,t),n.generation=e.version;else if(e.version>0){let r=e.image;if(r===void 0)f(`Renderer: Texture marked for update but image is undefined.`);else if(r.complete===!1)f(`Renderer: Texture marked for update but image is incomplete.`);else{if(e.images){let n=[];for(let t of e.images)n.push(t);t.images=n}else t.image=r;(n.isDefaultTexture===void 0||n.isDefaultTexture===!0)&&(i.createTexture(e,t),n.isDefaultTexture=!1,n.generation=e.version),e.source.dataReady===!0&&i.updateTexture(e,t);let a=e.isStorageTexture===!0&&e.mipmapsAutoUpdate===!1;t.needsMipmaps&&e.mipmaps.length===0&&!a&&i.generateMipmaps(e),e.onUpdate&&e.onUpdate(e)}}else i.createDefaultTexture(e),n.isDefaultTexture=!0,n.generation=e.version;n.initialized!==!0&&(n.initialized=!0,n.generation=e.version,n.bindGroups=new Set,this.info.createTexture(e),e.isVideoTexture&&Ci.enabled===!0&&Ci.getTransfer(e.colorSpace)!==`srgb`&&f(`WebGPURenderer: Video textures must use a color space with a sRGB transfer function, e.g. SRGBColorSpace.`),n.onDispose=()=>{this._destroyTexture(e)},e.addEventListener(`dispose`,n.onDispose)),n.version=e.version}updateSampler(e){return this.backend.updateSampler(e)}getSize(e,t=hk){let n=e.images?e.images[0]:e.image;return n?(n.image!==void 0&&(n=n.image),e.isHTMLTexture?(t.width=n.offsetWidth||1,t.height=n.offsetHeight||1,t.depth=1):typeof HTMLVideoElement<`u`&&n instanceof HTMLVideoElement?(t.width=n.videoWidth||1,t.height=n.videoHeight||1,t.depth=1):typeof VideoFrame<`u`&&n instanceof VideoFrame?(t.width=n.displayWidth||1,t.height=n.displayHeight||1,t.depth=1):(t.width=n.width||1,t.height=n.height||1,t.depth=e.isCubeTexture?6:n.depth||1)):t.width=t.height=t.depth=1,t}getMipLevels(e,t,n){let r;return r=e.mipmaps.length>0?e.mipmaps.length:e.isCompressedTexture===!0?1:Math.floor(Math.log2(Math.max(t,n)))+1,r}needsMipmaps(e){return e.generateMipmaps===!0||e.mipmaps.length>0}_destroyRenderTarget(e){if(this.has(e)===!0){let t=this.get(e),n=t.textures,r=t.depthTexture;e.removeEventListener(`dispose`,t.onDispose);for(let e=0;e{t.isOverrideContextNode===!0&&e.push(t.value.overrideNodes)});let t=new Map(e.flatMap(e=>Array.from(e.entries()))),n=super.getFlowContextData();return n.overrideNodes=t,n}},B(`overrideNode`,(e,t,n)=>nm(t,n,e)),B(`overrideNodes`,(e,t)=>rm(t,e)),yk=class extends Ag{static get type(){return`ParameterNode`}constructor(e,t=null){super(e,t),this.isParameterNode=!0}getMemberType(e,t){let n=this.getNodeType(e),r=e.getStructTypeNode(n),i;return r===null?(p(`TSL: Member "${t}" not found in struct "${n}".`,new Jm),i=`float`):i=r.getMemberType(e,t),i}getHash(){return String(this.id)}generate(){return this.name}},bk=(e,t)=>new yk(e,t),xk=class extends dh{static get type(){return`StackNode`}constructor(e=null){super(),this.nodes=[],this.outputNode=null,this.parent=e,this._currentCond=null,this._expressionNode=null,this._currentNode=null,this._nodeDataLibrary=new Map,this.isStackNode=!0}getElementType(e){return this.outputNode?this.outputNode.getElementType(e):`void`}generateNodeType(e){return this.outputNode?this.outputNode.getNodeType(e):`void`}getMemberType(e,t){return this.outputNode?this.outputNode.getMemberType(e,t):`void`}addToStack(e,t=-1){if(e.isNode!==!0)return p(`TSL: Invalid node added to stack.`,new Jm),this;if(t===-1){if(this._currentNode){let e=this._nodeDataLibrary.get(this._currentNode);e===void 0&&(e={delta:0},this._nodeDataLibrary.set(this._currentNode,e)),e.delta++,t=this.nodes.indexOf(this._currentNode)+e.delta}else t=this.nodes.length}return this.nodes.splice(t,0,e),this}addToStackBefore(e){let t=this._currentNode?this.nodes.indexOf(this._currentNode):0;return this.addToStack(e,t)}If(e,t){let n=new up(t);return this._currentCond=by(e,n),this.addToStack(this._currentCond)}ElseIf(e,t){let n=new up(t),r=by(e,n);return this._currentCond.elseNode=r,this._currentCond=r,this}Else(e){return this._currentCond.elseNode=new up(e),this}Switch(e){return this._expressionNode=Qh(e),this}Case(...e){let t=[];if(e.length>=2)for(let n=0;ne.name===t);return n?n.type:`void`}generateNodeType(e){return e.getStructTypeFromNode(this,this.membersLayout,this.name).name}setup(e){e.getStructTypeFromNode(this,this.membersLayout,this.name),e.addInclude(this)}generate(e){return this.getNodeType(e)}},wk=class extends dh{static get type(){return`StructNode`}constructor(e,t){super(`vec3`),this.structTypeNode=e,this.values=t,this.isStructNode=!0}generateNodeType(e){return this.structTypeNode.getNodeType(e)}getMemberType(e,t){return this.structTypeNode.getMemberType(e,t)}_getChildren(){let e=super._getChildren(),t=e.find(e=>e.childNode===this.structTypeNode);return e.splice(e.indexOf(t),1),e.push(t),e}generate(e){let t=e.getVarFromNode(this),n=t.type,r=e.getPropertyName(t);return e.addLineFlowCode(`${r} = ${e.generateStruct(n,this.structTypeNode.membersLayout,this.values)}`,this),t.name}},Tk=(e,t=null)=>{let n=new Ck(e,t);return ig((...t)=>{let r=null;if(t.length>0){if(ap(t)){r={};let n=Object.keys(e);for(let e=0;enew Nk(e,`int`,`float`),Ik=e=>new Nk(e,`uint`,`float`),Lk=e=>new Nk(e,`float`,`int`),Rk=e=>new Nk(e,`float`,`uint`),zk={},Bk=class e extends q{static get type(){return`BitcountNode`}constructor(e,t){super(e,t),this.isBitcountNode=!0}_resolveElementType(e,t,n){n===`int`?t.assign(Pk(e,`uint`)):t.assign(e)}_returnDataNode(e){switch(e){case`uint`:return G;case`int`:return W;case`uvec2`:return hg;case`uvec3`:return vg;case`uvec4`:return Sg;case`ivec2`:return mg;case`ivec3`:return _g;case`ivec4`:return xg}}_createTrailingZerosBaseLayout(e,t){let n=this._returnDataNode(t);return V(([e])=>{lg(e.equal(G(0)),()=>G(32));let r=G(0);this._resolveElementType(e,r,t);let i=U(r.bitAnd(Nv(r))),a=Ik(i).shiftRight(23).sub(127);return n(a)}).setLayout({name:e,type:t,inputs:[{name:`value`,type:t}]})}_createLeadingZerosBaseLayout(e,t){let n=this._returnDataNode(t);return V(([e])=>{lg(e.equal(G(0)),()=>G(32));let r=G(0),i=G(0);return this._resolveElementType(e,r,t),lg(r.shiftRight(16).equal(0),()=>{i.addAssign(16),r.shiftLeftAssign(16)}),lg(r.shiftRight(24).equal(0),()=>{i.addAssign(8),r.shiftLeftAssign(8)}),lg(r.shiftRight(28).equal(0),()=>{i.addAssign(4),r.shiftLeftAssign(4)}),lg(r.shiftRight(30).equal(0),()=>{i.addAssign(2),r.shiftLeftAssign(2)}),lg(r.shiftRight(31).equal(0),()=>{i.addAssign(1)}),n(i)}).setLayout({name:e,type:t,inputs:[{name:`value`,type:t}]})}_createOneBitsBaseLayout(e,t){let n=this._returnDataNode(t);return V(([e])=>{let r=G(0);this._resolveElementType(e,r,t),r.assign(r.sub(r.shiftRight(G(1)).bitAnd(G(1431655765)))),r.assign(r.bitAnd(G(858993459)).add(r.shiftRight(G(2)).bitAnd(G(858993459))));let i=r.add(r.shiftRight(G(4))).bitAnd(G(252645135)).mul(G(16843009)).shiftRight(G(24));return n(i)}).setLayout({name:e,type:t,inputs:[{name:`value`,type:t}]})}_createMainLayout(e,t,n,r){let i=this._returnDataNode(t);return V(([e])=>{if(n===1)return i(r(e));{let t=i(0),a=[`x`,`y`,`z`,`w`];for(let i=0;id(r))()}static get COUNT_TRAILING_ZEROS(){return`countTrailingZeros`}static get COUNT_LEADING_ZEROS(){return`countLeadingZeros`}static get COUNT_ONE_BITS(){return`countOneBits`}},Vk=H(Bk,Bk.COUNT_TRAILING_ZEROS).setParameterLength(1),Hk=H(Bk,Bk.COUNT_LEADING_ZEROS).setParameterLength(1),Uk=H(Bk,Bk.COUNT_ONE_BITS).setParameterLength(1),Wk=V(([e])=>{let t=e.toUint().mul(747796405).add(2891336453),n=t.shiftRight(t.shiftRight(28).add(4)).bitXor(t).mul(277803737);return n.shiftRight(22).bitXor(n).toFloat().mul(1/2**32)}),Gk=(e,t)=>Qv(k_(4,e.mul(O_(1,e))),t),Kk=(e,t)=>by(e.lessThan(.5),Qv(k_(2,e),t).mul(.5),O_(1,Qv(k_(2,O_(1,e)),t).mul(.5))),qk=(e,t,n)=>Qv(A_(Qv(e,t),D_(Qv(e,t),Qv(O_(1,e),n))),A_(1,t)),Jk=(e,t)=>{let n=Av(ev.mul(t.mul(e).sub(1))).max(1e-6).toConst();return vv(n).div(n)},Yk=class extends mh{static get type(){return`PackFloatNode`}constructor(e,t){super(),this.vectorNode=t,this.encoding=e,this.layout=`2x16`,this.isPackFloatNode=!0}generateNodeType(){return`uint`}generate(e){let t=this.vectorNode.getNodeType(e);return`${e.getFloatPackingMethod(this.encoding,this.layout)}(${this.vectorNode.build(e,t)})`}},Xk=H(Yk,`snorm`).setParameterLength(1),Zk=H(Yk,`unorm`).setParameterLength(1),Qk=H(Yk,`float16`).setParameterLength(1),$k=H(Yk,`snorm`,null,{layout:`4x8`}).setParameterLength(1),eA=H(Yk,`unorm`,null,{layout:`4x8`}).setParameterLength(1),tA=class e extends mh{static get type(){return`Packed4x8IntegerNode`}constructor(e,t,n=null){super(),this.method=e,this.aNode=t,this.bNode=n,this.isPacked4x8IntegerNode=!0}getInputType(){let t=this.method;return t===e.PACK4X_I8||t===e.PACK4X_I8_CLAMP?`ivec4`:t===e.PACK4X_U8||t===e.PACK4X_U8_CLAMP?`uvec4`:`uint`}generateNodeType(){let t=this.method;return t===e.DOT4_I8_PACKED?`int`:t===e.UNPACK4X_I8?`ivec4`:t===e.UNPACK4X_U8?`uvec4`:`uint`}_getEmulatedFn(){switch(this.method){case e.DOT4_U8_PACKED:return cA;case e.DOT4_I8_PACKED:return lA;case e.PACK4X_I8:return rA;case e.PACK4X_U8:return nA;case e.PACK4X_I8_CLAMP:return aA;case e.PACK4X_U8_CLAMP:return iA;case e.UNPACK4X_I8:return sA;case e.UNPACK4X_U8:return oA}}setup(e){if(e.renderer.backend.isWebGPUBackend===!0&&typeof navigator<`u`&&navigator.gpu!==void 0&&navigator.gpu.wgslLanguageFeatures!==void 0&&navigator.gpu.wgslLanguageFeatures.has(`packed_4x8_integer_dot_product`))return super.setup(e);let{aNode:t,bNode:n}=this,r=this._getEmulatedFn();return n===null?r(t):r(t,n)}generate(e,t){if(e.getNodeProperties(this).outputNode)return super.generate(e,t);let n=this.getNodeType(e),r=this.getInputType(),i=[this.aNode.build(e,r)];return this.bNode!==null&&i.push(this.bNode.build(e,r)),e.format(`${this.method}( ${i.join(`, `)} )`,n,t)}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}static get DOT4_U8_PACKED(){return`dot4U8Packed`}static get DOT4_I8_PACKED(){return`dot4I8Packed`}static get PACK4X_I8(){return`pack4xI8`}static get PACK4X_U8(){return`pack4xU8`}static get PACK4X_I8_CLAMP(){return`pack4xI8Clamp`}static get PACK4X_U8_CLAMP(){return`pack4xU8Clamp`}static get UNPACK4X_I8(){return`unpack4xI8`}static get UNPACK4X_U8(){return`unpack4xU8`}},nA=V(([e])=>{let t=e.x.bitAnd(G(255)),n=e.y.bitAnd(G(255)),r=e.z.bitAnd(G(255)),i=e.w.bitAnd(G(255));return t.bitOr(n.shiftLeft(G(8))).bitOr(r.shiftLeft(G(16))).bitOr(i.shiftLeft(G(24)))}).setLayout({name:`tsl_packed4x8_pack4xU8`,type:`uint`,inputs:[{name:`v`,type:`uvec4`}]}),rA=V(([e])=>nA(Sg(e))).setLayout({name:`tsl_packed4x8_pack4xI8`,type:`uint`,inputs:[{name:`v`,type:`ivec4`}]}),iA=V(([e])=>nA(cy(e,Sg(0),Sg(255)))).setLayout({name:`tsl_packed4x8_pack4xU8Clamp`,type:`uint`,inputs:[{name:`v`,type:`uvec4`}]}),aA=V(([e])=>rA(cy(e,xg(-128),xg(127)))).setLayout({name:`tsl_packed4x8_pack4xI8Clamp`,type:`uint`,inputs:[{name:`v`,type:`ivec4`}]}),oA=V(([e])=>Sg(e.bitAnd(G(255)),e.shiftRight(G(8)).bitAnd(G(255)),e.shiftRight(G(16)).bitAnd(G(255)),e.shiftRight(G(24)).bitAnd(G(255)))).setLayout({name:`tsl_packed4x8_unpack4xU8`,type:`uvec4`,inputs:[{name:`v`,type:`uint`}]}),sA=V(([e])=>xg(om(e,0),om(e,8),om(e,16),om(e,24))).setLayout({name:`tsl_packed4x8_unpack4xI8`,type:`ivec4`,inputs:[{name:`v`,type:`uint`}]}),cA=V(([e,t])=>{let n=oA(e),r=oA(t);return n.x.mul(r.x).add(n.y.mul(r.y)).add(n.z.mul(r.z)).add(n.w.mul(r.w))}).setLayout({name:`tsl_packed4x8_dot4U8Packed`,type:`uint`,inputs:[{name:`a`,type:`uint`},{name:`b`,type:`uint`}]}),lA=V(([e,t])=>{let n=sA(e),r=sA(t);return n.x.mul(r.x).add(n.y.mul(r.y)).add(n.z.mul(r.z)).add(n.w.mul(r.w))}).setLayout({name:`tsl_packed4x8_dot4I8Packed`,type:`int`,inputs:[{name:`a`,type:`uint`},{name:`b`,type:`uint`}]}),uA=H(tA,tA.DOT4_U8_PACKED).setParameterLength(2),dA=H(tA,tA.DOT4_I8_PACKED).setParameterLength(2),fA=H(tA,tA.PACK4X_I8).setParameterLength(1),pA=H(tA,tA.PACK4X_U8).setParameterLength(1),mA=H(tA,tA.PACK4X_I8_CLAMP).setParameterLength(1),hA=H(tA,tA.PACK4X_U8_CLAMP).setParameterLength(1),gA=H(tA,tA.UNPACK4X_I8).setParameterLength(1),_A=H(tA,tA.UNPACK4X_U8).setParameterLength(1),vA=class extends mh{static get type(){return`UnpackFloatNode`}constructor(e,t){super(),this.uintNode=t,this.encoding=e,this.layout=`2x16`,this.isUnpackFloatNode=!0}generateNodeType(){return this.layout===`4x8`?`vec4`:`vec2`}generate(e){let t=this.uintNode.getNodeType(e);return`${e.getFloatUnpackingMethod(this.encoding,this.layout)}(${this.uintNode.build(e,t)})`}},yA=H(vA,`snorm`).setParameterLength(1),bA=H(vA,`unorm`).setParameterLength(1),xA=H(vA,`float16`).setParameterLength(1),SA=H(vA,`snorm`,null,{layout:`4x8`}).setParameterLength(1),CA=H(vA,`unorm`,null,{layout:`4x8`}).setParameterLength(1),wA=V(([e])=>e.fract().sub(.5).abs()).setLayout({name:`tri`,type:`float`,inputs:[{name:`x`,type:`float`}]}),TA=V(([e])=>K(wA(e.z.add(wA(e.y.mul(1)))),wA(e.z.add(wA(e.x.mul(1)))),wA(e.y.add(wA(e.x.mul(1)))))).setLayout({name:`tri3`,type:`vec3`,inputs:[{name:`p`,type:`vec3`}]}),EA=V(([e,t,n])=>{let r=K(e).toVar(),i=U(1.4).toVar(),a=U(0).toVar(),o=K(r).toVar();return Xw({start:U(0),end:U(3),type:`float`,condition:`<=`},()=>{let e=K(TA(o.mul(2))).toVar();r.addAssign(e.add(n.mul(U(.1).mul(t)))),o.mulAssign(1.8),i.mulAssign(1.5),r.mulAssign(1.2);let s=U(wA(r.z.add(wA(r.x.add(wA(r.y)))))).toVar();a.addAssign(s.div(i)),o.addAssign(.14)}),a}).setLayout({name:`triNoise3D`,type:`float`,inputs:[{name:`position`,type:`vec3`},{name:`speed`,type:`float`},{name:`time`,type:`float`}]}),DA=class extends dh{static get type(){return`FunctionOverloadingNode`}constructor(e=[],...t){super(),this.functionNodes=e,this.parametersNodes=t,this._candidateFn=null,this.global=!0}generateNodeType(e){return this.getCandidateFn(e).shaderNode.layout.type}getCandidateFn(e){let t=this.parametersNodes,n=this._candidateFn;if(n===null){let r=null,i=-1;for(let n of this.functionNodes){let a=n.shaderNode.layout;if(a===null)throw Error(`THREE.FunctionOverloadingNode: FunctionNode must be a layout.`);let o=a.inputs;if(t.length===o.length){let a=0;for(let n=0;ni&&(r=n,i=a)}}this._candidateFn=n=r}return n}setup(e){return this.getCandidateFn(e)(...this.parametersNodes)}},OA=ng(DA),kA=e=>(...t)=>OA(e,...t),AA=v_(0).setGroup(h_).onRenderUpdate(e=>e.time),jA=v_(0).setGroup(h_).onRenderUpdate(e=>e.deltaTime),MA=v_(0,`uint`).setGroup(h_).onRenderUpdate(e=>e.frameId),NA=(e=AA)=>e.add(.75).mul(Math.PI*2).sin().mul(.5).add(.5),PA=(e=AA)=>e.fract().round(),FA=(e=AA)=>e.add(.5).fract().mul(2).sub(1).abs(),IA=(e=AA)=>e.fract(),LA=V(([e,t,n=pg(.5)])=>DO(e.sub(n),t).add(n)),RA=V(([e,t,n=pg(.5)])=>{let r=e.sub(n),i=r.dot(r),a=i.mul(i).mul(t);return e.add(r.mul(a))}),zA=V(({position:e=null,horizontal:t=!0,vertical:n=!1,horizontalRotation:r=!1})=>{let i;i=e===null?sS.sub(Kx.mul(bg(iS,0)).xyz):Qh(e);let a=Kx.toVar();a[3][0]=i.x,a[3][1]=i.y,a[3][2]=i.z;let o=Ax.mul(a),s=Kx[0].length(),c=Kx[1].length(),l=Kx[2].length(),u,d,f;if(lp(r)){let e=a[3].xyz,t=Nx.sub(e),n=K(t.x,0,t.z).normalize(),r=K(n.z,0,n.x.negate());u=Ax.mul(bg(r,0)).xyz.mul(s),d=Ax[1].xyz.mul(c),f=Ax.mul(bg(n,0)).xyz.mul(l)}else lp(t)&&(u=K(s,0,0)),lp(n)&&(d=K(0,c,0)),f=K(0,0,1);return u&&(o[0][0]=u.x,o[0][1]=u.y,o[0][2]=u.z),d&&(o[1][0]=d.x,o[1][1]=d.y,o[1][2]=d.z),f&&(o[2][0]=f.x,o[2][1]=f.y,o[2][2]=f.z),Ox.mul(o).mul(iS)}),BA=V(([e=null])=>{let t=kT();return kT(_T(e)).sub(t).lessThan(0).select(ix,e)}),VA=V(([e,t=Mb(),n=U(0)])=>{let r=e.x,i=e.y,a=n.mod(r.mul(i)).floor(),o=a.mod(r),s=i.sub(a.add(1).div(r).ceil()),c=e.reciprocal(),l=pg(o,s);return t.add(l).mul(c)}),HA=V(([e,t=null,n=null,r=U(1),i=aS,a=_S])=>{let o=a.abs().normalize();o=o.div(o.dot(K(1)));let s=i.yz.mul(r),c=i.zx.mul(r),l=i.xy.mul(r),u=e.value,d=t===null?u:t.value,f=n===null?u:n.value,p=Vb(u,s).mul(o.x),m=Vb(d,c).mul(o.y),h=Vb(f,l).mul(o.z);return D_(p,m,h)}),UA=(...e)=>HA(...e),WA=new Oo,GA=new P,KA=new P,qA=new P,JA=new F,YA=new P(0,0,-1),XA=new Mi,ZA=new P,QA=new P,$A=new Mi,ej=new N,tj=new Ni,nj=ix.flipX(),tj.depthTexture=new Ac(1,1),rj=!1,ij=class e extends zb{static get type(){return`ReflectorNode`}constructor(e={}){super(e.defaultTexture||tj.texture,nj),this._reflectorBaseNode=e.reflector||new aj(this,e),this._depthNode=null,this.setUpdateMatrix(!1)}get reflector(){return this._reflectorBaseNode}get target(){return this._reflectorBaseNode.target}getDepthNode(){if(this._depthNode===null){if(this._reflectorBaseNode.depth!==!0)throw Error(`THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. `);this._depthNode=new e({defaultTexture:tj.depthTexture,reflector:this._reflectorBaseNode})}return this._depthNode}setup(e){return e.object.isQuadMesh||this._reflectorBaseNode.build(e),super.setup(e)}clone(){let e=new this.constructor(this.reflectorNode);return e.uvNode=this.uvNode,e.levelNode=this.levelNode,e.biasNode=this.biasNode,e.sampler=this.sampler,e.depthNode=this.depthNode,e.compareNode=this.compareNode,e.gradNode=this.gradNode,e.gatherNode=this.gatherNode,e.offsetNode=this.offsetNode,e._reflectorBaseNode=this._reflectorBaseNode,e}dispose(){super.dispose(),this._reflectorBaseNode.dispose()}},aj=class extends dh{static get type(){return`ReflectorBaseNode`}constructor(e,t={}){super();let{target:n=new da,resolutionScale:r=1,generateMipmaps:i=!1,bounces:a=!0,depth:o=!1,samples:s=0}=t;this.textureNode=e,this.target=n,this.resolutionScale=r,t.resolution!==void 0&&(m(`ReflectorNode: The "resolution" parameter has been renamed to "resolutionScale".`),this.resolutionScale=t.resolution),this.generateMipmaps=i,this.bounces=a,this.depth=o,this.samples=s,this.updateBeforeType=a?nh.RENDER:nh.FRAME,this.virtualCameras=new WeakMap,this.renderTargets=new Map,this.forceUpdate=!1,this.hasOutput=!1}_updateResolution(e,t){let n=this.resolutionScale;t.getDrawingBufferSize(ej),e.setSize(Math.round(ej.width*n),Math.round(ej.height*n))}setup(e){return this._updateResolution(tj,e.renderer),super.setup(e)}dispose(){super.dispose();for(let e of this.renderTargets.values())e.dispose()}getVirtualCamera(e){let t=this.virtualCameras.get(e);return t===void 0&&(t=e.clone(),this.virtualCameras.set(e,t)),t}getRenderTarget(e){let t=this.renderTargets.get(e);return t===void 0&&(t=new Ni(1,1,{type:_n,samples:this.samples}),this.generateMipmaps===!0&&(t.texture.minFilter=ln,t.texture.generateMipmaps=!0),this.depth===!0&&(t.depthTexture=new Ac),this.renderTargets.set(e,t)),t}updateBefore(e){if(this.bounces===!1&&rj)return!1;rj=!0;let{scene:t,camera:n,renderer:r,material:i}=e,{target:a}=this,o=this.getVirtualCamera(n),s=this.getRenderTarget(o);r.getDrawingBufferSize(ej),this._updateResolution(s,r),KA.setFromMatrixPosition(a.matrixWorld),qA.setFromMatrixPosition(n.matrixWorld),JA.extractRotation(a.matrixWorld),GA.set(0,0,1),GA.applyMatrix4(JA),ZA.subVectors(KA,qA);let c=ZA.dot(GA)>0,l=!1;if(c===!0&&this.forceUpdate===!1){if(this.hasOutput===!1){rj=!1;return}l=!0}ZA.reflect(GA).negate(),ZA.add(KA),JA.extractRotation(n.matrixWorld),YA.set(0,0,-1),YA.applyMatrix4(JA),YA.add(qA),QA.subVectors(KA,YA),QA.reflect(GA).negate(),QA.add(KA),o.coordinateSystem=n.coordinateSystem,o.position.copy(ZA),o.up.set(0,1,0),o.up.applyMatrix4(JA),o.up.reflect(GA),o.lookAt(QA),o.near=n.near,o.far=n.far,o.updateMatrixWorld(),o.projectionMatrix.copy(n.projectionMatrix),WA.setFromNormalAndCoplanarPoint(GA,KA),WA.applyMatrix4(o.matrixWorldInverse),XA.set(WA.normal.x,WA.normal.y,WA.normal.z,WA.constant);let u=o.projectionMatrix;$A.x=(Math.sign(XA.x)+u.elements[8])/u.elements[0],$A.y=(Math.sign(XA.y)+u.elements[9])/u.elements[5],$A.z=-1,$A.w=(1+u.elements[10])/u.elements[14],XA.multiplyScalar(1/XA.dot($A)),u.elements[2]=XA.x,u.elements[6]=XA.y,u.elements[10]=r.coordinateSystem===2001?XA.z-0:XA.z+1-0,u.elements[14]=XA.w,this.textureNode.value=s.texture,this.depth===!0&&(this.textureNode.getDepthNode().value=s.depthTexture),i.visible=!1;let d=r.getRenderTarget(),f=r.getMRT(),p=r.autoClear;r.setMRT(null),r.setRenderTarget(s),r.autoClear=!0;let m=t.name;t.name=(t.name||`Scene`)+` [ Reflector ]`,l?(r.clear(),this.hasOutput=!1):(r.render(t,o),this.hasOutput=!0),t.name=m,r.setMRT(f),r.setRenderTarget(d),r.autoClear=p,i.visible=!0,rj=!1,this.forceUpdate=!1}get resolution(){return m(`ReflectorNode: The "resolution" property has been renamed to "resolutionScale".`),this.resolutionScale}set resolution(e){m(`ReflectorNode: The "resolution" property has been renamed to "resolutionScale".`),this.resolutionScale=e}},oj=e=>new ij(e),sj=new Iu(-1,1,1,-1,0,1),cj=class extends xo{constructor(e=!1){super();let t=e===!1?[0,-1,0,1,2,1]:[0,2,0,0,2,0];this.setAttribute(`position`,new R([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute(`uv`,new R(t,2))}},lj=new cj,uj=bg(b_([-1,-1,3]).element(ib),b_([3,-1,-1]).element(ib),0,1),dj=class extends z{constructor(e){super(lj,e),this.camera=sj,this.isQuadMesh=!0}async renderAsync(e){m(`QuadMesh: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.`),await e.init(),e.render(this,sj)}render(e){let t=this.material.vertexNode;this.material.vertexNode=uj,e.render(this,sj),this.material.vertexNode=t}},fj=Object.freeze({__proto__:null,resetRendererAndSceneState:hm,resetRendererState:lm,resetSceneState:fm,restoreRendererAndSceneState:gm,restoreRendererState:um,restoreSceneState:pm,saveRendererAndSceneState:mm,saveRendererState:cm,saveSceneState:dm}),pj=new N,mj=class extends zb{static get type(){return`RTTNode`}constructor(e,t=null,n=null,r={}){let{autoUpdate:i=!0,resolutionScale:a=1}=r,o=new Ni(t??1,n??1,{type:_n,...r});super(o.texture,Mb()),this.isRTTNode=!0,this.node=e,this.width=t,this.height=n,this.renderTarget=o,this.textureNeedsUpdate=!0,this.autoUpdate=i,this._resolutionScale=a,this._quadMesh=new dj(new VT),this._rendererState={},this.updateBeforeType=nh.FRAME}get autoResize(){return this.width===null}setup(e){return this._quadMesh.material.contextNode=Sy(e.getSharedContext()),this._quadMesh.material.fragmentNode=this.node,this._quadMesh.material.name=`RTT`,this._quadMesh.material.needsUpdate=!0,super.setup(e)}setSize(e,t){let n=Math.floor(e*this._resolutionScale),r=Math.floor(t*this._resolutionScale);this.renderTarget.setSize(n,r),this.textureNeedsUpdate=!0}setResolutionScale(e){return this._resolutionScale=e,this.autoResize===!1&&this.setSize(this.width,this.height),this}getResolutionScale(){return this._resolutionScale}set value(e){this.renderTarget&&e!==this.renderTarget.texture&&p(`TSL: "rtt()" does not allow overwriting the value.`)}get value(){return this.renderTarget?this.renderTarget.texture:null}updateBefore(e){let{renderer:t}=e;if(this.textureNeedsUpdate===!1&&this.autoUpdate===!1)return;if(this.textureNeedsUpdate=!1,this.autoResize===!0){let e=t.getDrawingBufferSize(pj),n=Math.floor(e.width*this._resolutionScale),r=Math.floor(e.height*this._resolutionScale);(n!==this.renderTarget.width||r!==this.renderTarget.height)&&(this.renderTarget.setSize(n,r),this.textureNeedsUpdate=!0)}let n=`RTT`,r=this.name||this.node.name;r&&(n=r+` [ `+n+` ]`),this._quadMesh.name=n,lm(t,this._rendererState),t.setRenderTarget(this.renderTarget),this._quadMesh.render(t),um(t,this._rendererState)}clone(){let e=new zb(this.value,this.uvNode,this.levelNode);return e.sampler=this.sampler,e.referenceNode=this,e}dispose(){this.renderTarget.dispose(),this._quadMesh.material.dispose(),super.dispose()}},hj=(e,...t)=>new mj(Qh(e),...t),gj=(e,...t)=>e.isSampleNode||e.isTextureNode?e:e.isPassNode?e.getTextureNode():hj(e,...t),_j=V(([e,t,n],r)=>{let i;r.renderer.coordinateSystem===2001?(e=pg(e.x,e.y.oneMinus()).mul(2).sub(1),i=bg(K(e,t),1)):i=bg(K(e.x,e.y.oneMinus(),t).mul(2).sub(1),1);let a=bg(n.mul(i));return a.xyz.div(a.w)}),vj=V(([e,t])=>{let n=t.mul(bg(e,1)),r=n.xy.div(n.w).mul(.5).add(.5).toVar();return pg(r.x,r.y.oneMinus())}),yj=V(([e])=>{let t=e.xy.div(e.w).mul(.5).add(.5).toVar();return pg(t.x,t.y.oneMinus())}).setLayout({name:`getScreenPositionFromClip`,type:`vec2`,inputs:[{name:`clipPosition`,type:`vec4`}]}),bj=V(([e,t,n])=>{let r=Pb(Ub(t)),i=mg(e.mul(r)).toVar(),a=Ub(t,i).toVar(),o=Ub(t,i.sub(mg(2,0))).toVar(),s=Ub(t,i.sub(mg(1,0))).toVar(),c=Ub(t,i.add(mg(1,0))).toVar(),l=Ub(t,i.add(mg(2,0))).toVar(),u=Ub(t,i.add(mg(0,2))).toVar(),d=Ub(t,i.add(mg(0,1))).toVar(),f=Ub(t,i.sub(mg(0,1))).toVar(),p=Ub(t,i.sub(mg(0,2))).toVar(),m=Av(O_(U(2).mul(s).sub(o),a)).toVar(),h=Av(O_(U(2).mul(c).sub(l),a)).toVar(),g=Av(O_(U(2).mul(d).sub(u),a)).toVar(),_=Av(O_(U(2).mul(f).sub(p),a)).toVar(),v=_j(e,a,n).toVar(),y=m.lessThan(h).select(v.sub(_j(e.sub(pg(U(1).div(r.x),0)),s,n)),v.negate().add(_j(e.add(pg(U(1).div(r.x),0)),c,n))),b=g.lessThan(_).select(v.sub(_j(e.add(pg(0,U(1).div(r.y))),d,n)),v.negate().add(_j(e.sub(pg(0,U(1).div(r.y))),f,n)));return gv(Zv(y,b))}),xj=V(([e])=>_v(U(52.9829189).mul(_v(Xv(e,pg(.06711056,.00583715)))))).setLayout({name:`interleavedGradientNoise`,type:`float`,inputs:[{name:`position`,type:`vec2`}]}),Sj=V(([e,t,n])=>{let r=U(2.399963229728653),i=fv(U(e).add(.5).div(U(t))),a=U(e).mul(r).add(n);return pg(bv(a),vv(a)).mul(i)}).setLayout({name:`vogelDiskSample`,type:`vec2`,inputs:[{name:`sampleIndex`,type:`int`},{name:`samplesCount`,type:`int`},{name:`phi`,type:`float`}]}),Cj=class extends dh{static get type(){return`SampleNode`}constructor(e,t=null){super(),this.callback=e,this.uvNode=t,this.isSampleNode=!0}setup(){return this.sample(Mb())}sample(e){return this.callback(e)}},wj=(e,t=null)=>new Cj(e,Qh(t)),Tj=class extends Ds{constructor(e,t,n=Float32Array){let r=ArrayBuffer.isView(e)?e:new n(e*t);super(r,t),this.isStorageInstancedBufferAttribute=!0}},Ej=class extends eo{constructor(e,t,n=Float32Array){let r=ArrayBuffer.isView(e)?e:new n(e*t);super(r,t),this.isStorageBufferAttribute=!0}},Dj=(e,t=`float`)=>{let n,r;t.isStructTypeNode===!0?(n=t.getLength(),r=Yf(`float`)):(n=Xf(t),r=Yf(t));let i=new Ej(e,n,r);return Mw(i,t,e)},Oj=(e,t=`float`)=>{let n,r;t.isStructTypeNode===!0?(n=t.getLength(),r=Yf(`float`)):(n=Xf(t),r=Yf(t));let i=new Tj(e,n,r);return Mw(i,t,i.count)},kj=class extends dh{static get type(){return`PointUVNode`}constructor(){super(`vec2`),this.isPointUVNode=!0}generate(){return`vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )`}},Aj=rg(kj),jj=new F,Mj=v_(0).setGroup(h_).onRenderUpdate(({scene:e})=>e.backgroundBlurriness),Nj=v_(1).setGroup(h_).onRenderUpdate(({scene:e})=>e.backgroundIntensity),Pj=v_(new F).setGroup(h_).onRenderUpdate(({scene:e})=>{let t=e.background;return t!==null&&t.isTexture&&t.mapping!==300||e.backgroundNode&&e.backgroundNode.isNode?jj.makeRotationFromEuler(e.backgroundRotation).transpose():jj.identity(),jj}),Fj=class extends zb{static get type(){return`StorageTextureNode`}constructor(e,t,n=null){super(e,t),this.storeNode=n,this.mipLevel=0,this.isStorageTextureNode=!0,this.access=ih.WRITE_ONLY}getInputType(){return`storageTexture`}getTransformedUV(e){return e}setup(e){super.setup(e);let t=e.getNodeProperties(this);return t.storeNode=this.storeNode,t}setAccess(e){return this.access=e,this}setMipLevel(e){return this.mipLevel=e,this}generate(e,t){return this.storeNode===null?super.generate(e,t):(this.generateStore(e),``)}generateSnippet(e,t,n,r,i,a,o,s,c){let l=this.value;return e.generateStorageTextureLoad(l,t,n,r,a,c)}toReadWrite(){return this.setAccess(ih.READ_WRITE)}toReadOnly(){return this.setAccess(ih.READ_ONLY)}toWriteOnly(){return this.setAccess(ih.WRITE_ONLY)}store(e,t){let n=this.clone();return n.referenceNode=this.getBase(),n.uvNode=e,n.storeNode=t,t!==null&&n.toStack(),n}generateStore(e){let{uvNode:t,storeNode:n,depthNode:r}=e.getNodeProperties(this),i=super.generate(e,`property`),a=t.build(e,this.value.is3DTexture===!0?`uvec3`:`uvec2`),o=e.getTypeFromLength(4,e.getComponentTypeFromTexture(this.value)),s=n.build(e,o),c=r?r.build(e,`int`):null,l=e.generateTextureStore(this.value,i,a,c,s);e.addLineFlowCode(l,this)}clone(){let e=super.clone();return e.storeNode=this.storeNode,e.mipLevel=this.mipLevel,e.access=this.access,e}},Ij=ng(Fj).setParameterLength(1,3),Lj=(e,t,n)=>{let r;return e.isStorageTextureNode===!0?r=e.store(t,n):(r=Ij(e,t,n),n!==null&&r.toStack()),r},Rj=class extends Fj{static get type(){return`StorageTexture3DNode`}constructor(e,t,n=null){super(e,t,n),this.isStorageTexture3DNode=!0}getDefaultUV(){return K(.5,.5,.5)}setUpdateMatrix(){}generateUV(e,t){return t.build(e,this.sampler===!0?`vec3`:`ivec3`)}generateOffset(e,t){return t.build(e,`ivec3`)}},zj=ng(Rj).setParameterLength(1,3),Bj=V(({texture:e,uv:t})=>{let n=1e-4,r=K().toVar();return lg(t.x.lessThan(n),()=>{r.assign(K(1,0,0))}).ElseIf(t.y.lessThan(n),()=>{r.assign(K(0,1,0))}).ElseIf(t.z.lessThan(n),()=>{r.assign(K(0,0,1))}).ElseIf(t.x.greaterThan(.9999),()=>{r.assign(K(-1,0,0))}).ElseIf(t.y.greaterThan(.9999),()=>{r.assign(K(0,-1,0))}).ElseIf(t.z.greaterThan(.9999),()=>{r.assign(K(0,0,-1))}).Else(()=>{let n=.01,i=e.sample(t.add(K(-.01,0,0))).r.sub(e.sample(t.add(K(n,0,0))).r),a=e.sample(t.add(K(0,-.01,0))).r.sub(e.sample(t.add(K(0,n,0))).r),o=e.sample(t.add(K(0,0,-.01))).r.sub(e.sample(t.add(K(0,0,n))).r);r.assign(K(i,a,o))}),r.normalize()}),Vj=class extends zb{static get type(){return`Texture3DNode`}constructor(e,t=null,n=null){super(e,t,n),this.isTexture3DNode=!0}getInputType(){return`texture3D`}getDefaultUV(){return K(.5,.5,.5)}setUpdateMatrix(){}generateUV(e,t){return t.build(e,this.sampler===!0?`vec3`:`ivec3`)}generateOffset(e,t){return t.build(e,`ivec3`)}normal(e){return Bj({texture:this,uv:e})}},Hj=ng(Vj).setParameterLength(1,3),Uj=(...e)=>Hj(...e).setSampler(!1),Wj=(e,t,n)=>Hj(e,t).level(n),Gj=class extends HS{static get type(){return`UserDataNode`}constructor(e,t,n=null){super(e,t,n),this.userData=n}updateReference(e){return this.reference=this.userData===null?e.object.userData:this.userData,this.reference}},Kj=(e,t,n)=>new Gj(e,t,n),qj=new WeakMap,Jj=class extends mh{static get type(){return`VelocityNode`}constructor(){super(`vec2`),this.projectionMatrix=null,this.updateType=nh.OBJECT,this.updateAfterType=nh.OBJECT,this.previousModelWorldMatrix=v_(new F),this.previousProjectionMatrix=v_(new F).setGroup(h_),this.previousCameraViewMatrix=v_(new F).setGroup(h_)}setProjectionMatrix(e){this.projectionMatrix=e}update({frameId:e,camera:t,object:n}){let r=vm(n);this.previousModelWorldMatrix.value.copy(r);let i=_m(t);i.frameId!==e&&(i.frameId=e,i.previousProjectionMatrix===void 0?(i.previousProjectionMatrix=new F,i.previousCameraViewMatrix=new F,i.currentProjectionMatrix=new F,i.currentCameraViewMatrix=new F,i.previousProjectionMatrix.copy(this.projectionMatrix||t.projectionMatrix),i.previousCameraViewMatrix.copy(t.matrixWorldInverse)):(i.previousProjectionMatrix.copy(i.currentProjectionMatrix),i.previousCameraViewMatrix.copy(i.currentCameraViewMatrix)),i.currentProjectionMatrix.copy(this.projectionMatrix||t.projectionMatrix),i.currentCameraViewMatrix.copy(t.matrixWorldInverse),this.previousProjectionMatrix.value.copy(i.previousProjectionMatrix),this.previousCameraViewMatrix.value.copy(i.previousCameraViewMatrix))}updateAfter({object:e}){vm(e).copy(e.matrixWorld)}setup(){let e=this.projectionMatrix===null?Ox:v_(this.projectionMatrix),t=this.previousCameraViewMatrix.mul(this.previousModelWorldMatrix),n=e.mul($x).mul(aS),r=this.previousProjectionMatrix.mul(t).mul(oS),i=n.xy.div(n.w),a=r.xy.div(r.w);return O_(i,a)}},Yj=rg(Jj),Xj=V(([e,t])=>Wv(1,e.oneMinus().div(t)).oneMinus()).setLayout({name:`blendBurn`,type:`vec3`,inputs:[{name:`base`,type:`vec3`},{name:`blend`,type:`vec3`}]}),Zj=V(([e,t])=>Wv(e.div(t.oneMinus()),1)).setLayout({name:`blendDodge`,type:`vec3`,inputs:[{name:`base`,type:`vec3`},{name:`blend`,type:`vec3`}]}),Qj=V(([e,t])=>e.oneMinus().mul(t.oneMinus()).oneMinus()).setLayout({name:`blendScreen`,type:`vec3`,inputs:[{name:`base`,type:`vec3`},{name:`blend`,type:`vec3`}]}),$j=V(([e,t])=>sy(e.mul(2).mul(t),e.oneMinus().mul(2).mul(t.oneMinus()).oneMinus(),Kv(.5,e))).setLayout({name:`blendOverlay`,type:`vec3`,inputs:[{name:`base`,type:`vec3`},{name:`blend`,type:`vec3`}]}),eM=V(([e,t])=>{let n=t.a.add(e.a.mul(t.a.oneMinus()));return bg(t.rgb.mul(t.a).add(e.rgb.mul(e.a).mul(t.a.oneMinus())).div(n),n)}).setLayout({name:`blendColor`,type:`vec4`,inputs:[{name:`base`,type:`vec4`},{name:`blend`,type:`vec4`}]}),tM=V(([e])=>aM(e.rgb)),nM=V(([e,t=U(1)])=>t.mix(aM(e.rgb),e.rgb).max(0)),rM=V(([e,t=U(0)])=>{let n=D_(e.r,e.g,e.b).div(3),r=e.r.max(e.g.max(e.b)),i=r.sub(n).mul(t).mul(-3);return sy(e.rgb,r,i).max(0)}),iM=V(([e,t=U(1)])=>{let n=K(.57735,.57735,.57735),r=t.cos();return K(e.rgb.mul(r).add(n.cross(e.rgb).mul(t.sin()).add(n.mul(Xv(n,e.rgb).mul(r.oneMinus()))))).max(0)}),aM=(e,t=K(Ci.getLuminanceCoefficients(new P)))=>Xv(e,t),oM=V(([e,t=K(1),n=K(0),r=K(1),i=U(1),a=K(Ci.getLuminanceCoefficients(new P,Nr))])=>{let o=e.rgb.dot(K(a)),s=Gv(e.rgb.mul(t).add(n),0),c=s.pow(r);return lg(s.r.greaterThan(0),()=>{s.r.assign(c.r)}),lg(s.g.greaterThan(0),()=>{s.g.assign(c.g)}),lg(s.b.greaterThan(0),()=>{s.b.assign(c.b)}),s.assign(o.add(s.sub(o).mul(i)).max(0)),bg(s.rgb,e.a)}),sM=V(([e,t])=>e.mul(t).floor().div(t)),cM=null,lM=class extends uT{static get type(){return`ViewportSharedTextureNode`}constructor(e=ix,t=null){cM===null&&(cM=new Cc),super(e,t,cM)}getTextureForReference(){return cM}updateReference(){return this}},uM=ng(lM).setParameterLength(0,2),dM=new N,fM=class extends zb{static get type(){return`PassTextureNode`}constructor(e,t){super(t),this.passNode=e,this.isPassTextureNode=!0,this.setUpdateMatrix(!1)}setup(e){let t=e.getNodeProperties(this);return t.passNode=this.passNode,super.setup(e)}clone(){return new this.constructor(this.passNode,this.value)}},pM=class extends fM{static get type(){return`PassMultipleTextureNode`}constructor(e,t,n=!1){super(e,null),this.textureName=t,this.previousTexture=n,this.isPassMultipleTextureNode=!0}updateTexture(){this.value=this.previousTexture?this.passNode.getPreviousTexture(this.textureName):this.passNode.getTexture(this.textureName)}setup(e){return this.updateTexture(),super.setup(e)}clone(){let e=new this.constructor(this.passNode,this.textureName,this.previousTexture);return e.uvNode=this.uvNode,e.levelNode=this.levelNode,e.biasNode=this.biasNode,e.sampler=this.sampler,e.depthNode=this.depthNode,e.compareNode=this.compareNode,e.gradNode=this.gradNode,e.gatherNode=this.gatherNode,e.offsetNode=this.offsetNode,e}},mM=class e extends mh{static get type(){return`PassNode`}constructor(t,n,r,i={}){super(`vec4`),this.scope=t,this.scene=n,this.camera=r,this.options=i,this._width=1,this._height=1;let a=new Ni(this._width,this._height,{type:_n,...i});a.texture.name=`output`;let o=null;(this.scope===e.DEPTH||i.depthBuffer!==!1)&&(o=i.depthTexture||new Ac,o.isRenderTargetTexture=!0,o.name=`depth`,a.depthTexture=o),this.renderTarget=a,this.overrideMaterial=null,this.transparent=!0,this.opaque=!0,this.lighting=null,this.autoClear=i.autoClear===void 0||i.autoClear,this.autoClearColor=i.autoClearColor===void 0||i.autoClearColor,this.autoClearDepth=i.autoClearDepth===void 0||i.autoClearDepth,this.autoClearStencil=i.autoClearStencil===void 0||i.autoClearStencil,this.contextNode=null,this._contextNodeCache=null,this._textures={output:a.texture},o!==null&&(this._textures.depth=o),this._textureNodes={},this._linearDepthNodes={},this._viewZNodes={},this._previousTextures={},this._previousTextureNodes={},this._cameraNear=v_(0),this._cameraFar=v_(0),this._mrt=null,this._layers=null,this._resolutionScale=1,this._viewport=null,this._scissor=null,this.isPassNode=!0,this.updateBeforeType=nh.FRAME,this.global=!0}setResolutionScale(e){return this._resolutionScale=e,this}getResolutionScale(){return this._resolutionScale}setResolution(e){return f(`PassNode: .setResolution() is deprecated. Use .setResolutionScale() instead.`),this.setResolutionScale(e)}getResolution(){return f(`PassNode: .getResolution() is deprecated. Use .getResolutionScale() instead.`),this.getResolutionScale()}setLayers(e){return this._layers=e,this}getLayers(){return this._layers}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getTexture(e){let t=this._textures[e];if(t===void 0){if(e===`depth`)throw Error(`THREE.PassNode: Depth texture is not available for this pass.`);t=this.renderTarget.texture.clone(),t.name=e,this._textures[e]=t,this.renderTarget.textures.push(t)}return t}getPreviousTexture(e){let t=this._previousTextures[e];return t===void 0&&(t=this.getTexture(e).clone(),this._previousTextures[e]=t),t}toggleTexture(e){let t=this._previousTextures[e];if(t!==void 0){let n=this._textures[e],r=this.renderTarget.textures.indexOf(n);this.renderTarget.textures[r]=t,this._textures[e]=t,this._previousTextures[e]=n,this._textureNodes[e].updateTexture(),this._previousTextureNodes[e].updateTexture()}}getTextureNode(e=`output`){let t=this._textureNodes[e];return t===void 0&&(t=new pM(this,e),t.updateTexture(),this._textureNodes[e]=t),t}getPreviousTextureNode(e=`output`){let t=this._previousTextureNodes[e];return t===void 0&&(this._textureNodes[e]===void 0&&this.getTextureNode(e),t=new pM(this,e,!0),t.updateTexture(),this._previousTextureNodes[e]=t),t}getViewZNode(e=`depth`){let t=this._viewZNodes[e];if(t===void 0){let n=this._cameraNear,r=this._cameraFar;this._viewZNodes[e]=t=wT(this.getTextureNode(e),n,r)}return t}getLinearDepthNode(e=`depth`){let t=this._linearDepthNodes[e];if(t===void 0){let n=this._cameraNear,r=this._cameraFar,i=this.getViewZNode(e);this._linearDepthNodes[e]=t=yT(i,n,r)}return t}async compileAsync(e){let t=e.getRenderTarget(),n=e.getMRT();e.setRenderTarget(this.renderTarget),e.setMRT(this._mrt),await e.compileAsync(this.scene,this.camera),e.setRenderTarget(t),e.setMRT(n)}setup({renderer:t}){return this.renderTarget.samples=this.options.samples===void 0?t.samples:this.options.samples,this.renderTarget.texture.type=t.getOutputBufferType(),t.reversedDepthBuffer===!0&&this.renderTarget.depthTexture!==null&&(this.renderTarget.depthTexture.type=gn),this.scope===e.COLOR?this.getTextureNode():this.getLinearDepthNode()}updateBefore(e){let{renderer:t}=e,{scene:n}=this,r,i=t.getOutputRenderTarget();i&&i.isXRRenderTarget===!0?(r=t.xr.getCamera(),t.xr.updateCamera(r),dM.set(i.width,i.height)):(r=this.camera,t.getDrawingBufferSize(dM)),this.setSize(dM.width,dM.height);let a=t.getRenderTarget(),o=t.getMRT(),s=t.autoClear,c=t.autoClearColor,l=t.autoClearDepth,u=t.autoClearStencil,d=t.transparent,f=t.opaque,p=t.lighting,m=r.layers.mask,h=t.contextNode,g=n.overrideMaterial;this._cameraNear.value=r.near,this._cameraFar.value=r.far,this._layers!==null&&(r.layers.mask=this._layers.mask);for(let e in this._previousTextures)this.toggleTexture(e);this.overrideMaterial!==null&&(n.overrideMaterial=this.overrideMaterial),t.setRenderTarget(this.renderTarget),t.setMRT(this._mrt),t.autoClear=this.autoClear,t.autoClearColor=this.autoClearColor,t.autoClearDepth=this.autoClearDepth,t.autoClearStencil=this.autoClearStencil,t.transparent=this.transparent,t.opaque=this.opaque,this.lighting!==null&&(t.lighting=this.lighting),this.contextNode!==null&&((this._contextNodeCache===null||this._contextNodeCache.version!==this.version)&&(this._contextNodeCache={version:this.version,context:Sy({...t.contextNode.getFlowContextData(),...this.contextNode.getFlowContextData()})}),t.contextNode=this._contextNodeCache.context);let _=n.name;n.name=this.name?this.name:n.name,t.render(n,r),n.name=_,n.overrideMaterial=g,t.setRenderTarget(a),t.setMRT(o),t.autoClear=s,t.autoClearColor=c,t.autoClearDepth=l,t.autoClearStencil=u,t.transparent=d,t.opaque=f,t.contextNode=h,t.lighting=p,r.layers.mask=m}setSize(e,t){this._width=e,this._height=t;let n=Math.floor(this._width*this._resolutionScale),r=Math.floor(this._height*this._resolutionScale);this.renderTarget.setSize(n,r),this._scissor===null?this.renderTarget.scissorTest=!1:(this.renderTarget.scissor.copy(this._scissor).multiplyScalar(this._resolutionScale).floor(),this.renderTarget.scissorTest=!0),this._viewport!==null&&this.renderTarget.viewport.copy(this._viewport).multiplyScalar(this._resolutionScale).floor()}setScissor(e,t,n,r){e===null?this._scissor=null:(this._scissor===null&&(this._scissor=new Mi),e.isVector4?this._scissor.copy(e):this._scissor.set(e,t,n,r))}setViewport(e,t,n,r){e===null?this._viewport=null:(this._viewport===null&&(this._viewport=new Mi),e.isVector4?this._viewport.copy(e):this._viewport.set(e,t,n,r))}dispose(){super.dispose(),this.renderTarget.dispose()}static get COLOR(){return`color`}static get DEPTH(){return`depth`}},hM=(e,t,n)=>new mM(mM.COLOR,e,t,n),gM=(e,t)=>new fM(e,t),_M=(e,t,n)=>new mM(mM.DEPTH,e,t,n),vM=class extends mM{static get type(){return`ToonOutlinePassNode`}constructor(e,t,n,r,i){super(mM.COLOR,e,t),this.colorNode=n,this.thicknessNode=r,this.alphaNode=i,this._materialCache=new WeakMap,this.name=`Outline Pass`}updateBefore(e){let{renderer:t}=e,n=t.getRenderObjectFunction();t.setRenderObjectFunction((e,n,r,i,a,o,s,c)=>{if((a.isMeshToonMaterial||a.isMeshToonNodeMaterial)&&a.wireframe===!1){let l=this._getOutlineMaterial(a);t.renderObject(e,n,r,i,l,o,s,c)}t.renderObject(e,n,r,i,a,o,s,c)}),super.updateBefore(e),t.setRenderObjectFunction(n)}_createMaterial(){let e=new VT;e.isMeshToonOutlineMaterial=!0,e.name=`Toon_Outline`,e.side=1;let t=_S.negate(),n=Ox.mul($x),r=U(1),i=n.mul(bg(aS,1)),a=n.mul(bg(aS.add(t),1)),o=gv(i.sub(a));return e.vertexNode=i.add(o.mul(this.thicknessNode).mul(i.w).mul(r)),e.colorNode=bg(this.colorNode,this.alphaNode),e}_getOutlineMaterial(e){let t=this._materialCache.get(e);return t===void 0&&(t=this._createMaterial(),this._materialCache.set(e,t)),t}},yM=(e,t,n=new L(0,0,0),r=.003,i=1)=>new vM(e,t,Qh(n),Qh(r),Qh(i)),bM=V(([e,t])=>e.mul(t).clamp()).setLayout({name:`linearToneMapping`,type:`vec3`,inputs:[{name:`color`,type:`vec3`},{name:`exposure`,type:`float`}]}),xM=V(([e,t])=>(e=e.mul(t),e.div(e.add(1)).clamp())).setLayout({name:`reinhardToneMapping`,type:`vec3`,inputs:[{name:`color`,type:`vec3`},{name:`exposure`,type:`float`}]}),SM=V(([e,t])=>{e=e.mul(t),e=e.sub(.004).max(0);let n=e.mul(e.mul(6.2).add(.5)),r=e.mul(e.mul(6.2).add(1.7)).add(.06);return n.div(r).pow(2.2)}).setLayout({name:`cineonToneMapping`,type:`vec3`,inputs:[{name:`color`,type:`vec3`},{name:`exposure`,type:`float`}]}),CM=V(([e])=>{let t=e.mul(e.add(.0245786)).sub(90537e-9),n=e.mul(e.add(.432951).mul(.983729)).add(.238081);return t.div(n)}),wM=V(([e,t])=>{let n=Tg(.59719,.35458,.04823,.076,.90834,.01566,.0284,.13383,.83777),r=Tg(1.60475,-.53108,-.07367,-.10208,1.10813,-.00605,-.00327,-.07276,1.07602);return e=e.mul(t).div(.6),e=n.mul(e),e=CM(e),e=r.mul(e),e.clamp()}).setLayout({name:`acesFilmicToneMapping`,type:`vec3`,inputs:[{name:`color`,type:`vec3`},{name:`exposure`,type:`float`}]}),TM=Tg(K(1.6605,-.1246,-.0182),K(-.5876,1.1329,-.1006),K(-.0728,-.0083,1.1187)),EM=Tg(K(.6274,.0691,.0164),K(.3293,.9195,.088),K(.0433,.0113,.8956)),DM=V(([e])=>{let t=K(e).toVar(),n=K(t.mul(t)).toVar(),r=K(n.mul(n)).toVar();return U(15.5).mul(r.mul(n)).sub(k_(40.14,r.mul(t))).add(k_(31.96,r).sub(k_(6.868,n.mul(t))).add(k_(.4298,n).add(k_(.1191,t).sub(.00232))))}),OM=V(([e,t])=>{let n=K(e).toVar(),r=Tg(K(.856627153315983,.137318972929847,.11189821299995),K(.0951212405381588,.761241990602591,.0767994186031903),K(.0482516061458583,.101439036467562,.811302368396859)),i=Tg(K(1.1271005818144368,-.1413297634984383,-.14132976349843826),K(-.11060664309660323,1.157823702216272,-.11060664309660294),K(-.016493938717834573,-.016493938717834257,1.2519364065950405)),a=U(-12.47393),o=U(4.026069);return n.mulAssign(t),n.assign(EM.mul(n)),n.assign(r.mul(n)),n.assign(Gv(n,1e-10)),n.assign(dv(n)),n.assign(n.sub(a).div(o.sub(a))),n.assign(cy(n,0,1)),n.assign(DM(n)),n.assign(i.mul(n)),n.assign(Qv(Gv(K(0),n),K(2.2))),n.assign(TM.mul(n)),n.assign(cy(n,0,1)),n}).setLayout({name:`agxToneMapping`,type:`vec3`,inputs:[{name:`color`,type:`vec3`},{name:`exposure`,type:`float`}]}),kM=V(([e,t])=>{let n=U(.76),r=U(.15);e=e.mul(t);let i=Wv(e.r,Wv(e.g,e.b)),a=by(i.lessThan(.08),i.sub(k_(6.25,i.mul(i))),.04);e.subAssign(a);let o=Gv(e.r,Gv(e.g,e.b));lg(o.lessThan(n),()=>e);let s=O_(1,n),c=O_(1,s.mul(s).div(o.add(s.sub(n))));e.mulAssign(c.div(o));let l=O_(1,A_(1,r.mul(o.sub(c)).add(1)));return sy(e,K(c),l)}).setLayout({name:`neutralToneMapping`,type:`vec3`,inputs:[{name:`color`,type:`vec3`},{name:`exposure`,type:`float`}]}),AM=class extends dh{static get type(){return`CodeNode`}constructor(e=``,t=[],n=``){super(`code`),this.isCodeNode=!0,this.global=!0,this.code=e,this.includes=t,this.language=n}setIncludes(e){return this.includes=e,this}getIncludes(){return this.includes}generate(e){let t=this.getIncludes(e);for(let n of t)n.build(e,`void`);let n=e.getCodeFromNode(this,this.getNodeType(e));return n.code=this.code,n.code}serialize(e){super.serialize(e),e.code=this.code,e.language=this.language}deserialize(e){super.deserialize(e),this.code=e.code,this.language=e.language}},jM=ng(AM).setParameterLength(1,3),MM=(e,t)=>jM(e,t,`js`),NM=(e,t)=>jM(e,t,`wgsl`),PM=(e,t)=>jM(e,t,`glsl`),FM=class extends AM{static get type(){return`FunctionNode`}constructor(e=``,t=[],n=``){super(e,t,n)}generateNodeType(e){return this.getNodeFunction(e).type}getMemberType(e,t){let n=this.getNodeType(e);return e.getStructTypeNode(n).getMemberType(e,t)}getInputs(e){return this.getNodeFunction(e).inputs}getNodeFunction(e){let t=e.getDataFromNode(this),n=t.nodeFunction;return n===void 0&&(n=e.parser.parseFunction(this.code),t.nodeFunction=n),n}generate(e,t){super.generate(e);let n=this.getNodeFunction(e),r=n.name,i=n.type,a=e.getCodeFromNode(this,i);if(r!==``){let t=e.getDataFromNode(this);t.declarationRegistered!==!0&&(a.name=r,e.registerDeclaration(a),t.declarationRegistered=!0)}let o=e.getPropertyName(a);return a.code=this.getNodeFunction(e).getCode(o)+` `,t===`property`?o:e.format(`${o}()`,i,t)}},IM=(e,t=[],n=``)=>{let r=new FM(e,t,n);return ig((...e)=>r.call(...e),r)},LM=(e,t)=>IM(e,t,`glsl`),RM=(e,t)=>IM(e,t,`wgsl`),zM=V(([e,t],n)=>{let r=ym(n);return dy(e,t,r)}),BM=V(([e],t)=>{let n=ym(t);return e.mul(e,n,n).negate().exp().oneMinus()}),VM=V(([e,t],n)=>{let r=ym(n),i=t.sub(sS.y).max(0).toConst().mul(r).toConst();return e.mul(e,i,i).negate().exp().oneMinus()}),HM=V(([e,t])=>bg(t.toFloat().mix($g.rgb,e.toVec3()),$g.a)),UM=null,WM=null,GM=class extends dh{static get type(){return`RangeNode`}constructor(e=U(),t=U()){super(),this.minNode=e,this.maxNode=t}getVectorLength(e){let t=this.getConstNode(this.minNode),n=this.getConstNode(this.maxNode),r=e.getTypeLength($f(t.value)),i=e.getTypeLength($f(n.value));return r>i?r:i}generateNodeType(e){return e.object.count>1?e.getTypeFromLength(this.getVectorLength(e)):`float`}getConstNode(e){let t=null;if(e.traverse(e=>{e.isConstNode===!0&&(t=e)}),t===null)throw new Lb(`THREE.TSL: No "ConstNode" found in node graph.`,this.stackTrace);return t}setup(e){let t=e.object,n=null;if(t.count>1){let r=this.getConstNode(this.minNode),i=this.getConstNode(this.maxNode),a=r.value,o=i.value,s=e.getTypeLength($f(a)),c=e.getTypeLength($f(o));UM||=new Mi,WM||=new Mi,UM.setScalar(0),WM.setScalar(0),s===1?UM.setScalar(a):a.isColor?UM.set(a.r,a.g,a.b,1):UM.set(a.x,a.y,a.z||0,a.w||0),c===1?WM.setScalar(o):o.isColor?WM.set(o.r,o.g,o.b,1):WM.set(o.x,o.y,o.z||0,o.w||0);let l=4*t.count,u=new Float32Array(l);for(let e=0;enew qM(e,t),YM=JM(`numWorkgroups`,`uvec3`),XM=JM(`workgroupId`,`uvec3`),ZM=JM(`globalId`,`uvec3`),QM=JM(`localId`,`uvec3`),$M=JM(`subgroupSize`,`uint`),eN=class extends dh{constructor(e){super(),this.scope=e,this.isBarrierNode=!0}setup(e){e.allowEarlyReturns=!1,e.allowGlobalVariables=!1}generate(e){let{scope:t}=this,{renderer:n,shaderStage:r}=e,i=`${t}Barrier`;r!==`compute`&&p(`TSL: "${i}" is not supported in the ${r} stage and can only be executed in compute.`),n.backend.isWebGLBackend===!0?e.addFlowCode(`\t// ${i}() \n`):e.addLineFlowCode(`${i}()`,this)}},tN=ng(eN),nN=()=>tN(`workgroup`).toStack(),rN=()=>tN(`storage`).toStack(),iN=()=>tN(`texture`).toStack(),aN=class extends fh{constructor(e,t){super(e,t),this.isWorkgroupInfoElementNode=!0}generate(e,t){let n,r=e.isContextAssign();if(n=super.generate(e),r!==!0){let r=this.getNodeType(e);n=e.format(n,r,t)}return n}},oN=class extends dh{constructor(e,t,n=0){super(t),this.bufferType=t,this.bufferCount=n,this.isAtomic=!1,this.isWorkgroupInfoNode=!0,this.elementType=t,this.scope=e,this.name=``}setName(e){return this.name=e,this}label(e){return f(`TSL: "label()" has been deprecated. Use "setName()" instead.`,new Jm),this.setName(e)}setScope(e){return this.scope=e,this}setAtomic(e){return this.isAtomic=e,this}toAtomic(){return this.setAtomic(!0)}getElementType(){return this.elementType}getInputType(){return`${this.scope}Array`}element(e){return new aN(this,e)}generate(e){e.shaderStage!==`compute`&&p(`TSL: "workgroupArray()" can only be executed within the compute shader stage`);let t=this.name===``?`${this.scope}Array_${this.id}`:this.name;return e.getScopedArray(t,this.scope.toLowerCase(),this.bufferType,this.bufferCount,this.isAtomic)}},sN=(e,t)=>new oN(`Workgroup`,e,t),cN=class extends dh{static get type(){return`AtomicFunctionNode`}constructor(e,t,n){super(`uint`),this.method=e,this.pointerNode=t,this.valueNode=n,this.parents=!0}getInputType(e){return this.pointerNode.getNodeType(e)}generateNodeType(e){return this.getInputType(e)}generate(e){let t=this.method;e.shaderStage===`vertex`&&p(`TSL: "${this.method}" is not supported in the vertex stage.`);let n=e.getNodeProperties(this),r=n.parents,i=this.getNodeType(e),a=this.getInputType(e),o=this.pointerNode,s=this.valueNode,c=[];c.push(`&${o.build(e,a)}`),s!==null&&c.push(s.build(e,a));let l=`${e.getMethod(t,i)}( ${c.join(`, `)} )`;if(r&&r.length===1&&r[0].isStackNode===!0)e.addLineFlowCode(l,this);else return n.constNode===void 0&&(n.constNode=yb(l,i).toConst()),n.constNode.build(e)}static get ATOMIC_LOAD(){return`atomicLoad`}static get ATOMIC_STORE(){return`atomicStore`}static get ATOMIC_ADD(){return`atomicAdd`}static get ATOMIC_SUB(){return`atomicSub`}static get ATOMIC_MAX(){return`atomicMax`}static get ATOMIC_MIN(){return`atomicMin`}static get ATOMIC_AND(){return`atomicAnd`}static get ATOMIC_OR(){return`atomicOr`}static get ATOMIC_XOR(){return`atomicXor`}},lN=ng(cN),uN=(e,t,n)=>lN(e,t,n).toStack(),dN=e=>uN(cN.ATOMIC_LOAD,e,null),fN=(e,t)=>uN(cN.ATOMIC_STORE,e,t),pN=(e,t)=>uN(cN.ATOMIC_ADD,e,t),mN=(e,t)=>uN(cN.ATOMIC_SUB,e,t),hN=(e,t)=>uN(cN.ATOMIC_MAX,e,t),gN=(e,t)=>uN(cN.ATOMIC_MIN,e,t),_N=(e,t)=>uN(cN.ATOMIC_AND,e,t),vN=(e,t)=>uN(cN.ATOMIC_OR,e,t),yN=(e,t)=>uN(cN.ATOMIC_XOR,e,t),bN=class e extends mh{static get type(){return`SubgroupFunctionNode`}constructor(e,t=null,n=null){super(),this.method=e,this.aNode=t,this.bNode=n}getInputType(e){let t=this.aNode?this.aNode.getNodeType(e):null,n=this.bNode?this.bNode.getNodeType(e):null;return(e.isMatrix(t)?0:e.getTypeLength(t))>(e.isMatrix(n)?0:e.getTypeLength(n))?t:n}generateNodeType(t){let n=this.method;return n===e.SUBGROUP_ELECT?`bool`:n===e.SUBGROUP_BALLOT?`uvec4`:this.getInputType(t)}generate(t,n){let r=this.method;t.shaderStage===`vertex`&&p(`TSL: "${this.method}" is not supported in the vertex shader stage.`);let i=this.getNodeType(t),a=this.getInputType(t),o=this.aNode,s=this.bNode,c=[];if(r===e.SUBGROUP_BROADCAST||r===e.SUBGROUP_SHUFFLE||r===e.QUAD_BROADCAST){let e=s.getNodeType(t);c.push(o.build(t,i),s.build(t,e===`float`?`int`:i))}else r===e.SUBGROUP_SHUFFLE_XOR||r===e.SUBGROUP_SHUFFLE_DOWN||r===e.SUBGROUP_SHUFFLE_UP?c.push(o.build(t,i),s.build(t,`uint`)):(o!==null&&c.push(o.build(t,a)),s!==null&&c.push(s.build(t,a)));let l=c.length===0?`()`:`( ${c.join(`, `)} )`;return t.format(`${t.getMethod(r,i)}${l}`,i,n)}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}static get SUBGROUP_ELECT(){return`subgroupElect`}static get SUBGROUP_BALLOT(){return`subgroupBallot`}static get SUBGROUP_ADD(){return`subgroupAdd`}static get SUBGROUP_INCLUSIVE_ADD(){return`subgroupInclusiveAdd`}static get SUBGROUP_EXCLUSIVE_ADD(){return`subgroupExclusiveAdd`}static get SUBGROUP_MUL(){return`subgroupMul`}static get SUBGROUP_INCLUSIVE_MUL(){return`subgroupInclusiveMul`}static get SUBGROUP_EXCLUSIVE_MUL(){return`subgroupExclusiveMul`}static get SUBGROUP_AND(){return`subgroupAnd`}static get SUBGROUP_OR(){return`subgroupOr`}static get SUBGROUP_XOR(){return`subgroupXor`}static get SUBGROUP_MIN(){return`subgroupMin`}static get SUBGROUP_MAX(){return`subgroupMax`}static get SUBGROUP_ALL(){return`subgroupAll`}static get SUBGROUP_ANY(){return`subgroupAny`}static get SUBGROUP_BROADCAST_FIRST(){return`subgroupBroadcastFirst`}static get QUAD_SWAP_X(){return`quadSwapX`}static get QUAD_SWAP_Y(){return`quadSwapY`}static get QUAD_SWAP_DIAGONAL(){return`quadSwapDiagonal`}static get SUBGROUP_BROADCAST(){return`subgroupBroadcast`}static get SUBGROUP_SHUFFLE(){return`subgroupShuffle`}static get SUBGROUP_SHUFFLE_XOR(){return`subgroupShuffleXor`}static get SUBGROUP_SHUFFLE_UP(){return`subgroupShuffleUp`}static get SUBGROUP_SHUFFLE_DOWN(){return`subgroupShuffleDown`}static get QUAD_BROADCAST(){return`quadBroadcast`}},xN=H(bN,bN.SUBGROUP_ELECT).setParameterLength(0),SN=H(bN,bN.SUBGROUP_BALLOT).setParameterLength(1),CN=H(bN,bN.SUBGROUP_ADD).setParameterLength(1),wN=H(bN,bN.SUBGROUP_INCLUSIVE_ADD).setParameterLength(1),TN=H(bN,bN.SUBGROUP_EXCLUSIVE_ADD).setParameterLength(1),EN=H(bN,bN.SUBGROUP_MUL).setParameterLength(1),DN=H(bN,bN.SUBGROUP_INCLUSIVE_MUL).setParameterLength(1),ON=H(bN,bN.SUBGROUP_EXCLUSIVE_MUL).setParameterLength(1),kN=H(bN,bN.SUBGROUP_AND).setParameterLength(1),AN=H(bN,bN.SUBGROUP_OR).setParameterLength(1),jN=H(bN,bN.SUBGROUP_XOR).setParameterLength(1),MN=H(bN,bN.SUBGROUP_MIN).setParameterLength(1),NN=H(bN,bN.SUBGROUP_MAX).setParameterLength(1),PN=H(bN,bN.SUBGROUP_ALL).setParameterLength(1),FN=H(bN,bN.SUBGROUP_ANY).setParameterLength(1),IN=H(bN,bN.SUBGROUP_BROADCAST_FIRST).setParameterLength(1),LN=H(bN,bN.QUAD_SWAP_X).setParameterLength(1),RN=H(bN,bN.QUAD_SWAP_Y).setParameterLength(1),zN=H(bN,bN.QUAD_SWAP_DIAGONAL).setParameterLength(1),BN=H(bN,bN.SUBGROUP_BROADCAST).setParameterLength(2),VN=H(bN,bN.SUBGROUP_SHUFFLE).setParameterLength(2),HN=H(bN,bN.SUBGROUP_SHUFFLE_XOR).setParameterLength(2),UN=H(bN,bN.SUBGROUP_SHUFFLE_UP).setParameterLength(2),WN=H(bN,bN.SUBGROUP_SHUFFLE_DOWN).setParameterLength(2),GN=H(bN,bN.QUAD_BROADCAST).setParameterLength(1),qN=e=>Ax.transformDirection(Cm(e).sub(wm(e))),JN=jg(`vec3`,`totalDiffuse`),YN=jg(`vec3`,`totalSpecular`),XN=jg(`vec3`,`outgoingLight`),ZN=e=>e.sort((e,t)=>e.id-t.id),QN=(e,t)=>{for(let n of t)if(n.isAnalyticLightNode&&n.light.id===e)return n;return null},$N=new WeakMap,eP=[],tP=class extends dh{static get type(){return`LightsNode`}constructor(){super(`vec3`),this.totalDiffuseNode=JN,this.totalSpecularNode=YN,this.outgoingLightNode=XN,this._lights=[],this.global=!0}customCacheKey(){let e=this.getBuiltinLights();for(let t=0;t0}},nP=(e=[])=>new tP().setLights(e),rP=new WeakMap,iP=new UO,aP=[],oP=e=>{let t=rP.get(e);return t===void 0&&(t=new VT,t.colorNode=bg(0,0,0,1),t.isShadowPassMaterial=!0,t.name=`ShadowMaterial`,t.blending=0,t.fog=!1,rP.set(e,t)),t},sP=e=>{let t=rP.get(e);t!==void 0&&(t.dispose(),rP.delete(e))},cP=(e,t,n,r)=>{aP[0]=e,aP[1]=t;let i=iP.get(aP);return(i===void 0||i.shadowType!==n||i.useVelocity!==r)&&(i=(i,a,o,s,c,l,u,d,f)=>{(i.castShadow===!0||i.receiveShadow&&n===3)&&(r&&(np(i).useVelocity=!0),i.onBeforeShadow(e,i,o,t.camera,s,a.overrideMaterial,l),e.renderObject(i,a,o,s,c,l,u,d,f),i.onAfterShadow(e,i,o,t.camera,s,a.overrideMaterial,l))},i.shadowType=n,i.useVelocity=r,iP.set(aP,i)),aP[0]=null,aP[1]=null,i},lP=class extends dh{static get type(){return`ShadowBaseNode`}constructor(e){super(),this.light=e,this.updateBeforeType=nh.RENDER,this.isShadowBaseNode=!0}getShadowMaterial(){return oP(this.light)}disposeShadowMaterial(){sP(this.light)}getShadowRenderObjectFunction(e,t=this.light.shadow){let n=e.shadowMap.type,r=e.getMRT(),i=r?r.has(`velocity`):!1;return cP(e,t,n,i)}setupShadowPosition({context:e,material:t}){uP.assign(t.receivedShadowPositionNode||e.shadowPositionWorld||sS)}},uP=jg(`vec3`,`shadowPositionWorld`),dP=V(({depthTexture:e,shadowCoord:t,depthLayer:n})=>{let r=Vb(e,t.xy).setName(`t_basic`);return e.isArrayTexture&&(r=r.depth(n)),r.compare(t.z)}),fP=V(({depthTexture:e,shadowCoord:t,shadow:n,depthLayer:r})=>{let i=(t,n)=>{let i=Vb(e,t);return e.isArrayTexture&&(i=i.depth(r)),i.compare(n)},a=US(`mapSize`,`vec2`,n).setGroup(h_),o=US(`radius`,`float`,n).setGroup(h_),s=pg(1).div(a),c=o.mul(s.x),l=xj(ox.xy).mul(6.28318530718);return D_(i(t.xy.add(Sj(0,5,l).mul(c)),t.z),i(t.xy.add(Sj(1,5,l).mul(c)),t.z),i(t.xy.add(Sj(2,5,l).mul(c)),t.z),i(t.xy.add(Sj(3,5,l).mul(c)),t.z),i(t.xy.add(Sj(4,5,l).mul(c)),t.z)).mul(1/5)}),pP=V(({depthTexture:e,shadowCoord:t,depthLayer:n},r)=>{let i=Vb(e).sample(t.xy);e.isArrayTexture&&(i=i.depth(n)),i=i.rg;let a=i.x,o=Gv(1e-7,i.y.mul(i.y)),s=r.renderer.reversedDepthBuffer?Kv(a,t.z):Kv(t.z,a),c=U(1).toVar();return lg(s.notEqual(1),()=>{let e=t.z.sub(a),n=o.div(o.add(e.mul(e)));n=cy(O_(n,.3).div(.65)),c.assign(Gv(s,n))}),c}),mP=V(({samples:e,radius:t,size:n,shadowPass:r,depthLayer:i})=>{let a=U(0).toVar(`meanVertical`),o=U(0).toVar(`squareMeanVertical`),s=e.lessThanEqual(U(1)).select(U(0),U(2).div(e.sub(1))),c=e.lessThanEqual(U(1)).select(U(0),U(-1));Xw({start:W(0),end:W(e),type:`int`,condition:`<`},({i:e})=>{let l=c.add(U(e).mul(s)),u=r.sample(D_(ox.xy,pg(0,l).mul(t)).div(n));r.value.isArrayTexture&&(u=u.depth(i)),u=u.x,a.addAssign(u),o.addAssign(u.mul(u))}),a.divAssign(e),o.divAssign(e);let l=fv(o.sub(a.mul(a)).max(0));return pg(a,l)}),hP=V(({samples:e,radius:t,size:n,shadowPass:r,depthLayer:i})=>{let a=U(0).toVar(`meanHorizontal`),o=U(0).toVar(`squareMeanHorizontal`),s=e.lessThanEqual(U(1)).select(U(0),U(2).div(e.sub(1))),c=e.lessThanEqual(U(1)).select(U(0),U(-1));Xw({start:W(0),end:W(e),type:`int`,condition:`<`},({i:e})=>{let l=c.add(U(e).mul(s)),u=r.sample(D_(ox.xy,pg(l,0).mul(t)).div(n));r.value.isArrayTexture&&(u=u.depth(i)),a.addAssign(u.x),o.addAssign(D_(u.y.mul(u.y),u.x.mul(u.x)))}),a.divAssign(e),o.divAssign(e);let l=fv(o.sub(a.mul(a)).max(0));return pg(a,l)}),gP=[dP,fP,null,pP],vP=new dj,yP=class extends lP{static get type(){return`ShadowNode`}constructor(e,t=null){super(e),this.shadow=t||e.shadow,this.shadowMap=null,this.vsmShadowMapVertical=null,this.vsmShadowMapHorizontal=null,this.vsmMaterialVertical=null,this.vsmMaterialHorizontal=null,this._node=null,this._currentShadowType=null,this._cameraFrameId=new WeakMap,this.isShadowNode=!0,this.depthLayer=0}setupShadowFilter(e,{filterFn:t,depthTexture:n,shadowCoord:r,shadow:i,depthLayer:a}){let o=r.x.greaterThanEqual(0).and(r.x.lessThanEqual(1)).and(r.y.greaterThanEqual(0)).and(r.y.lessThanEqual(1)).and(r.z.lessThanEqual(1)),s=t({depthTexture:n,shadowCoord:r,shadow:i,depthLayer:a});return o.select(s,U(1))}setupShadowCoord(e,t){let{shadow:n}=this,{renderer:r}=e,i=n.biasNode||US(`bias`,`float`,n).setGroup(h_),a=t,o;if(n.camera.isOrthographicCamera||r.logarithmicDepthBuffer!==!0)a=a.xyz.div(a.w),o=a.z;else{let e=a.w;a=a.xy.div(e);let t=US(`near`,`float`,n.camera).setGroup(h_),r=US(`far`,`float`,n.camera).setGroup(h_);o=TT(e.negate(),t,r)}return a=K(a.x,a.y.oneMinus(),r.reversedDepthBuffer?o.sub(i):o.add(i)),a}getShadowFilterFn(e){return gP[e]}setupRenderTarget(e,t){let n=new Ac(e.mapSize.width,e.mapSize.height);n.name=`ShadowDepthTexture`,n.compareFunction=t.renderer.reversedDepthBuffer?518:515;let r=t.createRenderTarget(e.mapSize.width,e.mapSize.height);return r.texture.name=`ShadowMap`,r.texture.type=e.mapType,r.depthTexture=n,{shadowMap:r,depthTexture:n}}setupShadow(e){let{renderer:t,camera:n}=e,{light:r,shadow:i}=this,{depthTexture:a,shadowMap:o}=this.setupRenderTarget(i,e),s=t.shadowMap.type,c=t.hasCompatibility(ii.TEXTURE_COMPARE);if(s===1&&c?(a.minFilter=an,a.magFilter=an):(a.minFilter=$t,a.magFilter=$t),i.camera.coordinateSystem=n.coordinateSystem,i.camera.updateProjectionMatrix(),s===3&&i.isPointLightShadow!==!0){a.compareFunction=null,o.depth>1?(o._vsmShadowMapVertical||(o._vsmShadowMapVertical=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:An,type:_n,depth:o.depth,depthBuffer:!1}),o._vsmShadowMapVertical.texture.name=`VSMVertical`),this.vsmShadowMapVertical=o._vsmShadowMapVertical,o._vsmShadowMapHorizontal||(o._vsmShadowMapHorizontal=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:An,type:_n,depth:o.depth,depthBuffer:!1}),o._vsmShadowMapHorizontal.texture.name=`VSMHorizontal`),this.vsmShadowMapHorizontal=o._vsmShadowMapHorizontal):(this.vsmShadowMapVertical=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:An,type:_n,depthBuffer:!1}),this.vsmShadowMapHorizontal=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:An,type:_n,depthBuffer:!1}));let t=Vb(a);a.isArrayTexture&&(t=t.depth(this.depthLayer));let n=Vb(this.vsmShadowMapVertical.texture);a.isArrayTexture&&(n=n.depth(this.depthLayer));let r=US(`blurSamples`,`float`,i).setGroup(h_),s=US(`radius`,`float`,i).setGroup(h_),c=US(`mapSize`,`vec2`,i).setGroup(h_),l=Sy(e.getSharedContext()),u=this.vsmMaterialVertical||=new VT;u.contextNode=l,u.fragmentNode=mP({samples:r,radius:s,size:c,shadowPass:t,depthLayer:this.depthLayer}),u.name=`VSMVertical`,u=this.vsmMaterialHorizontal||=new VT,u.contextNode=l,u.fragmentNode=hP({samples:r,radius:s,size:c,shadowPass:n,depthLayer:this.depthLayer}),u.name=`VSMHorizontal`}let l=US(`intensity`,`float`,i).setGroup(h_),u=US(`normalBias`,`float`,i).setGroup(h_),d=xm(r),f=SS.mul(u),p;p=!t.highPrecision||e.material.receivedShadowPositionNode||e.context.shadowPositionWorld?d.mul(uP.add(f)):v_(`mat4`).onObjectUpdate(({object:e},t)=>t.value.multiplyMatrices(d.value,e.matrixWorld)).mul(aS).add(d.mul(bg(f,0)));let m=this.setupShadowCoord(e,p),h=i.filterNode||this.getShadowFilterFn(t.shadowMap.type)||null;if(h===null)throw Error(`THREE.WebGPURenderer: Shadow map type not supported yet.`);let g=s===3&&i.isPointLightShadow!==!0?this.vsmShadowMapHorizontal.texture:a,_=this.setupShadowFilter(e,{filterFn:h,shadowTexture:o.texture,depthTexture:g,shadowCoord:m,shadow:i,depthLayer:this.depthLayer}),v;t.shadowMap.transmitted===!0&&(o.texture.isCubeTexture?v=BS(o.texture,m.xyz):(v=Vb(o.texture,m),a.isArrayTexture&&(v=v.depth(this.depthLayer))));let y;y=v?sy(1,_.rgb.mix(v,1),l.mul(v.a)).toVar():sy(1,_,l).toVar(),this.shadowMap=o,this.shadow.map=o;let b=`${this.light.type} Shadow [ ${this.light.name||`ID: `+this.light.id} ]`;return v&&y.toInspector(`${b} / Color`,()=>this.shadowMap.texture.isCubeTexture?BS(this.shadowMap.texture,aE()):Vb(this.shadowMap.texture)),y.toInspector(`${b} / Depth`,()=>{let e=US(`near`,`float`,this.shadow.camera),t=US(`far`,`float`,this.shadow.camera),n;n=this.shadowMap.texture.isCubeTexture?BS(this.shadowMap.depthTexture,aE()).r:Vb(this.shadowMap.depthTexture).r;let r;return r=this.shadow.camera.isPerspectiveCamera?wT(n,e,t):xT(n,e,t),r=yT(r,e,t),r.oneMinus()})}setup(e){if(e.renderer.shadowMap.enabled!==!1)return V(()=>{let t=e.renderer.shadowMap.type;this._currentShadowType!==t&&(this._reset(),this._node=null);let n=this._node;return this.setupShadowPosition(e),n===null&&(this._node=n=this.setupShadow(e),this._currentShadowType=t),e.material.receivedShadowNode&&(n=e.material.receivedShadowNode(n)),n})()}renderShadow(e){let{shadow:t,shadowMap:n,light:r}=this,{renderer:i,scene:a}=e;t.updateMatrices(r),n.setSize(t.mapSize.width,t.mapSize.height,n.depth);let o=a.name;a.name=`Shadow Map [ ${r.name||`ID: `+r.id} ]`,i.render(a,t.camera),a.name=o}updateShadow(e){let{shadowMap:t,shadow:n}=this,{renderer:r,scene:i,camera:a}=e,o=r.shadowMap.type,s=t.depthTexture.version;this._depthVersionCached=s;let c=n.camera.layers.mask;n.camera.layers.mask&4294967294||(n.camera.layers.mask=a.layers.mask);let l=r.getRenderObjectFunction();_P=hm(r,i,_P),i.overrideMaterial=this.getShadowMaterial(),r.setRenderObjectFunction(this.getShadowRenderObjectFunction(r,this.shadow||this.light.shadow)),r.setClearColor(0,0),r.setRenderTarget(t),this.renderShadow(e),r.setRenderObjectFunction(l),o===3&&n.isPointLightShadow!==!0&&this.vsmPass(r),n.camera.layers.mask=c,gm(r,i,_P)}vsmPass(e){let{shadow:t}=this,n=this.shadowMap.depth;this.vsmShadowMapVertical.setSize(t.mapSize.width,t.mapSize.height,n),this.vsmShadowMapHorizontal.setSize(t.mapSize.width,t.mapSize.height,n),e.setRenderTarget(this.vsmShadowMapVertical),vP.material=this.vsmMaterialVertical,vP.render(e),e.setRenderTarget(this.vsmShadowMapHorizontal),vP.material=this.vsmMaterialHorizontal,vP.render(e)}dispose(){this._reset(),super.dispose()}_reset(){this._currentShadowType=null,this.disposeShadowMaterial(),this.shadowMap&&=(this.shadowMap.dispose(),null),this.vsmShadowMapVertical!==null&&(this.vsmShadowMapVertical.dispose(),this.vsmShadowMapVertical=null,this.vsmMaterialVertical.dispose(),this.vsmMaterialVertical=null),this.vsmShadowMapHorizontal!==null&&(this.vsmShadowMapHorizontal.dispose(),this.vsmShadowMapHorizontal=null,this.vsmMaterialHorizontal.dispose(),this.vsmMaterialHorizontal=null)}updateBefore(e){if(e.renderer._isPreCompiling===!0)return;let{shadow:t}=this,n=t.needsUpdate||t.autoUpdate;n&&(this._cameraFrameId.get(e.camera)===e.frameId&&(n=!1),this._cameraFrameId.set(e.camera,e.frameId)),n&&(this.updateShadow(e),this.shadowMap.depthTexture.version===this._depthVersionCached&&(t.needsUpdate=!1))}},bP=(e,t)=>new yP(e,t),xP=new L,SP=new F,CP=new P,wP=new P,TP=[new P(1,0,0),new P(-1,0,0),new P(0,-1,0),new P(0,1,0),new P(0,0,1),new P(0,0,-1)],EP=[new P(0,-1,0),new P(0,-1,0),new P(0,0,-1),new P(0,0,1),new P(0,-1,0),new P(0,-1,0)],DP=[new P(1,0,0),new P(-1,0,0),new P(0,1,0),new P(0,-1,0),new P(0,0,1),new P(0,0,-1)],OP=[new P(0,-1,0),new P(0,-1,0),new P(0,0,1),new P(0,0,-1),new P(0,-1,0),new P(0,-1,0)],kP=V(({depthTexture:e,bd3D:t,dp:n})=>BS(e,t).compare(n)),AP=V(({depthTexture:e,bd3D:t,dp:n,shadow:r})=>{let i=US(`radius`,`float`,r).setGroup(h_),a=US(`mapSize`,`vec2`,r).setGroup(h_),o=i.div(a.x),s=Av(t),c=gv(Zv(t,s.x.greaterThan(s.z).select(K(0,1,0),K(1,0,0)))),l=Zv(t,c),u=xj(ox.xy).mul(6.28318530718),d=Sj(0,5,u),f=Sj(1,5,u),p=Sj(2,5,u),m=Sj(3,5,u),h=Sj(4,5,u);return BS(e,t.add(c.mul(d.x).add(l.mul(d.y)).mul(o))).compare(n).add(BS(e,t.add(c.mul(f.x).add(l.mul(f.y)).mul(o))).compare(n)).add(BS(e,t.add(c.mul(p.x).add(l.mul(p.y)).mul(o))).compare(n)).add(BS(e,t.add(c.mul(m.x).add(l.mul(m.y)).mul(o))).compare(n)).add(BS(e,t.add(c.mul(h.x).add(l.mul(h.y)).mul(o))).compare(n)).mul(1/5)}),jP=V(({filterFn:e,depthTexture:t,shadowCoord:n,shadow:r},i)=>{let a=n.xyz.toConst(),o=a.abs().toConst(),s=o.x.max(o.y).max(o.z),c=v_(`float`).setGroup(h_).onRenderUpdate(()=>r.camera.near),l=v_(`float`).setGroup(h_).onRenderUpdate(()=>r.camera.far),u=US(`bias`,`float`,r).setGroup(h_),d=U(1).toVar();return lg(s.sub(l).lessThanEqual(0).and(s.sub(c).greaterThanEqual(0)),()=>{let n;i.renderer.reversedDepthBuffer?(n=CT(s.negate(),c,l),n.subAssign(u)):i.renderer.logarithmicDepthBuffer?(n=TT(s.negate(),c,l),n.addAssign(u)):(n=ST(s.negate(),c,l),n.addAssign(u));let o=a.normalize();d.assign(e({depthTexture:t,bd3D:o,dp:n,shadow:r}))}),d}),MP=class extends yP{static get type(){return`PointShadowNode`}constructor(e,t=null){super(e,t)}getShadowFilterFn(e){return e===0?kP:AP}setupShadowCoord(e,t){return t}setupShadowFilter(e,{filterFn:t,depthTexture:n,shadowCoord:r,shadow:i}){return jP({filterFn:t,depthTexture:n,shadowCoord:r,shadow:i})}setupRenderTarget(e,t){let n=new jc(e.mapSize.width);n.name=`PointShadowDepthTexture`,n.compareFunction=t.renderer.reversedDepthBuffer?518:515;let r=t.createCubeRenderTarget(e.mapSize.width);return r.texture.name=`PointShadowMap`,r.depthTexture=n,{shadowMap:r,depthTexture:n}}renderShadow(e){let{shadow:t,shadowMap:n,light:r}=this,{renderer:i,scene:a}=e,o=t.camera,s=t.matrix,c=i.coordinateSystem===ei,l=c?TP:DP,u=c?EP:OP;n.setSize(t.mapSize.width,t.mapSize.width);let d=i.autoClear,f=i.getClearColor(xP),p=i.getClearAlpha();i.autoClear=!1,i.setClearColor(t.clearColor,t.clearAlpha);for(let e=0;e<6;e++){i.setRenderTarget(n,e),i.clear();let c=r.distance||o.far;c!==o.far&&(o.far=c,o.updateProjectionMatrix()),CP.setFromMatrixPosition(r.matrixWorld),o.position.copy(CP),wP.copy(o.position),wP.add(l[e]),o.up.copy(u[e]),o.lookAt(wP),o.updateMatrixWorld(),s.makeTranslation(-CP.x,-CP.y,-CP.z),SP.multiplyMatrices(o.projectionMatrix,o.matrixWorldInverse),t._frustum.setFromProjectionMatrix(SP,o.coordinateSystem,o.reversedDepth);let d=a.name;a.name=`Point Light Shadow [ ${r.name||`ID: `+r.id} ] - Face ${e+1}`,i.render(a,o),a.name=d}i.autoClear=d,i.setClearColor(f,p)}},NP=(e,t)=>new MP(e,t),PP=class extends iT{static get type(){return`AnalyticLightNode`}constructor(e=null){super(),this.light=e,this.color=new L,this.colorNode=e&&e.colorNode||v_(this.color).setGroup(h_),this.baseColorNode=null,this.shadowNode=null,this.shadowColorNode=null,this.isAnalyticLightNode=!0,this.updateType=nh.FRAME,e&&e.shadow&&(this._shadowDisposeListener=()=>{this.disposeShadow()},e.addEventListener(`dispose`,this._shadowDisposeListener))}dispose(){this._shadowDisposeListener&&this.light.removeEventListener(`dispose`,this._shadowDisposeListener),super.dispose()}disposeShadow(){this.shadowNode!==null&&(this.shadowNode.dispose(),this.shadowNode=null),this.shadowColorNode=null,this.baseColorNode!==null&&(this.colorNode=this.baseColorNode,this.baseColorNode=null)}getHash(){return this.light.uuid}getLightVector(e){return Tm(this.light).sub(e.context.positionView||lS)}setupDirect(){}setupDirectRectArea(){}setupShadowNode(){return bP(this.light)}setupShadow(e){let{renderer:t}=e;if(t.shadowMap.enabled===!1)return;let n=this.shadowColorNode;if(n===null){let e=this.light.shadow.shadowNode,t;t=e===void 0?this.setupShadowNode():Qh(e),this.shadowNode=t,this.shadowColorNode=n=this.colorNode.mul(t),this.baseColorNode=this.colorNode}e.context.getShadow&&(n=e.context.getShadow(this,e)),this.colorNode=n}setup(e){this.colorNode=this.baseColorNode||this.colorNode,this.light.castShadow?e.object.receiveShadow&&this.setupShadow(e):this.shadowNode!==null&&(this.shadowNode.dispose(),this.shadowNode=null,this.shadowColorNode=null);let t=this.setupDirect(e),n=this.setupDirectRectArea(e);t&&e.lightsNode.setupDirectLight(e,this,t),n&&e.lightsNode.setupDirectRectAreaLight(e,this,n)}update(){let{light:e}=this;this.color.copy(e.color).multiplyScalar(e.intensity)}},FP=V(({lightDistance:e,cutoffDistance:t,decayExponent:n})=>{let r=e.pow(n).max(.01).reciprocal();return t.greaterThan(0).select(r.mul(e.div(t).pow4().oneMinus().clamp().pow2()),r)}),IP=({color:e,lightVector:t,cutoffDistance:n,decayExponent:r})=>{let i=t.normalize(),a=t.length(),o=FP({lightDistance:a,cutoffDistance:n,decayExponent:r});return{lightDirection:i,lightColor:e.mul(o)}},LP=class extends PP{static get type(){return`PointLightNode`}constructor(e=null){super(e),this.cutoffDistanceNode=v_(0).setGroup(h_),this.decayExponentNode=v_(2).setGroup(h_)}update(e){let{light:t}=this;super.update(e),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}setupShadowNode(){return NP(this.light)}setupDirect(e){return IP({color:this.colorNode,lightVector:this.getLightVector(e),cutoffDistance:this.cutoffDistanceNode,decayExponent:this.decayExponentNode})}},RP=V(([e=Mb()])=>{let t=e.mul(2),n=t.x.floor(),r=t.y.floor();return n.add(r).mod(2).sign()}),zP=V(([e=Mb()],{renderer:t,material:n})=>{let r=oy(e.mul(2).sub(1)),i;if(n.alphaToCoverage&&t.currentSamples>0){let e=U(r.fwidth()).toVar();i=dy(e.oneMinus(),e.add(1),r).oneMinus()}else i=by(r.greaterThan(1),0,1);return i}),BP=(e,t=0)=>{e=pg(e),t=U(t);let n=k_(t,Math.PI/180),r=vv(n),i=bv(n),a=e.x,o=e.y;return pg(D_(k_(i,a),k_(r,o)),O_(k_(i,o),k_(r,a)))},VP=(e,t=0,n=K(0,1,0))=>{e=K(e),t=U(t),n=K(n);let r=gv(n),i=k_(t,Math.PI/180),a=vv(i),o=bv(i),s=O_(1,o);return e.mul(o).add(e.cross(r).mul(a)).add(r.mul(r.dot(e).mul(s)))},HP=V(([e,t,n])=>{let r=U(n).toVar(),i=U(t).toVar(),a=fg(e).toVar();return by(a,i,r).uniformFlow()}).setLayout({name:`mx_select`,type:`float`,inputs:[{name:`b`,type:`bool`},{name:`t`,type:`float`},{name:`f`,type:`float`}]}),UP=V(([e,t])=>{let n=fg(t).toVar(),r=U(e).toVar();return by(n,r.negate(),r).uniformFlow()}).setLayout({name:`mx_negate_if`,type:`float`,inputs:[{name:`val`,type:`float`},{name:`b`,type:`bool`}]}),WP=V(([e])=>{let t=U(e).toVar();return W(mv(t))}).setLayout({name:`mx_floor`,type:`int`,inputs:[{name:`x`,type:`float`}]}),GP=V(([e,t])=>{let n=U(e).toVar();return t.assign(WP(n)),n.sub(U(t))}),KP=(e,t,n,r,i,a)=>{let o=U(O_(1,i)).toVar();return O_(1,a).mul(e.mul(o).add(t.mul(i))).add(a.mul(n.mul(o).add(r.mul(i))))},qP=(e,t,n,r,i,a,o,s,c,l,u)=>{let d=U(O_(1,c)).toVar(),f=U(O_(1,l)).toVar();return U(O_(1,u)).toVar().mul(f.mul(e.mul(d).add(t.mul(c))).add(l.mul(n.mul(d).add(r.mul(c))))).add(u.mul(f.mul(i.mul(d).add(a.mul(c))).add(l.mul(o.mul(d).add(s.mul(c))))))},JP=kA([V(([e,t,n,r,i,a])=>{let o=U(a).toVar(),s=U(i).toVar(),c=U(r).toVar(),l=U(n).toVar(),u=U(t).toVar(),d=U(e).toVar();return KP(d,u,l,c,s,o)}).setLayout({name:`mx_bilerp_0`,type:`float`,inputs:[{name:`v0`,type:`float`},{name:`v1`,type:`float`},{name:`v2`,type:`float`},{name:`v3`,type:`float`},{name:`s`,type:`float`},{name:`t`,type:`float`}]}),V(([e,t,n,r,i,a])=>{let o=U(a).toVar(),s=U(i).toVar(),c=K(r).toVar(),l=K(n).toVar(),u=K(t).toVar(),d=K(e).toVar();return KP(d,u,l,c,s,o)}).setLayout({name:`mx_bilerp_1`,type:`vec3`,inputs:[{name:`v0`,type:`vec3`},{name:`v1`,type:`vec3`},{name:`v2`,type:`vec3`},{name:`v3`,type:`vec3`},{name:`s`,type:`float`},{name:`t`,type:`float`}]})]),YP=kA([V(([e,t,n,r,i,a,o,s,c,l,u])=>{let d=U(u).toVar(),f=U(l).toVar(),p=U(c).toVar(),m=U(s).toVar(),h=U(o).toVar(),g=U(a).toVar(),_=U(i).toVar(),v=U(r).toVar(),y=U(n).toVar(),b=U(t).toVar(),x=U(e).toVar();return qP(x,b,y,v,_,g,h,m,p,f,d)}).setLayout({name:`mx_trilerp_0`,type:`float`,inputs:[{name:`v0`,type:`float`},{name:`v1`,type:`float`},{name:`v2`,type:`float`},{name:`v3`,type:`float`},{name:`v4`,type:`float`},{name:`v5`,type:`float`},{name:`v6`,type:`float`},{name:`v7`,type:`float`},{name:`s`,type:`float`},{name:`t`,type:`float`},{name:`r`,type:`float`}]}),V(([e,t,n,r,i,a,o,s,c,l,u])=>{let d=U(u).toVar(),f=U(l).toVar(),p=U(c).toVar(),m=K(s).toVar(),h=K(o).toVar(),g=K(a).toVar(),_=K(i).toVar(),v=K(r).toVar(),y=K(n).toVar(),b=K(t).toVar(),x=K(e).toVar();return qP(x,b,y,v,_,g,h,m,p,f,d)}).setLayout({name:`mx_trilerp_1`,type:`vec3`,inputs:[{name:`v0`,type:`vec3`},{name:`v1`,type:`vec3`},{name:`v2`,type:`vec3`},{name:`v3`,type:`vec3`},{name:`v4`,type:`vec3`},{name:`v5`,type:`vec3`},{name:`v6`,type:`vec3`},{name:`v7`,type:`vec3`},{name:`s`,type:`float`},{name:`t`,type:`float`},{name:`r`,type:`float`}]})]),XP=kA([V(([e,t,n])=>{let r=U(n).toVar(),i=U(t).toVar(),a=G(e).toVar(),o=G(a.bitAnd(G(7))).toVar(),s=U(HP(o.lessThan(G(4)),i,r)).toVar(),c=U(k_(2,HP(o.lessThan(G(4)),r,i))).toVar();return UP(s,fg(o.bitAnd(G(1)))).add(UP(c,fg(o.bitAnd(G(2)))))}).setLayout({name:`mx_gradient_float_0`,type:`float`,inputs:[{name:`hash`,type:`uint`},{name:`x`,type:`float`},{name:`y`,type:`float`}]}),V(([e,t,n,r])=>{let i=U(r).toVar(),a=U(n).toVar(),o=U(t).toVar(),s=G(e).toVar(),c=G(s.bitAnd(G(15))).toVar(),l=U(HP(c.lessThan(G(8)),o,a)).toVar(),u=U(HP(c.lessThan(G(4)),a,HP(c.equal(G(12)).or(c.equal(G(14))),o,i))).toVar();return UP(l,fg(c.bitAnd(G(1)))).add(UP(u,fg(c.bitAnd(G(2)))))}).setLayout({name:`mx_gradient_float_1`,type:`float`,inputs:[{name:`hash`,type:`uint`},{name:`x`,type:`float`},{name:`y`,type:`float`},{name:`z`,type:`float`}]})]),ZP=kA([V(([e,t,n])=>{let r=U(n).toVar(),i=U(t).toVar(),a=vg(e).toVar();return K(XP(a.x,i,r),XP(a.y,i,r),XP(a.z,i,r))}).setLayout({name:`mx_gradient_vec3_0`,type:`vec3`,inputs:[{name:`hash`,type:`uvec3`},{name:`x`,type:`float`},{name:`y`,type:`float`}]}),V(([e,t,n,r])=>{let i=U(r).toVar(),a=U(n).toVar(),o=U(t).toVar(),s=vg(e).toVar();return K(XP(s.x,o,a,i),XP(s.y,o,a,i),XP(s.z,o,a,i))}).setLayout({name:`mx_gradient_vec3_1`,type:`vec3`,inputs:[{name:`hash`,type:`uvec3`},{name:`x`,type:`float`},{name:`y`,type:`float`},{name:`z`,type:`float`}]})]),QP=V(([e])=>{let t=U(e).toVar();return k_(.6616,t)}).setLayout({name:`mx_gradient_scale2d_0`,type:`float`,inputs:[{name:`v`,type:`float`}]}),$P=V(([e])=>{let t=U(e).toVar();return k_(.982,t)}).setLayout({name:`mx_gradient_scale3d_0`,type:`float`,inputs:[{name:`v`,type:`float`}]}),eF=kA([QP,V(([e])=>{let t=K(e).toVar();return k_(.6616,t)}).setLayout({name:`mx_gradient_scale2d_1`,type:`vec3`,inputs:[{name:`v`,type:`vec3`}]})]),tF=kA([$P,V(([e])=>{let t=K(e).toVar();return k_(.982,t)}).setLayout({name:`mx_gradient_scale3d_1`,type:`vec3`,inputs:[{name:`v`,type:`vec3`}]})]),nF=V(([e,t])=>{let n=W(t).toVar(),r=G(e).toVar();return r.shiftLeft(n).bitOr(r.shiftRight(W(32).sub(n)))}).setLayout({name:`mx_rotl32`,type:`uint`,inputs:[{name:`x`,type:`uint`},{name:`k`,type:`int`}]}),rF=V(([e,t,n])=>(e=G(e).toVar(),t=G(t).toVar(),n=G(n).toVar(),e.subAssign(n),e.bitXorAssign(nF(n,W(4))),n.addAssign(t),t.subAssign(e),t.bitXorAssign(nF(e,W(6))),e.addAssign(n),n.subAssign(t),n.bitXorAssign(nF(t,W(8))),t.addAssign(e),e.subAssign(n),e.bitXorAssign(nF(n,W(16))),n.addAssign(t),t.subAssign(e),t.bitXorAssign(nF(e,W(19))),e.addAssign(n),n.subAssign(t),n.bitXorAssign(nF(t,W(4))),t.addAssign(e),vg(e,t,n))).setLayout({name:`mx_bjmix`,type:`uvec3`,inputs:[{name:`a`,type:`uint`},{name:`b`,type:`uint`},{name:`c`,type:`uint`}]}),iF=V(([e,t,n])=>{let r=G(n).toVar(),i=G(t).toVar(),a=G(e).toVar();return r.bitXorAssign(i),r.subAssign(nF(i,W(14))),a.bitXorAssign(r),a.subAssign(nF(r,W(11))),i.bitXorAssign(a),i.subAssign(nF(a,W(25))),r.bitXorAssign(i),r.subAssign(nF(i,W(16))),a.bitXorAssign(r),a.subAssign(nF(r,W(4))),i.bitXorAssign(a),i.subAssign(nF(a,W(14))),r.bitXorAssign(i),r.subAssign(nF(i,W(24))),r}).setLayout({name:`mx_bjfinal`,type:`uint`,inputs:[{name:`a`,type:`uint`},{name:`b`,type:`uint`},{name:`c`,type:`uint`}]}),aF=V(([e])=>{let t=G(e).toVar();return U(t).div(U(G(4294967295)))}).setLayout({name:`mx_bits_to_01`,type:`float`,inputs:[{name:`bits`,type:`uint`}]}),oF=V(([e])=>{let t=U(e).toVar();return t.mul(t).mul(t).mul(t.mul(t.mul(6).sub(15)).add(10))}).setLayout({name:`mx_fade`,type:`float`,inputs:[{name:`t`,type:`float`}]}),sF=kA([V(([e])=>{let t=W(e).toVar(),n=G(G(1)).toVar(),r=G(G(3735928559).add(n.shiftLeft(G(2))).add(G(13))).toVar();return iF(r.add(G(t)),r,r)}).setLayout({name:`mx_hash_int_0`,type:`uint`,inputs:[{name:`x`,type:`int`}]}),V(([e,t])=>{let n=W(t).toVar(),r=W(e).toVar(),i=G(G(2)).toVar(),a=G().toVar(),o=G().toVar(),s=G().toVar();return a.assign(o.assign(s.assign(G(3735928559).add(i.shiftLeft(G(2))).add(G(13))))),a.addAssign(G(r)),o.addAssign(G(n)),iF(a,o,s)}).setLayout({name:`mx_hash_int_1`,type:`uint`,inputs:[{name:`x`,type:`int`},{name:`y`,type:`int`}]}),V(([e,t,n])=>{let r=W(n).toVar(),i=W(t).toVar(),a=W(e).toVar(),o=G(G(3)).toVar(),s=G().toVar(),c=G().toVar(),l=G().toVar();return s.assign(c.assign(l.assign(G(3735928559).add(o.shiftLeft(G(2))).add(G(13))))),s.addAssign(G(a)),c.addAssign(G(i)),l.addAssign(G(r)),iF(s,c,l)}).setLayout({name:`mx_hash_int_2`,type:`uint`,inputs:[{name:`x`,type:`int`},{name:`y`,type:`int`},{name:`z`,type:`int`}]}),V(([e,t,n,r])=>{let i=W(r).toVar(),a=W(n).toVar(),o=W(t).toVar(),s=W(e).toVar(),c=G(G(4)).toVar(),l=G().toVar(),u=G().toVar(),d=G().toVar();l.assign(u.assign(d.assign(G(3735928559).add(c.shiftLeft(G(2))).add(G(13))))),l.addAssign(G(s)),u.addAssign(G(o)),d.addAssign(G(a));let f=vg(rF(l,u,d)).toVar();return l.assign(f.x),u.assign(f.y),d.assign(f.z),l.addAssign(G(i)),iF(l,u,d)}).setLayout({name:`mx_hash_int_3`,type:`uint`,inputs:[{name:`x`,type:`int`},{name:`y`,type:`int`},{name:`z`,type:`int`},{name:`xx`,type:`int`}]}),V(([e,t,n,r,i])=>{let a=W(i).toVar(),o=W(r).toVar(),s=W(n).toVar(),c=W(t).toVar(),l=W(e).toVar(),u=G(G(5)).toVar(),d=G().toVar(),f=G().toVar(),p=G().toVar();d.assign(f.assign(p.assign(G(3735928559).add(u.shiftLeft(G(2))).add(G(13))))),d.addAssign(G(l)),f.addAssign(G(c)),p.addAssign(G(s));let m=vg(rF(d,f,p)).toVar();return d.assign(m.x),f.assign(m.y),p.assign(m.z),d.addAssign(G(o)),f.addAssign(G(a)),iF(d,f,p)}).setLayout({name:`mx_hash_int_4`,type:`uint`,inputs:[{name:`x`,type:`int`},{name:`y`,type:`int`},{name:`z`,type:`int`},{name:`xx`,type:`int`},{name:`yy`,type:`int`}]})]),cF=kA([V(([e,t])=>{let n=W(t).toVar(),r=W(e).toVar(),i=G(sF(r,n)).toVar(),a=vg().toVar();return a.x.assign(i.bitAnd(W(255))),a.y.assign(i.shiftRight(W(8)).bitAnd(W(255))),a.z.assign(i.shiftRight(W(16)).bitAnd(W(255))),a}).setLayout({name:`mx_hash_vec3_0`,type:`uvec3`,inputs:[{name:`x`,type:`int`},{name:`y`,type:`int`}]}),V(([e,t,n])=>{let r=W(n).toVar(),i=W(t).toVar(),a=W(e).toVar(),o=G(sF(a,i,r)).toVar(),s=vg().toVar();return s.x.assign(o.bitAnd(W(255))),s.y.assign(o.shiftRight(W(8)).bitAnd(W(255))),s.z.assign(o.shiftRight(W(16)).bitAnd(W(255))),s}).setLayout({name:`mx_hash_vec3_1`,type:`uvec3`,inputs:[{name:`x`,type:`int`},{name:`y`,type:`int`},{name:`z`,type:`int`}]})]),lF=kA([V(([e])=>{let t=pg(e).toVar(),n=W().toVar(),r=W().toVar(),i=U(GP(t.x,n)).toVar(),a=U(GP(t.y,r)).toVar(),o=U(oF(i)).toVar(),s=U(oF(a)).toVar(),c=U(JP(XP(sF(n,r),i,a),XP(sF(n.add(W(1)),r),i.sub(1),a),XP(sF(n,r.add(W(1))),i,a.sub(1)),XP(sF(n.add(W(1)),r.add(W(1))),i.sub(1),a.sub(1)),o,s)).toVar();return eF(c)}).setLayout({name:`mx_perlin_noise_float_0`,type:`float`,inputs:[{name:`p`,type:`vec2`}]}),V(([e])=>{let t=K(e).toVar(),n=W().toVar(),r=W().toVar(),i=W().toVar(),a=U(GP(t.x,n)).toVar(),o=U(GP(t.y,r)).toVar(),s=U(GP(t.z,i)).toVar(),c=U(oF(a)).toVar(),l=U(oF(o)).toVar(),u=U(oF(s)).toVar(),d=U(YP(XP(sF(n,r,i),a,o,s),XP(sF(n.add(W(1)),r,i),a.sub(1),o,s),XP(sF(n,r.add(W(1)),i),a,o.sub(1),s),XP(sF(n.add(W(1)),r.add(W(1)),i),a.sub(1),o.sub(1),s),XP(sF(n,r,i.add(W(1))),a,o,s.sub(1)),XP(sF(n.add(W(1)),r,i.add(W(1))),a.sub(1),o,s.sub(1)),XP(sF(n,r.add(W(1)),i.add(W(1))),a,o.sub(1),s.sub(1)),XP(sF(n.add(W(1)),r.add(W(1)),i.add(W(1))),a.sub(1),o.sub(1),s.sub(1)),c,l,u)).toVar();return tF(d)}).setLayout({name:`mx_perlin_noise_float_1`,type:`float`,inputs:[{name:`p`,type:`vec3`}]})]),uF=kA([V(([e])=>{let t=pg(e).toVar(),n=W().toVar(),r=W().toVar(),i=U(GP(t.x,n)).toVar(),a=U(GP(t.y,r)).toVar(),o=U(oF(i)).toVar(),s=U(oF(a)).toVar(),c=K(JP(ZP(cF(n,r),i,a),ZP(cF(n.add(W(1)),r),i.sub(1),a),ZP(cF(n,r.add(W(1))),i,a.sub(1)),ZP(cF(n.add(W(1)),r.add(W(1))),i.sub(1),a.sub(1)),o,s)).toVar();return eF(c)}).setLayout({name:`mx_perlin_noise_vec3_0`,type:`vec3`,inputs:[{name:`p`,type:`vec2`}]}),V(([e])=>{let t=K(e).toVar(),n=W().toVar(),r=W().toVar(),i=W().toVar(),a=U(GP(t.x,n)).toVar(),o=U(GP(t.y,r)).toVar(),s=U(GP(t.z,i)).toVar(),c=U(oF(a)).toVar(),l=U(oF(o)).toVar(),u=U(oF(s)).toVar(),d=K(YP(ZP(cF(n,r,i),a,o,s),ZP(cF(n.add(W(1)),r,i),a.sub(1),o,s),ZP(cF(n,r.add(W(1)),i),a,o.sub(1),s),ZP(cF(n.add(W(1)),r.add(W(1)),i),a.sub(1),o.sub(1),s),ZP(cF(n,r,i.add(W(1))),a,o,s.sub(1)),ZP(cF(n.add(W(1)),r,i.add(W(1))),a.sub(1),o,s.sub(1)),ZP(cF(n,r.add(W(1)),i.add(W(1))),a,o.sub(1),s.sub(1)),ZP(cF(n.add(W(1)),r.add(W(1)),i.add(W(1))),a.sub(1),o.sub(1),s.sub(1)),c,l,u)).toVar();return tF(d)}).setLayout({name:`mx_perlin_noise_vec3_1`,type:`vec3`,inputs:[{name:`p`,type:`vec3`}]})]),dF=kA([V(([e])=>{let t=U(e).toVar(),n=W(WP(t)).toVar();return aF(sF(n))}).setLayout({name:`mx_cell_noise_float_0`,type:`float`,inputs:[{name:`p`,type:`float`}]}),V(([e])=>{let t=pg(e).toVar(),n=W(WP(t.x)).toVar(),r=W(WP(t.y)).toVar();return aF(sF(n,r))}).setLayout({name:`mx_cell_noise_float_1`,type:`float`,inputs:[{name:`p`,type:`vec2`}]}),V(([e])=>{let t=K(e).toVar(),n=W(WP(t.x)).toVar(),r=W(WP(t.y)).toVar(),i=W(WP(t.z)).toVar();return aF(sF(n,r,i))}).setLayout({name:`mx_cell_noise_float_2`,type:`float`,inputs:[{name:`p`,type:`vec3`}]}),V(([e])=>{let t=bg(e).toVar(),n=W(WP(t.x)).toVar(),r=W(WP(t.y)).toVar(),i=W(WP(t.z)).toVar(),a=W(WP(t.w)).toVar();return aF(sF(n,r,i,a))}).setLayout({name:`mx_cell_noise_float_3`,type:`float`,inputs:[{name:`p`,type:`vec4`}]})]),fF=kA([V(([e])=>{let t=U(e).toVar(),n=W(WP(t)).toVar();return K(aF(sF(n,W(0))),aF(sF(n,W(1))),aF(sF(n,W(2))))}).setLayout({name:`mx_cell_noise_vec3_0`,type:`vec3`,inputs:[{name:`p`,type:`float`}]}),V(([e])=>{let t=pg(e).toVar(),n=W(WP(t.x)).toVar(),r=W(WP(t.y)).toVar();return K(aF(sF(n,r,W(0))),aF(sF(n,r,W(1))),aF(sF(n,r,W(2))))}).setLayout({name:`mx_cell_noise_vec3_1`,type:`vec3`,inputs:[{name:`p`,type:`vec2`}]}),V(([e])=>{let t=K(e).toVar(),n=W(mv(t.x)).toVar(),r=W(mv(t.y)).toVar(),i=W(mv(t.z)).toVar(),a=G(3735928588).toVar(),o=G().toVar(),s=G().toVar(),c=G().toVar();o.assign(s.assign(c.assign(a))),o.addAssign(G(n)),s.addAssign(G(r)),c.addAssign(G(i));let l=vg(rF(o,s,c)).toVar(),u=iF(l.x,l.y,l.z),d=iF(D_(l.x,G(1)),l.y,l.z),f=iF(D_(l.x,G(2)),l.y,l.z);return K(aF(u),aF(d),aF(f))}).setLayout({name:`mx_cell_noise_vec3_2`,type:`vec3`,inputs:[{name:`p`,type:`vec3`}]}),V(([e])=>{let t=bg(e).toVar(),n=W(WP(t.x)).toVar(),r=W(WP(t.y)).toVar(),i=W(WP(t.z)).toVar(),a=W(WP(t.w)).toVar(),o=G(3735928592).toVar(),s=G().toVar(),c=G().toVar(),l=G().toVar();s.assign(c.assign(l.assign(o))),s.addAssign(G(n)),c.addAssign(G(r)),l.addAssign(G(i));let u=vg(rF(s,c,l)).toVar();return s.assign(u.x),c.assign(u.y),l.assign(u.z),s.addAssign(G(a)),K(aF(iF(s,c,l)),aF(iF(s,D_(c,G(1)),l)),aF(iF(s,D_(c,G(2)),l)))}).setLayout({name:`mx_cell_noise_vec3_3`,type:`vec3`,inputs:[{name:`p`,type:`vec4`}]})]),pF=V(([e])=>{let t=K(e).toVar(),n=W(mv(t.x)).toVar(),r=W(mv(t.y)).toVar(),i=W(mv(t.z)).toVar(),a=G(3735928588).toVar(),o=G().toVar(),s=G().toVar(),c=G().toVar();o.assign(s.assign(c.assign(a))),o.addAssign(G(n)),s.addAssign(G(r)),c.addAssign(G(i));let l=vg(rF(o,s,c)).toVar(),u=iF(l.x,l.y,l.z),d=iF(D_(l.x,G(1)),l.y,l.z),f=iF(D_(l.x,G(2)),l.y,l.z);return K(aF(u),aF(d),aF(f))}),mF=V(([e,t,n,r])=>{let i=U(r).toVar(),a=U(n).toVar(),o=W(t).toVar(),s=pg(e).toVar(),c=U(0).toVar(),l=U(1).toVar();return Xw(o,()=>{c.addAssign(l.mul(lF(s))),l.mulAssign(i),s.mulAssign(a)}),c}).setLayout({name:`mx_fractal_noise_float_2d`,type:`float`,inputs:[{name:`p`,type:`vec2`},{name:`octaves`,type:`int`},{name:`lacunarity`,type:`float`},{name:`diminish`,type:`float`}]}),hF=V(([e,t,n,r])=>{let i=U(r).toVar(),a=U(n).toVar(),o=W(t).toVar(),s=K(e).toVar(),c=U(0).toVar(),l=U(1).toVar();return Xw(o,()=>{c.addAssign(l.mul(lF(s))),l.mulAssign(i),s.mulAssign(a)}),c}).setLayout({name:`mx_fractal_noise_float`,type:`float`,inputs:[{name:`p`,type:`vec3`},{name:`octaves`,type:`int`},{name:`lacunarity`,type:`float`},{name:`diminish`,type:`float`}]}),gF=V(([e,t,n,r])=>{let i=U(r).toVar(),a=U(n).toVar(),o=W(t).toVar(),s=K(e).toVar(),c=K(0).toVar(),l=U(1).toVar();return Xw(o,()=>{c.addAssign(l.mul(uF(s))),l.mulAssign(i),s.mulAssign(a)}),c}).setLayout({name:`mx_fractal_noise_vec3`,type:`vec3`,inputs:[{name:`p`,type:`vec3`},{name:`octaves`,type:`int`},{name:`lacunarity`,type:`float`},{name:`diminish`,type:`float`}]}),_F=V(([e,t,n,r])=>{let i=U(r).toVar(),a=U(n).toVar(),o=W(t).toVar(),s=K(e).toVar();return pg(hF(s,o,a,i),hF(s.add(K(W(19),W(193),W(17))),o,a,i))}).setLayout({name:`mx_fractal_noise_vec2`,type:`vec2`,inputs:[{name:`p`,type:`vec3`},{name:`octaves`,type:`int`},{name:`lacunarity`,type:`float`},{name:`diminish`,type:`float`}]}),vF=V(([e,t,n,r])=>{let i=U(r).toVar(),a=U(n).toVar(),o=W(t).toVar(),s=K(e).toVar(),c=K(gF(s,o,a,i)).toVar(),l=U(hF(s.add(K(W(19),W(193),W(17))),o,a,i)).toVar();return bg(c,l)}).setLayout({name:`mx_fractal_noise_vec4`,type:`vec4`,inputs:[{name:`p`,type:`vec3`},{name:`octaves`,type:`int`},{name:`lacunarity`,type:`float`},{name:`diminish`,type:`float`}]}),yF=kA([V(([e,t,n,r,i,a,o])=>{let s=W(o).toVar(),c=U(a).toVar(),l=W(i).toVar(),u=W(r).toVar(),d=W(n).toVar(),f=W(t).toVar(),p=pg(e).toVar(),m=K(fF(pg(f.add(u),d.add(l)))).toVar(),h=pg(m.x,m.y).toVar();h.subAssign(.5),h.mulAssign(c),h.addAssign(.5);let g=pg(pg(U(f),U(d)).add(h)).toVar(),_=pg(g.sub(p)).toVar();return lg(s.equal(W(2)),()=>Av(_.x).add(Av(_.y))),lg(s.equal(W(3)),()=>Gv(Av(_.x),Av(_.y))),Xv(_,_)}).setLayout({name:`mx_worley_distance_0`,type:`float`,inputs:[{name:`p`,type:`vec2`},{name:`x`,type:`int`},{name:`y`,type:`int`},{name:`xoff`,type:`int`},{name:`yoff`,type:`int`},{name:`jitter`,type:`float`},{name:`metric`,type:`int`}]}),V(([e,t,n,r,i,a,o,s,c])=>{let l=W(c).toVar(),u=U(s).toVar(),d=W(o).toVar(),f=W(a).toVar(),p=W(i).toVar(),m=W(r).toVar(),h=W(n).toVar(),g=W(t).toVar(),_=K(e).toVar(),v=K(pF(K(g.add(p),h.add(f),m.add(d)))).toVar();v.subAssign(.5),v.mulAssign(u),v.addAssign(.5);let y=K(K(U(g),U(h),U(m)).add(v)).toVar(),b=K(y.sub(_)).toVar();return lg(l.equal(W(2)),()=>Av(b.x).add(Av(b.y)).add(Av(b.z))),lg(l.equal(W(3)),()=>Gv(Av(b.x),Av(b.y),Av(b.z))),Xv(b,b)}).setLayout({name:`mx_worley_distance_1`,type:`float`,inputs:[{name:`p`,type:`vec3`},{name:`x`,type:`int`},{name:`y`,type:`int`},{name:`z`,type:`int`},{name:`xoff`,type:`int`},{name:`yoff`,type:`int`},{name:`zoff`,type:`int`},{name:`jitter`,type:`float`},{name:`metric`,type:`int`}]})]),bF=(e,t=1,n=0)=>lF(e).mul(t).add(n),xF=V(([e,t,n])=>{let r=K(e).toVar(),i=U(t).toVar(),a=W(n).toVar(),o=W().toVar(),s=W().toVar(),c=W().toVar(),l=K(GP(r.x,o),GP(r.y,s),GP(r.z,c)).toVar(),u=U(1e6).toVar(),d=K(0,0,0).toVar();return Xw({start:-1,end:W(1),name:`x`,condition:`<=`},({x:e})=>{Xw({start:-1,end:W(1),name:`y`,condition:`<=`},({y:t})=>{Xw({start:-1,end:W(1),name:`z`,condition:`<=`},({z:n})=>{let r=U(yF(l,e,t,n,o,s,c,i,W(0))).toVar(),a=K(pF(K(o.add(e),s.add(t),c.add(n)))).toVar();a.subAssign(.5),a.mulAssign(i),a.addAssign(.5);let f=K(K(U(e),U(t),U(n)).add(a).sub(l)).toVar();lg(r.lessThan(u),()=>{u.assign(r),d.assign(f)})})})}),lg(a.equal(W(1)),()=>{u.assign(dF(d.add(r)))}).Else(()=>{u.assign(fv(u))}),u}),SF=V(([e,t,n])=>{let r=pg(e).toVar(),i=U(t).toVar(),a=W(n).toVar(),o=mv(r).toVar(),s=pg(_v(r.x),_v(r.y)).toVar(),c=U(1e6).toVar(),l=pg(0,0).toVar();return Xw({start:-1,end:W(1),name:`x`,condition:`<=`},({x:e})=>{Xw({start:-1,end:W(1),name:`y`,condition:`<=`},({y:t})=>{let n=pg(U(e),U(t)).toVar(),r=pg(n.x.add(o.x),n.y.add(o.y)).toVar(),a=pg(dF(K(r.x,r.y,0)),dF(K(r.x,r.y,1))).toVar();a.subAssign(.5),a.mulAssign(i),a.addAssign(.5);let u=pg(n.add(a).sub(s)).toVar(),d=Xv(u,u).toVar();lg(d.lessThan(c),()=>{c.assign(d),l.assign(u)})})}),lg(a.equal(W(1)),()=>{c.assign(dF(l.add(r)))}).Else(()=>{c.assign(fv(c))}),c}),CF=V(([e,t,n])=>{let r=W(n).toVar(),i=U(t).toVar(),a=pg(e).toVar(),o=W().toVar(),s=W().toVar(),c=pg(GP(a.x,o),GP(a.y,s)).toVar(),l=pg(1e6,1e6).toVar();return Xw({start:-1,end:W(1),name:`x`,condition:`<=`},({x:e})=>{Xw({start:-1,end:W(1),name:`y`,condition:`<=`},({y:t})=>{let n=U(yF(c,e,t,o,s,i,r)).toVar();lg(n.lessThan(l.x),()=>{l.y.assign(l.x),l.x.assign(n)}).ElseIf(n.lessThan(l.y),()=>{l.y.assign(n)})})}),lg(r.equal(W(0)),()=>{l.assign(fv(l))}),l}).setLayout({name:`mx_worley_noise_vec2_0`,type:`vec2`,inputs:[{name:`p`,type:`vec2`},{name:`jitter`,type:`float`},{name:`metric`,type:`int`}]}),wF=V(([e,t,n])=>{let r=W(n).toVar(),i=U(t).toVar(),a=pg(e).toVar(),o=W().toVar(),s=W().toVar(),c=pg(GP(a.x,o),GP(a.y,s)).toVar(),l=K(1e6,1e6,1e6).toVar();return Xw({start:-1,end:W(1),name:`x`,condition:`<=`},({x:e})=>{Xw({start:-1,end:W(1),name:`y`,condition:`<=`},({y:t})=>{let n=U(yF(c,e,t,o,s,i,r)).toVar();lg(n.lessThan(l.x),()=>{l.z.assign(l.y),l.y.assign(l.x),l.x.assign(n)}).ElseIf(n.lessThan(l.y),()=>{l.z.assign(l.y),l.y.assign(n)}).ElseIf(n.lessThan(l.z),()=>{l.z.assign(n)})})}),lg(r.equal(W(0)),()=>{l.assign(fv(l))}),l}).setLayout({name:`mx_worley_noise_vec3_0`,type:`vec3`,inputs:[{name:`p`,type:`vec2`},{name:`jitter`,type:`float`},{name:`metric`,type:`int`}]}),TF=kA([CF,V(([e,t,n])=>{let r=W(n).toVar(),i=U(t).toVar(),a=K(e).toVar(),o=W().toVar(),s=W().toVar(),c=W().toVar(),l=K(GP(a.x,o),GP(a.y,s),GP(a.z,c)).toVar(),u=pg(1e6,1e6).toVar();return Xw({start:-1,end:W(1),name:`x`,condition:`<=`},({x:e})=>{Xw({start:-1,end:W(1),name:`y`,condition:`<=`},({y:t})=>{Xw({start:-1,end:W(1),name:`z`,condition:`<=`},({z:n})=>{let a=U(yF(l,e,t,n,o,s,c,i,r)).toVar();lg(a.lessThan(u.x),()=>{u.y.assign(u.x),u.x.assign(a)}).ElseIf(a.lessThan(u.y),()=>{u.y.assign(a)})})})}),lg(r.equal(W(0)),()=>{u.assign(fv(u))}),u}).setLayout({name:`mx_worley_noise_vec2_1`,type:`vec2`,inputs:[{name:`p`,type:`vec3`},{name:`jitter`,type:`float`},{name:`metric`,type:`int`}]})]),EF=kA([wF,V(([e,t,n])=>{let r=W(n).toVar(),i=U(t).toVar(),a=K(e).toVar(),o=W().toVar(),s=W().toVar(),c=W().toVar(),l=K(GP(a.x,o),GP(a.y,s),GP(a.z,c)).toVar(),u=K(1e6,1e6,1e6).toVar();return Xw({start:-1,end:W(1),name:`x`,condition:`<=`},({x:e})=>{Xw({start:-1,end:W(1),name:`y`,condition:`<=`},({y:t})=>{Xw({start:-1,end:W(1),name:`z`,condition:`<=`},({z:n})=>{let a=U(yF(l,e,t,n,o,s,c,i,r)).toVar();lg(a.lessThan(u.x),()=>{u.z.assign(u.y),u.y.assign(u.x),u.x.assign(a)}).ElseIf(a.lessThan(u.y),()=>{u.z.assign(u.y),u.y.assign(a)}).ElseIf(a.lessThan(u.z),()=>{u.z.assign(a)})})})}),lg(r.equal(W(0)),()=>{u.assign(fv(u))}),u}).setLayout({name:`mx_worley_noise_vec3_1`,type:`vec3`,inputs:[{name:`p`,type:`vec3`},{name:`jitter`,type:`float`},{name:`metric`,type:`int`}]})]),DF=kA([V(([e,t,n,r])=>{let i=W(r).toVar(),a=W(n).toVar(),o=U(t).toVar(),s=pg(e).toVar(),c=W().toVar(),l=W().toVar(),u=pg(GP(s.x,c),GP(s.y,l)).toVar(),d=U(1e6).toVar(),f=pg(0,0).toVar();Xw({start:-1,end:W(1),name:`x`,condition:`<=`},({x:e})=>{Xw({start:-1,end:W(1),name:`y`,condition:`<=`},({y:t})=>{let n=U(yF(u,e,t,c,l,o,i)).toVar(),r=K(fF(pg(c.add(e),l.add(t)))).toVar(),a=pg(r.x,r.y).toVar();a.subAssign(.5),a.mulAssign(o),a.addAssign(.5);let s=pg(pg(U(e),U(t)).add(a).sub(u)).toVar();lg(n.lessThan(d),()=>{d.assign(n),f.assign(s)})})});let p=K(EF(s,o,i)).toVar();return lg(a.equal(W(1)),()=>{p.assign(fF(f.add(s)))}),p}).setLayout({name:`mx_worley_noise_vec3_style_0`,type:`vec3`,inputs:[{name:`p`,type:`vec2`},{name:`jitter`,type:`float`},{name:`style`,type:`int`},{name:`metric`,type:`int`}]}),V(([e,t,n,r])=>{let i=W(r).toVar(),a=W(n).toVar(),o=U(t).toVar(),s=K(e).toVar(),c=W().toVar(),l=W().toVar(),u=W().toVar(),d=K(GP(s.x,c),GP(s.y,l),GP(s.z,u)).toVar(),f=U(1e6).toVar(),p=K(0,0,0).toVar();Xw({start:-1,end:W(1),name:`x`,condition:`<=`},({x:e})=>{Xw({start:-1,end:W(1),name:`y`,condition:`<=`},({y:t})=>{Xw({start:-1,end:W(1),name:`z`,condition:`<=`},({z:n})=>{let r=U(yF(d,e,t,n,c,l,u,o,i)).toVar(),a=K(pF(K(c.add(e),l.add(t),u.add(n)))).toVar();a.subAssign(.5),a.mulAssign(o),a.addAssign(.5);let s=K(K(U(e),U(t),U(n)).add(a).sub(d)).toVar();lg(r.lessThan(f),()=>{f.assign(r),p.assign(s)})})})});let m=K(EF(s,o,i)).toVar();return lg(a.equal(W(1)),()=>{m.assign(pF(p.add(s)))}),m}).setLayout({name:`mx_worley_noise_vec3_style_1`,type:`vec3`,inputs:[{name:`p`,type:`vec3`},{name:`jitter`,type:`float`},{name:`style`,type:`int`},{name:`metric`,type:`int`}]})]),OF=V(([e,t,n,r,i,a,o,s,c,l,u,d])=>{let f=W(e).toVar(),p=pg(t).toVar(),m=pg(n).toVar(),h=pg(r).toVar(),g=U(i).toVar(),_=U(a).toVar(),v=U(o).toVar(),y=U(s).toVar(),b=W(c).toVar(),x=U(l).toVar(),S=U(u).toVar(),C=W(d).toVar(),w=k_(p,m).toVar(),T=D_(w,h).toVar(),E=k_(O_(g,1),9e4).toVar(),D=BP(T,E).toVar(),ee=K(T.x,T.y,E).toVar(),O=U(0).toVar();lg(f.equal(W(0)),()=>{O.assign(bF(D,.5,.5))}),lg(f.equal(W(1)),()=>{O.assign(dF(D))}),lg(f.equal(W(2)),()=>{O.assign(SF(T,g,C))}),lg(f.equal(W(3)),()=>{O.assign(hF(ee,b,x,S))});let k=D_(_,k_(O,O_(v,_))).toVar(),te=cy(k,_,v).toVar(),A=k.toVar();return lg(y.equal(U(1)),()=>{A.assign(te)}),A}),kF=V(([e,t,n,r,i,a,o,s,c,l,u,d])=>{let f=W(e).toVar(),p=K(t).toVar(),m=K(n).toVar(),h=K(r).toVar(),g=U(i).toVar(),_=U(a).toVar(),v=U(o).toVar(),y=U(s).toVar(),b=W(c).toVar(),x=U(l).toVar(),S=U(u).toVar(),C=W(d).toVar(),w=k_(p,m).toVar(),T=D_(w,h).toVar(),E=k_(O_(g,1),9e4).toVar(),D=VP(T,E,K(.1,1,0)).toVar(),ee=bF(D,.5,.5),O=dF(D),k=xF(T,g,C),te=hF(D,b,x,S),A=ee.toVar();lg(f.equal(W(1)),()=>{A.assign(O)}),lg(f.equal(W(2)),()=>{A.assign(k)}),lg(f.equal(W(3)),()=>{A.assign(te)});let ne=D_(_,k_(A,O_(v,_))).toVar(),re=cy(ne,_,v).toVar(),ie=ne.toVar();return lg(y.equal(U(1)),()=>{ie.assign(re)}),ie}),AF=V(([e])=>{let t=e.y,n=e.z,r=K().toVar();return lg(t.lessThan(1e-4),()=>{r.assign(K(n,n,n))}).Else(()=>{let i=e.x;i=i.sub(mv(i)).mul(6).toVar();let a=W(zv(i)),o=i.sub(U(a)),s=n.mul(t.oneMinus()),c=n.mul(t.mul(o).oneMinus()),l=n.mul(t.mul(o.oneMinus()).oneMinus());lg(a.equal(W(0)),()=>{r.assign(K(n,l,s))}).ElseIf(a.equal(W(1)),()=>{r.assign(K(c,n,s))}).ElseIf(a.equal(W(2)),()=>{r.assign(K(s,n,l))}).ElseIf(a.equal(W(3)),()=>{r.assign(K(s,c,n))}).ElseIf(a.equal(W(4)),()=>{r.assign(K(l,s,n))}).Else(()=>{r.assign(K(n,s,c))})}),r}).setLayout({name:`mx_hsvtorgb`,type:`vec3`,inputs:[{name:`hsv`,type:`vec3`}]}),jF=V(([e])=>{let t=K(e).toVar(),n=U(t.x).toVar(),r=U(t.y).toVar(),i=U(t.z).toVar(),a=U(Wv(n,Wv(r,i))).toVar(),o=U(Gv(n,Gv(r,i))).toVar(),s=U(o.sub(a)).toVar(),c=U().toVar(),l=U().toVar(),u=U().toVar();return u.assign(o),lg(o.greaterThan(0),()=>{l.assign(s.div(o))}).Else(()=>{l.assign(0)}),lg(l.lessThanEqual(0),()=>{c.assign(0)}).Else(()=>{lg(n.greaterThanEqual(o),()=>{c.assign(r.sub(i).div(s))}).ElseIf(r.greaterThanEqual(o),()=>{c.assign(D_(2,i.sub(n).div(s)))}).Else(()=>{c.assign(D_(4,n.sub(r).div(s)))}),c.mulAssign(1/6),lg(c.lessThan(0),()=>{c.addAssign(1)})}),K(c,l,u)}).setLayout({name:`mx_rgbtohsv`,type:`vec3`,inputs:[{name:`c`,type:`vec3`}]}),MF=V(([e])=>{let t=K(e).toVar(),n=yg(F_(t,K(.04045))).toVar(),r=K(t.div(12.92)).toVar(),i=K(Qv(Gv(t.add(K(.055)),K(0)).div(1.055),K(2.4))).toVar();return sy(r,i,n)}).setLayout({name:`mx_srgb_texture_to_lin_rec709`,type:`vec3`,inputs:[{name:`color`,type:`vec3`}]}),NF=(e,t)=>{e=U(e),t=U(t);let n=pg(t.dFdx(),t.dFdy()).length().mul(.7071067811865476);return dy(e.sub(n),e.add(n),t)},PF=(e,t,n,r)=>sy(e,t,n[r].clamp()),FF=(e,t,n=Mb())=>PF(e,t,n,`x`),IF=(e,t,n=Mb())=>PF(e,t,n,`y`),LF=(e,t,n,r,i=Mb())=>{let a=i.x.clamp(),o=i.y.clamp(),s=sy(e,t,a),c=sy(n,r,a);return sy(c,s,o)},RF=(e,t,n,r,i)=>sy(e,t,NF(n,r[i])),zF=(e,t,n,r=Mb())=>RF(e,t,n,r,`x`),BF=(e,t,n,r=Mb())=>RF(e,t,n,r,`y`),VF=(e=1,t=0,n=Mb())=>n.mul(e).add(t),HF=(e,t=1)=>(e=U(e),e.abs().pow(t).mul(e.sign())),UF=(e,t=1,n=.5)=>U(e).sub(n).mul(t).add(n),WF=(e=Mb(),t=1,n=0)=>lF(e.convert(`vec2|vec3`)).mul(t).add(n),GF=(e=Mb(),t=1,n=0)=>uF(e.convert(`vec2|vec3`)).mul(t).add(n),KF=(e=Mb(),t=1,n=0)=>(e=e.convert(`vec2|vec3`),bg(uF(e),lF(e.add(pg(19,73)))).mul(t).add(n)),qF=(e,t=0,n=1)=>{let r=O_(n,t),i=Gv(Av(r),U(1e-6)),a=cy(A_(O_(e,t),i),U(0),U(1)),o=k_(k_(a,a),O_(U(3),k_(U(2),a))),s=Kv(n,e),c=Kv(n,t);return sy(o,s,c)},JF=(e=Mb())=>fF(e.convert(`vec2|vec3`)),YF=(e=Mb(),t=1,n=0)=>SF(e,t,n),XF=(e=Mb(),t=1,n=0)=>xF(e,t,n),ZF=(e,t=Mb(),n=pg(1,1),r=pg(0,0),i=1,a=0,o=1,s=!1,c=1,l=2,u=.5,d=0)=>OF(e,t,n,r,i,a,o,s,c,l,u,d),QF=(e,t=Mb(),n=K(1,1,1),r=K(0,0,0),i=1,a=0,o=1,s=!1,c=1,l=2,u=.5,d=0)=>kF(e,t,n,r,i,a,o,s,c,l,u,d),$F=(e=Mb(),t=1,n=0)=>XF(e.convert(`vec2|vec3`),t,n),eI=(e=Mb(),t=1)=>TF(e.convert(`vec2|vec3`),t,W(1)),tI=(e=Mb(),t=1,n=1)=>EF(e.convert(`vec2|vec3`),t,W(n)),nI=(e=Mb(),t=1,n=0,r=0)=>DF(e.convert(`vec2|vec3`),t,W(n),W(r)),rI=(e=Mb())=>dF(e.convert(`vec2|vec3`)),iI=(e=Mb(),t=3,n=2,r=.5,i=1)=>mF(e,W(t),n,r).mul(i),aI=(e=Mb(),t=3,n=2,r=.5,i=1)=>hF(e,W(t),n,r).mul(i),oI=(e=Mb(),t=3,n=2,r=.5,i=1)=>_F(e,W(t),n,r).mul(i),sI=(e=Mb(),t=3,n=2,r=.5,i=1)=>gF(e,W(t),n,r).mul(i),cI=(e=Mb(),t=3,n=2,r=.5,i=1)=>vF(e,W(t),n,r).mul(i),lI=(e,t=U(0))=>D_(e,t),uI=(e,t=U(0))=>O_(e,t),dI=(e,t=U(1))=>k_(e,t),fI=(e,t=U(1))=>A_(e,t),pI=(e,t=U(1))=>O_(e,k_(t,mv(A_(e,t)))),mI=(e,t=U(1))=>Qv(e,t),hI=(e=U(0),t=U(1))=>Ov(e,t),gI=()=>AA,_I=()=>MA,vI=(e,t=U(1))=>O_(t,e),yI=(e,t,n,r)=>e.greaterThan(t).mix(r,n),bI=(e,t,n,r)=>e.greaterThanEqual(t).mix(r,n),xI=(e,t,n,r)=>e.equal(t).mix(r,n),SI=(e,t=null)=>{if(typeof t==`string`){let n={x:0,r:0,y:1,g:1,z:2,b:2,w:3,a:3},r=t.replace(/^out/,``).toLowerCase();if(n[r]!==void 0)return e.element(n[r])}if(typeof t==`number`)return e.element(t);if(typeof t==`string`&&t.length===1){let n={x:0,r:0,y:1,g:1,z:2,b:2,w:3,a:3};if(n[t]!==void 0)return e.element(n[t])}return e},CI=(e,t=pg(0,0),n=pg(1,1),r=U(0),i=pg(0,0),a=W(0))=>{let o=O_(e,t),s=D_(O_(BP(A_(o,n),r),i),t),c=D_(A_(BP(O_(o,i),r),n),t);return typeof a==`number`?Math.abs(a)>2**-52?c:s:sy(s,c,Kv(.5,U(a)))},wI=(e,t=1,n=Mb())=>{let r=U(1/16),i=U(e),a=pg(n),o=pg(i.dFdx(),i.dFdy()).mul(U(t)).mul(r),s=pg(a.x.dFdx(),a.x.dFdy()),c=pg(a.y.dFdx(),a.y.dFdy()),l=K(s.x,c.x,o.x),u=K(s.y,c.y,o.y),d=Zv(l,u);return d=Xv(d,d).lessThan(U(1e-12)).mix(d,K(0,0,1)),d=d.z.lessThan(U(0)).mix(d,d.mul(-1)),gv(d).mul(.5).add(.5)},TI=V(([e,t,n])=>{let r=gv(e).toVar(),i=t.mul(.5).add(n).sub(sS).div(r).toVar(),a=t.mul(-.5).add(n).sub(sS).div(r).toVar(),o=K().toVar();o.x=r.x.greaterThan(U(0)).select(i.x,a.x),o.y=r.y.greaterThan(U(0)).select(i.y,a.y),o.z=r.z.greaterThan(U(0)).select(i.z,a.z);let s=Wv(o.x,o.y,o.z).toVar();return sS.add(r.mul(s)).toVar().sub(n)}),EI=V(([e,t])=>{let n=e.x,r=e.y,i=e.z,a=t.element(0).mul(.886227);return a=a.add(t.element(1).mul(1.023328).mul(r)),a=a.add(t.element(2).mul(1.023328).mul(i)),a=a.add(t.element(3).mul(1.023328).mul(n)),a=a.add(t.element(4).mul(.858086).mul(n).mul(r)),a=a.add(t.element(5).mul(.858086).mul(r).mul(i)),a=a.add(t.element(6).mul(i.mul(i).mul(.743125).sub(.247708))),a=a.add(t.element(7).mul(.858086).mul(n).mul(i)),a=a.add(t.element(8).mul(.429043).mul(k_(n,n).sub(k_(r,r)))),a}),X=Object.freeze({__proto__:null,BRDF_GGX:ME,BRDF_Lambert:gE,BRDF_Sheen:BE,BasicPointShadowFilter:kP,BasicShadowFilter:dP,Break:Qw,Const:Oy,Continue:Zw,DFGLUT:FE,D_GGX:kE,D_GGX_Anisotropic:jE,Discard:bb,EPSILON:Q_,EnvironmentBRDF:IE,F_Schlick:hE,Fn:V,HALF_PI:rv,INFINITY:$_,If:lg,LTC_Evaluate:WE,LTC_Evaluate_Volume:GE,LTC_Uv:VE,Loop:Xw,NodeAccess:ih,NodeShaderStage:th,NodeType:rh,NodeUpdateType:nh,OnAfterObjectUpdate:Cw,OnAfterRenderPipeline:Ow,OnBeforeFrameUpdate:Ew,OnBeforeMaterialUpdate:Tw,OnBeforeObjectUpdate:ww,OnBeforeRenderPipeline:Dw,OnFrameUpdate:Sw,OnMaterialUpdate:xw,OnObjectUpdate:bw,PCFShadowFilter:fP,PI:ev,PI2:tv,PointShadowFilter:AP,Return:xb,Schlick_to_F0:LE,ShaderNode:up,Stack:dp,Switch:ug,TBNViewMatrix:gC,TWO_PI:nv,VSMShadowFilter:pP,V_GGX_SmithCorrelated:DE,V_GGX_SmithCorrelated_Anisotropic:OE,Var:Dy,VarIntent:ky,abs:Av,acesFilmicToneMapping:wM,acos:Ev,acosh:Dv,add:D_,addMethodChaining:B,addNodeElement:xp,agxToneMapping:OM,all:iv,alphaT:Gg,ambientOcclusion:u_,and:R_,anisotropy:Kg,anisotropyB:Jg,anisotropyT:qg,any:av,array:b_,asin:wv,asinh:Tv,assign:S_,atan:Ov,atanh:kv,atomicAdd:pN,atomicAnd:_N,atomicFunc:uN,atomicLoad:dN,atomicMax:hN,atomicMin:gN,atomicOr:vN,atomicStore:fN,atomicSub:mN,atomicXor:yN,attenuationColor:s_,attenuationDistance:o_,attribute:jb,attributeArray:Dj,backgroundBlurriness:Mj,backgroundIntensity:Nj,backgroundRotation:Pj,batch:Ww,batchColor:Hw,batchIndirectIndex:Uw,bentNormalView:yC,billboarding:zA,bitAnd:H_,bitNot:U_,bitOr:W_,bitXor:G_,bitangentGeometry:fC,bitangentLocal:pC,bitangentView:mC,bitangentViewFrame:oC,bitangentWorld:hC,bitcast:Pk,blendBurn:Xj,blendColor:eM,blendDodge:Zj,blendOverlay:$j,blendScreen:Qj,bool:fg,buffer:Jb,bufferAttribute:$y,builtin:$b,builtinAOContext:pp,builtinGIContext:mp,builtinShadowContext:fp,bumpMap:AC,bvec2:gg,bvec3:yg,bvec4:Cg,bypass:gb,cache:vp,call:w_,cameraFar:Dx,cameraIndex:Tx,cameraNear:Ex,cameraNormalMatrix:Mx,cameraPosition:Nx,cameraProjectionMatrix:Ox,cameraProjectionMatrixInverse:kx,cameraViewMatrix:Ax,cameraViewport:Px,cameraWorldMatrix:jx,cbrt:ay,cdl:oM,ceil:hv,checker:RP,cineonToneMapping:SM,clamp:cy,clearcoat:Rg,clearcoatNormalView:CS,clearcoatRoughness:zg,clipSpace:rS,clipping:MT,clippingAlpha:NT,code:jM,color:dg,colorSpaceToWorking:Vy,colorToDirection:wC,compute:fb,computeKernel:db,computeSkinning:Jw,context:Sy,convert:Og,convertColorSpace:Hy,convertToTexture:gj,cos:bv,cosh:xv,countLeadingZeros:Hk,countOneBits:Uk,countTrailingZeros:Vk,cross:Zv,cubeTexture:BS,cubeTextureBase:zS,dFdx:Fv,dFdy:Iv,dashSize:e_,debug:Db,decrement:Z_,decrementBefore:Y_,defaultBuildStages:oh,defaultShaderStages:ah,defined:lp,degrees:sv,deltaTime:jA,densityFogFactor:BM,depth:OT,depthPass:_M,determinant:Hv,difference:Yv,diffuseColor:Ng,diffuseContribution:Pg,directPointLight:IP,directionToColor:CC,directionToFaceDirection:hS,dispersion:c_,distance:Jv,div:A_,dot:Xv,dot4I8Packed:dA,dot4U8Packed:uA,drawIndex:lb,dynamicBufferAttribute:eb,element:Dg,emissive:Fg,equal:M_,equirectDirection:aE,equirectUV:iE,exp:cv,exp2:lv,exponentialHeightFogFactor:VM,expression:yb,faceDirection:pS,faceForward:fy,faceforward:_y,float:U,floatBitsToInt:Fk,floatBitsToUint:Ik,floor:mv,fog:HM,fract:_v,frameGroup:m_,frameId:MA,frontFacing:fS,fwidth:Bv,gain:Kk,gapSize:t_,getConstNodeType:Zh,getCurrentStack:cg,getDistanceAttenuation:FP,getGeometryRoughness:TE,getNormalFromDepth:bj,getParallaxCorrectNormal:TI,getRoughness:EE,getScreenPosition:vj,getScreenPositionFromClip:yj,getShIrradianceAt:EI,getTextureIndex:am,getViewPosition:_j,globalId:ZM,glsl:PM,glslFn:LM,grayscale:tM,greaterThan:F_,greaterThanEqual:L_,hardwareClipping:PT,hash:Wk,highpModelNormalViewMatrix:nS,highpModelViewMatrix:tS,hue:iM,increment:X_,incrementBefore:J_,inspect:bp,instance:Lw,instanceColor:Iw,instanceIndex:ab,instancedArray:Oj,instancedBufferAttribute:tb,instancedDynamicBufferAttribute:nb,instancedMesh:Rw,int:W,intBitsToFloat:Lk,interleavedGradientNoise:xj,inverse:Uv,inverseSqrt:pv,inversesqrt:vy,invocationLocalIndex:cb,invocationSubgroupIndex:sb,ior:r_,iridescence:Hg,iridescenceIOR:Ug,iridescenceThickness:Wg,isolate:mb,ivec2:mg,ivec3:_g,ivec4:xg,js:MM,label:hp,length:Mv,lengthSq:oy,lessThan:P_,lessThanEqual:I_,lightPosition:Cm,lightProjectionUV:Sm,lightShadowMatrix:xm,lightTargetDirection:qN,lightTargetPosition:wm,lightViewPosition:Tm,lightingContext:sT,lights:nP,linearDepth:kT,linearToneMapping:bM,localId:QM,log:uv,log2:dv,logarithmicDepthToViewZ:ET,luminance:aM,mat2:wg,mat3:Tg,mat4:Eg,matcapUV:CO,materialAO:hw,materialAlphaTest:MC,materialAnisotropy:ZC,materialAnisotropyVector:gw,materialAttenuationColor:aw,materialAttenuationDistance:iw,materialClearcoat:GC,materialClearcoatNormal:qC,materialClearcoatRoughness:KC,materialColor:NC,materialDispersion:fw,materialEmissive:FC,materialEnvIntensity:jS,materialEnvRotation:MS,materialIOR:rw,materialIridescence:QC,materialIridescenceIOR:$C,materialIridescenceThickness:ew,materialLightMap:mw,materialLineDashOffset:uw,materialLineDashSize:sw,materialLineGapSize:cw,materialLineScale:ow,materialLineWidth:lw,materialMetalness:UC,materialNormal:WC,materialOpacity:IC,materialPointSize:dw,materialReference:KS,materialReflectivity:VC,materialRefractionRatio:AS,materialRetroreflectivity:pw,materialRotation:JC,materialRoughness:HC,materialSheen:YC,materialSheenRoughness:XC,materialShininess:PC,materialSpecular:LC,materialSpecularColor:zC,materialSpecularIntensity:RC,materialSpecularStrength:BC,materialThickness:nw,materialTransmission:tw,max:Gv,maxMipLevel:Ib,mediumpModelViewMatrix:eS,metalness:Lg,min:Wv,mix:sy,mixElement:my,mod:j_,modelDirection:Gx,modelNormalMatrix:Zx,modelPosition:qx,modelRadius:Xx,modelScale:Jx,modelViewMatrix:$x,modelViewPosition:Yx,modelViewProjection:_w,modelWorldMatrix:Kx,modelWorldMatrixInverse:Qx,morphReference:rT,mrt:Mk,mul:k_,mx_aastep:NF,mx_add:lI,mx_atan2:hI,mx_cell_noise_float:rI,mx_cell_noise_vec3:JF,mx_contrast:UF,mx_divide:fI,mx_fractal_noise_float:aI,mx_fractal_noise_float_2d:iI,mx_fractal_noise_vec2:oI,mx_fractal_noise_vec3:sI,mx_fractal_noise_vec4:cI,mx_frame:_I,mx_heighttonormal:wI,mx_hsvtorgb:AF,mx_ifequal:xI,mx_ifgreater:yI,mx_ifgreatereq:bI,mx_invert:vI,mx_modulo:pI,mx_multiply:dI,mx_noise_float:WF,mx_noise_vec3:GF,mx_noise_vec4:KF,mx_place2d:CI,mx_power:mI,mx_ramp4:LF,mx_ramplr:FF,mx_ramptb:IF,mx_rgbtohsv:jF,mx_rotate2d:BP,mx_rotate3d:VP,mx_safepower:HF,mx_separate:SI,mx_smoothstep:qF,mx_splitlr:zF,mx_splittb:BF,mx_srgb_texture_to_lin_rec709:MF,mx_subtract:uI,mx_timer:gI,mx_transform_uv:VF,mx_unifiednoise2d:ZF,mx_unifiednoise3d:QF,mx_worley_noise_float:$F,mx_worley_noise_float_2d:YF,mx_worley_noise_float_3d:XF,mx_worley_noise_vec2:eI,mx_worley_noise_vec3:tI,mx_worley_noise_vec3_style:nI,negate:Nv,negateOnBackSide:mS,neutralToneMapping:kM,nodeArray:tg,nodeImmutable:rg,nodeObject:Qh,nodeObjectIntent:$h,nodeObjects:eg,nodeProxy:ng,nodeProxyConstructor:ig,nodeProxyIntent:H,normalFlat:vS,normalGeometry:gS,normalLocal:_S,normalMap:EC,normalView:xS,normalViewGeometry:yS,normalWorld:SS,normalWorldGeometry:bS,normalize:gv,not:B_,notEqual:N_,numWorkgroups:YM,objectDirection:Lx,objectGroup:g_,objectPosition:zx,objectRadius:Hx,objectScale:Bx,objectViewPosition:Vx,objectWorldMatrix:Rx,oneMinus:Pv,or:z_,orthographicDepthToViewZ:xT,oscSawtooth:IA,oscSine:NA,oscSquare:PA,oscTriangle:FA,output:$g,outputStruct:Dk,overloadingFn:kA,overrideNode:nm,overrideNodes:rm,pack4xI8:fA,pack4xI8Clamp:mA,pack4xU8:pA,pack4xU8Clamp:hA,packHalf2x16:Qk,packNormalToRGB:bC,packSnorm2x16:Xk,packSnorm4x8:$k,packUnorm2x16:Zk,packUnorm4x8:eA,parabola:Gk,parallaxDirection:_C,parallaxUV:vC,parameter:bk,pass:hM,passTexture:gM,pcurve:qk,perspectiveDepthToViewZ:wT,pmremTexture:sO,pointShadow:NP,pointUV:Aj,pointWidth:n_,positionGeometry:iS,positionLocal:aS,positionPrevious:oS,positionView:lS,positionViewDirection:uS,positionWorld:sS,positionWorldDirection:cS,posterize:sM,pow:Qv,pow2:$v,pow3:ey,pow4:ty,premultiplyAlpha:Sb,property:jg,quadBroadcast:GN,quadSwapDiagonal:zN,quadSwapX:LN,quadSwapY:RN,radians:ov,rand:py,range:KM,rangeFogFactor:zM,reciprocal:Rv,reference:US,referenceBuffer:WS,reflect:qv,reflectVector:FS,reflectView:NS,reflector:oj,refract:uy,refractVector:IS,refractView:PS,reinhardToneMapping:xM,remap:_b,remapClamp:yp,renderGroup:h_,renderOutput:Tb,rendererReference:qy,replaceDefaultUV:sm,retroreflectivity:l_,rotate:DO,rotateUV:LA,roughness:Ig,round:Lv,rtt:hj,sRGBTransferEOTF:Fy,sRGBTransferOETF:Iy,sample:wj,sampler:Gb,samplerComparison:Kb,saturate:ly,saturation:nM,screenCoordinate:ox,screenDPR:rx,screenSize:ax,screenUV:ix,select:by,setCurrentStack:sg,setName:wy,shaderStages:sh,shadow:bP,shadowPositionWorld:uP,shapeCircle:zP,sharedUniformGroup:p_,sheen:Bg,sheenRoughness:Vg,shiftLeft:K_,shiftRight:q_,shininess:Qg,sign:jv,sin:vv,sinc:Jk,sinh:yv,skinning:qw,smoothstep:dy,smoothstepElement:hy,specularColor:Yg,specularColorBlended:Xg,specularF90:Zg,spherizeUV:RA,split:kg,spritesheetUV:VA,sqrt:fv,stack:Sk,step:Kv,stepElement:gy,storage:Mw,storageBarrier:rN,storageElement:Aw,storageTexture:Ij,storageTexture3D:zj,struct:Tk,sub:O_,subBuild:jy,subgroupAdd:CN,subgroupAll:PN,subgroupAnd:kN,subgroupAny:FN,subgroupBallot:SN,subgroupBroadcast:BN,subgroupBroadcastFirst:IN,subgroupElect:xN,subgroupExclusiveAdd:TN,subgroupExclusiveMul:ON,subgroupInclusiveAdd:wN,subgroupInclusiveMul:DN,subgroupIndex:ob,subgroupMax:NN,subgroupMin:MN,subgroupMul:EN,subgroupOr:AN,subgroupShuffle:VN,subgroupShuffleDown:WN,subgroupShuffleUp:UN,subgroupShuffleXor:HN,subgroupSize:$M,subgroupXor:jN,tan:Sv,tangentGeometry:sC,tangentLocal:cC,tangentView:lC,tangentViewFrame:aC,tangentWorld:uC,tanh:Cv,texture:Vb,texture3D:Hj,texture3DLevel:Wj,texture3DLoad:Uj,textureBarrier:iN,textureBicubic:rD,textureBicubicLevel:nD,textureLevel:Wb,textureLoad:Ub,textureSize:Pb,textureStore:Lj,thickness:a_,time:AA,toneMapping:Yy,toneMappingExposure:Xy,toonOutlinePass:yM,transformDirection:ny,transformNormal:wS,transformNormalByInverseViewMatrix:iy,transformNormalByViewMatrix:ry,transformNormalToView:TS,transformedClearcoatNormalView:OS,transformedNormalView:ES,transformedNormalWorld:DS,transmission:i_,transpose:Vv,triNoise3D:EA,triplanarTexture:UA,triplanarTextures:HA,trunc:zv,uint:G,uintBitsToFloat:Rk,uniform:v_,uniformArray:Zb,uniformCubeTexture:VS,uniformFlow:Cy,uniformGroup:f_,uniformTexture:Hb,unpack4xI8:gA,unpack4xU8:_A,unpackHalf2x16:xA,unpackNormal:SC,unpackRGBToNormal:xC,unpackSnorm2x16:yA,unpackSnorm4x8:SA,unpackUnorm2x16:bA,unpackUnorm4x8:CA,unpremultiplyAlpha:Cb,userData:Kj,uv:Mb,uvec2:hg,uvec3:vg,uvec4:Sg,varying:Ny,varyingProperty:Mg,vec2:pg,vec3:K,vec4:bg,vectorComponents:ch,velocity:Yj,vertexColor:BT,vertexIndex:ib,vertexStage:Py,vibrance:rM,viewZToLogarithmicDepth:TT,viewZToOrthographicDepth:yT,viewZToPerspectiveDepth:ST,viewZToReversedOrthographicDepth:bT,viewZToReversedPerspectiveDepth:CT,viewport:sx,viewportCoordinate:lx,viewportDepthTexture:_T,viewportLinearDepth:AT,viewportMipTexture:fT,viewportOpaqueMipTexture:mT,viewportSafeUV:BA,viewportSharedTexture:uM,viewportSize:cx,viewportTexture:dT,viewportUV:ux,vogelDiskSample:Sj,wgsl:NM,wgslFn:RM,workgroupArray:sN,workgroupBarrier:nN,workgroupId:XM,workingToColorSpace:By,xor:V_}),DI=new _k,OI=class extends YO{constructor(e,t){super(),this.renderer=e,this.nodes=t}update(e,t,n){let r=this.renderer,i=this.nodes.getBackgroundNode(e)||e.background,a=!1;if(i===null)r._clearColor.getRGB(DI),DI.a=r._clearColor.a;else if(i.isColor===!0)i.getRGB(DI),DI.a=1,a=!0;else if(i.isNode===!0){let n=this.get(e),a=i;DI.copy(r._clearColor);let o=n.backgroundMesh;if(o===void 0){let e=bg(a).mul(Nj).context({getUV:()=>Pj.mul(bS),getTextureLevel:()=>Mj}),t=Ox.element(3).element(3).equal(1),r=A_(1,Ox.element(1).element(1)).mul(3),s=t.select(aS.mul(r),aS),c=$x.mul(bg(s,0)),l=Ox.mul(bg(c.xyz,1));l=l.setZ(l.w);let u=new VT;u.name=`Background.material`,u.side=1,u.depthTest=!1,u.depthWrite=!1,u.allowOverride=!1,u.fog=!1,u.lights=!1,u.vertexNode=l,u.colorNode=e,n.backgroundMeshNode=e,n.backgroundMesh=o=new z(new xl(1,32,32),u),o.frustumCulled=!1,o.name=`Background.mesh`;function d(){i.removeEventListener(`dispose`,d),o.material.dispose(),o.geometry.dispose()}i.addEventListener(`dispose`,d)}let s=a.getCacheKey();n.backgroundCacheKey!==s&&(n.backgroundMeshNode.node=bg(a).mul(Nj),n.backgroundMeshNode.needsUpdate=!0,o.material.needsUpdate=!0,n.backgroundCacheKey=s),t.unshift(o,o.geometry,o.material,0,0,null,null)}else p(`Renderer: Unsupported background configuration.`,i);let o=r.xr.getEnvironmentBlendMode();if(o===`additive`?DI.set(0,0,0,1):o===`alpha-blend`&&DI.set(0,0,0,0),r.autoClear===!0||a===!0){let e=n.clearColorValue;e.r=DI.r,e.g=DI.g,e.b=DI.b,e.a=DI.a,(r.backend.isWebGLBackend===!0||r.alpha===!0)&&(e.r*=e.a,e.g*=e.a,e.b*=e.a),n.depthClearValue=r.getClearDepth(),n.stencilClearValue=r.getClearStencil(),n.clearColor=r.autoClearColor===!0,n.clearDepth=r.autoClearDepth===!0,n.clearStencil=r.autoClearStencil===!0}else n.clearColor=!1,n.clearDepth=!1,n.clearStencil=!1}},kI=0,AI=class{constructor(e=``,t=[]){this.name=e,this.bindings=t,this.id=kI++}},jI=class{constructor(e,t,n,r,i,a,o,s,c,l,u=[]){this.vertexShader=e,this.fragmentShader=t,this.computeShader=n,this.transforms=u,this.nodeAttributes=r,this.bindings=i,this.updateNodes=a,this.updateBeforeNodes=o,this.updateAfterNodes=s,this.observer=c,this.hardwareClipping=l,this.usedTimes=0}createBindings(){let e=[];for(let t of this.bindings)if(t.bindings[0].groupNode.shared!==!0){let n=new AI(t.name,[]);e.push(n);for(let e of t.bindings)n.bindings.push(e.clone())}else e.push(t);return e}},MI=class{constructor(e,t,n=null){this.isNodeAttribute=!0,this.name=e,this.type=t,this.node=n}},NI=class{constructor(e,t,n){this.isNodeUniform=!0,this.name=e,this.type=t,this.node=n}get value(){return this.node.value}set value(e){this.node.value=e}get id(){return this.node.id}get groupNode(){return this.node.groupNode}},PI=class{constructor(e,t,n=!1,r=null){this.isNodeVar=!0,this.name=e,this.type=t,this.readOnly=n,this.count=r}},FI=class extends PI{constructor(e,t,n=null,r=null){super(e,t),this.needsInterpolation=!1,this.isNodeVarying=!0,this.interpolationType=n,this.interpolationSampling=r}},II=class{constructor(e,t,n=``){this.name=e,this.type=t,this.code=n,Object.defineProperty(this,"isNodeCode",{value:!0})}},LI=0,RI=class{constructor(e=null){this.id=LI++,this.nodesData=new WeakMap,this.parent=e}getData(e){let t=this.nodesData.get(e);return t===void 0&&this.parent!==null&&(t=this.parent.getData(e)),t}setData(e,t){this.nodesData.set(e,t)}},zI=class{constructor(e,t){this.name=e,this.members=t,this.output=!1}},BI=class{constructor(e,t){this.name=e,this.value=t,this.boundary=0,this.itemSize=0,this.offset=0,this.index=-1}setValue(e){this.value=e}getValue(){return this.value}},VI=class extends BI{constructor(e,t=0){super(e,t),this.isNumberUniform=!0,this.boundary=4,this.itemSize=1}},HI=class extends BI{constructor(e,t=new N){super(e,t),this.isVector2Uniform=!0,this.boundary=8,this.itemSize=2}},UI=class extends BI{constructor(e,t=new P){super(e,t),this.isVector3Uniform=!0,this.boundary=16,this.itemSize=3}},WI=class extends BI{constructor(e,t=new Mi){super(e,t),this.isVector4Uniform=!0,this.boundary=16,this.itemSize=4}},GI=class extends BI{constructor(e,t=new L){super(e,t),this.isColorUniform=!0,this.boundary=16,this.itemSize=3}},KI=class extends BI{constructor(e,t=new ef){super(e,t),this.isMatrix2Uniform=!0,this.boundary=8,this.itemSize=4}},qI=class extends BI{constructor(e,t=new yi){super(e,t),this.isMatrix3Uniform=!0,this.boundary=48,this.itemSize=12}},JI=class extends BI{constructor(e,t=new F){super(e,t),this.isMatrix4Uniform=!0,this.boundary=64,this.itemSize=16}},YI=class extends VI{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}},XI=class extends HI{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}},ZI=class extends UI{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}},QI=class extends WI{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}},$I=class extends GI{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}},eL=class extends KI{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}},tL=class extends qI{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}},nL=class extends JI{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}},rL=0,iL=new WeakMap,aL=new WeakMap,oL=new WeakMap,sL=new Map([[Int8Array,`int`],[Int16Array,`int`],[Int32Array,`int`],[Uint8Array,`uint`],[Uint16Array,`uint`],[Uint32Array,`uint`],[Float32Array,`float`]]),cL=e=>/e/g.test(e)?String(e).replace(/\+/g,``):(e=Number(e),e+(e%1?``:`.0`)),lL=e=>{if(e.writeUsageCount>0)return!0;if(e.subBuildsCache!==void 0){for(let t in e.subBuildsCache)if(lL(e.subBuildsCache[t]))return!0}return!1},uL=class{constructor(e,t,n){this.object=e,this.material=e&&e.material||null,this.geometry=e&&e.geometry||null,this.compute=null,this.renderer=t,this.parser=n,this.scene=null,this.camera=null,this.nodes=new Set,this.sequentialNodes=new Set,this.updateNodes=[],this.updateBeforeNodes=[],this.updateAfterNodes=[],this.hashNodes={},this.observer=null,this.lightsNode=null,this.environmentNode=null,this.fogNode=null,this.clippingContext=null,this.hardwareClipping=!1,this.vertexShader=null,this.fragmentShader=null,this.computeShader=null,this.flowNodes={vertex:[],fragment:[],compute:[]},this.flowCode={vertex:``,fragment:``,compute:``},this.uniforms={vertex:[],fragment:[],compute:[],index:0},this.structs={vertex:[],fragment:[],compute:[],index:0},this.types={vertex:[],fragment:[],compute:[],index:0},this.bindings={vertex:{},fragment:{},compute:{}},this.bindingsIndexes={},this.bindGroups=null,this.attributes=[],this.bufferAttributes=[],this.varyings=[],this.codes={},this.vars={},this.declarations={},this.flow={code:``},this.chaining=[],this.stack=Sk(),this.stacks=[],this.tab=` `,this.currentFunctionNode=null,this.context={material:this.material},this.cache=new RI,this.globalCache=this.cache,this.flowsData=new WeakMap,this.shaderStage=null,this.buildStage=null,this.subBuildLayers=[],this.activeStacks=[],this.subBuildFn=null,this.fnCall=null,Object.defineProperty(this,"id",{value:rL++})}isFlatShading(){return this.material.flatShading===!0||this.geometry.hasAttribute(`normal`)===!1}isOpaque(){let e=this.material;return e.transparent===!1&&e.blending===1&&e.alphaToCoverage===!1}createRenderTarget(e,t,n){return new Ni(e,t,n)}createCubeRenderTarget(e,t){return new oE(e,t)}includes(e){return this.nodes.has(e)}getOutputType(e=0){let t=this.renderer.getRenderTarget();return t===null?`vec4`:ep(t.textures[e])}getOutputStructName(){}_getBindGroup(e,t){let n=t[0].groupNode,r=n.shared;if(r)for(let e=1;ee.nodeUniform.node.id-t.nodeUniform.node.id);for(let t of e.uniforms)n+=t.nodeUniform.node.id}else n+=e.nodeUniform.id;let r=this.renderer._currentRenderContext||this.renderer,a=iL.get(r);a===void 0&&(a=new Map,iL.set(r,a));let o=Ym(n);i=a.get(o),i===void 0&&(i=new AI(e,t),a.set(o,i))}else i=new AI(e,t);return i}getBindGroupArray(e,t){let n=this.bindings[t],r=n[e];return r===void 0&&(this.bindingsIndexes[e]===void 0&&(this.bindingsIndexes[e]={binding:0,group:Object.keys(this.bindingsIndexes).length}),n[e]=r=[]),r}getBindings(){let e=this.bindGroups;if(e===null){let t={},n=this.bindings;for(let e of sh)for(let r in n[e]){let i=n[e][r],a=t[r]||(t[r]=[]);for(let e of i)a.includes(e)===!1&&a.push(e)}e=[];for(let n in t){let r=t[n],i=this._getBindGroup(n,r);e.push(i)}this.bindGroups=e}return e}sortBindingGroups(){let e=this.getBindings();e.sort((e,t)=>e.bindings[0].groupNode.order-t.bindings[0].groupNode.order);for(let t=0;t=0?`${Math.round(t)}u`:`0u`;if(e===`bool`)return t?`true`:`false`;if(e===`color`)return`${this.getType(`vec3`)}( ${cL(t.r)}, ${cL(t.g)}, ${cL(t.b)} )`;let n=this.getTypeLength(e),r=this.getComponentType(e),i=e=>this.generateConst(r,e);if(n===2)return`${this.getType(e)}( ${i(t.x)}, ${i(t.y)} )`;if(n===3)return`${this.getType(e)}( ${i(t.x)}, ${i(t.y)}, ${i(t.z)} )`;if(n===4&&e!==`mat2`)return`${this.getType(e)}( ${i(t.x)}, ${i(t.y)}, ${i(t.z)}, ${i(t.w)} )`;if(n>=4&&t&&(t.isMatrix2||t.isMatrix3||t.isMatrix4))return`${this.getType(e)}( ${t.elements.map(i).join(`, `)} )`;if(n>4)return`${this.getType(e)}()`;throw Error(`THREE.NodeBuilder: Type '${e}' not found in generate constant attempt.`)}getType(e){return e===`color`?`vec3`:e}hasGeometryAttribute(e){return this.geometry&&this.geometry.getAttribute(e)!==void 0}getAttribute(e,t){let n=this.attributes;for(let t of n)if(t.name===e)return t;let r=new MI(e,t);return this.registerDeclaration(r),n.push(r),r}getPropertyName(e){return e.name}isReservedKeyword(){return!1}isVector(e){return/vec\d/.test(e)}isMatrix(e){return/mat\d/.test(e)}isReference(e){return e===`void`||e===`property`||e===`sampler`||e===`samplerComparison`||e===`texture`||e===`cubeTexture`||e===`storageTexture`||e===`depthTexture`||e===`texture3D`}needsToWorkingColorSpace(){return!1}getComponentTypeFromTexture(e){let t=e.type;return e.isDepthTexture===!0?`float`:t===1013?`int`:t===1014?`uint`:`float`}getElementType(e){return e===`mat2`?`vec2`:e===`mat3`?`vec3`:e===`mat4`?`vec4`:this.getComponentType(e)}getComponentType(e){if(e=this.getVectorType(e),e===`float`||e===`bool`||e===`int`||e===`uint`)return e;let t=/(b|i|u|)(vec|mat)([2-4])/.exec(e);return t===null?null:t[1]===`b`?`bool`:t[1]===`i`?`int`:t[1]===`u`?`uint`:`float`}getVectorType(e){return e===`color`?`vec3`:e===`texture`||e===`cubeTexture`||e===`storageTexture`||e===`texture3D`?`vec4`:e}getTypeFromLength(e,t=`float`){if(e===1)return t;let n=Jf(e),r=t===`float`?``:t[0];return/mat2/.test(t)===!0&&(n=n.replace(`vec`,`mat`)),r+n}getTypeFromArray(e){return sL.get(e.constructor)}isInteger(e){return/int|uint|(i|u)vec/.test(e)}getTypeFromAttribute(e){let t=e;e.isInterleavedBufferAttribute&&(t=e.data);let n=t.array,r=e.itemSize,i=e.normalized,a;return!(e instanceof co)&&i!==!0&&(a=this.getTypeFromArray(n)),this.getTypeFromLength(r,a)}getTypeLength(e){let t=this.getVectorType(e),n=/vec([2-4])/.exec(t);return n===null?t===`float`||t===`bool`||t===`int`||t===`uint`?1:/mat2/.test(e)===!0?4:/mat3/.test(e)===!0?9:/mat4/.test(e)===!0?16:0:Number(n[1])}getVectorFromMatrix(e){return e.replace(`mat`,`vec`)}changeComponentType(e,t){return this.getTypeFromLength(this.getTypeLength(e),t)}getIntegerType(e){let t=this.getComponentType(e);return t===`int`||t===`uint`?e:this.changeComponentType(e,`int`)}setActiveStack(e){this.activeStacks.push(e)}removeActiveStack(e){if(this.activeStacks[this.activeStacks.length-1]===e)this.activeStacks.pop();else throw Error(`THREE.NodeBuilder: Invalid active stack removal.`)}getActiveStack(){return this.activeStacks[this.activeStacks.length-1]}getBaseStack(){return this.activeStacks[0]}addStack(){this.stack=Sk(this.stack);let e=cg();return this.stacks.push(e),sg(this.stack),this.stack}removeStack(){let e=this.stack;for(let t of e.nodes){let n=this.getDataFromNode(t);n.stack=e}return this.stack=e.parent,sg(this.stacks.pop()),e}getDataFromNode(e,t=this.shaderStage,n=null){n=n===null?e.isGlobal(this)?this.globalCache:this.cache:n;let r=n.getData(e);r===void 0&&(r={},n.setData(e,r)),r[t]===void 0&&(r[t]={});let i=r[t];if(this.subBuildLayers.length===0)return i;let a=r.any?r.any.subBuilds:null,o=this.getClosestSubBuild(a);return o&&(i.subBuildsCache===void 0&&(i.subBuildsCache={}),i=i.subBuildsCache[o]||(i.subBuildsCache[o]={}),i.subBuilds=a),i}getNodeProperties(e,t=`any`){let n=this.getDataFromNode(e,t);return n.properties||={outputNode:null}}getBufferAttributeFromNode(e,t,n=null){let r=this.getDataFromNode(e,`vertex`),i=r.bufferAttribute;if(i===void 0){let a=this.uniforms.index++;n===null&&(n=`nodeAttribute`+a),i=new MI(n,t,e),this.bufferAttributes.push(i),r.bufferAttribute=i}return i}getStructTypeNode(e,t=this.shaderStage){return this.types[t][e]||null}getStructTypeFromNode(e,t,n=null,r=this.shaderStage){let i=this.getDataFromNode(e,r,this.globalCache),a=i.structType;if(a===void 0){let o=this.structs.index++;n===null&&(n=`StructType`+o),a=new zI(n,t),this.structs[r].push(a),this.types[r][n]=e,i.structType=a}return a}getOutputStructTypeFromNode(e,t){let n=this.getStructTypeFromNode(e,t,`OutputType`,`fragment`);return n.output=!0,n}getUniformFromNode(e,t,n=this.shaderStage,r=null){let i=this.getDataFromNode(e,n,this.globalCache),a=i.uniform;if(a===void 0){let o=this.uniforms.index++;a=new NI(r||`nodeUniform`+o,t,e),this.uniforms[n].push(a),this.registerDeclaration(a),i.uniform=a}return a}getVarFromNode(e,t=null,n=e.getNodeType(this),r=this.shaderStage,i=!1){let a=this.getDataFromNode(e,r),o=this.getSubBuildProperty(`variable`,a.subBuilds),s=a[o];if(s===void 0){let c=i?`_const`:`_var`,l=this.vars[r]||(this.vars[r]=[]),u=this.vars[c]||(this.vars[c]=0);t===null&&(t=(i?`nodeConst`:`nodeVar`)+u,this.vars[c]++),o!==`variable`&&(t=this.getSubBuildProperty(t,a.subBuilds));let d=e.getArrayCount(this);s=new PI(t,n,i,d),i||l.push(s),this.registerDeclaration(s),a[o]=s}return s}isDeterministic(e){if(e.isMathNode)return this.isDeterministic(e.aNode)&&(!e.bNode||this.isDeterministic(e.bNode))&&(!e.cNode||this.isDeterministic(e.cNode));if(e.isOperatorNode)return this.isDeterministic(e.aNode)&&(!e.bNode||this.isDeterministic(e.bNode));if(e.isArrayNode){if(e.values!==null){for(let t of e.values)if(!this.isDeterministic(t))return!1}return!0}return!!e.isConstNode}getVaryingFromNode(e,t=null,n=e.getNodeType(this),r=null,i=null){let a=this.getDataFromNode(e,`any`),o=this.getSubBuildProperty(`varying`,a.subBuilds),s=a[o];if(s===void 0){let e=this.varyings,c=e.length;t===null&&(t=`nodeVarying`+c),o!==`varying`&&(t=this.getSubBuildProperty(t,a.subBuilds)),s=new FI(t,n,r,i),e.push(s),this.registerDeclaration(s),a[o]=s}return s}registerDeclaration(e){let t=this.shaderStage,n=this.declarations[t]||(this.declarations[t]={}),r=this.renderer.debug.diagnostics.keywords,i=e.name,a=i,o=this.getPropertyName(e),s=1;for(;r&&this.isReservedKeyword(a)||n[o]!==void 0;)a=i+`_`+s++,e.name=a,o=this.getPropertyName(e);a!==i&&f(`TSL: Declaration name '${i}' of '${e.type}' is a reserved keyword or already in use. Renamed to '${a}'.`),n[o]=e}getCodeFromNode(e,t,n=this.shaderStage){let r=this.getDataFromNode(e),i=r.code;if(i===void 0){let e=this.codes[n]||(this.codes[n]=[]),a=e.length;i=new II(`nodeCode`+a,t),e.push(i),r.code=i}return i}addFlowCodeHierarchy(e,t){let{flowCodes:n,flowCodeBlock:r}=this.getDataFromNode(e),i=!0,a=t;for(;a;){if(r.get(a)===!0){i=!1;break}a=this.getDataFromNode(a).parentNodeBlock}if(i)for(let e of n)this.addLineFlowCode(e)}addLineFlowCodeBlock(e,t,n){let r=this.getDataFromNode(e),i=r.flowCodes||=[],a=r.flowCodeBlock||=new WeakMap;i.push(t),a.set(n,!0)}addLineFlowCode(e,t=null){return e===``?this:(t!==null&&this.context.nodeBlock&&this.addLineFlowCodeBlock(t,e,this.context.nodeBlock),e=this.tab+e,/;\s*$/.test(e)||(e+=`; `),this.flow.code+=e,this)}addFlowCode(e){return this.flow.code+=e,this}addFlowTab(){return this.tab+=` `,this}removeFlowTab(){return this.tab=this.tab.slice(0,-1),this}getFlowData(e){return this.flowsData.get(e)}flowNode(e){let t=e.getNodeType(this),n=this.flowChildNode(e,t);return this.flowsData.set(e,n),n}addInclude(e){this.currentFunctionNode!==null&&this.currentFunctionNode.includes.push(e)}buildFunctionNode(e){let t=this.renderer.backend,n=aL.get(t);n===void 0&&(n=new WeakMap,aL.set(t,n));let r=n.get(e);if(r===void 0){r=new FM;let t=this.currentFunctionNode;this.currentFunctionNode=r,r.code=this.buildFunctionCode(e),this.currentFunctionNode=t,n.set(e,r)}return r}flowShaderNode(e){let t=e.layout,n={[Symbol.iterator](){let e=0,t=Object.values(this);return{next:()=>({value:t[e],done:e++>=t.length})}}};for(let e of t.inputs)n[e.name]=new yk(e.type,e.name);e.layout=null;let r=e.call(n),i=this.flowStagesNode(r,t.type);return e.layout=t,i}flowBuildStage(e,t,n=null){let r=this.getBuildStage();this.setBuildStage(t);let i=e.build(this,n);return this.setBuildStage(r),i}flowStagesNode(e,t=null){let n=this.flow,r=this.vars,i=this.declarations,a=this.cache,o=this.buildStage,s=this.stack,c={code:``};this.flow=c,this.vars={},this.declarations={},this.cache=new RI,this.stack=Sk();for(let n of oh)this.setBuildStage(n),c.result=e.build(this,t);return c.vars=this.getVars(this.shaderStage),this.flow=n,this.vars=r,this.declarations=i,this.cache=a,this.stack=s,this.setBuildStage(o),c}getFunctionOperator(){return null}buildFunctionCode(){f(`Abstract function.`)}flowChildNode(e,t=null){let n=this.flow,r={code:``};return this.flow=r,r.result=e.build(this,t),this.flow=n,r}flowNodeFromShaderStage(e,t,n=null,r=null){let i=this.tab,a=this.cache,o=this.shaderStage,s=this.context;this.setShaderStage(e);let c={...this.context};delete c.nodeBlock,this.cache=this.globalCache,this.tab=` `,this.context=c;let l=null;if(this.buildStage===`generate`){let i=this.flowChildNode(t,n);r!==null&&(i.code+=`${this.tab+r} = ${i.result};\n`),this.flowCode[e]=this.flowCode[e]+i.code,l=i}else l=t.build(this);return this.setShaderStage(o),this.cache=a,this.tab=i,this.context=s,l}getAttributesArray(){return this.attributes.concat(this.bufferAttributes)}getAttributes(){f(`Abstract function.`)}getVaryings(){f(`Abstract function.`)}getVar(e,t,n=null){return`${n===null?this.getType(e):this.generateArrayDeclaration(e,n)} ${t}`}getVars(e,t=!1){let n=[],r=this.vars[e];if(r!==void 0)for(let e of r)n.push(`${this.getVar(e.type,e.name,e.count)};`);return n.join(t?` `:` `)}getUniforms(){f(`Abstract function.`)}getCodes(e){let t=this.codes[e],n=``;if(t!==void 0)for(let e of t)n+=e.code+` `;return n}getHash(){return this.vertexShader+this.fragmentShader+this.computeShader}setShaderStage(e){this.shaderStage=e}getShaderStage(){return this.shaderStage}setBuildStage(e){this.buildStage=e}getBuildStage(){return this.buildStage}buildCode(){f(`Abstract function.`)}get subBuild(){return this.subBuildLayers[this.subBuildLayers.length-1]||null}addSubBuild(e){this.subBuildLayers.push(e)}removeSubBuild(){return this.subBuildLayers.pop()}getClosestSubBuild(e){let t;if(t=e&&e.isNode?e.isShaderCallNodeInternal?e.shaderNode.subBuilds:e.isStackNode?[e.subBuild]:this.getDataFromNode(e,`any`).subBuilds:e instanceof Set?[...e]:e,!t)return null;let n=this.subBuildLayers;for(let e=t.length-1;e>=0;e--){let r=t[e];if(n.includes(r))return r}return null}getSubBuildOutput(e){return this.getSubBuildProperty(`outputNode`,e)}getSubBuildProperty(e=``,t=null){let n;n=t===null?this.subBuildFn:this.getClosestSubBuild(t);let r;return r=n?e?n+`_`+e:n:e,r}prebuild(){let{renderer:e,material:t}=this;if(e.contextNode.isContextNode===!0?this.context={...this.context,...e.contextNode.getFlowContextData()}:p('NodeBuilder: "renderer.contextNode" must be an instance of `context()`.'),t&&t.contextNode&&(t.contextNode.isContextNode===!0?this.context={...this.context,...t.contextNode.getFlowContextData()}:p('NodeBuilder: "material.contextNode" must be an instance of `context()`.')),t!==null){let n=e.library.fromMaterial(t);n===null&&(p(`NodeBuilder: Material "${t.type}" is not compatible.`),n=new VT),n.build(this)}else this.addFlow(`compute`,this.compute)}build(){this.prebuild();for(let e of oh){this.setBuildStage(e),this.context.position&&this.context.position.isNode&&this.flowNodeFromShaderStage(`vertex`,this.context.position);for(let t of sh){this.setShaderStage(t);let n=this.flowNodes[t];for(let t of n)e===`generate`?this.flowNode(t):t.build(this)}}return this.setBuildStage(null),this.setShaderStage(null),this.buildCode(),this.buildUpdateNodes(),this}async buildAsync(){this.prebuild();for(let e of oh){this.setBuildStage(e),this.context.position&&this.context.position.isNode&&this.flowNodeFromShaderStage(`vertex`,this.context.position);for(let t of sh){this.setShaderStage(t);let n=this.flowNodes[t];for(let t of n)e===`generate`?this.flowNode(t):t.build(this);await h()}}return this.setBuildStage(null),this.setShaderStage(null),this.buildCode(),this.buildUpdateNodes(),this}getSharedDataFromNode(e){let t=oL.get(e);return t===void 0&&(t={}),t}getNodeUniform(e,t){let n=this.getSharedDataFromNode(e),r=n.cache;if(r===void 0){if(t===`float`||t===`int`||t===`uint`)r=new YI(e);else if(t===`vec2`||t===`ivec2`||t===`uvec2`)r=new XI(e);else if(t===`vec3`||t===`ivec3`||t===`uvec3`)r=new ZI(e);else if(t===`vec4`||t===`ivec4`||t===`uvec4`)r=new QI(e);else if(t===`color`)r=new $I(e);else if(t===`mat2`)r=new eL(e);else if(t===`mat3`)r=new tL(e);else if(t===`mat4`)r=new nL(e);else throw Error(`THREE.NodeBuilder: Uniform "${t}" not implemented.`);n.cache=r}return r}format(e,t,n){if(t=this.getVectorType(t),n=this.getVectorType(n),t===n||n===null||this.isReference(n))return e;let r=this.getTypeLength(t),i=this.getTypeLength(n);return r===16&&i===9?`${this.getType(n)}( ${e}[ 0 ].xyz, ${e}[ 1 ].xyz, ${e}[ 2 ].xyz )`:r===9&&i===4?`${this.getType(n)}( ${e}[ 0 ].xy, ${e}[ 1 ].xy )`:r>4||i>4||i===0?e:r===i?`${this.getType(n)}( ${e} )`:r>i?(e=n===`bool`?`all( ${e} )`:`${e}.${`xyz`.slice(0,i)}`,this.format(e,this.getTypeFromLength(i,this.getComponentType(t)),n)):i===4&&r>1?`${this.getType(n)}( ${this.format(e,t,`vec3`)}, 1.0 )`:r===2?`${this.getType(n)}( ${this.format(e,t,`vec2`)}, 0.0 )`:(r===1&&i>1&&t!==this.getComponentType(n)&&(e=`${this.getType(this.getComponentType(n))}( ${e} )`),`${this.getType(n)}( ${e} )`)}getSignature(){return`// Three.js r186 - Node System `}needsPreviousData(){let e=this.renderer.getMRT();return e&&e.has(`velocity`)||this.object!==null&&np(this.object).useVelocity===!0}},dL=class{constructor(){this.time=0,this.deltaTime=0,this.frameId=0,this.renderId=0,this.updateMap=new WeakMap,this.updateBeforeMap=new WeakMap,this.updateAfterMap=new WeakMap,this.renderer=null,this.material=null,this.camera=null,this.object=null,this.scene=null,this.compute=null}_getMaps(e,t){let n=e.get(t);return n===void 0&&(n={renderId:0,frameId:0},e.set(t,n)),n}updateBeforeNode(e){let t=e.getUpdateBeforeType(this),n=e.updateReference(this);if(t===nh.FRAME){let t=this._getMaps(this.updateBeforeMap,n);if(t.frameId!==this.frameId){let n=t.frameId;t.frameId=this.frameId,e.updateBefore(this)===!1&&(t.frameId=n)}}else if(t===nh.RENDER){let t=this._getMaps(this.updateBeforeMap,n);if(t.renderId!==this.renderId){let n=t.renderId;t.renderId=this.renderId,e.updateBefore(this)===!1&&(t.renderId=n)}}else t===nh.OBJECT&&e.updateBefore(this)}updateAfterNode(e){let t=e.getUpdateAfterType(this),n=e.updateReference(this);if(t===nh.FRAME){let t=this._getMaps(this.updateAfterMap,n);t.frameId!==this.frameId&&e.updateAfter(this)!==!1&&(t.frameId=this.frameId)}else if(t===nh.RENDER){let t=this._getMaps(this.updateAfterMap,n);t.renderId!==this.renderId&&e.updateAfter(this)!==!1&&(t.renderId=this.renderId)}else t===nh.OBJECT&&e.updateAfter(this)}updateNode(e){let t=e.getUpdateType(this),n=e.updateReference(this);if(t===nh.FRAME){let t=this._getMaps(this.updateMap,n);t.frameId!==this.frameId&&e.update(this)!==!1&&(t.frameId=this.frameId)}else if(t===nh.RENDER){let t=this._getMaps(this.updateMap,n);t.renderId!==this.renderId&&e.update(this)!==!1&&(t.renderId=this.renderId)}else t===nh.OBJECT&&e.update(this)}update(){this.frameId++,this.lastTime===void 0&&(this.lastTime=performance.now()),this.deltaTime=(performance.now()-this.lastTime)/1e3,this.lastTime=performance.now(),this.time+=this.deltaTime}},fL=class{constructor(e,t,n=null,r=``,i=!1){this.type=e,this.name=t,this.count=n,this.qualifier=r,this.isConst=i}},fL.isNodeFunctionInput=!0,pL=class extends PP{static get type(){return`AmbientLightNode`}constructor(e=null){super(e)}setup({context:e}){e.irradiance.addAssign(this.colorNode)}},mL=class extends PP{static get type(){return`DirectionalLightNode`}constructor(e=null){super(e)}setupDirect(){let e=this.colorNode;return{lightDirection:qN(this.light),lightColor:e}}},hL=class extends PP{static get type(){return`HemisphereLightNode`}constructor(e=null){super(e),this.lightPositionNode=Cm(e),this.lightDirectionNode=this.lightPositionNode.normalize(),this.groundColorNode=v_(new L).setGroup(h_)}update(e){let{light:t}=this;super.update(e),this.lightPositionNode.object3d=t,this.groundColorNode.value.copy(t.groundColor).multiplyScalar(t.intensity)}setup(e){let{colorNode:t,groundColorNode:n,lightDirectionNode:r}=this,i=SS.dot(r).mul(.5).add(.5),a=sy(n,t,i);e.context.irradiance.addAssign(a)}},gL=class extends PP{static get type(){return`SpotLightNode`}constructor(e=null){super(e),this.coneCosNode=v_(0).setGroup(h_),this.penumbraCosNode=v_(0).setGroup(h_),this.cutoffDistanceNode=v_(0).setGroup(h_),this.decayExponentNode=v_(0).setGroup(h_),this.colorNode=v_(this.color).setGroup(h_)}update(e){super.update(e);let{light:t}=this;this.coneCosNode.value=Math.cos(t.angle),this.penumbraCosNode.value=Math.cos(t.angle*(1-t.penumbra)),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}getSpotAttenuation(e,t){let{coneCosNode:n,penumbraCosNode:r}=this;return dy(n,r,t)}getLightCoord(e){let t=e.getNodeProperties(this),n=t.projectionUV;return n===void 0&&(n=Sm(this.light,e.context.positionWorld),t.projectionUV=n),n}setupDirect(e){let{colorNode:t,cutoffDistanceNode:n,decayExponentNode:r,light:i}=this,a=this.getLightVector(e),o=a.normalize(),s=o.dot(qN(i)),c=this.getSpotAttenuation(e,s),l=a.length(),u=FP({lightDistance:l,cutoffDistance:n,decayExponent:r}),d=t.mul(c).mul(u),f,p;return i.colorNode?(p=this.getLightCoord(e),f=i.colorNode(p)):i.map&&(p=this.getLightCoord(e),f=Vb(i.map,p.xy).onRenderUpdate(()=>i.map)),f&&(d=p.mul(2).sub(1).abs().lessThan(1).all().select(d.mul(f),d)),{lightColor:d,lightDirection:o}}},_L=class extends gL{static get type(){return`IESSpotLightNode`}constructor(e=null){super(e),this._iesTextureNode=null}getSpotAttenuation(e,t){let n=this.light.iesMap,r=null;if(n&&n.isTexture===!0){let e=t.acos().mul(1/Math.PI);this._iesTextureNode=Vb(n,pg(e,0),0),r=this._iesTextureNode.r}else r=super.getSpotAttenuation(e,t);return r}update(e){super.update(e),this._iesTextureNode!==null&&this.light.iesMap&&(this._iesTextureNode.value=this.light.iesMap)}},vL=class extends PP{static get type(){return`LightProbeNode`}constructor(e=null){super(e);let t=[];for(let e=0;e<9;e++)t.push(new P);this.lightProbe=Zb(t)}update(e){let{light:t}=this;super.update(e);for(let e=0;e<9;e++)this.lightProbe.array[e].copy(t.sh.coefficients[e]).multiplyScalar(t.intensity)}setup(e){let t=EI(SS,this.lightProbe);e.context.irradiance.addAssign(t)}},yL=V(([e,t])=>{let n=e.abs().sub(t);return Mv(Gv(n,0)).add(Wv(Gv(n.x,n.y),0))}),bL=class extends gL{static get type(){return`ProjectorLightNode`}update(e){super.update(e);let t=this.light;if(this.penumbraCosNode.value=Math.min(Math.cos(t.angle*(1-t.penumbra)),.99999),t.aspect===null){let e=1;t.map!==null&&(e=t.map.width/t.map.height),t.shadow.aspect=e}else t.shadow.aspect=t.aspect}getSpotAttenuation(e){let t=U(0),n=this.penumbraCosNode,r=xm(this.light).mul(e.context.positionWorld||sS);return lg(r.w.greaterThan(0),()=>{let e=r.xyz.div(r.w),i=yL(e.xy.sub(pg(.5)),pg(.5)),a=A_(-1,O_(1,Ev(n)).sub(1));t.assign(ly(i.mul(-2).mul(a)))}),t}},xL=new F,SL=new F,CL=null,wL=class extends PP{static get type(){return`RectAreaLightNode`}constructor(e=null){super(e),this.halfHeight=v_(new P).setGroup(h_),this.halfWidth=v_(new P).setGroup(h_),this.updateType=nh.RENDER}update(e){super.update(e);let{light:t}=this,n=e.camera.matrixWorldInverse;SL.identity(),xL.copy(t.matrixWorld),xL.premultiply(n),SL.extractRotation(xL),this.halfWidth.value.set(t.width*.5,0,0),this.halfHeight.value.set(0,t.height*.5,0),this.halfWidth.value.applyMatrix4(SL),this.halfHeight.value.applyMatrix4(SL)}setupDirectRectArea(e){let t,n;e.isAvailable(`float32Filterable`)?(t=Vb(CL.LTC_FLOAT_1),n=Vb(CL.LTC_FLOAT_2)):(t=Vb(CL.LTC_HALF_1),n=Vb(CL.LTC_HALF_2));let{colorNode:r,light:i}=this;return{lightColor:r,lightPosition:Tm(i),halfWidth:this.halfWidth,halfHeight:this.halfHeight,ltc_1:t,ltc_2:n}}static setLTC(e){CL=e}},TL=class{parseFunction(){f(`Abstract function.`)}},EL=class{constructor(e,t,n=``,r=``){this.type=e,this.inputs=t,this.name=n,this.precision=r}getCode(){f(`Abstract function.`)}},EL.isNodeFunction=!0,DL=/^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i,OL=/[a-z_0-9]+/gi,kL=`#pragma main`,AL=e=>{e=e.trim();let t=e.indexOf(kL),n=(t===-1?e:e.slice(t+12)).replace(/^(?:\s*\/\/[^\r\n]*|\s*\/\*[\s\S]*?\*\/|\s*)+/,``),r=n.match(DL);if(r!==null&&r.length===5){let i=r[4],a=[],o=null;for(;(o=OL.exec(i))!==null;)a.push(o);let s=[],c=0;for(;c{let n=this._createNodeBuilder(e,e.material);try{t?await n.buildAsync():n.build()}catch(r){n=this._createNodeBuilder(e,new VT),t?await n.buildAsync():n.build(),p(`TSL: `+r)}return n};if(t)return o().then(e=>(r=this._createNodeBuilderState(e),i.set(a,r),r.usedTimes++,n.nodeBuilderState=r,r));{let t=this._createNodeBuilder(e,e.material);try{t.build()}catch(n){t=this._createNodeBuilder(e,new VT),t.build();let r=n.stackTrace;!r&&n.stack&&(r=new Jm(n.stack)),p(`TSL: `+n,r)}r=this._createNodeBuilderState(t),i.set(a,r)}}r.usedTimes++,n.nodeBuilderState=r}return r}getForRenderAsync(e){let t=this.getForRender(e,!0);return t.then?t:Promise.resolve(t)}getForRenderDeferred(e){let t=this.get(e);if(t.nodeBuilderState!==void 0)return t.nodeBuilderState;let n=this.getForRenderCacheKey(e),r=this.nodeBuilderCache.get(n);return r===void 0?(t.pendingBuild!==!0&&(t.pendingBuild=!0,this._buildQueue.push(()=>this.getForRenderAsync(e).then(()=>{t.pendingBuild=!1})),this._processBuildQueue()),null):(r.usedTimes++,t.nodeBuilderState=r,r)}_processBuildQueue(){this._buildInProgress||this._buildQueue.length===0||(this._buildInProgress=!0,this._buildQueue.shift()().then(()=>{this._buildInProgress=!1,this._processBuildQueue()}))}delete(e){if(e.isRenderObject){let t=this.get(e).nodeBuilderState;t!==void 0&&(t.usedTimes--,t.usedTimes===0&&this.nodeBuilderCache.delete(this.getForRenderCacheKey(e)))}return super.delete(e)}getForCompute(e,t=!1){let n=this.get(e),r=n.nodeBuilderState;if(r===void 0||n.version!==e.version){let i=this.backend.createNodeBuilder(null,this.renderer);i.compute=e;let a=this.renderer.debug.onNodeBuilderCreated;if(a!==null&&a(i,e),t)return i.buildAsync().then(()=>(r=this._createNodeBuilderState(i),n.nodeBuilderState=r,n.version=e.version,r));i.build(),r=this._createNodeBuilderState(i),n.nodeBuilderState=r,n.version=e.version}return r}getForComputeAsync(e){let t=this.getForCompute(e,!0);return t.then?t:Promise.resolve(t)}_createNodeBuilderState(e){return new jI(e.vertexShader,e.fragmentShader,e.computeShader,e.getAttributesArray(),e.getBindings(),e.updateNodes,e.updateBeforeNodes,e.updateAfterNodes,e.observer,e.hardwareClipping,e.transforms)}getEnvironmentNode(e){if(this.renderer.lighting.enabled===!1)return null;this.updateEnvironment(e);let t=null;if(e.environmentNode&&e.environmentNode.isNode)t=e.environmentNode;else{let n=this.get(e);n.environmentNode&&(t=n.environmentNode)}return t}getBackgroundNode(e){this.updateBackground(e);let t=null;if(e.backgroundNode&&e.backgroundNode.isNode)t=e.backgroundNode;else{let n=this.get(e);n.backgroundNode&&(t=n.backgroundNode)}return t}getFogNode(e){return this.updateFog(e),e.fogNode||this.get(e).fogNode||null}getCacheKey(e,t){NL[0]=e,NL[1]=t;let n=this.renderer.info.calls,r=this.callHashCache.get(NL)||{};if(r.callId!==n){if(PL.push(this.renderer.getOutputRenderTarget()&&this.renderer.getOutputRenderTarget().multiview?1:0),PL.push(+!!this.renderer.lighting.enabled),this.renderer.lighting.enabled){PL.push(t.getCacheKey(!0)),PL.push(+!!this.renderer.shadowMap.enabled),PL.push(this.renderer.shadowMap.type);let n=this.getEnvironmentNode(e);n&&PL.push(n.getCacheKey())}let i=this.getFogNode(e);i&&PL.push(i.getCacheKey()),r.callId=n,r.cacheKey=Xm(PL),this.callHashCache.set(NL,r),PL.length=0}return NL[0]=null,NL[1]=null,r.cacheKey}get isToneMappingState(){return!this.renderer.getRenderTarget()}updateBackground(e){let t=this.get(e),n=e.background;if(n){let r=e.backgroundBlurriness===0&&t.backgroundBlurriness>0||e.backgroundBlurriness>0&&t.backgroundBlurriness===0;(t.background!==n||r)&&(t.backgroundNode=this.getCacheNode(`background`,n,()=>{if(n.isCubeTexture===!0||n.mapping===303||n.mapping===304||n.mapping===306){if(e.backgroundBlurriness>0||n.mapping===306)return sO(n);{let e;return e=n.isCubeTexture===!0?BS(n):Vb(n),lE(e)}}if(n.isTexture===!0)return Vb(n,ix.flipY()).setUpdateMatrix(!0);n.isColor!==!0&&p(`WebGPUNodes: Unsupported background configuration.`,n)},r),t.background=n,t.backgroundBlurriness=e.backgroundBlurriness)}else t.backgroundNode&&(delete t.backgroundNode,delete t.background)}getCacheNode(e,t,n,r=!1){let i=this.cacheLib[e]||(this.cacheLib[e]=new WeakMap),a=i.get(t);if(a===void 0||r){if(a===void 0&&t.isTexture===!0){let e=()=>{t.removeEventListener(`dispose`,e);let n=i.get(t);n!==void 0&&(i.delete(t),n.dispose())};t.addEventListener(`dispose`,e)}a=n(),i.set(t,a)}return a}updateFog(e){let t=this.get(e),n=e.fog;n?t.fog!==n&&(t.fogNode=this.getCacheNode(`fog`,n,()=>{if(n.isFogExp2){let e=US(`color`,`color`,n).setGroup(h_),t=US(`density`,`float`,n).setGroup(h_);return HM(e,BM(t))}if(n.isFog){let e=US(`color`,`color`,n).setGroup(h_),t=US(`near`,`float`,n).setGroup(h_),r=US(`far`,`float`,n).setGroup(h_);return HM(e,zM(t,r))}p(`Renderer: Unsupported fog configuration.`,n)}),t.fog=n):(delete t.fogNode,delete t.fog)}updateEnvironment(e){let t=this.get(e),n=e.environment;n?t.environment!==n&&(t.environmentNode=this.getCacheNode(`environment`,n,()=>{if(n.isCubeTexture===!0)return BS(n);if(n.isTexture===!0)return Vb(n);p(`Nodes: Unsupported environment configuration.`,n)}),t.environment=n):t.environmentNode&&(delete t.environmentNode,delete t.environment)}getNodeFrame(e=this.renderer,t=null,n=null,r=null,i=null,a=null){let o=this.nodeFrame;return o.renderer=e,o.scene=t,o.object=n,o.camera=r,o.material=i,o.compute=a,o}getNodeFrameForRender(e){return this.getNodeFrame(e.renderer,e.scene,e.object,e.camera,e.material)}getNodeFrameForCompute(e){return this.getNodeFrame(this.renderer,null,null,null,null,e)}getOutputCacheKey(){let e=this.renderer;return e.toneMapping+`,`+e.currentColorSpace+`,`+e.xr.isPresenting}getOutputNode(e){let t=this.renderer,n;return n=e.isArrayTexture?this.backend.isWebGLBackend?Vb(e,ix).depth($b(`gl_ViewID_OVR`)).renderOutput(t.toneMapping,t.currentColorSpace):Vb(e,ix).depth(FL).renderOutput(t.toneMapping,t.currentColorSpace):Vb(e,ix).renderOutput(t.toneMapping,t.currentColorSpace),n}setOutputLayerIndex(e){FL.value=e}updateBefore(e){let t=e.getNodeBuilderState();for(let n of t.updateBeforeNodes)this.getNodeFrameForRender(e).updateBeforeNode(n)}updateAfter(e){let t=e.getNodeBuilderState();for(let n of t.updateAfterNodes)this.getNodeFrameForRender(e).updateAfterNode(n)}updateBeforeForCompute(e){let t=this.getForCompute(e);for(let n of t.updateBeforeNodes)this.getNodeFrameForCompute(e).updateBeforeNode(n)}updateAfterForCompute(e){let t=this.getForCompute(e);for(let n of t.updateAfterNodes)this.getNodeFrameForCompute(e).updateAfterNode(n)}updateForCompute(e){let t=this.getNodeFrame(),n=this.getForCompute(e);for(let e of n.updateNodes)t.updateNode(e)}updateForRender(e){let t=this.getNodeFrameForRender(e),n=e.getNodeBuilderState();for(let e of n.updateNodes)t.updateNode(e)}needsRefresh(e){let t=this.getNodeFrameForRender(e);return e.getMonitor().needsRefresh(e,t)}dispose(){super.dispose(),this.nodeFrame=new dL,this.nodeBuilderCache=new Map,this.cacheLib={}}},LL=new Oo,RL=0,zL=class e{constructor(e=null){this.id=RL++,this.version=0,this.clipIntersection=null,this.cacheKey=``,this.shadowPass=!1,this.viewMatrix=new F,this.viewNormalMatrix=new yi,this.clippingGroupContexts=new WeakMap,this.intersectionPlanes=[],this.unionPlanes=[],this.parentVersion=null,e!==null&&(this.viewMatrix=e.viewMatrix,this.viewNormalMatrix=e.viewNormalMatrix,this.clippingGroupContexts=e.clippingGroupContexts,this.shadowPass=e.shadowPass)}projectPlanes(e,t,n){let r=e.length;for(let i=0;iTb(e,n.toneMapping,n.outputColorSpace),...i.getFlowContextData()}),YL.set(i,a))}else a=i;n.contextNode=a,n.setRenderTarget(r.renderTarget),r.rendercall(),n.contextNode=i}n.setRenderTarget(a),n._setXRLayerSize(i.x,i.y),this.isPresenting=r}getSession(){return this._session}async setSession(e){let t=this._renderer;t.initialized===!1&&await t.init(),this._gl=t.getContext();let n=this._gl;if(this._session=e,e!==null){if(e.addEventListener(`select`,this._onSessionEvent),e.addEventListener(`selectstart`,this._onSessionEvent),e.addEventListener(`selectend`,this._onSessionEvent),e.addEventListener(`squeeze`,this._onSessionEvent),e.addEventListener(`squeezestart`,this._onSessionEvent),e.addEventListener(`squeezeend`,this._onSessionEvent),e.addEventListener(`end`,this._onSessionEnd),e.addEventListener(`inputsourceschange`,this._onInputSourcesChange),this._validateWebGPUSession(),this._currentPixelRatio=t.getPixelRatio(),t.getSize(this._currentSize),this._currentAnimationContext=t._animation.getContext(),this._currentAnimationLoop=t._animation.getAnimationLoop(),t._animation.stop(),this._isWebGPUSession())await this._initWebGPUSession(e);else if(this._supportsLayers===!0){let r=null,i=null,a=null,o=n.getContextAttributes();await t.backend.makeXRCompatible(),this.setFoveation(this.getFoveation()),t.depth&&(a=t.stencil?n.DEPTH24_STENCIL8:n.DEPTH_COMPONENT24,r=t.stencil?Dn:En,i=t.stencil?bn:hn);let s={colorFormat:n.RGBA8,depthFormat:a,scaleFactor:this._framebufferScaleFactor,clearOnAccess:!1};this._useMultiviewIfPossible&&t.hasFeature(`OVR_multiview2`)&&(s.textureType=`texture-array`,this._useMultiview=!0),this._glBinding=this.getBinding();let c=this._glBinding.createProjectionLayer(s),l=[c];this._glProjLayer=c,t.setPixelRatio(1),t._setXRLayerSize(c.textureWidth,c.textureHeight);let u=this._useMultiview?2:1,d=new Ac(c.textureWidth,c.textureHeight,i,void 0,void 0,void 0,void 0,void 0,void 0,r,u);if(this._xrRenderTarget=new KL(c.textureWidth,c.textureHeight,{format:Tn,type:un,colorSpace:t.outputColorSpace,depthTexture:d,stencilBuffer:t.stencil,samples:o.antialias?4:0,resolveDepthBuffer:c.ignoreDepthValues===!1,resolveStencilBuffer:c.ignoreDepthValues===!1,storeMultisampledColorBuffer:!1,storeMultisampledDepthBuffer:c.ignoreDepthValues===!1,storeMultisampledStencilBuffer:c.ignoreDepthValues===!1,depth:this._useMultiview?2:1,multiview:this._useMultiview}),this._xrRenderTarget._hasExternalTextures=!0,this._xrRenderTarget.depth=this._useMultiview?2:1,this._sessionUsesLayers=e.enabledFeatures.includes(`layers`),this._referenceSpace=await e.requestReferenceSpace(this.getReferenceSpaceType()),this._sessionUsesLayers)for(let e of this._layers)e.plane.material=new es({color:16777215,side:+(e.type===`cylinder`)}),e.plane.material.blending=5,e.plane.material.blendEquation=100,e.plane.material.blendSrc=200,e.plane.material.blendDst=200,e.xrlayer=this._createXRLayer(e),l.unshift(e.xrlayer);e.updateRenderState({layers:l})}else{await t.backend.makeXRCompatible(),this.setFoveation(this.getFoveation());let r={antialias:t.currentSamples>0,alpha:!0,depth:t.depth,stencil:t.stencil,framebufferScaleFactor:this.getFramebufferScaleFactor()},i=new XRWebGLLayer(e,n,r);this._glBaseLayer=i,e.updateRenderState({baseLayer:i}),t.setPixelRatio(1),t._setXRLayerSize(i.framebufferWidth,i.framebufferHeight),this._xrRenderTarget=new KL(i.framebufferWidth,i.framebufferHeight,{format:Tn,type:un,colorSpace:t.outputColorSpace,stencilBuffer:t.stencil}),this._xrRenderTarget._isOpaqueFramebuffer=!0,this._referenceSpace=await e.requestReferenceSpace(this.getReferenceSpaceType())}t._animation.setAnimationLoop(this._onAnimationFrame),t._animation.setContext(e),t._animation.start(),this.isPresenting=!0,this.dispatchEvent({type:`sessionstart`})}}updateCamera(e){let t=this._session;if(t===null)return;let n=e.near,r=e.far,i=this._cameraXR,a=this._cameraL,o=this._cameraR;i.near=o.near=a.near=n,i.far=o.far=a.far=r,i.isMultiViewCamera=this._useMultiview,(this._currentDepthNear!==i.near||this._currentDepthFar!==i.far)&&(t.updateRenderState({depthNear:i.near,depthFar:i.far}),this._currentDepthNear=i.near,this._currentDepthFar=i.far),i.layers.mask=e.layers.mask|6,a.layers.mask=i.layers.mask&-5,o.layers.mask=i.layers.mask&-3;let s=e.parent,c=i.cameras;Dm(i,s);for(let e=0;e{await this.compileAsync(n,t,e);let r=this.needsFrameBufferTarget&&this._renderTarget===null?this._getFrameBufferTarget():this._renderTarget||this._outputRenderTarget,i=this._renderLists.get(e,t,this.lighting),a=this._renderContexts.get(r,this._mrt),o=e.overrideMaterial||n.material,{fragmentShader:s,vertexShader:c}=this._objects.get(n,o,e,t,i.lightsNode,a,a.clippingContext).getNodeBuilderState();return{fragmentShader:s,vertexShader:c}}}}async init(){return this._initPromise===null&&(this._initPromise=new Promise(async(e,t)=>{let n=this.backend;try{await n.init(this)}catch(e){if(this._getFallback!==null)try{this.backend=n=this._getFallback(e),await n.init(this)}catch(e){t(e);return}else{t(e);return}}this._nodes=new IL(this,n),this._animation=new HO(this,this._nodes,this.info),this._attributes=new QO(n,this.info),this._background=new OI(this,this._nodes),this._geometries=new $O(this._attributes,this.info),this._textures=new gk(this,n,this.info),this._pipelines=new ok(n,this._nodes,this.info),this._bindings=new sk(n,this._nodes,this._textures,this._attributes,this._pipelines,this.info),this._objects=new JO(this,this._nodes,this._geometries,this._pipelines,this._bindings,this.info),this._renderLists=new dk,this._bundles=new HL,this._renderContexts=new mk(this),this._animation.start(),this._initialized=!0,e(this)})),this._initPromise}get domElement(){return this._canvasTarget.domElement}get coordinateSystem(){return this.backend.coordinateSystem}async compileAsync(e,t,n=null,r=null){if(this._isDeviceLost===!0)return;this._initialized===!1&&await this.init(),this.shadowMap.type===2&&(f(`WebGPURenderer: PCFSoftShadowMap has been removed. Using PCFShadowMap instead.`),this.shadowMap.type=1);let i=this._nodes.nodeFrame,a=i.renderId,o=this._currentRenderContext,s=this._currentRenderObjectFunction,c=this._handleObjectFunction,l=this._compilationPromises;n===null&&(n=e);let u=e.isScene===!0?e:n.isScene===!0?n:QL,d=this.needsFrameBufferTarget&&this._renderTarget===null,p=this._renderTarget||this._outputRenderTarget,m=this.xr.isPresenting===!0&&this.isOutputTarget,g=d?this._getFrameBufferTarget():p,_=this._renderContexts.get(g,this._mrt),v=this._activeMipmapLevel,y=[];this._currentRenderContext=_,this._currentRenderObjectFunction=this.renderObject,this._handleObjectFunction=this._createObjectPipeline,this._compilationPromises=y,i.renderId++,i.update(),_.depth=this.depth,_.stencil=this.stencil,_.clippingContext||=new zL,_.clippingContext.updateGlobal(u,t),e.matrixWorldAutoUpdate===!0&&e.updateMatrixWorld(),t=this._updateCamera(t,m),u.onBeforeRender(this,e,t,g),rR.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),t.isArrayCamera?nR.setFromArrayCamera(t):tR.setFromProjectionMatrix(rR,t.coordinateSystem,t.reversedDepth);let b=this._renderLists.get(u,t,this.lighting);if(b.begin(),this._projectObject(e,t,0,b,_.clippingContext),n!==e&&n.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&b.pushLight(e)}),b.finish(),g!==null){this._textures.updateRenderTarget(g,v);let e=this._textures.get(g);_.textures=e.textures,_.depthTexture=e.depthTexture}else _.textures=null,_.depthTexture=null;n===e?this._background.update(u,b,_):this._background.update(n,b,_);let x=b.opaque,S=b.transparent,C=b.transparentDoublePass,w=b.lightsNode;this.opaque===!0&&x.length>0&&this._renderObjects(x,t,u,w),this.transparent===!0&&S.length>0&&this._renderTransparents(S,C,t,u,w),i.renderId=a,this._currentRenderContext=o,this._currentRenderObjectFunction=s,this._handleObjectFunction=c,this._compilationPromises=l;let T=y.length,E=0;for(let e of y){let t=this._objects.get(e.object,e.material,e.scene,e.camera,e.lightsNode,e.renderContext,e.clippingContext,e.passId);t.drawRange=e.object.geometry.drawRange,t.group=e.group,await this._nodes.getForRenderAsync(t),this._isPreCompiling=!0,this._nodes.updateBefore(t),this._geometries.updateForRender(t),this._nodes.updateForRender(t),this._bindings.updateForRender(t),this._isPreCompiling=!1;let n=[];this._pipelines.getForRender(t,n),n.length>0&&await Promise.all(n),this._isPreCompiling=!0,this._nodes.updateAfter(t),this._isPreCompiling=!1,E++,r!==null&&r(new ProgressEvent(`progress`,{lengthComputable:!0,loaded:E,total:T})),await h()}}async compileComputeAsync(e,t=null){if(this._isDeviceLost===!0)return;this._initialized===!1&&await this.init();let n=Array.isArray(e)?e:[e];if(n.length===0||n.some(e=>e==null||e.isComputeNode!==!0))throw Error(`THREE.Renderer: .compileComputeAsync() expects a ComputeNode.`);let r=n.length,i=0,a=this._pipelines,o=this._bindings,s=this._nodes;for(let e of n){if(a.has(e)===!1){let t=()=>{e.removeEventListener(`dispose`,t),a.delete(e),o.deleteForCompute(e),s.delete(e)};e.addEventListener(`dispose`,t);let n=e.onInitFunction;n!==null&&n.call(e,{renderer:this})}await s.getForComputeAsync(e),s.updateBeforeForCompute(e),s.updateForCompute(e),o.updateForCompute(e);let n=o.getForCompute(e),c=[];a.getForCompute(e,n,c),await Promise.all(c),s.updateAfterForCompute(e),i++,t!==null&&t(new ProgressEvent(`progress`,{lengthComputable:!0,loaded:i,total:r})),i0&&this._renderObjects(u,i,t,n),this.transparent===!0&&l.length>0&&this._renderTransparents(l,e,i,t,n),this._currentRenderBundle=null,this.backend.finishBundle(o,s),c.version=r.version}else{let{renderObjects:e}=c;for(let t=0,n=e.length;t{i.removeEventListener(`dispose`,o),a.dispose(),this._frameBufferTargets.delete(i)};i.addEventListener(`dispose`,o),this._frameBufferTargets.set(i,a)}let o=this.getOutputRenderTarget();a.depthBuffer=n,a.stencilBuffer=r,o===null?a.setSize(e,t,1):a.setSize(o.width,o.height,o.depth);let s=this._outputRenderTarget?this._outputRenderTarget.viewport:i._viewport,c=this._outputRenderTarget?this._outputRenderTarget.scissor:i._scissor,l=this._outputRenderTarget?1:i._pixelRatio,u=this._outputRenderTarget?this._outputRenderTarget.scissorTest:i._scissorTest;return a.viewport.copy(s),a.scissor.copy(c),a.viewport.multiplyScalar(l),a.scissor.multiplyScalar(l),a.scissorTest=u,a.multiview=o!==null&&o.multiview,a.useArrayDepthTexture=o!==null&&o.useArrayDepthTexture,a.resolveDepthBuffer=o===null||o.resolveDepthBuffer,a.resolveStencilBuffer=o===null||o.resolveStencilBuffer,a.storeMultisampledColorBuffer=o===null||o.storeMultisampledColorBuffer,a.storeMultisampledDepthBuffer=o===null||o.storeMultisampledDepthBuffer,a.storeMultisampledStencilBuffer=o===null||o.storeMultisampledStencilBuffer,a._autoAllocateDepthBuffer=o!==null&&o._autoAllocateDepthBuffer,a}_renderScene(e,t,n=!0){if(this._isDeviceLost===!0)return;this.shadowMap.type===2&&(f(`WebGPURenderer: PCFSoftShadowMap has been removed. Using PCFShadowMap instead.`),this.shadowMap.type=1);let r=n?this._getFrameBufferTarget():null,i=this._nodes.nodeFrame,a=i.renderId,o=this._currentRenderContext,s=this._currentRenderObjectFunction,c=this._handleObjectFunction;this.lighting.beginRender(e),this._callDepth++;let l=e.isScene===!0?e:QL,u=this._renderTarget||this._outputRenderTarget,d=this.xr.isPresenting===!0&&this.isOutputTarget,p=this._activeCubeFace,m=this._activeMipmapLevel,h;if(r===null?h=u:(h=r,this.setRenderTarget(h)),h!==null&&h.depthBuffer===!0){let e=this._textures.get(h);e.depthInitialized!==!0&&((this.autoClear===!1||this.autoClear===!0&&this.autoClearDepth===!1)&&this.clearDepth(),e.depthInitialized=!0)}let g=this._renderContexts.get(h,this._mrt,this._callDepth);this._currentRenderContext=g,this._currentRenderObjectFunction=this._renderObjectFunction||this.renderObject,this._handleObjectFunction=this._renderObjectDirect,this.info.calls++,this.info.render.calls++,this.info.render.frameCalls++,i.renderId=this.info.calls,this.backend.updateTimeStampUID(g),this.inspector.beginRender(this.backend.getTimestampUID(g),e,t,h),e.matrixWorldAutoUpdate===!0&&e.updateMatrixWorld(),t=this._updateCamera(t,d);let _=this._canvasTarget,v=_._viewport,y=_._scissor,b=_._pixelRatio;h!==null&&(v=h.viewport,y=h.scissor,b=1),this.getDrawingBufferSize($L),eR.set(0,0,$L.width,$L.height);let x=v.minDepth===void 0?0:v.minDepth,S=v.maxDepth===void 0?1:v.maxDepth;g.viewportValue.copy(v).multiplyScalar(b).floor(),g.viewportValue.width>>=m,g.viewportValue.height>>=m,g.viewportValue.minDepth=x,g.viewportValue.maxDepth=S,g.viewport=g.viewportValue.equals(eR)===!1,g.scissorValue.copy(y).multiplyScalar(b).floor(),g.scissor=_._scissorTest&&g.scissorValue.equals(eR)===!1,g.scissorValue.width>>=m,g.scissorValue.height>>=m,g.clippingContext||=new zL,g.clippingContext.updateGlobal(l,t),l.onBeforeRender(this,e,t,h),rR.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),t.isArrayCamera?nR.setFromArrayCamera(t):tR.setFromProjectionMatrix(rR,t.coordinateSystem,t.reversedDepth),this._renderLists.update(i.frameId);let C=this._renderLists.get(e,t,this.lighting);if(C.begin(),this._projectObject(e,t,0,C,g.clippingContext),C.finish(),this.sortObjects===!0&&C.sort(this._opaqueSort,this._transparentSort),h!==null){this._textures.updateRenderTarget(h,m);let e=this._textures.get(h);g.textures=e.textures,g.depthTexture=e.depthTexture,g.width=e.width,g.height=e.height,g.renderTarget=h,g.depth=h.depthBuffer,g.stencil=h.stencilBuffer}else g.textures=null,g.depthTexture=null,g.width=$L.width,g.height=$L.height,g.depth=this.depth,g.stencil=this.stencil;g.width>>=m,g.height>>=m,g.activeCubeFace=p,g.activeMipmapLevel=m,g.occlusionQueryCount=C.occlusionQueryCount,g.fullscreenPass=e.isQuadMesh===!0,g.scissorValue.max(iR.set(0,0,0,0)),g.scissorValue.x+g.scissorValue.width>g.width&&(g.scissorValue.width=Math.max(g.width-g.scissorValue.x,0)),g.scissorValue.y+g.scissorValue.height>g.height&&(g.scissorValue.height=Math.max(g.height-g.scissorValue.y,0)),this._background.update(l,C,g),g.camera=t,this.backend.beginRender(g);let{bundles:w,lightsNode:T,transparentDoublePass:E,transparent:D,opaque:ee}=C;return w.length>0&&this._renderBundles(w,l,T),this.opaque===!0&&ee.length>0&&this._renderObjects(ee,t,l,T),this.transparent===!0&&D.length>0&&this._renderTransparents(D,E,t,l,T),this.backend.finishRender(g),i.renderId=a,this._currentRenderContext=o,this._currentRenderObjectFunction=s,this._handleObjectFunction=c,this.lighting.finishRender(e),this._callDepth--,r!==null&&(this.setRenderTarget(u,p,m),this._renderOutput(h)),l.onAfterRender(this,e,t,h),this.inspector.finishRender(this.backend.getTimestampUID(g)),g}_setXRLayerSize(e,t){this._canvasTarget._width=e,this._canvasTarget._height=t,this.setViewport(0,0,e,t)}_renderOutput(e){let t=this._nodes.getOutputCacheKey(),n=this._quadCache.get(e.texture),r;if(n===void 0){r=new dj(new VT),r.name=`Output Color Transform`,r.material.name=`outputColorTransform`,r.material.fragmentNode=this._nodes.getOutputNode(e.texture),n={quad:r,cacheKey:t},this._quadCache.set(e.texture,n);let i=()=>{r.material.dispose(),this._quadCache.delete(e.texture),e.texture.removeEventListener(`dispose`,i)};e.texture.addEventListener(`dispose`,i)}else r=n.quad,n.cacheKey!==t&&(r.material.fragmentNode=this._nodes.getOutputNode(e.texture),r.material.needsUpdate=!0,n.cacheKey=t);let i=this.autoClear,a=this.xr.enabled;this.autoClear=!1,this.xr.enabled=!1,this._renderOutputLayers(r,e),this.autoClear=i,this.xr.enabled=a}getMaxAnisotropy(){return this.backend.capabilities.getMaxAnisotropy()}getActiveCubeFace(){return this._activeCubeFace}getActiveMipmapLevel(){return this._activeMipmapLevel}async setAnimationLoop(e){this._initialized===!1&&await this.init(),this._animation.setAnimationLoop(e)}getAnimationLoop(){return this._animation.getAnimationLoop()}async getArrayBufferAsync(e,t=null,n=0,r=-1){if(t!==null&&t.isReadbackBuffer&&this.info.memoryMap.has(t)===!1){this.info.createReadbackBuffer(t);let e=()=>{t.removeEventListener(`dispose`,e),this.info.destroyReadbackBuffer(t)};t.addEventListener(`dispose`,e)}if(n%4!=0||r>0&&r%4!=0)throw Error(`THREE.Renderer: "getArrayBufferAsync()" offset and count must be a multiple of 4.`);return await this.backend.getArrayBufferAsync(e,t,n,r)}getContext(){return this.backend.getContext()}getPixelRatio(){return this._canvasTarget.getPixelRatio()}getDrawingBufferSize(e){return this._canvasTarget.getDrawingBufferSize(e)}getSize(e){return this._canvasTarget.getSize(e)}setPixelRatio(e=1){this._canvasTarget.setPixelRatio(e)}setDrawingBufferSize(e,t,n){this.xr&&this.xr.isPresenting||this._canvasTarget.setDrawingBufferSize(e,t,n)}setSize(e,t,n=!0){this.xr&&this.xr.isPresenting||this._canvasTarget.setSize(e,t,n)}setOpaqueSort(e){this._opaqueSort=e}setTransparentSort(e){this._transparentSort=e}getScissor(e){return this._canvasTarget.getScissor(e)}setScissor(e,t,n,r){this._canvasTarget.setScissor(e,t,n,r)}getScissorTest(){return this._canvasTarget.getScissorTest()}setScissorTest(e){this._canvasTarget.setScissorTest(e),this.backend.setScissorTest(e)}resetState(){if(this._initialized===!1)throw Error(`THREE.Renderer: .resetState() called before the backend is initialized. Use "await renderer.init();" before using this method.`);this.backend.resetState()}getViewport(e){return this._canvasTarget.getViewport(e)}setViewport(e,t,n,r,i=0,a=1){this._canvasTarget.setViewport(e,t,n,r,i,a)}getClearColor(e){return e.copy(this._clearColor)}setClearColor(e,t=1){this._clearColor.set(e),this._clearColor.a=t}getClearAlpha(){return this._clearColor.a}setClearAlpha(e){this._clearColor.a=e}getClearDepth(){return this.reversedDepthBuffer===!0?1-this._clearDepth:this._clearDepth}setClearDepth(e){this._clearDepth=e}getClearStencil(){return this._clearStencil}setClearStencil(e){this._clearStencil=e}isOccluded(e){let t=this._currentRenderContext;return t&&this.backend.isOccluded(t,e)}clear(e=!0,t=!0,n=!0){if(this._initialized===!1)throw Error(`THREE.Renderer: .clear() called before the backend is initialized. Use "await renderer.init();" before using this method.`);let r=this._renderTarget||this._getFrameBufferTarget(),i=null;if(r!==null){this._textures.updateRenderTarget(r);let e=this._textures.get(r);i=this._renderContexts.get(r,null,-1),i.textures=e.textures,i.depthTexture=e.depthTexture,i.width=e.width,i.height=e.height,i.renderTarget=r,i.depth=r.depthBuffer,i.stencil=r.stencilBuffer;let t=this.backend.getClearColor();i.clearColorValue.r=t.r,i.clearColorValue.g=t.g,i.clearColorValue.b=t.b,i.clearColorValue.a=t.a,i.clearDepthValue=this.getClearDepth(),i.clearStencilValue=this.getClearStencil(),i.activeCubeFace=this.getActiveCubeFace(),i.activeMipmapLevel=this.getActiveMipmapLevel(),r.depthBuffer===!0&&(e.depthInitialized=!0)}this.backend.clear(e,t,n,i),r!==null&&this._renderTarget===null&&this._renderOutput(r)}clearColor(){this.clear(!0,!1,!1)}clearDepth(){this.clear(!1,!0,!1)}clearStencil(){this.clear(!1,!1,!0)}async clearAsync(e=!0,t=!0,n=!0){m(`Renderer: "clearAsync()" has been deprecated. Use "clear()" and "await renderer.init();" when creating the renderer.`),await this.init(),this.clear(e,t,n)}async clearColorAsync(){m(`Renderer: "clearColorAsync()" has been deprecated. Use "clearColor()" and "await renderer.init();" when creating the renderer.`),this.clear(!0,!1,!1)}async clearDepthAsync(){m(`Renderer: "clearDepthAsync()" has been deprecated. Use "clearDepth()" and "await renderer.init();" when creating the renderer.`),this.clear(!1,!0,!1)}async clearStencilAsync(){m(`Renderer: "clearStencilAsync()" has been deprecated. Use "clearStencil()" and "await renderer.init();" when creating the renderer.`),this.clear(!1,!1,!0)}get needsFrameBufferTarget(){let e=this.currentToneMapping!==0,t=this.currentColorSpace!==Ci.workingColorSpace;return e||t}get samples(){return this._samples}get currentSamples(){let e=this._samples;return this._renderTarget===null?(this.needsFrameBufferTarget||this._currentRenderContext?.fullscreenPass===!0)&&(e=0):e=this._renderTarget.samples,e}get currentToneMapping(){return this.isOutputTarget?this.toneMapping:0}get currentColorSpace(){return this.isOutputTarget?this.outputColorSpace:Ci.workingColorSpace}get isOutputTarget(){return this._renderTarget===this._outputRenderTarget||this._renderTarget===null}async dispose(){if(this._initialized===!0){this.info.dispose(),this._inspector.dispose(),this._animation.dispose(),this._objects.dispose(),this._geometries.dispose(),this._pipelines.dispose(),this._nodes.dispose(),this._bindings.dispose(),this._renderLists.dispose(),this._renderContexts.dispose(),this._textures.dispose();for(let e of this._frameBufferTargets.keys())e.dispose();await this.backend.dispose()}this.setRenderTarget(null),this.setAnimationLoop(null)}setRenderTarget(e,t=0,n=0){this._renderTarget=e,this._activeCubeFace=t,this._activeMipmapLevel=n}getRenderTarget(){return this._renderTarget}setOutputRenderTarget(e){this._outputRenderTarget=e}getOutputRenderTarget(){return this._outputRenderTarget}setCanvasTarget(e){this._canvasTarget.removeEventListener(`resize`,this._onCanvasTargetResize),this._canvasTarget=e,this._canvasTarget.addEventListener(`resize`,this._onCanvasTargetResize)}getCanvasTarget(){return this._canvasTarget}_resetXRState(){this.backend.setXRTarget(null),this.setOutputRenderTarget(null),this.setRenderTarget(null);for(let e of this._frameBufferTargets.keys())e.dispose()}setRenderObjectFunction(e){this._renderObjectFunction=e}getRenderObjectFunction(){return this._renderObjectFunction}compute(e,t=null){if(this._isDeviceLost===!0)return;if(this._initialized===!1)return f(`Renderer: ".compute()" called before the backend is initialized. Try using ".computeAsync()" instead.`),this.computeAsync(e,t);let n=this._nodes.nodeFrame,r=n.renderId;this.info.calls++,this.info.compute.calls++,this.info.compute.frameCalls++,n.renderId=this.info.calls,this.backend.updateTimeStampUID(e),this.inspector.beginCompute(this.backend.getTimestampUID(e),e);let i=this.backend,a=this._pipelines,o=this._bindings,s=this._nodes,c=Array.isArray(e)?e:[e];if(c[0]===void 0||c[0].isComputeNode!==!0)throw Error(`THREE.Renderer: .compute() expects a ComputeNode.`);i.beginCompute(e);for(let n of c){if(a.has(n)===!1){let e=()=>{n.removeEventListener(`dispose`,e),a.delete(n),o.deleteForCompute(n),s.delete(n)};n.addEventListener(`dispose`,e);let t=n.onInitFunction;t!==null&&t.call(n,{renderer:this})}s.updateBeforeForCompute(n),s.updateForCompute(n),o.updateForCompute(n);let r=o.getForCompute(n),c=a.getForCompute(n,r);i.compute(e,n,r,c,t),s.updateAfterForCompute(n)}i.finishCompute(e),n.renderId=r,this.inspector.finishCompute(this.backend.getTimestampUID(e))}async computeAsync(e,t=null){this._initialized===!1&&await this.init(),this.compute(e,t)}async hasFeatureAsync(e){return m(`Renderer: "hasFeatureAsync()" has been deprecated. Use "hasFeature()" and "await renderer.init();" when creating the renderer.`),await this.init(),this.hasFeature(e)}async resolveTimestampsAsync(e=`render`){return this._initialized===!1&&await this.init(),this.backend.resolveTimestampsAsync(e)}hasFeature(e){if(this._initialized===!1)throw Error(`THREE.Renderer: .hasFeature() called before the backend is initialized. Use "await renderer.init();" before using this method.`);return this.backend.hasFeature(e)}hasInitialized(){return this._initialized}async initTextureAsync(e){m(`Renderer: "initTextureAsync()" has been deprecated. Use "initTexture()" and "await renderer.init();" when creating the renderer.`),await this.init(),this.initTexture(e)}initTexture(e){if(this._initialized===!1)throw Error(`THREE.Renderer: .initTexture() called before the backend is initialized. Use "await renderer.init();" before using this method.`);this._textures.updateTexture(e)}initRenderTarget(e){if(this._initialized===!1)throw Error(`THREE.Renderer: .initRenderTarget() called before the backend is initialized. Use "await renderer.init();" before using this method.`);this._textures.updateRenderTarget(e);let t=this._textures.get(e),n=this._renderContexts.get(e);n.textures=t.textures,n.depthTexture=t.depthTexture,n.width=t.width,n.height=t.height,n.renderTarget=e,n.depth=e.depthBuffer,n.stencil=e.stencilBuffer,this.backend.initRenderTarget(n)}copyFramebufferToTexture(e,t=null){if(t!==null){if(t.isVector2)t=iR.set(t.x,t.y,e.image.width,e.image.height).floor();else if(t.isVector4)t=iR.copy(t).floor();else{p(`Renderer.copyFramebufferToTexture: Invalid rectangle.`);return}}else t=iR.set(0,0,e.image.width,e.image.height);let n=this._currentRenderContext,r;n===null?(r=this._renderTarget||this._getFrameBufferTarget(),r!==null&&(this._textures.updateRenderTarget(r),n=this._textures.get(r))):r=n.renderTarget,this._textures.updateTexture(e,{renderTarget:r}),this.backend.copyFramebufferToTexture(e,n,t),this._inspector.copyFramebufferToTexture(e)}copyTextureToTexture(e,t,n=null,r=null,i=0,a=0){this._textures.updateTexture(e),this._textures.updateTexture(t),this.backend.copyTextureToTexture(e,t,n,r,i,a),this._inspector.copyTextureToTexture(e,t)}async readRenderTargetPixelsAsync(e,t,n,r,i,a=0,o=0){return this.backend.copyTextureToBuffer(e.textures[a],t,n,r,i,o)}_projectObject(e,t,n,r,i){if(e.visible===!1)return;if(e.layers.test(t.layers)){if(e.isGroup)n=e.renderOrder,e.isClippingGroup&&e.enabled&&(i=i.getGroupContext(e));else if(e.isLOD)e.autoUpdate===!0&&e.update(t);else if(e.isLight)r.pushLight(e);else if(e.isSprite){let a=t.isArrayCamera?nR:tR;if(!e.frustumCulled||e.intersectsFrustum(a)){this.sortObjects===!0&&iR.setFromMatrixPosition(e.matrixWorld).applyMatrix4(rR);let{geometry:t,material:a}=e;a.visible&&r.push(e,t,a,n,iR.z,null,i)}}else if(e.isLineLoop)p(`Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.`);else if(e.isMesh||e.isLine||e.isPoints){let a=t.isArrayCamera?nR:tR;if(!e.frustumCulled||e.intersectsFrustum(a)){let{geometry:t,material:a}=e;if(this.sortObjects===!0&&(t.boundingSphere===null&&t.computeBoundingSphere(),iR.copy(t.boundingSphere.center).applyMatrix4(e.matrixWorld).applyMatrix4(rR)),Array.isArray(a)){let o=t.groups;for(let s=0,c=o.length;s0){for(let{material:e}of t)e.side=1;this._renderObjects(t,n,r,i,`backSide`);for(let{material:e}of t)e.side=0;this._renderObjects(e,n,r,i);for(let{material:e}of t)e.side=2}else this._renderObjects(e,n,r,i)}_renderObjects(e,t,n,r,i=null){for(let a=0,o=e.length;a(t.not().discard(),e))(c)}}e.depthNode&&e.depthNode.isNode&&(l=e.depthNode),e.castShadowPositionNode&&e.castShadowPositionNode.isNode?s=e.castShadowPositionNode:e.positionNode&&e.positionNode.isNode&&(s=e.positionNode),n={version:t,colorNode:c,depthNode:l,positionNode:s},this._cacheShadowNodes.set(e,n)}return n}_updateCamera(e,t){let n=this.xr;if(n.isPresenting===!1||t===!1){let t=!1;if(this.reversedDepthBuffer===!0&&e.reversedDepth!==!0){if(e._reversedDepth=!0,e.isArrayCamera)for(let t of e.cameras)t._reversedDepth=!0;t=!0}let n=this.coordinateSystem;if(e.coordinateSystem!==n){if(e.coordinateSystem=n,e.isArrayCamera)for(let t of e.cameras)t.coordinateSystem=n;t=!0}if(t===!0&&(e.updateProjectionMatrix(),e.isArrayCamera))for(let t of e.cameras)t.updateProjectionMatrix()}return e.parent===null&&e.matrixWorldAutoUpdate===!0&&e.updateMatrixWorld(),t===!0&&n.enabled===!0&&n.isPresenting===!0&&(n.cameraAutoUpdate===!0&&n.updateCamera(e),e=n.getCamera()),e}renderObject(e,t,n,r,i,a,o,s=null,c=null){let l=!1,u,d,f,p,m,h,g,_=this._currentSourceMaterial;if(e.onBeforeRender(this,t,n,r,i,a),i.allowOverride===!0&&t.overrideMaterial!==null){this._currentSourceMaterial=i;let e=t.overrideMaterial;if(l=!0,u=e.isNodeMaterial?e.colorNode:null,d=e.isNodeMaterial?e.depthNode:null,f=e.isNodeMaterial?e.positionNode:null,p=t.overrideMaterial.side,m=e.displacementMap,h=e.displacementScale,g=e.displacementBias,i.positionNode&&i.positionNode.isNode&&(e.positionNode=i.positionNode),e.alphaTest=i.alphaTest,e.alphaMap=i.alphaMap,e.displacementMap=i.displacementMap,e.displacementScale=i.displacementScale,e.displacementBias=i.displacementBias,e.transparent=i.transparent||i.transmission>0||i.transmissionNode&&i.transmissionNode.isNode||i.backdropNode&&i.backdropNode.isNode,e.isShadowPassMaterial){let{colorNode:t,depthNode:n,positionNode:r}=this._getShadowNodes(i);e.side=this.shadowMap.type===3?i.shadowSide===null?i.side:i.shadowSide:i.shadowSide===null?aR[i.side]:i.shadowSide,t!==null&&(e.colorNode=t),n!==null&&(e.depthNode=n),r!==null&&(e.positionNode=r)}i=e}i.transparent===!0&&i.side===2&&i.forceSinglePass===!1?(i.side=1,this._handleObjectFunction(e,i,t,n,o,a,s,`backSide`),i.side=0,this._handleObjectFunction(e,i,t,n,o,a,s,c),i.side=2):this._handleObjectFunction(e,i,t,n,o,a,s,c),l&&(t.overrideMaterial.colorNode=u,t.overrideMaterial.depthNode=d,t.overrideMaterial.positionNode=f,t.overrideMaterial.side=p,t.overrideMaterial.displacementMap=m,t.overrideMaterial.displacementScale=h,t.overrideMaterial.displacementBias=g),this._currentSourceMaterial=_,e.onAfterRender(this,t,n,r,i,a)}hasCompatibility(e){if(this._initialized===!1)throw Error(`THREE.Renderer: .hasCompatibility() called before the backend is initialized. Use "await renderer.init();" before using this method.`);return this.backend.hasCompatibility(e)}_renderObjectDirect(e,t,n,r,i,a,o,s){let c=this._objects.get(e,t,n,r,i,this._currentRenderContext,o,s);c.drawRange=e.geometry.drawRange,c.group=a,this._currentRenderBundle!==null&&(this.backend.get(this._currentRenderBundle).renderObjects.push(c),c.bundle=this._currentRenderBundle.bundleGroup);let l=this._nodes.needsRefresh(c);l===ai.FULL?(this._nodes.updateBefore(c),this._geometries.updateForRender(c),this._nodes.updateForRender(c),this._bindings.updateForRender(c)):l===ai.SHARED&&(this._nodes.updateBefore(c),this._nodes.updateForRender(c),this._bindings.updateSharedForRender(c)),this._pipelines.updateForRender(c),this._pipelines.isReady(c)&&(this.backend.draw(c,this.info),l!==ai.NONE&&this._nodes.updateAfter(c))}_createObjectPipeline(e,t,n,r,i,a,o,s){if(this._compilationPromises!==null){this._compilationPromises.push({object:e,material:t,scene:n,camera:r,lightsNode:i,group:a,clippingContext:o,passId:s,renderContext:this._currentRenderContext});return}let c=this._objects.get(e,t,n,r,i,this._currentRenderContext,o,s);c.drawRange=e.geometry.drawRange,c.group=a,this._nodes.updateBefore(c),this._geometries.updateForRender(c),this._nodes.updateForRender(c),this._bindings.updateForRender(c),this._pipelines.getForRender(c,this._compilationPromises),this._nodes.updateAfter(c)}_onCanvasTargetResize(){this._initialized&&this.backend.updateSize()}get compile(){return this.compileAsync}},sR=class{constructor(e=``){this.name=e,this.visibility=0}setVisibility(e){this.visibility|=e}getVisibility(){return this.visibility}clone(){return Object.assign(new this.constructor,this)}},cR=class extends sR{constructor(e,t=null){super(e),this.isBuffer=!0,this.bytesPerElement=Float32Array.BYTES_PER_ELEMENT,this._buffer=t,this._updateRanges=[]}get updateRanges(){return this._updateRanges}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}get byteLength(){return Pm(this._buffer.byteLength)}get buffer(){return this._buffer}update(){return!0}release(){this._buffer=null}},lR=class extends cR{constructor(e,t=null){super(e,t),this.isUniformBuffer=!0}},uR=0,dR=class extends lR{constructor(e,t){let n=e&&e.name?e.name:uR++;super(`UniformBuffer_`+n,e?e.value:null),this.nodeUniform=e,this.groupNode=t,this.isNodeUniformBuffer=!0}set updateRanges(e){this.nodeUniform.updateRanges=e}get updateRanges(){return this.nodeUniform.updateRanges}addUpdateRange(e,t){this.nodeUniform.addUpdateRange(e,t)}clearUpdateRanges(){this.nodeUniform.clearUpdateRanges()}get byteLength(){return Pm(this.buffer.byteLength)}get buffer(){return this.nodeUniform.value}},fR=class extends lR{constructor(e){super(e),this.isUniformsGroup=!0,this._values=null,this.uniforms=[],this._updateRangeCache=new Map,this._addedIndices=new Set}addUniformUpdateRange(e){let t=e.index;if(this._addedIndices.has(t))return;let n=this._updateRangeCache.get(t);n===void 0&&(n={start:0,count:0},this._updateRangeCache.set(t,n)),n.start=e.offset,n.count=e.itemSize,this._addedIndices.add(t),this.updateRanges.push(n)}clearUpdateRanges(){this._addedIndices.clear(),super.clearUpdateRanges()}addUniform(e){return this.uniforms.push(e),this}removeUniform(e){let t=this.uniforms.indexOf(e);return t!==-1&&this.uniforms.splice(t,1),this}get values(){return this._values===null&&(this._values=Array.from(this.buffer)),this._values}get buffer(){let e=this._buffer;if(e===null){let t=this.byteLength;e=new Float32Array(new ArrayBuffer(t)),this._buffer=e}return e}get byteLength(){let e=this.bytesPerElement,t=0;for(let n=0,r=this.uniforms.length;n> 24 ) / 127.0, -1.0 ); }`),floatunpack_unorm_4x8:new AM(`vec4 tsl_unpackUnorm4x8( uint x ) { return vec4( uvec4( x, x >> 8, x >> 16, x >> 24 ) & 0xffu ) / 255.0; }`)},SR={equals:`equal`,bitcast_float_int:`floatBitsToInt`,bitcast_int_float:`intBitsToFloat`,bitcast_uint_float:`uintBitsToFloat`,bitcast_float_uint:`floatBitsToUint`,floatpack_snorm_2x16:`packSnorm2x16`,floatpack_unorm_2x16:`packUnorm2x16`,floatpack_float16_2x16:`packHalf2x16`,floatpack_snorm_4x8:`tsl_packSnorm4x8`,floatpack_unorm_4x8:`tsl_packUnorm4x8`,floatunpack_snorm_2x16:`unpackSnorm2x16`,floatunpack_unorm_2x16:`unpackUnorm2x16`,floatunpack_float16_2x16:`unpackHalf2x16`,floatunpack_snorm_4x8:`tsl_unpackSnorm4x8`,floatunpack_unorm_4x8:`tsl_unpackUnorm4x8`},CR={low:`lowp`,medium:`mediump`,high:`highp`},wR={swizzleAssign:!0,storageBuffer:!1},TR={perspective:`smooth`,linear:`noperspective`},ER={centroid:`centroid`},DR=` precision highp float; precision highp int; precision highp sampler2D; precision highp sampler3D; precision highp samplerCube; precision highp sampler2DArray; precision highp usampler2D; precision highp usampler3D; precision highp usamplerCube; precision highp usampler2DArray; precision highp isampler2D; precision highp isampler3D; precision highp isamplerCube; precision highp isampler2DArray; precision highp sampler2DShadow; precision highp sampler2DArrayShadow; precision highp samplerCubeShadow; `,OR=new Set(`const.uniform.buffer.shared.attribute.varying.coherent.volatile.restrict.readonly.writeonly.atomic_uint.layout.centroid.flat.smooth.noperspective.patch.sample.invariant.precise.break.continue.do.for.while.switch.case.default.if.else.subroutine.in.out.inout.int.void.bool.true.false.float.double.discard.return.vec2.vec3.vec4.ivec2.ivec3.ivec4.bvec2.bvec3.bvec4.uint.uvec2.uvec3.uvec4.dvec2.dvec3.dvec4.mat2.mat3.mat4.mat2x2.mat2x3.mat2x4.mat3x2.mat3x3.mat3x4.mat4x2.mat4x3.mat4x4.dmat2.dmat3.dmat4.dmat2x2.dmat2x3.dmat2x4.dmat3x2.dmat3x3.dmat3x4.dmat4x2.dmat4x3.dmat4x4.lowp.mediump.highp.precision.sampler2D.sampler3D.samplerCube.sampler2DShadow.samplerCubeShadow.sampler2DArray.sampler2DArrayShadow.isampler2D.isampler3D.isamplerCube.isampler2DArray.usampler2D.usampler3D.usamplerCube.usampler2DArray.struct.common.partition.active.asm.class.union.enum.typedef.template.this.resource.goto.inline.noinline.public.static.extern.external.interface.long.short.half.fixed.unsigned.superp.input.output.hvec2.hvec3.hvec4.fvec2.fvec3.fvec4.sampler3DRect.filter.sizeof.cast.namespace.using.main`.split(`.`)),kR=class extends uL{constructor(e,t){super(e,t,new ML),this.uniformGroups={},this.transforms=[],this.extensions={},this.builtins={vertex:[],fragment:[],compute:[]}}needsToWorkingColorSpace(e){return e.isVideoTexture===!0&&e.colorSpace!==``}_include(e){let t=xR[e];return t.build(this),this.addInclude(t),t}getMethod(e){return xR[e]!==void 0&&this._include(e),SR[e]||e}getBitcastMethod(e,t){let n=this.getComponentType(t),r=this.getComponentType(e);return n!==`float`&&r!==`float`&&this.getTypeLength(t)===this.getTypeLength(e)?this.getType(e):this.getMethod(`bitcast_${n}_${r}`)}getFloatPackingMethod(e,t=`2x16`){return this.getMethod(`floatpack_${e}_${t}`)}getFloatUnpackingMethod(e,t=`2x16`){return this.getMethod(`floatunpack_${e}_${t}`)}getTernary(e,t,n){return`${e} ? ${t} : ${n}`}getOutputStructName(){return``}buildFunctionCode(e){let t=e.layout,n=this.flowShaderNode(e),r=[];for(let e of t.inputs)r.push(this.getType(e.type)+` `+e.name);return`${this.getType(t.type)} ${t.name}( ${r.join(`, `)} ) { ${n.vars} ${n.code} return ${n.result}; }`}setupPBO(e){let t=e.value;if(t.pbo===void 0){let e=t.array,n=t.count*t.itemSize,{itemSize:r}=t,i=t.array.constructor.name.toLowerCase().includes(`int`),a=i?kn:On;r===2?a=i?jn:An:r===3?a=i?Mn:wn:r===4&&(a=i?Nn:Tn);let o={Float32Array:gn,Uint8Array:un,Uint16Array:pn,Uint32Array:hn,Int8Array:dn,Int16Array:fn,Int32Array:mn,Uint8ClampedArray:un},s=2**Math.ceil(Math.log2(Math.sqrt(n/r))),c=Math.ceil(n/r/s);s*c*r0?i:``;t=`${n.name} {\n\t${r} ${e.name}[${a}];\n};\n`}else{let t=e.groupNode.name;if(r[t]===void 0){let e=this.uniformGroups[t];if(e!==void 0){let n=[];for(let t of e.uniforms){let e=t.getType(),r=this.getVectorType(e),i=t.nodeUniform.node.precision,a=`${r} ${t.name};`;i!==null&&(a=CR[i]+` `+a),n.push(` `+a)}r[t]=n}}i=!0}if(!i){let r=e.node.precision;r!==null&&(t=CR[r]+` `+t),t=`uniform `+t,n.push(t)}}let i=``;for(let e in r){let t=r[e];i+=this._getGLSLUniformStruct(e,t.join(` `))+` `}return i+=n.join(` `),i}getTypeFromAttribute(e){let t=super.getTypeFromAttribute(e);if(/^[iu]/.test(t)&&e.gpuType!==1013){let n=e;e.isInterleavedBufferAttribute&&(n=e.data);let r=n.array;r instanceof Uint32Array||r instanceof Int32Array||(t=t.slice(1))}return t}getAttributes(e){let t=``;if(e===`vertex`||e===`compute`){let e=this.getAttributesArray(),n=0;for(let r of e)t+=`layout( location = ${n++} ) in ${r.type} ${r.name};\n`}return t}getStructMembers(e){let t=[];for(let n of e.members)t.push(`\t${n.type} ${n.name};`);return t.join(` `)}getStructs(e){let t=[],n=this.structs[e],r=[];for(let e of n)if(e.output)for(let t of e.members)r.push(`layout( location = ${t.index} ) out ${t.type} ${t.name};`);else{let n=`struct `+e.name+` { `;n+=this.getStructMembers(e),n+=` }; `,t.push(n)}return e===`fragment`&&r.length===0&&r.push(`layout( location = 0 ) out ${this.getOutputType()} fragColor;`),` `+r.join(` `)+` `+t.join(` `)}getVaryings(e){let t=``,n=this.varyings;if(e===`vertex`||e===`compute`)for(let r of n){e===`compute`&&(r.needsInterpolation=!0);let n=this.getType(r.type);if(r.needsInterpolation){if(r.interpolationType){let e=TR[r.interpolationType]||r.interpolationType,i=ER[r.interpolationSampling]||``;t+=`${e} ${i} out ${n} ${r.name};\n`}else{let e=n.includes(`int`)||n.includes(`uv`)||n.includes(`iv`)?`flat `:``;t+=`${e}out ${n} ${r.name};\n`}}else t+=`${n} ${r.name};\n`}else if(e===`fragment`){for(let e of n)if(e.needsInterpolation){let n=this.getType(e.type);if(e.interpolationType){let r=TR[e.interpolationType]||e.interpolationType,i=ER[e.interpolationSampling]||``;t+=`${r} ${i} in ${n} ${e.name};\n`}else{let r=n.includes(`int`)||n.includes(`uv`)||n.includes(`iv`)?`flat `:``;t+=`${r}in ${n} ${e.name};\n`}}}for(let n of this.builtins[e])t+=`${n};\n`;return t}getVertexIndex(){return`uint( gl_VertexID )`}getInstanceIndex(){return`uint( gl_InstanceID )`}getInvocationLocalIndex(){return`uint( gl_InstanceID ) % ${this.compute.workgroupSize.reduce((e,t)=>e*t,1)}u`}getSubgroupSize(){p(`GLSLNodeBuilder: WebGLBackend does not support the subgroupSize node`)}getInvocationSubgroupIndex(){p(`GLSLNodeBuilder: WebGLBackend does not support the invocationSubgroupIndex node`)}getSubgroupIndex(){p(`GLSLNodeBuilder: WebGLBackend does not support the subgroupIndex node`)}getDrawIndex(){return this.renderer.backend.extensions.has(`WEBGL_multi_draw`)?`uint( gl_DrawID )`:`nodeUniformDrawId`}getFrontFacing(){return`gl_FrontFacing`}getFragCoord(){return`gl_FragCoord.xy`}getFragDepth(){return`gl_FragDepth`}enableExtension(e,t,n=this.shaderStage){let r=this.extensions[n]||(this.extensions[n]=new Map);r.has(e)===!1&&r.set(e,{name:e,behavior:t})}getExtensions(e){let t=[];if(e===`vertex`){let t=this.renderer.backend.extensions;this.object.isBatchedMesh&&t.has(`WEBGL_multi_draw`)&&this.enableExtension(`GL_ANGLE_multi_draw`,`require`,e)}let n=this.extensions[e];if(n!==void 0)for(let{name:e,behavior:r}of n.values())t.push(`#extension ${e} : ${r}`);return t.join(` `)}getClipDistance(){return`gl_ClipDistance`}isAvailable(e){let t=wR[e];if(t===void 0){let n;switch(t=!1,e){case`float32Filterable`:n=`OES_texture_float_linear`;break;case`clipDistance`:n=`WEBGL_clip_cull_distance`}if(n!==void 0){let e=this.renderer.backend.extensions;e.has(n)&&(e.get(n),t=!0)}wR[e]=t}return t}isFlipY(){return!0}enableHardwareClipping(e){this.enableExtension(`GL_ANGLE_clip_cull_distance`,`require`),this.builtins.vertex.push(`out float gl_ClipDistance[ ${e} ]`)}enableMultiview(){this.enableExtension(`GL_OVR_multiview2`,`require`,`fragment`),this.enableExtension(`GL_OVR_multiview2`,`require`,`vertex`),this.builtins.vertex.push(`layout(num_views = 2) in`)}registerTransform(e,t){this.transforms.push({varyingName:e,attributeNode:t})}getTransforms(){let e=this.transforms,t=``;for(let n=0;n0&&(n+=` `),n+=`\t// flow -> ${a}\n\t`),n+=`${r.code}\n\t`,e===i&&t!==`compute`&&(n+=`// result `,t===`vertex`?(n+=`gl_Position = `,n+=`${this.format(r.result,i.getNodeType(this),`vec4`)};`):t===`fragment`&&(e.outputNode.isOutputStructNode||(n+=`fragColor = `,n+=`${this.format(r.result,i.getNodeType(this),this.getOutputType())};`)))}let a=e[t];if(a.extensions=this.getExtensions(t),a.uniforms=this.getUniforms(t),a.attributes=this.getAttributes(t),a.varyings=this.getVaryings(t),a.vars=this.getVars(t,!0),a.structs=this.getStructs(t),a.codes=this.getCodes(t),a.transforms=this.getTransforms(t),a.flow=n,t===`vertex`){let e=this.renderer.backend.extensions;this.object.isBatchedMesh&&e.has(`WEBGL_multi_draw`)===!1&&(a.uniforms+=` uniform uint nodeUniformDrawId; `)}}this.material===null?this.computeShader=this._getGLSLVertexCode(e.compute):(this.vertexShader=this._getGLSLVertexCode(e.vertex),this.fragmentShader=this._getGLSLFragmentCode(e.fragment))}getUniformFromNode(e,t,n,r=null){let i=super.getUniformFromNode(e,t,n,r),a=this.getDataFromNode(e,n,this.globalCache),o=a.uniformGPU;if(o===void 0){let r=e.groupNode,s=r.name,c=this.getBindGroupArray(s,n);if(t===`texture`)o=new vR(i.name,i.node,r),c.push(o);else if(t===`cubeTexture`||t===`cubeDepthTexture`)o=new yR(i.name,i.node,r),c.push(o);else if(t===`texture3D`)o=new bR(i.name,i.node,r),c.push(o);else if(t===`buffer`){i.name=`buffer${e.id}`;let t=this.getSharedDataFromNode(e),n=t.buffer;n===void 0&&(e.name=`NodeBuffer_${e.id}`,n=new dR(e,r),n.name=e.name,t.buffer=n),c.push(n),o=n}else{let e=this.uniformGroups[s];e===void 0?(e=new mR(s,r),this.uniformGroups[s]=e,c.push(e)):c.indexOf(e)===-1&&c.push(e),o=this.getNodeUniform(i,t);let n=o.name;e.uniforms.some(e=>e.name===n)||e.addUniform(o)}a.uniformGPU=o}return i}},AR=null,jR=null,MR=class{constructor(e={}){this.parameters=Object.assign({},e),this.data=new WeakMap,this.renderer=null,this.domElement=null,this.timestampQueryPool={[ti.RENDER]:null,[ti.COMPUTE]:null},this.trackTimestamp=e.trackTimestamp===!0}async init(e){this.renderer=e}get coordinateSystem(){}beginRender(){}finishRender(){}setXRTarget(){}beginCompute(){}finishCompute(){}draw(){}compute(){}createProgram(){}destroyProgram(){}createBindings(){}updateBindings(){}updateBinding(){}createRenderPipeline(){}createComputePipeline(){}needsRenderUpdate(){}getRenderCacheKey(){}createNodeBuilder(){}updateSampler(){}destroySampler(){}createDefaultTexture(){}createTexture(){}updateTexture(){}generateMipmaps(){}destroyTexture(){}async copyTextureToBuffer(){}copyTextureToTexture(){}copyFramebufferToTexture(){}createAttribute(){}createIndexAttribute(){}createStorageAttribute(){}createUniformBuffer(){}destroyUniformBuffer(){}updateAttribute(){}destroyAttribute(){}getContext(){}updateSize(){}updateViewport(){}updateTimeStampUID(e){let t=this.get(e),n=this.renderer.info.frame,r,i=e.id;Array.isArray(e)?(i=e.map(e=>e.id).join(`,`),r=`c:`+this.renderer.info.compute.frameCalls):r=e.isComputeNode===!0?`c:`+this.renderer.info.compute.frameCalls:`r:`+this.renderer.info.render.frameCalls,t.timestampUID=r+`:`+i+`:f`+n}getTimestampUID(e){return this.get(e).timestampUID}getTimestampFrames(e){let t=this.timestampQueryPool[e];return t?t.getTimestampFrames():[]}_getQueryPool(e){let t=e.startsWith(`c:`)?ti.COMPUTE:ti.RENDER;return this.timestampQueryPool[t]}getTimestamp(e){return this._getQueryPool(e).getTimestamp(e)}get hasTimestamp(){return!1}hasTimestampQuery(e){return this._getQueryPool(e).hasTimestampQuery(e)}isOccluded(){}async resolveTimestampsAsync(e=`render`){if(!this.trackTimestamp){m(`WebGPURenderer: Timestamp tracking is disabled.`);return}let t=this.timestampQueryPool[e];if(!t)return;let n=await t.resolveQueriesAsync();return this.renderer.info[e].timestamp=n,n}async getArrayBufferAsync(){}async hasFeatureAsync(){}hasFeature(){}getDrawingBufferSize(){return AR||=new N,this.renderer.getDrawingBufferSize(AR)}setScissorTest(){}resetState(){}getClearColor(){let e=this.renderer;return jR||=new _k,e.getClearColor(jR),jR.getRGB(jR),jR}getDomElement(){let e=this.domElement;return e===null&&(e=this.parameters.canvas===void 0?s():this.parameters.canvas,`setAttribute`in e&&e.setAttribute(`data-engine`,`three.js r186 webgpu`),this.domElement=e),e}hasCompatibility(){return!1}initRenderTarget(){}set(e,t){this.data.set(e,t)}get(e){let t=this.data.get(e);return t===void 0&&(t={},this.data.set(e,t)),t}has(e){return this.data.has(e)}delete(e){this.data.delete(e)}deleteBindGroupData(){}async dispose(){for(let e of Object.values(this.timestampQueryPool))e!==null&&await e.dispose()}},NR=0,PR=class{constructor(e,t){this.buffers=[e.bufferGPU,t],this.type=e.type,this.bufferType=e.bufferType,this.pbo=e.pbo,this.byteLength=e.byteLength,this.bytesPerElement=e.BYTES_PER_ELEMENT,this.version=e.version,this.isInteger=e.isInteger,this.activeBufferIndex=0,this.baseId=e.id}get id(){return`${this.baseId}|${this.activeBufferIndex}`}get bufferGPU(){return this.buffers[this.activeBufferIndex]}get transformBuffer(){return this.buffers[this.activeBufferIndex^1]}switchBuffers(){this.activeBufferIndex^=1}},FR=class{constructor(e){this.backend=e}createAttribute(e,t){let n=this.backend,{gl:r}=n,i=e.array,a=e.usage||r.STATIC_DRAW,o=e.isInterleavedBufferAttribute?e.data:e,s=n.get(o),c=s.bufferGPU;c===void 0&&(c=this._createBuffer(r,t,i,a),s.bufferGPU=c,s.bufferType=t,s.version=o.version);let l;if(i instanceof Float32Array)l=r.FLOAT;else if(typeof Float16Array<`u`&&i instanceof Float16Array)l=r.HALF_FLOAT;else if(i instanceof Uint16Array)l=e.isFloat16BufferAttribute?r.HALF_FLOAT:r.UNSIGNED_SHORT;else if(i instanceof Int16Array)l=r.SHORT;else if(i instanceof Uint32Array)l=r.UNSIGNED_INT;else if(i instanceof Int32Array)l=r.INT;else if(i instanceof Int8Array)l=r.BYTE;else if(i instanceof Uint8Array)l=r.UNSIGNED_BYTE;else if(i instanceof Uint8ClampedArray)l=r.UNSIGNED_BYTE;else throw Error(`THREE.WebGLBackend: Unsupported buffer data format: `+i);let u={bufferGPU:c,bufferType:t,type:l,byteLength:i.byteLength,bytesPerElement:i.BYTES_PER_ELEMENT,version:e.version,pbo:e.pbo,isInteger:l===r.INT||l===r.UNSIGNED_INT||e.gpuType===1013,id:NR++};if(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute){let e=this._createBuffer(r,t,i,a);u=new PR(u,e)}n.set(e,u)}updateAttribute(e){let t=this.backend,{gl:n}=t,r=e.array,i=e.isInterleavedBufferAttribute?e.data:e,a=t.get(i),o=a.bufferType,s=e.isInterleavedBufferAttribute?e.data.updateRanges:e.updateRanges;if(n.bindBuffer(o,a.bufferGPU),s.length===0)n.bufferSubData(o,0,r);else{for(let e=0,t=s.length;e{t.buffer=null,t._mapped=!1,t.removeEventListener(`release`,e),t.removeEventListener(`dispose`,e)};t.addEventListener(`release`,e),t.addEventListener(`dispose`,e),u=new Uint8Array(new ArrayBuffer(l)),t.buffer=u.buffer}else u=new Uint8Array(t);return a.bindBuffer(a.COPY_READ_BUFFER,c),a.getBufferSubData(a.COPY_READ_BUFFER,n,u),a.bindBuffer(a.COPY_READ_BUFFER,null),a.bindBuffer(a.COPY_WRITE_BUFFER,null),t&&t.isReadbackBuffer?t:u.buffer}_createBuffer(e,t,n,r){let i=e.createBuffer();return e.bindBuffer(t,i),e.bufferData(t,n,r),e.bindBuffer(t,null),i}},RR=class{constructor(e){this.backend=e,this.gl=this.backend.gl,this.enabled={},this.parameters={},this.currentFlipSided=null,this.currentCullFace=null,this.currentProgram=null,this.currentBlendingEnabled=!1,this.currentBlending=null,this.currentBlendEquation=null,this.currentBlendEquationAlpha=null,this.currentBlendSrc=null,this.currentBlendDst=null,this.currentBlendSrcAlpha=null,this.currentBlendDstAlpha=null,this.currentBlendColor=new L(0,0,0),this.currentBlendAlpha=0,this.currentPremultipledAlpha=null,this.currentPolygonOffsetFactor=null,this.currentPolygonOffsetUnits=null,this.currentColorMask=null,this.currentDepthReversed=!1,this.currentDepthFunc=null,this.currentDepthMask=null,this.currentStencilFunc=null,this.currentStencilRef=null,this.currentStencilFuncMask=null,this.currentStencilFail=null,this.currentStencilZFail=null,this.currentStencilZPass=null,this.currentStencilMask=null,this.currentLineWidth=null,this.currentClippingPlanes=0,this.currentVAO=null,this.currentIndex=null,this.currentBoundFramebuffers={},this.currentDrawbuffers=new WeakMap,this.maxTextures=this.gl.getParameter(this.gl.MAX_TEXTURE_IMAGE_UNITS),this.currentTextureSlot=null,this.currentBoundTextures={},this.currentBoundBufferBases={},this._init()}_init(){let e=this.gl;IR={100:e.FUNC_ADD,101:e.FUNC_SUBTRACT,102:e.FUNC_REVERSE_SUBTRACT,103:e.MIN,104:e.MAX},LR={200:e.ZERO,201:e.ONE,202:e.SRC_COLOR,204:e.SRC_ALPHA,210:e.SRC_ALPHA_SATURATE,208:e.DST_COLOR,206:e.DST_ALPHA,203:e.ONE_MINUS_SRC_COLOR,205:e.ONE_MINUS_SRC_ALPHA,209:e.ONE_MINUS_DST_COLOR,207:e.ONE_MINUS_DST_ALPHA,211:e.CONSTANT_COLOR,212:e.ONE_MINUS_CONSTANT_COLOR,213:e.CONSTANT_ALPHA,214:e.ONE_MINUS_CONSTANT_ALPHA};let t=e.getParameter(e.SCISSOR_BOX),n=e.getParameter(e.VIEWPORT);this.currentScissor=new Mi().fromArray(t),this.currentViewport=new Mi().fromArray(n),this._tempVec4=new Mi}enable(e){let{enabled:t}=this;t[e]!==!0&&(this.gl.enable(e),t[e]=!0)}disable(e){let{enabled:t}=this;t[e]!==!1&&(this.gl.disable(e),t[e]=!1)}setFlipSided(e){if(this.currentFlipSided!==e){let{gl:t}=this;e?t.frontFace(t.CW):t.frontFace(t.CCW),this.currentFlipSided=e}}setCullFace(e){let{gl:t}=this;e===0?this.disable(t.CULL_FACE):(this.enable(t.CULL_FACE),e!==this.currentCullFace&&(e===1?t.cullFace(t.BACK):e===2?t.cullFace(t.FRONT):t.cullFace(t.FRONT_AND_BACK))),this.currentCullFace=e}setLineWidth(e){let{currentLineWidth:t,gl:n}=this;e!==t&&(n.lineWidth(e),this.currentLineWidth=e)}setMRTBlending(e,t,n){let r=this.gl,i=this.backend.drawBuffersIndexedExt;if(!i){m(`WebGPURenderer: Multiple Render Targets (MRT) blending configuration is not fully supported in compatibility mode. The material blending will be used for all render targets.`);return}for(let a=0;a0?this.enable(r.SAMPLE_ALPHA_TO_COVERAGE):this.disable(r.SAMPLE_ALPHA_TO_COVERAGE),this.currentClippingPlanes!==n){let e=12288;for(let t=0;t<8;t++)t{function i(){let a=e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0);if(a===e.WAIT_FAILED){e.deleteSync(t),r();return}if(a===e.TIMEOUT_EXPIRED){requestAnimationFrame(i);return}e.deleteSync(t),n()}i()})}},BR=!1,WR=class{constructor(e){this.backend=e,this.gl=e.gl,this.extensions=e.extensions,this.defaultTextures={},this._srcFramebuffer=null,this._dstFramebuffer=null,BR===!1&&(this._init(),BR=!0)}_init(){let e=this.gl;VR={[Xt]:e.REPEAT,[Zt]:e.CLAMP_TO_EDGE,[Qt]:e.MIRRORED_REPEAT},HR={[$t]:e.NEAREST,[en]:e.NEAREST_MIPMAP_NEAREST,[nn]:e.NEAREST_MIPMAP_LINEAR,[an]:e.LINEAR,[on]:e.LINEAR_MIPMAP_NEAREST,[cn]:e.LINEAR_MIPMAP_LINEAR},UR={512:e.NEVER,519:e.ALWAYS,513:e.LESS,515:e.LEQUAL,514:e.EQUAL,518:e.GEQUAL,516:e.GREATER,517:e.NOTEQUAL}}getGLTextureType(e){let{gl:t}=this,n;return n=e.isCubeTexture===!0?t.TEXTURE_CUBE_MAP:e.isArrayTexture===!0||e.isDataArrayTexture===!0||e.isCompressedArrayTexture===!0?t.TEXTURE_2D_ARRAY:e.isData3DTexture===!0?t.TEXTURE_3D:t.TEXTURE_2D,n}getInternalFormat(e,t,n,r,i,a=!1){let{gl:o,extensions:s}=this;if(e!==null){if(o[e]!==void 0)return o[e];f(`WebGLBackend: Attempt to use non-existing WebGL internal format '`+e+`'`)}let c=null;r&&(c=s.get(`EXT_texture_norm16`),c||f(`WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension`));let l=t;if(t===o.RED&&(n===o.FLOAT&&(l=o.R32F),n===o.HALF_FLOAT&&(l=o.R16F),n===o.UNSIGNED_BYTE&&(l=o.R8),n===o.BYTE&&(l=o.R8_SNORM),n===o.UNSIGNED_SHORT&&c&&(l=c.R16_EXT),n===o.SHORT&&c&&(l=c.R16_SNORM_EXT)),t===o.RED_INTEGER&&(n===o.UNSIGNED_BYTE&&(l=o.R8UI),n===o.UNSIGNED_SHORT&&(l=o.R16UI),n===o.UNSIGNED_INT&&(l=o.R32UI),n===o.BYTE&&(l=o.R8I),n===o.SHORT&&(l=o.R16I),n===o.INT&&(l=o.R32I)),t===o.RG&&(n===o.FLOAT&&(l=o.RG32F),n===o.HALF_FLOAT&&(l=o.RG16F),n===o.UNSIGNED_BYTE&&(l=o.RG8),n===o.BYTE&&(l=o.RG8_SNORM),n===o.UNSIGNED_SHORT&&c&&(l=c.RG16_EXT),n===o.SHORT&&c&&(l=c.RG16_SNORM_EXT)),t===o.RG_INTEGER&&(n===o.UNSIGNED_BYTE&&(l=o.RG8UI),n===o.UNSIGNED_SHORT&&(l=o.RG16UI),n===o.UNSIGNED_INT&&(l=o.RG32UI),n===o.BYTE&&(l=o.RG8I),n===o.SHORT&&(l=o.RG16I),n===o.INT&&(l=o.RG32I)),t===o.RGB){let e=a?Pr:Ci.getTransfer(i);n===o.FLOAT&&(l=o.RGB32F),n===o.HALF_FLOAT&&(l=o.RGB16F),n===o.UNSIGNED_BYTE&&(l=e===`srgb`?o.SRGB8:o.RGB8),n===o.BYTE&&(l=o.RGB8_SNORM),n===o.UNSIGNED_SHORT&&c&&(l=c.RGB16_EXT),n===o.SHORT&&c&&(l=c.RGB16_SNORM_EXT),n===o.UNSIGNED_SHORT_5_6_5&&(l=o.RGB565),n===o.UNSIGNED_SHORT_5_5_5_1&&(l=o.RGB5_A1),n===o.UNSIGNED_SHORT_4_4_4_4&&(l=o.RGB4),n===o.UNSIGNED_INT_5_9_9_9_REV&&(l=o.RGB9_E5),n===o.UNSIGNED_INT_10F_11F_11F_REV&&(l=o.R11F_G11F_B10F)}if(t===o.RGB_INTEGER&&(n===o.UNSIGNED_BYTE&&(l=o.RGB8UI),n===o.UNSIGNED_SHORT&&(l=o.RGB16UI),n===o.UNSIGNED_INT&&(l=o.RGB32UI),n===o.BYTE&&(l=o.RGB8I),n===o.SHORT&&(l=o.RGB16I),n===o.INT&&(l=o.RGB32I)),t===o.RGBA){let e=a?Pr:Ci.getTransfer(i);n===o.FLOAT&&(l=o.RGBA32F),n===o.HALF_FLOAT&&(l=o.RGBA16F),n===o.UNSIGNED_BYTE&&(l=e===`srgb`?o.SRGB8_ALPHA8:o.RGBA8),n===o.BYTE&&(l=o.RGBA8_SNORM),n===o.UNSIGNED_SHORT&&c&&(l=c.RGBA16_EXT),n===o.SHORT&&c&&(l=c.RGBA16_SNORM_EXT),n===o.UNSIGNED_SHORT_4_4_4_4&&(l=o.RGBA4),n===o.UNSIGNED_SHORT_5_5_5_1&&(l=o.RGB5_A1)}return t===o.RGBA_INTEGER&&(n===o.UNSIGNED_BYTE&&(l=o.RGBA8UI),n===o.UNSIGNED_SHORT&&(l=o.RGBA16UI),n===o.UNSIGNED_INT&&(l=o.RGBA32UI),n===o.BYTE&&(l=o.RGBA8I),n===o.SHORT&&(l=o.RGBA16I),n===o.INT&&(l=o.RGBA32I)),t===o.DEPTH_COMPONENT&&(n===o.UNSIGNED_SHORT&&(l=o.DEPTH_COMPONENT16),n===o.UNSIGNED_INT&&(l=o.DEPTH_COMPONENT24),n===o.FLOAT&&(l=o.DEPTH_COMPONENT32F)),t===o.DEPTH_STENCIL&&n===o.UNSIGNED_INT_24_8&&(l=o.DEPTH24_STENCIL8),(l===o.R16F||l===o.R32F||l===o.RG16F||l===o.RG32F||l===o.RGBA16F||l===o.RGBA32F)&&s.get(`EXT_color_buffer_float`),l}setTextureParameters(e,t){let{gl:n,extensions:r,backend:i}=this,{state:a}=this.backend,o=Ci.getPrimaries(Ci.workingColorSpace),s=t.colorSpace===``?null:Ci.getPrimaries(t.colorSpace),c=t.colorSpace===``||o===s?n.NONE:n.BROWSER_DEFAULT_WEBGL;a.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,t.flipY),a.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),a.pixelStorei(n.UNPACK_ALIGNMENT,t.unpackAlignment),a.pixelStorei(n.UNPACK_COLORSPACE_CONVERSION_WEBGL,c),n.texParameteri(e,n.TEXTURE_WRAP_S,VR[t.wrapS]),n.texParameteri(e,n.TEXTURE_WRAP_T,VR[t.wrapT]),(e===n.TEXTURE_3D||e===n.TEXTURE_2D_ARRAY)&&(t.isArrayTexture||n.texParameteri(e,n.TEXTURE_WRAP_R,VR[t.wrapR])),n.texParameteri(e,n.TEXTURE_MAG_FILTER,HR[t.magFilter]);let l=t.mipmaps!==void 0&&t.mipmaps.length>0,u=t.minFilter===1006&&l?cn:t.minFilter;if(n.texParameteri(e,n.TEXTURE_MIN_FILTER,HR[u]),t.compareFunction&&(n.texParameteri(e,n.TEXTURE_COMPARE_MODE,n.COMPARE_REF_TO_TEXTURE),n.texParameteri(e,n.TEXTURE_COMPARE_FUNC,UR[t.compareFunction])),r.has(`EXT_texture_filter_anisotropic`)===!0){if(t.magFilter===1003||t.minFilter!==1005&&t.minFilter!==1008||t.type===1015&&r.has(`OES_texture_float_linear`)===!1)return;if(t.anisotropy>1){let a=r.get(`EXT_texture_filter_anisotropic`);n.texParameterf(e,a.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(t.anisotropy,i.capabilities.getMaxAnisotropy()))}}}createDefaultTexture(e){let{gl:t,backend:n,defaultTextures:r}=this,i=this.getGLTextureType(e),a=r[i];a===void 0&&(a=t.createTexture(),n.state.bindTexture(i,a),t.texParameteri(i,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(i,t.TEXTURE_MAG_FILTER,t.NEAREST),r[i]=a),n.set(e,{textureGPU:a,glTextureType:i})}createTexture(e,t){let{gl:n,backend:r}=this,i,a,o,s,c;if(e.isExternalTexture===!0)i=e.sourceTexture,a=this.getGLTextureType(e);else{let{levels:l,width:u,height:d,depth:f}=t;o=r.utils.convert(e.format,e.colorSpace),s=r.utils.convert(e.type),c=this.getInternalFormat(e.internalFormat,o,s,e.normalized,e.colorSpace,e.isVideoTexture),i=n.createTexture(),a=this.getGLTextureType(e),r.state.bindTexture(a,i),this.setTextureParameters(a,e),e.isArrayTexture||e.isDataArrayTexture||e.isCompressedArrayTexture?n.texStorage3D(n.TEXTURE_2D_ARRAY,l,c,u,d,f):e.isData3DTexture?n.texStorage3D(n.TEXTURE_3D,l,c,u,d,f):e.isVideoTexture||n.texStorage2D(a,l,c,u,d)}r.set(e,{textureGPU:i,glTextureType:a,glFormat:o,glType:s,glInternalFormat:c})}copyBufferToTexture(e,t){let{gl:n,backend:r}=this,{state:i}=r,{textureGPU:a,glTextureType:o,glFormat:s,glType:c}=r.get(t),{width:l,height:u}=t.source.data;n.bindBuffer(n.PIXEL_UNPACK_BUFFER,e),r.state.bindTexture(o,a),i.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,!1),i.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),n.texSubImage2D(o,0,0,0,l,u,s,c,0),n.bindBuffer(n.PIXEL_UNPACK_BUFFER,null),r.state.unbindTexture()}updateTexture(e,t){let{gl:n}=this,{width:r,height:i}=t,{textureGPU:a,glTextureType:o,glFormat:s,glType:c,glInternalFormat:l}=this.backend.get(e);if(!(e.isRenderTargetTexture||a===void 0)){if(this.backend.state.bindTexture(o,a),this.setTextureParameters(o,e),e.isCompressedTexture){let r=e.mipmaps,i=t.image;for(let t=0;t0){let r=Wt(a.width,a.height,e.format,e.type);for(let i of e.layerUpdates){let e=a.data.subarray(i*r/a.data.BYTES_PER_ELEMENT,(i+1)*r/a.data.BYTES_PER_ELEMENT);n.compressedTexSubImage3D(n.TEXTURE_2D_ARRAY,t,0,0,i,a.width,a.height,1,s,e)}}else n.compressedTexSubImage3D(n.TEXTURE_2D_ARRAY,t,0,0,0,a.width,a.height,i.depth,s,a.data)}else f(`WebGLBackend: Attempt to load unsupported compressed texture format in .uploadTexture()`)}else n.texSubImage3D(n.TEXTURE_2D_ARRAY,t,0,0,0,a.width,a.height,i.depth,s,c,a.data)}else s===null?f(`WebGLBackend: Unsupported compressed texture format`):n.compressedTexSubImage2D(n.TEXTURE_2D,t,0,0,a.width,a.height,s,a.data)}e.isCompressedArrayTexture&&e.layerUpdates.size>0&&e.clearLayerUpdates()}else if(e.isCubeTexture){let a=t.images,o=e.mipmaps;for(let e=0;e<6;e++){let t=Lm(a[e]);n.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,0,0,r,i,s,c,t);for(let t=0;t0){let t=Wt(r.width,r.height,e.format,e.type);for(let i of e.layerUpdates){let e=r.data.subarray(i*t/r.data.BYTES_PER_ELEMENT,(i+1)*t/r.data.BYTES_PER_ELEMENT);n.texSubImage3D(n.TEXTURE_2D_ARRAY,0,0,0,i,r.width,r.height,1,s,c,e)}e.clearLayerUpdates()}else n.texSubImage3D(n.TEXTURE_2D_ARRAY,0,0,0,0,r.width,r.height,r.depth,s,c,r.data)}else if(e.isData3DTexture){let e=t.image;n.texSubImage3D(n.TEXTURE_3D,0,0,0,0,e.width,e.height,e.depth,s,c,e.data)}else if(e.isVideoTexture)e.update(),n.texImage2D(o,0,l,s,c,t.image);else if(e.isHTMLTexture)typeof n.texElementImage2D==`function`&&(n.texElementImage2D.length===3?n.texElementImage2D(n.TEXTURE_2D,n.RGBA8,t.image):n.texElementImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,t.image));else{let a=e.mipmaps;if(a.length>0)for(let e=0,t=a.length;e0,d=t.renderTarget?t.renderTarget.height:this.backend.getDrawingBufferSize().y;if(u){let n=o!==0||s!==0,u,f;if(e.isDepthTexture===!0?(u=r.DEPTH_BUFFER_BIT,f=r.DEPTH_ATTACHMENT,t.stencil&&(u|=r.STENCIL_BUFFER_BIT)):(u=r.COLOR_BUFFER_BIT,f=r.COLOR_ATTACHMENT0),n){let e=this.backend.get(t.renderTarget),n=e.framebuffers[t.getCacheKey()],f=e.msaaFrameBuffer;i.bindFramebuffer(r.DRAW_FRAMEBUFFER,n),i.bindFramebuffer(r.READ_FRAMEBUFFER,f);let p=d-s-l;r.blitFramebuffer(o,p,o+c,p+l,o,p,o+c,p+l,u,r.NEAREST),i.bindFramebuffer(r.READ_FRAMEBUFFER,n),i.bindTexture(r.TEXTURE_2D,a),r.copyTexSubImage2D(r.TEXTURE_2D,0,0,0,o,p,c,l),i.unbindTexture()}else{let e=r.createFramebuffer();i.bindFramebuffer(r.DRAW_FRAMEBUFFER,e),r.framebufferTexture2D(r.DRAW_FRAMEBUFFER,f,r.TEXTURE_2D,a,0),r.blitFramebuffer(0,0,c,l,0,0,c,l,u,r.NEAREST),r.deleteFramebuffer(e)}}else i.bindTexture(r.TEXTURE_2D,a),r.copyTexSubImage2D(r.TEXTURE_2D,0,0,0,o,d-l-s,c,l),i.unbindTexture();e.generateMipmaps&&this.generateMipmaps(e),this.backend._setFramebuffer(t)}setupRenderBufferStorage(e,t,n,r=!1){let{gl:i}=this,a=t.renderTarget,{depthTexture:o,depthBuffer:s,stencilBuffer:c,width:l,height:u}=a;if(i.bindRenderbuffer(i.RENDERBUFFER,e),s&&!c){let t=i.DEPTH_COMPONENT24;r===!0?this.extensions.get(`WEBGL_multisampled_render_to_texture`).renderbufferStorageMultisampleEXT(i.RENDERBUFFER,a.samples,t,l,u):n>0?(o&&o.isDepthTexture&&o.type===i.FLOAT&&(t=i.DEPTH_COMPONENT32F),i.renderbufferStorageMultisample(i.RENDERBUFFER,n,t,l,u)):i.renderbufferStorage(i.RENDERBUFFER,t,l,u),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.RENDERBUFFER,e)}else s&&c&&(n>0?i.renderbufferStorageMultisample(i.RENDERBUFFER,n,i.DEPTH24_STENCIL8,l,u):i.renderbufferStorage(i.RENDERBUFFER,i.DEPTH_STENCIL,l,u),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,i.RENDERBUFFER,e));i.bindRenderbuffer(i.RENDERBUFFER,null)}async copyTextureToBuffer(e,t,n,r,i,a){let{backend:o,gl:s}=this,{textureGPU:c,glFormat:l,glType:u}=this.backend.get(e),d=s.createFramebuffer();if(o.state.bindFramebuffer(s.READ_FRAMEBUFFER,d),e.isData3DTexture||e.isDataArrayTexture||e.isArrayTexture)s.framebufferTextureLayer(s.READ_FRAMEBUFFER,s.COLOR_ATTACHMENT0,c,0,a);else{let t=e.isCubeTexture?s.TEXTURE_CUBE_MAP_POSITIVE_X+a:s.TEXTURE_2D;s.framebufferTexture2D(s.READ_FRAMEBUFFER,s.COLOR_ATTACHMENT0,t,c,0)}let f=this._getTypedArrayType(u),p=this._getBytesPerTexel(u,l),m=r*i*p,h=s.createBuffer();s.bindBuffer(s.PIXEL_PACK_BUFFER,h),s.bufferData(s.PIXEL_PACK_BUFFER,m,s.STREAM_READ),s.readPixels(t,n,r,i,l,u,0),s.bindBuffer(s.PIXEL_PACK_BUFFER,null),await o.utils._clientWaitAsync();let g=new f(m/f.BYTES_PER_ELEMENT);return s.bindBuffer(s.PIXEL_PACK_BUFFER,h),s.getBufferSubData(s.PIXEL_PACK_BUFFER,0,g),s.bindBuffer(s.PIXEL_PACK_BUFFER,null),o.state.bindFramebuffer(s.READ_FRAMEBUFFER,null),s.deleteBuffer(h),s.deleteFramebuffer(d),g}_getTypedArrayType(e){let{gl:t}=this;if(e===t.UNSIGNED_BYTE)return Uint8Array;if(e===t.UNSIGNED_SHORT_4_4_4_4||e===t.UNSIGNED_SHORT_5_5_5_1||e===t.UNSIGNED_SHORT_5_6_5||e===t.UNSIGNED_SHORT)return Uint16Array;if(e===t.UNSIGNED_INT)return Uint32Array;if(e===t.HALF_FLOAT)return Uint16Array;if(e===t.FLOAT)return Float32Array;throw Error(`THREE.WebGLTextureUtils: Unsupported WebGL type: ${e}`)}_getBytesPerTexel(e,t){let{gl:n}=this,r=0;if(e===n.UNSIGNED_BYTE&&(r=1),(e===n.UNSIGNED_SHORT_4_4_4_4||e===n.UNSIGNED_SHORT_5_5_5_1||e===n.UNSIGNED_SHORT_5_6_5||e===n.UNSIGNED_SHORT||e===n.HALF_FLOAT)&&(r=2),(e===n.UNSIGNED_INT||e===n.FLOAT)&&(r=4),t===n.RGBA)return r*4;if(t===n.RGB)return r*3;if(t===n.ALPHA)return r}dispose(){let{gl:e}=this;this._srcFramebuffer!==null&&e.deleteFramebuffer(this._srcFramebuffer),this._dstFramebuffer!==null&&e.deleteFramebuffer(this._dstFramebuffer)}},GR=class{constructor(e){this.backend=e,this.gl=this.backend.gl,this.availableExtensions=this.gl.getSupportedExtensions(),this.extensions={}}get(e){let t=this.extensions[e];return t===void 0&&(t=this.gl.getExtension(e),this.extensions[e]=t),t}has(e){return this.availableExtensions.includes(e)}},KR=class{constructor(e){this.backend=e,this.maxAnisotropy=null,this.maxUniformBlockSize=null}getMaxAnisotropy(){if(this.maxAnisotropy!==null)return this.maxAnisotropy;let e=this.backend.gl,t=this.backend.extensions;if(t.has(`EXT_texture_filter_anisotropic`)===!0){let n=t.get(`EXT_texture_filter_anisotropic`);this.maxAnisotropy=e.getParameter(n.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else this.maxAnisotropy=0;return this.maxAnisotropy}getUniformBufferLimit(){if(this.maxUniformBlockSize!==null)return this.maxUniformBlockSize;let e=this.backend.gl;return this.maxUniformBlockSize=e.getParameter(e.MAX_UNIFORM_BLOCK_SIZE),this.maxUniformBlockSize}},qR={WEBGL_multi_draw:`WEBGL_multi_draw`,WEBGL_compressed_texture_astc:`texture-compression-astc`,WEBGL_compressed_texture_etc:`texture-compression-etc2`,WEBGL_compressed_texture_etc1:`texture-compression-etc1`,WEBGL_compressed_texture_pvrtc:`texture-compression-pvrtc`,WEBGL_compressed_texture_s3tc:`texture-compression-s3tc`,EXT_texture_compression_bptc:`texture-compression-bc`,EXT_disjoint_timer_query_webgl2:`timestamp-query`,OVR_multiview2:`OVR_multiview2`},JR=class{constructor(e){this.gl=e.gl,this.extensions=e.extensions,this.info=e.renderer.info,this.mode=null,this.index=0,this.type=null,this.object=null}render(e,t){let{gl:n,mode:r,object:i,type:a,info:o,index:s}=this;s===0?n.drawArrays(r,e,t):n.drawElements(r,t,a,e),o.update(i,t,1)}renderInstances(e,t,n){let{gl:r,mode:i,type:a,index:o,object:s,info:c}=this;n!==0&&(o===0?r.drawArraysInstanced(i,e,t,n):r.drawElementsInstanced(i,t,a,e,n),c.update(s,t,n))}renderMultiDraw(e,t,n){let{extensions:r,mode:i,object:a,info:o}=this;if(n===0)return;let s=r.get(`WEBGL_multi_draw`);if(s===null)for(let r=0;rthis.maxQueries&&(this.resolveQueriesAsync(),this.currentQueryIndex=0,this.queryOffsets.clear(),this.queryStates.clear(),this.activeQuery=null);let t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryStates.set(t,`inactive`),this.queryOffsets.set(e,t),t}beginQuery(e){if(!this.trackTimestamp||this.isDisposed)return;let t=this.queryOffsets.get(e);if(t==null||this.activeQuery!==null)return;let n=this.queries[t];if(n)try{this.queryStates.get(t)===`inactive`&&(this.gl.beginQuery(this.ext.TIME_ELAPSED_EXT,n),this.activeQuery=t,this.queryStates.set(t,`started`))}catch(e){p(`Error in beginQuery:`,e),this.activeQuery=null,this.queryStates.set(t,`inactive`)}}endQuery(e){if(!this.trackTimestamp||this.isDisposed)return;let t=this.queryOffsets.get(e);if(t!=null&&this.activeQuery===t)try{this.gl.endQuery(this.ext.TIME_ELAPSED_EXT),this.queryStates.set(t,`ended`),this.activeQuery=null}catch(e){p(`Error in endQuery:`,e),this.queryStates.set(t,`inactive`),this.activeQuery=null}}async resolveQueriesAsync(){if(!this.trackTimestamp||this.pendingResolve)return this.lastValue;this.pendingResolve=!0;try{let e=new Map;for(let[t,n]of this.queryOffsets)if(this.queryStates.get(n)===`ended`){let r=this.queries[n];e.set(t,this.resolveQuery(r))}if(e.size===0)return this.lastValue;let t={},n=[];this.timestamps.clear();for(let[r,i]of e){let e=r.match(/^(.*):f(\d+)$/),a=parseInt(e[2]);n.includes(a)===!1&&n.push(a),t[a]===void 0&&(t[a]=0);let o=await i;this.timestamps.set(r,o),t[a]+=o}let r=t[n[n.length-1]];return this.lastValue=r,this.frames=n,this.currentQueryIndex=0,this.queryOffsets.clear(),this.queryStates.clear(),this.activeQuery=null,r}catch(e){return p(`Error resolving queries:`,e),this.lastValue}finally{this.pendingResolve=!1}}async resolveQuery(e){return new Promise(t=>{if(this.isDisposed){t(this.lastValue);return}let n,r=!1,i=()=>{n&&=(clearTimeout(n),null)},a=e=>{r||(r=!0,i(),t(e))},o=()=>{if(this.isDisposed){a(this.lastValue);return}try{if(this.gl.getParameter(this.ext.GPU_DISJOINT_EXT)){a(this.lastValue);return}if(!this.gl.getQueryParameter(e,this.gl.QUERY_RESULT_AVAILABLE)){n=setTimeout(o,1);return}let r=this.gl.getQueryParameter(e,this.gl.QUERY_RESULT);t(Number(r)/1e6)}catch(e){p(`Error checking query:`,e),t(this.lastValue)}};o()})}dispose(){if(!this.isDisposed&&(this.isDisposed=!0,this.trackTimestamp)){for(let e of this.queries)this.gl.deleteQuery(e);this.queries=[],this.queryStates.clear(),this.queryOffsets.clear(),this.timestamps.clear(),this.frames=[],this.lastValue=0,this.activeQuery=null}}},ZR=[],QR=class extends MR{constructor(e={}){super(e),this.isWebGLBackend=!0,this.attributeUtils=null,this.extensions=null,this.capabilities=null,this.textureUtils=null,this.bufferRenderer=null,this.gl=null,this.state=null,this.utils=null,this.vaoCache={},this.transformFeedbackCache={},this.discard=!1,this.disjoint=null,this.parallel=null,this._currentContext=null,this._knownBindings=new WeakSet,this._supportsInvalidateFramebuffer=typeof navigator>`u`?!1:/OculusBrowser/g.test(navigator.userAgent),this._xrFramebuffer=null}init(e){super.init(e);let t=this.parameters,n={antialias:e.currentSamples>0,alpha:!0,depth:e.depth,stencil:e.stencil},r=t.context===void 0?e.domElement.getContext(`webgl2`,n):t.context;function i(t){t.preventDefault();let n={api:`WebGL`,message:t.statusMessage||`Unknown reason`,reason:null,originalEvent:t};e.onDeviceLost(n)}this._onContextLost=i,e.domElement.addEventListener(`webglcontextlost`,i,!1),this.gl=r,this.extensions=new GR(this),this.capabilities=new KR(this),this.attributeUtils=new FR(this),this.textureUtils=new WR(this),this.bufferRenderer=new JR(this),this.state=new RR(this),this.utils=new zR(this),this.extensions.get(`EXT_color_buffer_float`),this.extensions.get(`WEBGL_clip_cull_distance`),this.extensions.get(`OES_texture_float_linear`),this.extensions.get(`EXT_color_buffer_half_float`),this.extensions.get(`WEBGL_multisampled_render_to_texture`),this.extensions.get(`WEBGL_render_shared_exponent`),this.extensions.get(`WEBGL_multi_draw`),this.extensions.get(`OVR_multiview2`),this.extensions.get(`EXT_clip_control`),this.disjoint=this.extensions.get(`EXT_disjoint_timer_query_webgl2`),this.parallel=this.extensions.get(`KHR_parallel_shader_compile`),this.drawBuffersIndexedExt=this.extensions.get(`OES_draw_buffers_indexed`),t.reversedDepthBuffer&&(this.extensions.has(`EXT_clip_control`)?e.reversedDepthBuffer=!0:(f(`WebGPURenderer: Unable to use reversed depth buffer due to missing EXT_clip_control extension. Fallback to default depth buffer.`),e.reversedDepthBuffer=!1)),e.reversedDepthBuffer&&this.state.setReversedDepth(!0)}get coordinateSystem(){return $r}get hasTimestamp(){return this.disjoint!==null}async getArrayBufferAsync(e,t=null,n=0,r=-1){return await this.attributeUtils.getArrayBufferAsync(e,t,n,r)}async makeXRCompatible(){this.gl.getContextAttributes().xrCompatible!==!0&&await this.gl.makeXRCompatible()}setXRTarget(e){this._xrFramebuffer=e}setXRRenderTargetTextures(e,t,n=null){let r=this.gl;if(this.set(e.texture,{textureGPU:t,glInternalFormat:r.RGBA8}),n!==null){let t=e.stencilBuffer?r.DEPTH24_STENCIL8:r.DEPTH_COMPONENT24;this.set(e.depthTexture,{textureGPU:n,glInternalFormat:t}),this.extensions.has(`WEBGL_multisampled_render_to_texture`)===!0&&e._autoAllocateDepthBuffer===!0&&e.multiview===!1&&f(`WebGLBackend: Render-to-texture extension was disabled because an external texture was provided`),e._autoAllocateDepthBuffer=!1}}initTimestampQuery(e,t){if(!this.disjoint||!this.trackTimestamp)return;this.timestampQueryPool[e]||(this.timestampQueryPool[e]=new XR(this.gl,e,2048));let n=this.timestampQueryPool[e];n.allocateQueriesForContext(t)!==null&&n.beginQuery(t)}prepareTimestampBuffer(e,t){this.disjoint&&this.trackTimestamp&&this.timestampQueryPool[e].endQuery(t)}getContext(){return this.gl}beginRender(e){let{state:t}=this,n=this.get(e);if(e.viewport)this.updateViewport(e);else{let{width:e,height:n}=this.getDrawingBufferSize();t.viewport(0,0,e,n)}if(e.scissor)this.updateScissor(e);else{let{width:e,height:n}=this.getDrawingBufferSize();t.scissor(0,0,e,n)}this.initTimestampQuery(ti.RENDER,this.getTimestampUID(e)),n.previousContext=this._currentContext,this._currentContext=e,this._setFramebuffer(e),this.clear(e.clearColor,e.clearDepth,e.clearStencil,e,!1);let r=e.occlusionQueryCount;r>0?(n.currentOcclusionQueries=n.occlusionQueries,n.currentOcclusionQueryObjects=n.occlusionQueryObjects,n.lastOcclusionObject=null,n.occlusionQueries=Array(r),n.occlusionQueryObjects=Array(r),n.occlusionQueryIndex=0):n.lastOcclusionObject!==void 0&&(n.lastOcclusionObject=void 0)}finishRender(e){let{gl:t,state:n}=this,r=this.get(e),i=r.previousContext;if(n.resetVertexState(),e.occlusionQueryCount>0){let n=r.lastOcclusionObject;n&&n.occlusionTest===!0&&t.endQuery(t.ANY_SAMPLES_PASSED),this.resolveOccludedAsync(e)}let a=e.textures;if(a!==null)for(let e=0;e{let o=!0;for(let t=0;t1?t.renderInstances(n,r,i):t.render(n,r)}draw(e){let{object:t,pipeline:n,material:r,context:i,hardwareClippingPlanes:a}=e,{programGPU:o}=this.get(n),{gl:s,state:c}=this,l=this.get(i),u=e.getDrawParameters();if(u===null)return;this._bindUniforms(e.getBindings());let d=t.isMesh&&t.matrixWorld.determinantAffine()<0;c.setMaterial(r,d,a),i.mrt!==null&&i.textures!==null&&c.setMRTBlending(i.textures,i.mrt,r),c.useProgram(o);let f=e.getAttributes(),p=this.get(f),m=p.vaoGPU;if(m===void 0){let e=this._getVaoKey(f);m=this.vaoCache[e],m===void 0&&(m=this._createVao(f),this.vaoCache[e]=m,p.vaoGPU=m)}let h=e.getIndex(),g=h===null?null:this.get(h).bufferGPU;c.setVertexState(m,g);let _=l.lastOcclusionObject;if(_!==t&&_!==void 0){if(_!==null&&_.occlusionTest===!0&&(s.endQuery(s.ANY_SAMPLES_PASSED),l.occlusionQueryIndex++),t.occlusionTest===!0){let e=s.createQuery();s.beginQuery(s.ANY_SAMPLES_PASSED,e),l.occlusionQueries[l.occlusionQueryIndex]=e,l.occlusionQueryObjects[l.occlusionQueryIndex]=t}l.lastOcclusionObject=t}let v=this.bufferRenderer;t.isPoints?v.mode=s.POINTS:t.isLineSegments?v.mode=s.LINES:t.isLine?v.mode=s.LINE_STRIP:t.isLineLoop?v.mode=s.LINE_LOOP:r.wireframe===!0?(c.setLineWidth(r.wireframeLinewidth*this.renderer.getPixelRatio()),v.mode=s.LINES):v.mode=s.TRIANGLES;let{vertexCount:y,instanceCount:b}=u,{firstVertex:x}=u;if(v.object=t,h!==null){x*=h.array.BYTES_PER_ELEMENT;let e=this.get(h);v.index=h.count,v.type=e.type}else v.index=0;if(e.camera.isArrayCamera===!0&&e.camera.cameras.length>0&&e.camera.isMultiViewCamera===!1){let n=this.get(e.camera),r=e.camera.cameras,i=e.getBindingGroup(`cameraIndex`).bindings[0];if(n.indexesGPU===void 0||n.indexesGPU.length!==r.length){let e=new Uint32Array([0,0,0,0]),t=[];for(let n=0,i=r.length;n{let i=this.parallel,a=()=>{n.getProgramParameter(o,i.COMPLETION_STATUS_KHR)?(this._completeCompile(e,r),t()):requestAnimationFrame(a)};a()});t.push(i);return}this._completeCompile(e,r)}_handleSource(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(` `)}_getShaderErrors(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+` `+this._handleSource(e.getShaderSource(t),r)}return i}_logProgramError(e,t,n){if(this.renderer.debug.checkShaderErrors){let r=this.gl,i=(r.getProgramInfoLog(e)||``).trim();if(r.getProgramParameter(e,r.LINK_STATUS)===!1){if(typeof this.renderer.debug.onShaderError==`function`)this.renderer.debug.onShaderError(r,e,n,t);else{let a=this._getShaderErrors(r,n,`vertex`),o=this._getShaderErrors(r,t,`fragment`);p(`WebGLProgram: Shader Error `+r.getError()+` - VALIDATE_STATUS `+r.getProgramParameter(e,r.VALIDATE_STATUS)+` Program Info Log: `+i+` `+a+` `+o)}}else i!==``&&f(`WebGLProgram: Program Info Log:`,i)}}_completeCompile(e,t){let{state:n,gl:r}=this,{programGPU:i,fragmentShader:a,vertexShader:o}=this.get(t);r.getProgramParameter(i,r.LINK_STATUS)===!1&&this._logProgramError(i,a,o),n.useProgram(i);let s=e.getBindings();this._setupBindings(s,i),this.set(t,{programGPU:i,pipeline:i})}createComputePipeline(e,t,n=null){let{gl:r}=this,i={stage:`fragment`,code:`#version 300 es precision highp float; void main() {}`};this.createProgram(i);let{computeProgram:a}=e,o=r.createProgram(),s=this.get(i).shaderGPU,c=this.get(a).shaderGPU,l=a.transforms,u=[],d=[];for(let e=0;e{let a=()=>{r.getProgramParameter(o,i.COMPLETION_STATUS_KHR)?(this._completeComputeCompile(e,t),n()):requestAnimationFrame(a)};a()});n.push(a);return}this._completeComputeCompile(e,t)}_completeComputeCompile(e,t){let{state:n,gl:r}=this,{programGPU:i,fragmentShader:a,vertexShader:o}=this.get(e);r.getProgramParameter(i,r.LINK_STATUS)===!1&&this._logProgramError(i,a,o),n.useProgram(i),this._setupBindings(t,i)}createBindings(e,t){if(this._knownBindings.has(t)===!1){this._knownBindings.add(t);let e=0,n=0;for(let r of t){this.set(r,{textures:n,uniformBuffers:e});for(let t of r.bindings)t.isUniformBuffer&&e++,t.isSampledTexture&&n++}}this.updateBindings(e,t)}updateBindings(e){let{gl:t}=this;for(let n of e.bindings){let e=this.get(n);if(n.isUniformsGroup||n.isUniformBuffer){let r=n.buffer,i=e.bufferGPU;t.bindBuffer(t.UNIFORM_BUFFER,i);let o=n.updateRanges;if(t.bindBuffer(t.UNIFORM_BUFFER,i),o.length===0)t.bufferData(t.UNIFORM_BUFFER,r,t.DYNAMIC_DRAW);else{let e=a(r),n=e?1:r.BYTES_PER_ELEMENT;for(let i=0,a=o.length;iqR[t]===e),n=this.extensions;for(let e=0;e1,d=i.isXRRenderTarget===!0,f=d===!0&&i._hasExternalTextures===!0,p=a.msaaFrameBuffer,h=a.depthRenderbuffer,g=this.extensions.get(`WEBGL_multisampled_render_to_texture`),_=this.extensions.get(`OVR_multiview2`),v=this._useMultisampledExtension(i),y=i.samples;e.depthTexture!==null&&e.depthTexture.renderTarget!==i&&v===!1&&y>0&&(m(`WebGLBackend: Shared depth texture is not supported with MSAA when "WEBGL_multisampled_render_to_texture" is unsupported. Falling back to single-sample rendering.`),y=0);let b=tm(e),x;if(c?(a.cubeFramebuffers||={},x=a.cubeFramebuffers[b]):d&&f===!1?x=this._xrFramebuffer:(a.framebuffers||={},x=a.framebuffers[b]),x===void 0){x=t.createFramebuffer(),n.bindFramebuffer(t.FRAMEBUFFER,x);let r=e.textures,o=[];if(c){a.cubeFramebuffers[b]=x;let{textureGPU:e}=this.get(r[0]),n=this.renderer._activeCubeFace,i=this.renderer._activeMipmapLevel;t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+n,e,i)}else{a.framebuffers[b]=x;for(let n=0;n0&&v===!1&&!i.multiview){if(p===void 0){p=t.createFramebuffer(),n.bindFramebuffer(t.FRAMEBUFFER,p);let r=[],i=e.textures;for(let n=0;n0&&i.msaaFrameBuffer!==void 0&&this._useMultisampledExtension(r)===!1){let a=i.framebuffers[e.getCacheKey()],o=r.resolveColorBuffer===!1?0:t.COLOR_BUFFER_BIT;r.resolveDepthBuffer&&(r.depthBuffer&&(o|=t.DEPTH_BUFFER_BIT),r.stencilBuffer&&r.resolveStencilBuffer&&(o|=t.STENCIL_BUFFER_BIT));let s=i.msaaFrameBuffer,c=i.msaaRenderbuffers,l=e.textures,u=l.length>1;if(n.bindFramebuffer(t.READ_FRAMEBUFFER,s),n.bindFramebuffer(t.DRAW_FRAMEBUFFER,a),u)for(let e=0;e0&&(t.invalidateFramebuffer(t.READ_FRAMEBUFFER,ZR),ZR.length=0)}}else if(this._supportsInvalidateFramebuffer===!0&&i.framebuffers&&(r._autoAllocateDepthBuffer===!0||r.samples>0&&r.storeMultisampledDepthBuffer===!1)){let r=i.framebuffers[e.getCacheKey()];n.bindFramebuffer(t.DRAW_FRAMEBUFFER,r),t.invalidateFramebuffer(t.DRAW_FRAMEBUFFER,i.depthInvalidationArray)}}}_useMultisampledExtension(e){return e.multiview===!0||e.samples>0&&this.extensions.has(`WEBGL_multisampled_render_to_texture`)===!0&&e._autoAllocateDepthBuffer!==!1}async dispose(){await super.dispose(),this.textureUtils!==null&&this.textureUtils.dispose();let e=this.extensions.get(`WEBGL_lose_context`);e&&e.loseContext(),this.renderer.domElement.removeEventListener(`webglcontextlost`,this._onContextLost)}},$R={PointList:`point-list`,LineList:`line-list`,LineStrip:`line-strip`,TriangleList:`triangle-list`},ez=typeof self<`u`&&self.GPUShaderStage?self.GPUShaderStage:{VERTEX:1,FRAGMENT:2,COMPUTE:4},tz={Never:`never`,Less:`less`,Equal:`equal`,LessEqual:`less-equal`,Greater:`greater`,NotEqual:`not-equal`,GreaterEqual:`greater-equal`,Always:`always`},nz={Store:`store`,Discard:`discard`},rz={Load:`load`,Clear:`clear`},iz={CCW:`ccw`,CW:`cw`},az={None:`none`,Back:`back`},oz={Uint16:`uint16`,Uint32:`uint32`},Z={R8Unorm:`r8unorm`,R8Snorm:`r8snorm`,R8Uint:`r8uint`,R8Sint:`r8sint`,R16Uint:`r16uint`,R16Sint:`r16sint`,R16Float:`r16float`,RG8Unorm:`rg8unorm`,RG8Snorm:`rg8snorm`,RG8Uint:`rg8uint`,RG8Sint:`rg8sint`,R16Unorm:`r16unorm`,R16Snorm:`r16snorm`,R32Uint:`r32uint`,R32Sint:`r32sint`,R32Float:`r32float`,RG16Uint:`rg16uint`,RG16Sint:`rg16sint`,RG16Float:`rg16float`,RGBA8Unorm:`rgba8unorm`,RGBA8UnormSRGB:`rgba8unorm-srgb`,RGBA8Snorm:`rgba8snorm`,RGBA8Uint:`rgba8uint`,RGBA8Sint:`rgba8sint`,BGRA8Unorm:`bgra8unorm`,BGRA8UnormSRGB:`bgra8unorm-srgb`,RG16Unorm:`rg16unorm`,RG16Snorm:`rg16snorm`,RGB9E5UFloat:`rgb9e5ufloat`,RGB10A2Unorm:`rgb10a2unorm`,RG11B10UFloat:`rg11b10ufloat`,RG32Uint:`rg32uint`,RG32Sint:`rg32sint`,RG32Float:`rg32float`,RGBA16Uint:`rgba16uint`,RGBA16Sint:`rgba16sint`,RGBA16Float:`rgba16float`,RGBA16Unorm:`rgba16unorm`,RGBA16Snorm:`rgba16snorm`,RGBA32Uint:`rgba32uint`,RGBA32Sint:`rgba32sint`,RGBA32Float:`rgba32float`,Depth16Unorm:`depth16unorm`,Depth24Plus:`depth24plus`,Depth24PlusStencil8:`depth24plus-stencil8`,Depth32Float:`depth32float`,Depth32FloatStencil8:`depth32float-stencil8`,BC1RGBAUnorm:`bc1-rgba-unorm`,BC1RGBAUnormSRGB:`bc1-rgba-unorm-srgb`,BC2RGBAUnorm:`bc2-rgba-unorm`,BC2RGBAUnormSRGB:`bc2-rgba-unorm-srgb`,BC3RGBAUnorm:`bc3-rgba-unorm`,BC3RGBAUnormSRGB:`bc3-rgba-unorm-srgb`,BC4RUnorm:`bc4-r-unorm`,BC4RSnorm:`bc4-r-snorm`,BC5RGUnorm:`bc5-rg-unorm`,BC5RGSnorm:`bc5-rg-snorm`,BC6HRGBUFloat:`bc6h-rgb-ufloat`,BC6HRGBFloat:`bc6h-rgb-float`,BC7RGBAUnorm:`bc7-rgba-unorm`,BC7RGBAUnormSRGB:`bc7-rgba-unorm-srgb`,ETC2RGB8Unorm:`etc2-rgb8unorm`,ETC2RGB8UnormSRGB:`etc2-rgb8unorm-srgb`,ETC2RGB8A1Unorm:`etc2-rgb8a1unorm`,ETC2RGB8A1UnormSRGB:`etc2-rgb8a1unorm-srgb`,ETC2RGBA8Unorm:`etc2-rgba8unorm`,ETC2RGBA8UnormSRGB:`etc2-rgba8unorm-srgb`,EACR11Unorm:`eac-r11unorm`,EACR11Snorm:`eac-r11snorm`,EACRG11Unorm:`eac-rg11unorm`,EACRG11Snorm:`eac-rg11snorm`,ASTC4x4Unorm:`astc-4x4-unorm`,ASTC4x4UnormSRGB:`astc-4x4-unorm-srgb`,ASTC5x4Unorm:`astc-5x4-unorm`,ASTC5x4UnormSRGB:`astc-5x4-unorm-srgb`,ASTC5x5Unorm:`astc-5x5-unorm`,ASTC5x5UnormSRGB:`astc-5x5-unorm-srgb`,ASTC6x5Unorm:`astc-6x5-unorm`,ASTC6x5UnormSRGB:`astc-6x5-unorm-srgb`,ASTC6x6Unorm:`astc-6x6-unorm`,ASTC6x6UnormSRGB:`astc-6x6-unorm-srgb`,ASTC8x5Unorm:`astc-8x5-unorm`,ASTC8x5UnormSRGB:`astc-8x5-unorm-srgb`,ASTC8x6Unorm:`astc-8x6-unorm`,ASTC8x6UnormSRGB:`astc-8x6-unorm-srgb`,ASTC8x8Unorm:`astc-8x8-unorm`,ASTC8x8UnormSRGB:`astc-8x8-unorm-srgb`,ASTC10x5Unorm:`astc-10x5-unorm`,ASTC10x5UnormSRGB:`astc-10x5-unorm-srgb`,ASTC10x6Unorm:`astc-10x6-unorm`,ASTC10x6UnormSRGB:`astc-10x6-unorm-srgb`,ASTC10x8Unorm:`astc-10x8-unorm`,ASTC10x8UnormSRGB:`astc-10x8-unorm-srgb`,ASTC10x10Unorm:`astc-10x10-unorm`,ASTC10x10UnormSRGB:`astc-10x10-unorm-srgb`,ASTC12x10Unorm:`astc-12x10-unorm`,ASTC12x10UnormSRGB:`astc-12x10-unorm-srgb`,ASTC12x12Unorm:`astc-12x12-unorm`,ASTC12x12UnormSRGB:`astc-12x12-unorm-srgb`},sz={ClampToEdge:`clamp-to-edge`,Repeat:`repeat`,MirrorRepeat:`mirror-repeat`},cz={Linear:`linear`,Nearest:`nearest`},lz={Zero:`zero`,One:`one`,Src:`src`,OneMinusSrc:`one-minus-src`,SrcAlpha:`src-alpha`,OneMinusSrcAlpha:`one-minus-src-alpha`,Dst:`dst`,OneMinusDst:`one-minus-dst`,DstAlpha:`dst-alpha`,OneMinusDstAlpha:`one-minus-dst-alpha`,SrcAlphaSaturated:`src-alpha-saturated`,Constant:`constant`,OneMinusConstant:`one-minus-constant`},uz={Add:`add`,Subtract:`subtract`,ReverseSubtract:`reverse-subtract`,Min:`min`,Max:`max`},dz={None:0,All:15},fz={Keep:`keep`,Zero:`zero`,Replace:`replace`,Invert:`invert`,IncrementClamp:`increment-clamp`,DecrementClamp:`decrement-clamp`,IncrementWrap:`increment-wrap`,DecrementWrap:`decrement-wrap`},pz={Storage:`storage`,ReadOnlyStorage:`read-only-storage`},mz={WriteOnly:`write-only`,ReadOnly:`read-only`,ReadWrite:`read-write`},hz={NonFiltering:`non-filtering`,Comparison:`comparison`},gz={Float:`float`,UnfilterableFloat:`unfilterable-float`,Depth:`depth`,SInt:`sint`,UInt:`uint`},_z={TwoD:`2d`,ThreeD:`3d`},vz={TwoD:`2d`,TwoDArray:`2d-array`,Cube:`cube`,ThreeD:`3d`},yz={All:`all`},bz={Vertex:`vertex`,Instance:`instance`},xz={CoreFeaturesAndLimits:`core-features-and-limits`,DepthClipControl:`depth-clip-control`,Depth32FloatStencil8:`depth32float-stencil8`,TextureCompressionBC:`texture-compression-bc`,TextureCompressionBCSliced3D:`texture-compression-bc-sliced-3d`,TextureCompressionETC2:`texture-compression-etc2`,TextureCompressionASTC:`texture-compression-astc`,TextureCompressionASTCSliced3D:`texture-compression-astc-sliced-3d`,TimestampQuery:`timestamp-query`,IndirectFirstInstance:`indirect-first-instance`,ShaderF16:`shader-f16`,RG11B10UFloat:`rg11b10ufloat-renderable`,BGRA8UNormStorage:`bgra8unorm-storage`,Float32Filterable:`float32-filterable`,Float32Blendable:`float32-blendable`,ClipDistances:`clip-distances`,DualSourceBlending:`dual-source-blending`,Subgroups:`subgroups`,TextureFormatsTier1:`texture-formats-tier1`,TextureFormatsTier2:`texture-formats-tier2`},Sz={"texture-compression-s3tc":`texture-compression-bc`,"texture-compression-etc1":`texture-compression-etc2`},Cz=class extends hR{constructor(e,t,n){super(e,t?t.value:null),this.textureNode=t,this.groupNode=n}update(){let{textureNode:e}=this;return this.texture===e.value?super.update():(this.texture=e.value,!0)}},wz=class extends cR{constructor(e,t){super(e,t?t.array:null),this._attribute=t,this.isStorageBuffer=!0}get attribute(){return this._attribute}},Tz=0,Ez=class extends wz{constructor(e,t){let n=e&&e.name?e.name:Tz++;super(`StorageBuffer_`+n,e?e.value:null),this.nodeUniform=e,this.access=e?e.access:ih.READ_WRITE,this.groupNode=t}get attribute(){return this.nodeUniform.value}get buffer(){return this.nodeUniform.value.array}},Dz=[null],Oz=class{constructor(e){this.backend=e,this._preferredCanvasFormat=null}getCurrentDepthStencilFormat(e){let t;return e.depth&&(t=e.depthTexture===null?e.stencil?this.backend.renderer.reversedDepthBuffer===!0?Z.Depth32FloatStencil8:Z.Depth24PlusStencil8:this.backend.renderer.reversedDepthBuffer===!0?Z.Depth32Float:Z.Depth24Plus:this.getTextureFormatGPU(e.depthTexture)),t}getTextureFormatGPU(e){return this.backend.get(e).format}getTextureSampleData(e){let t;if(e.isFramebufferTexture)t=1;else if(e.isDepthTexture&&!e.renderTarget){let n=this.backend.get(e);t=n.texture===void 0?this.backend.renderer.currentSamples:n.texture.sampleCount}else e.renderTarget&&(t=e.renderTarget.samples);t=this.getSampleCount(t||1);let n=t>1&&e.renderTarget!==null&&e.isDepthTexture!==!0&&e.isFramebufferTexture!==!0,r=t>1&&e.renderTarget!==null&&e.isDepthTexture===!0&&e.isArrayTexture===!0;return{samples:t,primarySamples:n||r?1:t,isMSAA:n}}getCurrentColorFormat(e){let t;return t=e.textures===null?this.getPreferredCanvasFormat():this.getTextureFormatGPU(e.textures[0]),t}getCurrentColorFormats(e){return e.textures===null?[this.getPreferredCanvasFormat()]:e.textures.map(e=>this.getTextureFormatGPU(e))}getCurrentColorSpace(e){return e.textures===null?this.backend.renderer.outputColorSpace:e.textures[0].colorSpace}getPrimitiveTopology(e,t){if(e.isPoints)return $R.PointList;if(e.isLineSegments||e.isMesh&&t.wireframe===!0)return $R.LineList;if(e.isLine)return $R.LineStrip;if(e.isMesh)return $R.TriangleList}getSampleCount(e){return e>=4?4:1}getSampleCountRenderContext(e){return e.textures===null?this.getSampleCount(this.backend.renderer.currentSamples):this.getSampleCount(e.sampleCount)}getPreferredCanvasFormat(){let e=this.backend.parameters.outputType;if(e===void 0)return this._preferredCanvasFormat===null&&(this._preferredCanvasFormat=navigator.gpu.getPreferredCanvasFormat()),this._preferredCanvasFormat;if(e===1009)return Z.BGRA8Unorm;if(e===1016)return Z.RGBA16Float;throw Error(`THREE.WebGPUUtils: Unsupported output buffer type.`)}},kz=class{constructor(){this.label=``,this.layout=null,this.entries=[]}reset(){this.label=``,this.layout=null,this.entries.length=0}},Az=class{constructor(){this.label=``,this.size=0,this.usage=0,this.mappedAtCreation=!1}reset(){this.label=``,this.size=0,this.usage=0,this.mappedAtCreation=!1}},jz=class{constructor(){this.label=``}reset(){this.label=``}},Mz=class{constructor(){this.label=``,this.colorFormats=null,this.depthStencilFormat=void 0,this.sampleCount=1,this.depthReadOnly=!1,this.stencilReadOnly=!1}reset(){this.label=``,this.colorFormats=null,this.depthStencilFormat=void 0,this.sampleCount=1,this.depthReadOnly=!1,this.stencilReadOnly=!1}},Nz=class{constructor(){this.view=null,this.depthSlice=void 0,this.resolveTarget=void 0,this.clearValue=void 0,this.loadOp=void 0,this.storeOp=void 0}reset(){this.view=null,this.depthSlice=void 0,this.resolveTarget=void 0,this.clearValue=void 0,this.loadOp=void 0,this.storeOp=void 0}},Pz=class{constructor(){this.label=``,this.colorAttachments=[],this.depthStencilAttachment=void 0,this.occlusionQuerySet=void 0,this.timestampWrites=void 0,this.maxDrawCount=5e7}reset(){this.label=``,this.colorAttachments.length=0,this.depthStencilAttachment=void 0,this.occlusionQuerySet=void 0,this.timestampWrites=void 0,this.maxDrawCount=5e7}},Fz=class{constructor(){this.label=``,this.layout=null,this.vertex=null,this.primitive={},this.depthStencil=void 0,this.multisample=new Iz,this.fragment=null}reset(){this.label=``,this.layout=null,this.vertex=null,this.primitive={},this.depthStencil=void 0,this.multisample.reset(),this.fragment=null}},Iz=class{constructor(){this.count=1,this.mask=4294967295,this.alphaToCoverageEnabled=!1}reset(){this.count=1,this.mask=4294967295,this.alphaToCoverageEnabled=!1}},Lz=class{constructor(){this.label=``,this.code=``,this.compilationHints=[]}reset(){this.label=``,this.code=``,this.compilationHints.length=0}},Rz=class{constructor(){this.label=``,this.size={width:0,height:1,depthOrArrayLayers:1},this.mipLevelCount=1,this.sampleCount=1,this.dimension=`2d`,this.format=void 0,this.usage=void 0,this.viewFormats=[],this.textureBindingViewDimension=void 0}reset(){this.label=``,this.size.width=0,this.size.height=1,this.size.depthOrArrayLayers=1,this.mipLevelCount=1,this.sampleCount=1,this.dimension=`2d`,this.format=void 0,this.usage=void 0,this.viewFormats.length=0,this.textureBindingViewDimension=void 0}},zz=class{constructor(){this.label=``,this.format=void 0,this.dimension=void 0,this.usage=0,this.aspect=`all`,this.baseMipLevel=0,this.mipLevelCount=void 0,this.baseArrayLayer=0,this.arrayLayerCount=void 0,this.swizzle=`rgba`}reset(){this.label=``,this.format=void 0,this.dimension=void 0,this.usage=0,this.aspect=`all`,this.baseMipLevel=0,this.mipLevelCount=void 0,this.baseArrayLayer=0,this.arrayLayerCount=void 0,this.swizzle=`rgba`}},Bz=new kz,Vz=new Az,Hz=new jz,Uz=new Mz,Wz=new Pz,Gz=new Fz,Kz=new Nz,qz=new Lz,Jz=new Rz,Yz=new zz,Xz=class extends YO{constructor(e){super(),this.device=e,this.mipmapSampler=e.createSampler({minFilter:cz.Linear}),this.flipYSampler=e.createSampler({minFilter:cz.Nearest}),Vz.size=4,Vz.usage=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,this.flipUniformBuffer=e.createBuffer(Vz),Vz.reset(),e.queue.writeBuffer(this.flipUniformBuffer,0,new Uint32Array([1])),Vz.size=4,Vz.usage=GPUBufferUsage.UNIFORM,this.noFlipUniformBuffer=e.createBuffer(Vz),Vz.reset(),this.transferPipelines={},qz.label=`mipmap`,qz.code=` struct VarysStruct { @builtin( position ) Position: vec4f, @location( 0 ) vTex : vec2f, @location( 1 ) @interpolate(flat, either) vBaseArrayLayer: u32, }; @group( 0 ) @binding ( 2 ) var flipY: u32; @vertex fn mainVS( @builtin( vertex_index ) vertexIndex : u32, @builtin( instance_index ) instanceIndex : u32 ) -> VarysStruct { var Varys : VarysStruct; var pos = array( vec2f( -1, -1 ), vec2f( -1, 3 ), vec2f( 3, -1 ), ); let p = pos[ vertexIndex ]; let mult = select( vec2f( 0.5, -0.5 ), vec2f( 0.5, 0.5 ), flipY != 0 ); Varys.vTex = p * mult + vec2f( 0.5 ); Varys.Position = vec4f( p, 0, 1 ); Varys.vBaseArrayLayer = instanceIndex; return Varys; } @group( 0 ) @binding( 0 ) var imgSampler : sampler; @group( 0 ) @binding( 1 ) var img2d : texture_2d; @fragment fn main_2d( Varys: VarysStruct ) -> @location( 0 ) vec4 { return textureSample( img2d, imgSampler, Varys.vTex ); } @group( 0 ) @binding( 1 ) var img2dArray : texture_2d_array; @fragment fn main_2d_array( Varys: VarysStruct ) -> @location( 0 ) vec4 { return textureSample( img2dArray, imgSampler, Varys.vTex, Varys.vBaseArrayLayer ); } const faceMat = array( mat3x3f( 0, 0, -2, 0, -2, 0, 1, 1, 1 ), // pos-x mat3x3f( 0, 0, 2, 0, -2, 0, -1, 1, -1 ), // neg-x mat3x3f( 2, 0, 0, 0, 0, 2, -1, 1, -1 ), // pos-y mat3x3f( 2, 0, 0, 0, 0, -2, -1, -1, 1 ), // neg-y mat3x3f( 2, 0, 0, 0, -2, 0, -1, 1, 1 ), // pos-z mat3x3f( -2, 0, 0, 0, -2, 0, 1, 1, -1 ), // neg-z ); @group( 0 ) @binding( 1 ) var imgCube : texture_cube; @fragment fn main_cube( Varys: VarysStruct ) -> @location( 0 ) vec4 { return textureSample( imgCube, imgSampler, faceMat[ Varys.vBaseArrayLayer ] * vec3f( fract( Varys.vTex ), 1 ) ); } `,this.mipmapShaderModule=e.createShaderModule(qz),qz.reset()}getTransferPipeline(e,t){t||=`2d-array`;let n=`${e}-${t}`,r=this.transferPipelines[n];return r===void 0&&(Gz.label=`mipmap-${e}-${t}`,Gz.vertex={module:this.mipmapShaderModule},Gz.fragment={module:this.mipmapShaderModule,entryPoint:`main_${t.replace(`-`,`_`)}`,targets:[{format:e}]},Gz.layout=`auto`,r=this.device.createRenderPipeline(Gz),Gz.reset(),this.transferPipelines[n]=r),r}flipY(e,t,n=0){let r=t.format,{width:i,height:a}=t.size;Jz.size.width=i,Jz.size.height=a,Jz.format=r,Jz.usage=GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING;let o=this.device.createTexture(Jz);Jz.reset();let s=this.getTransferPipeline(r,e.textureBindingViewDimension),c=this.getTransferPipeline(r,o.textureBindingViewDimension),l=this.device.createCommandEncoder(Hz),u=(e,t,n,r,i,a)=>{let o=e.getBindGroupLayout(0);Yz.dimension=t.textureBindingViewDimension||`2d-array`,Yz.mipLevelCount=1;let s=t.createView(Yz);Yz.reset(),Bz.layout=o,Bz.entries.push({binding:0,resource:this.flipYSampler},{binding:1,resource:s},{binding:2,resource:{buffer:a?this.flipUniformBuffer:this.noFlipUniformBuffer}});let c=this.device.createBindGroup(Bz);Bz.reset(),Yz.dimension=`2d`,Yz.mipLevelCount=1,Yz.baseArrayLayer=i,Yz.arrayLayerCount=1;let u=r.createView(Yz);Yz.reset(),Kz.view=u,Kz.loadOp=rz.Clear,Kz.storeOp=nz.Store,Wz.colorAttachments.push(Kz);let d=l.beginRenderPass(Wz);Wz.reset(),Kz.reset(),d.setPipeline(e),d.setBindGroup(0,c),d.draw(3,1,0,n),d.end()};u(s,e,n,o,0,!1),u(c,o,0,e,n,!0),Rm(this.device,l.finish()),o.destroy()}generateMipmaps(e,t=null){let n=this.get(e),r=n.layers||this._mipmapCreateBundles(e),i=t;i===null&&(Hz.label=`mipmapEncoder`,i=this.device.createCommandEncoder(Hz),Hz.reset()),this._mipmapRunBundles(i,r),t===null&&Rm(this.device,i.finish()),n.layers=r}_mipmapCreateBundles(e){let t=e.textureBindingViewDimension||`2d-array`,n=this.getTransferPipeline(e.format,t),r=n.getBindGroupLayout(0),i=[];for(let a=1;a1&&m!==null&&o>1&&c===_z.TwoD,g=GPUTextureUsage.TRANSIENT_ATTACHMENT!==void 0&&h===!1,_=e.isDepthTexture===!0&&g&&m?.storeMultisampledDepthBuffer===!1&&(m.stencilBuffer===!1||m.storeMultisampledStencilBuffer===!1),v=e.isDepthTexture!==!0&&g&&m?.storeMultisampledColorBuffer===!1,y=GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC;e.isStorageTexture===!0&&(y|=GPUTextureUsage.STORAGE_BINDING),e.isCompressedTexture!==!0&&e.isCompressedArrayTexture!==!0&&l!==Z.RGB9E5UFloat&&(y|=GPUTextureUsage.RENDER_ATTACHMENT),d>1&&_&&(y=GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TRANSIENT_ATTACHMENT);let b=new Rz;if(b.label=e.name,b.size.width=i,b.size.height=a,b.size.depthOrArrayLayers=o,b.mipLevelCount=s,b.sampleCount=d,b.dimension=c,b.format=l,b.usage=y,l===void 0){f(`WebGPURenderer: Texture format not supported.`),this.createDefaultTexture(e);return}e.isCubeTexture&&(b.textureBindingViewDimension=vz.Cube);try{r.texture=n.device.createTexture(b)}catch{f(`WebGPURenderer: Failed to create texture with descriptor:`,b),this.createDefaultTexture(e);return}if(p||h){let e=Object.assign({},b);if(e.label+=`-msaa`,e.sampleCount=u,e.mipLevelCount=1,(_||v)&&(e.usage=GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TRANSIENT_ATTACHMENT),h){e.size=Object.assign({},e.size,{depthOrArrayLayers:1}),r.msaaTextures=[];for(let t=0;t0)for(let t=0,a=r.length;t0){for(let r of e.layerUpdates)this._copyBufferToTexture(t.image,n.texture,i,r,e.flipY,r);e.clearLayerUpdates()}else for(let r=0;r0?(this._copyCompressedBufferToTexture(e.mipmaps,n.texture,i,e.layerUpdates),e.clearLayerUpdates()):this._copyCompressedBufferToTexture(e.mipmaps,n.texture,i);else if(e.isCubeTexture)this._copyCubeMapToTexture(e,n.texture,i);else if(e.isHTMLTexture){let t=this.backend.device,r=this.backend.renderer.domElement,a=e.image;if(typeof t.queue.copyElementImageToTexture!=`function`)return;if(!n.hasPaintCallback){n.hasPaintCallback=!0,r.requestPaint();return}let o=i.size.width,s=i.size.height;t.queue.copyElementImageToTexture.length===2?t.queue.copyElementImageToTexture({source:a},{destination:{texture:n.texture},width:o,height:s}):t.queue.copyElementImageToTexture(a,o,s,{texture:n.texture}),e.flipY&&this._flipY(n.texture,i)}else if(r.length>0)for(let t=0,a=r.length;t0?e.width:n.size.width,l=o>0?e.height:n.size.height;uB.source=e,uB.flipY=i,dB.texture=t,dB.mipLevel=o,dB.origin.z=r,dB.premultipliedAlpha=a,pB.width=c,pB.height=l;try{s.queue.copyExternalImageToTexture(uB,dB,pB)}catch{}finally{uB.reset(),dB.reset(),pB.reset()}}_getPassUtils(){let e=this._passUtils;return e===null&&(this._passUtils=e=new Xz(this.backend.device)),e}_generateMipmaps(e,t=null){this._getPassUtils().generateMipmaps(e,t)}_flipY(e,t,n=0){this._getPassUtils().flipY(e,t,n)}_copyBufferToTexture(e,t,n,r,i,a=0,o=0){let s=this.backend.device,c=e.data,l=this._getBytesPerTexel(n.format),u=e.width*l;sB.texture=t,sB.mipLevel=o,sB.origin.z=r,lB.offset=e.width*e.height*l*a,lB.bytesPerRow=u,pB.width=e.width,pB.height=e.height,s.queue.writeTexture(sB,c,lB,pB),sB.reset(),lB.reset(),pB.reset(),i===!0&&this._flipY(t,n,r)}_copyCompressedBufferToTexture(e,t,n,r=null){let i=this.backend.device,a=this._getBlockData(n.format),o=n.size.depthOrArrayLayers>1,s=r&&r.size>0?r:null;for(let r=0;r]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i,vB=/([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/gi,yB={f32:`float`,i32:`int`,u32:`uint`,bool:`bool`,"vec2":`vec2`,"vec2":`ivec2`,"vec2":`uvec2`,"vec2":`bvec2`,vec2f:`vec2`,vec2i:`ivec2`,vec2u:`uvec2`,vec2b:`bvec2`,"vec3":`vec3`,"vec3":`ivec3`,"vec3":`uvec3`,"vec3":`bvec3`,vec3f:`vec3`,vec3i:`ivec3`,vec3u:`uvec3`,vec3b:`bvec3`,"vec4":`vec4`,"vec4":`ivec4`,"vec4":`uvec4`,"vec4":`bvec4`,vec4f:`vec4`,vec4i:`ivec4`,vec4u:`uvec4`,vec4b:`bvec4`,"mat2x2":`mat2`,mat2x2f:`mat2`,"mat3x3":`mat3`,mat3x3f:`mat3`,"mat4x4":`mat4`,mat4x4f:`mat4`,sampler:`sampler`,sampler_comparison:`samplerComparison`,texture_1d:`texture`,texture_2d:`texture`,texture_2d_array:`texture`,texture_multisampled_2d:`cubeTexture`,texture_depth_2d:`depthTexture`,texture_depth_2d_array:`depthTexture`,texture_depth_multisampled_2d:`depthTexture`,texture_depth_cube:`depthTexture`,texture_depth_cube_array:`depthTexture`,texture_3d:`texture3D`,texture_cube:`cubeTexture`,texture_cube_array:`cubeTexture`,texture_storage_1d:`storageTexture`,texture_storage_2d:`storageTexture`,texture_storage_2d_array:`storageTexture`,texture_storage_3d:`storageTexture`},bB=e=>{e=e.replace(/^(?:\s*\/\/[^\r\n]*|\s*\/\*[\s\S]*?\*\/|\s*)+/,``);let t=e.match(_B);if(t!==null&&t.length===4){let n=t[2],r=[],i=null;for(;(i=vB.exec(n))!==null;)r.push({name:i[1],type:i[2]});let a=[];for(let e=0;e `+this.outputType;return`fn ${e} ( ${this.inputsCode.trim()} ) ${t}`+this.blockCode}},SB=class extends TL{parseFunction(e){return new xB(e)}},CB={[ih.READ_ONLY]:`read`,[ih.WRITE_ONLY]:`write`,[ih.READ_WRITE]:`read_write`},wB={[Xt]:`repeat`,[Zt]:`clamp`,[Qt]:`mirror`},TB={vertex:ez.VERTEX,fragment:ez.FRAGMENT,compute:ez.COMPUTE},EB={instance:!0,swizzleAssign:!1,storageBuffer:!0},DB={"^^":`tsl_xor`},OB={float:`f32`,int:`i32`,uint:`u32`,bool:`bool`,color:`vec3`,vec2:`vec2`,ivec2:`vec2`,uvec2:`vec2`,bvec2:`vec2`,vec3:`vec3`,ivec3:`vec3`,uvec3:`vec3`,bvec3:`vec3`,vec4:`vec4`,ivec4:`vec4`,uvec4:`vec4`,bvec4:`vec4`,mat2:`mat2x2`,mat3:`mat3x3`,mat4:`mat4x4`},kB={},AB={tsl_xor:new AM(`fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }`),mod_float:new AM(`fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }`),mod_vec2:new AM(`fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }`),mod_vec3:new AM(`fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }`),mod_vec4:new AM(`fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }`),equals_bool:new AM(`fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }`),equals_bvec2:new AM(`fn tsl_equals_bvec2( a : vec2f, b : vec2f ) -> vec2 { return vec2( a.x == b.x, a.y == b.y ); }`),equals_bvec3:new AM(`fn tsl_equals_bvec3( a : vec3f, b : vec3f ) -> vec3 { return vec3( a.x == b.x, a.y == b.y, a.z == b.z ); }`),equals_bvec4:new AM(`fn tsl_equals_bvec4( a : vec4f, b : vec4f ) -> vec4 { return vec4( a.x == b.x, a.y == b.y, a.z == b.z, a.w == b.w ); }`),repeatWrapping_float:new AM(`fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }`),mirrorWrapping_float:new AM(`fn tsl_mirrorWrapping_float( coord: f32 ) -> f32 { let mirrored = fract( coord * 0.5 ) * 2.0; return 1.0 - abs( 1.0 - mirrored ); }`),clampWrapping_float:new AM(`fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }`),inverse_mat2:new AM(` fn tsl_inverse_mat2( m : mat2x2 ) -> mat2x2 { let det = m[ 0 ][ 0 ] * m[ 1 ][ 1 ] - m[ 0 ][ 1 ] * m[ 1 ][ 0 ]; return mat2x2( m[ 1 ][ 1 ], - m[ 0 ][ 1 ], - m[ 1 ][ 0 ], m[ 0 ][ 0 ] ) * ( 1.0 / det ); } `),inverse_mat3:new AM(` fn tsl_inverse_mat3( m : mat3x3 ) -> mat3x3 { let a00 = m[ 0 ][ 0 ]; let a01 = m[ 0 ][ 1 ]; let a02 = m[ 0 ][ 2 ]; let a10 = m[ 1 ][ 0 ]; let a11 = m[ 1 ][ 1 ]; let a12 = m[ 1 ][ 2 ]; let a20 = m[ 2 ][ 0 ]; let a21 = m[ 2 ][ 1 ]; let a22 = m[ 2 ][ 2 ]; let b01 = a22 * a11 - a12 * a21; let b11 = - a22 * a10 + a12 * a20; let b21 = a21 * a10 - a11 * a20; let det = a00 * b01 + a01 * b11 + a02 * b21; return mat3x3( b01, ( - a22 * a01 + a02 * a21 ), ( a12 * a01 - a02 * a11 ), b11, ( a22 * a00 - a02 * a20 ), ( - a12 * a00 + a02 * a10 ), b21, ( - a21 * a00 + a01 * a20 ), ( a11 * a00 - a01 * a10 ) ) * ( 1.0 / det ); } `),inverse_mat4:new AM(` fn tsl_inverse_mat4( m : mat4x4 ) -> mat4x4 { let a00 = m[ 0 ][ 0 ]; let a01 = m[ 0 ][ 1 ]; let a02 = m[ 0 ][ 2 ]; let a03 = m[ 0 ][ 3 ]; let a10 = m[ 1 ][ 0 ]; let a11 = m[ 1 ][ 1 ]; let a12 = m[ 1 ][ 2 ]; let a13 = m[ 1 ][ 3 ]; let a20 = m[ 2 ][ 0 ]; let a21 = m[ 2 ][ 1 ]; let a22 = m[ 2 ][ 2 ]; let a23 = m[ 2 ][ 3 ]; let a30 = m[ 3 ][ 0 ]; let a31 = m[ 3 ][ 1 ]; let a32 = m[ 3 ][ 2 ]; let a33 = m[ 3 ][ 3 ]; let b00 = a00 * a11 - a01 * a10; let b01 = a00 * a12 - a02 * a10; let b02 = a00 * a13 - a03 * a10; let b03 = a01 * a12 - a02 * a11; let b04 = a01 * a13 - a03 * a11; let b05 = a02 * a13 - a03 * a12; let b06 = a20 * a31 - a21 * a30; let b07 = a20 * a32 - a22 * a30; let b08 = a20 * a33 - a23 * a30; let b09 = a21 * a32 - a22 * a31; let b10 = a21 * a33 - a23 * a31; let b11 = a22 * a33 - a23 * a32; let det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; return mat4x4( a11 * b11 - a12 * b10 + a13 * b09, a02 * b10 - a01 * b11 - a03 * b09, a31 * b05 - a32 * b04 + a33 * b03, a22 * b04 - a21 * b05 - a23 * b03, a12 * b08 - a10 * b11 - a13 * b07, a00 * b11 - a02 * b08 + a03 * b07, a32 * b02 - a30 * b05 - a33 * b01, a20 * b05 - a22 * b02 + a23 * b01, a10 * b10 - a11 * b08 + a13 * b06, a01 * b08 - a00 * b10 - a03 * b06, a30 * b04 - a31 * b02 + a33 * b00, a21 * b02 - a20 * b04 - a23 * b00, a11 * b07 - a10 * b09 - a12 * b06, a00 * b09 - a01 * b07 + a02 * b06, a31 * b01 - a30 * b03 - a32 * b00, a20 * b03 - a21 * b01 + a22 * b00 ) * ( 1.0 / det ); } `),biquadraticTexture:new AM(` fn tsl_biquadraticTexture( map : texture_2d, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f { let res = vec2f( iRes ); let uvScaled = coord * res; let uvWrapping = ( ( uvScaled % res ) + res ) % res; // https://www.shadertoy.com/view/WtyXRy let uv = uvWrapping - 0.5; let iuv = floor( uv ); let f = fract( uv ); let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level ); let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level ); let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level ); let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level ); return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y ); } `),biquadraticTextureArray:new AM(` fn tsl_biquadraticTexture_array( map : texture_2d_array, coord : vec2f, iRes : vec2u, layer : u32, level : u32 ) -> vec4f { let res = vec2f( iRes ); let uvScaled = coord * res; let uvWrapping = ( ( uvScaled % res ) + res ) % res; // https://www.shadertoy.com/view/WtyXRy let uv = uvWrapping - 0.5; let iuv = floor( uv ); let f = fract( uv ); let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, layer, level ); let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, layer, level ); let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, layer, level ); let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, layer, level ); return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y ); } `)},jB={dFdx:`dpdx`,dFdy:`- dpdy`,mod_float:`tsl_mod_float`,mod_vec2:`tsl_mod_vec2`,mod_vec3:`tsl_mod_vec3`,mod_vec4:`tsl_mod_vec4`,equals_bool:`tsl_equals_bool`,equals_bvec2:`tsl_equals_bvec2`,equals_bvec3:`tsl_equals_bvec3`,equals_bvec4:`tsl_equals_bvec4`,inverse_mat2:`tsl_inverse_mat2`,inverse_mat3:`tsl_inverse_mat3`,inverse_mat4:`tsl_inverse_mat4`,inversesqrt:`inverseSqrt`,faceforward:`faceForward`,bitcast:`bitcast`,floatpack_snorm_2x16:`pack2x16snorm`,floatpack_unorm_2x16:`pack2x16unorm`,floatpack_float16_2x16:`pack2x16float`,floatpack_snorm_4x8:`pack4x8snorm`,floatpack_unorm_4x8:`pack4x8unorm`,floatunpack_snorm_2x16:`unpack2x16snorm`,floatunpack_unorm_2x16:`unpack2x16unorm`,floatunpack_float16_2x16:`unpack2x16float`,floatunpack_snorm_4x8:`unpack4x8snorm`,floatunpack_unorm_4x8:`unpack4x8unorm`},MB=new Set(`alias.break.case.const.const_assert.continue.continuing.default.diagnostic.discard.else.enable.false.fn.for.if.let.loop.override.requires.return.struct.switch.true.var.while.NULL.Self.abstract.active.alignas.alignof.as.asm.asm_fragment.async.attribute.auto.await.become.binding_array.cast.catch.class.co_await.co_return.co_yield.coherent.column_major.common.compile.compile_fragment.concept.const_cast.consteval.constexpr.constinit.crate.debugger.decltype.delete.demote.demote_to_helper.do.dynamic_cast.enum.explicit.export.extends.extern.external.fallthrough.filter.final.finally.friend.from.fxgroup.get.goto.groupshared.highp.impl.implements.import.inline.instanceof.interface.layout.lowp.macro.macro_rules.match.mediump.meta.mod.module.move.mut.mutable.namespace.new.nil.noexcept.noinline.nointerpolation.non_coherent.noncoherent.noperspective.null.nullptr.of.operator.package.packoffset.partition.pass.patch.pixelfragment.precise.precision.premerge.priv.protected.pub.public.readonly.ref.regardless.register.reinterpret_cast.require.resource.restrict.self.set.shared.sizeof.smooth.snorm.static.static_assert.static_cast.std.subroutine.super.target.template.this.thread_local.throw.trait.try.type.typedef.typeid.typename.typeof.union.unless.unorm.unsafe.unsized.use.using.varying.virtual.volatile.wgsl.where.with.writeonly.yield.main`.split(`.`)),NB=``,(typeof navigator<`u`&&/Firefox|Deno/g.test(navigator.userAgent))!==!0&&(NB+=`diagnostic( off, derivative_uniformity ); `),PB=class extends uL{constructor(e,t){super(e,t,new SB),this.uniformGroups={},this.uniformGroupsBindings={},this.builtins={},this.directives={},this.scopedArrays=new Map,this.allowEarlyReturns=!0,this.allowGlobalVariables=!0}_generateTextureSample(e,t,n,r,i,a=this.shaderStage){return a===`fragment`?r?i?`textureSample( ${t}, ${t}_sampler, ${n}, ${r}, ${i} )`:`textureSample( ${t}, ${t}_sampler, ${n}, ${r} )`:i?`textureSample( ${t}, ${t}_sampler, ${n}, ${i} )`:`textureSample( ${t}, ${t}_sampler, ${n} )`:this.generateTextureSampleLevel(e,t,n,`0`,r)}generateTextureSampleLevel(e,t,n,r,i,a){return this.isUnfilterable(e)===!1?i?a?`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${i}, ${r}, ${a} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${i}, ${r} )`:a?`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${r}, ${a} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${r} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,n,a,r,i):this.generateTextureLod(e,t,n,i,a,r)}generateWrapFunction(e){let t=`tsl_coord_${wB[e.wrapS]}S_${wB[e.wrapT]}T_${e.is3DTexture||e.isData3DTexture?`3d`:`2d`}`,n=kB[t];if(n===void 0){let r=[],i=e.is3DTexture||e.isData3DTexture?`vec3f`:`vec2f`,a=`fn ${t}( coord : ${i} ) -> ${i} {\n\n\treturn ${i}(\n`,o=(e,t)=>{e===1e3?(r.push(AB.repeatWrapping_float),a+=`\t\ttsl_repeatWrapping_float( coord.${t} )`):e===1001?(r.push(AB.clampWrapping_float),a+=`\t\ttsl_clampWrapping_float( coord.${t} )`):e===1002?(r.push(AB.mirrorWrapping_float),a+=`\t\ttsl_mirrorWrapping_float( coord.${t} )`):(a+=`\t\tcoord.${t}`,f(`WebGPURenderer: Unsupported texture wrap type "${e}" for vertex shader.`))};o(e.wrapS,`x`),a+=`, `,o(e.wrapT,`y`),(e.is3DTexture||e.isData3DTexture)&&(a+=`, `,o(e.wrapR,`z`)),a+=` ); } `,kB[t]=n=new AM(a,r)}return n.build(this),t}generateArrayDeclaration(e,t){return`array< ${this.getType(e)}, ${t} >`}generateTextureDimension(e,t,n){let r=this.getDataFromNode(e,this.shaderStage,this.cache);r.dimensionsSnippet===void 0&&(r.dimensionsSnippet={});let i=r.dimensionsSnippet[n];if(r.dimensionsSnippet[n]===void 0){let a,o,{primarySamples:s}=this.renderer.backend.utils.getTextureSampleData(e),c=s>1;o=e.is3DTexture||e.isData3DTexture?`vec3`:`vec2`,a=c||e.isStorageTexture?t:`${t}${n?`, u32( ${n} )`:``}`,i=new Ty(new vb(`textureDimensions( ${a} )`,o)),r.dimensionsSnippet[n]=i,(e.isArrayTexture||e.isDataArrayTexture||e.is3DTexture||e.isData3DTexture)&&(r.arrayLayerCount=new Ty(new vb(`textureNumLayers(${t})`,`u32`))),e.isTextureCube&&(r.cubeFaceCount=new Ty(new vb(`6u`,`u32`)))}return i.build(this)}generateTextureSize(e,t,n){let{primarySamples:r}=this.renderer.backend.utils.getTextureSampleData(e);return`textureDimensions( ${r>1||e.isStorageTexture?t:`${t}, ${n}`} )`}generateFilteredTexture(e,t,n,r,i=`0u`,a){let o=this.generateWrapFunction(e),s=this.generateTextureDimension(e,t,i);return r&&(n=`${n} + vec2(${r}) / ${s}`),a?(this._include(`biquadraticTextureArray`),`tsl_biquadraticTexture_array( ${t}, ${o}( ${n} ), ${s}, u32( ${a} ), u32( ${i} ) )`):(this._include(`biquadraticTexture`),`tsl_biquadraticTexture( ${t}, ${o}( ${n} ), ${s}, u32( ${i} ) )`)}generateTextureLod(e,t,n,r,i,a=`0u`){if(e.isCubeTexture===!0){i&&(n=`${n} + vec3(${i})`);let r=e.isDepthTexture?`u32`:`f32`;return`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${r}( ${a} ) )`}let o=this.generateWrapFunction(e),s=this.generateTextureDimension(e,t,a),c=e.is3DTexture||e.isData3DTexture?`vec3`:`vec2`,l=c===`vec3`?`vec3( 1, 1, 1 )`:`vec2( 1, 1 )`;i&&(n=`${n} + ${c}(${i}) / ${c}( ${s} )`);let u=`${c}( 0 )`,d=`${c}( ${s} - ${l} )`;return n=`${c}( clamp( floor( ${o}( ${n} ) * ${c}( ${s} ) ), ${u}, ${d} ) )`,this.generateTextureLoad(e,t,n,a,r,null)}generateStorageTextureLoad(e,t,n,r,i,a){a&&(n=`${n} + ${a}`);let o;return o=i?`textureLoad( ${t}, ${n}, ${i} )`:`textureLoad( ${t}, ${n} )`,o}generateTextureLoad(e,t,n,r,i,a){r===null&&(r=`0u`),a&&(n=`${n} + ${a}`);let o;return i?o=`textureLoad( ${t}, ${n}, ${i}, u32( ${r} ) )`:(o=`textureLoad( ${t}, ${n}, u32( ${r} ) )`,this.renderer.backend.compatibilityMode&&e.isDepthTexture&&(o+=`.x`)),o}generateTextureStore(e,t,n,r,i){let a;return a=r?`textureStore( ${t}, ${n}, ${r}, ${i} )`:`textureStore( ${t}, ${n}, ${i} )`,a}isSampleCompare(e){return e.isDepthTexture===!0&&e.compareFunction!==null&&this.renderer.hasCompatibility(ii.TEXTURE_COMPARE)}isUnfilterable(e){return this.getComponentTypeFromTexture(e)!==`float`||!this.isAvailable(`float32Filterable`)&&e.type===1015||this.isSampleCompare(e)===!1&&e.minFilter===1003&&e.magFilter===1003||this.renderer.backend.utils.getTextureSampleData(e).primarySamples>1||e.normalized===!0&&(e.type===1011||e.type===1012)}generateTexture(e,t,n,r,i,a=this.shaderStage){let o=null;return o=this.isUnfilterable(e)?this.generateTextureLod(e,t,n,r,i,`0`,a):this._generateTextureSample(e,t,n,r,i,a),o}generateTextureGrad(e,t,n,r,i,a,o=this.shaderStage){if(o===`fragment`)return i?a?`textureSampleGrad( ${t}, ${t}_sampler, ${n}, ${i}, ${r[0]}, ${r[1]}, ${a} )`:`textureSampleGrad( ${t}, ${t}_sampler, ${n}, ${i}, ${r[0]}, ${r[1]} )`:a?`textureSampleGrad( ${t}, ${t}_sampler, ${n}, ${r[0]}, ${r[1]}, ${a} )`:`textureSampleGrad( ${t}, ${t}_sampler, ${n}, ${r[0]}, ${r[1]} )`;p(`WebGPURenderer: THREE.TextureNode.gradient() does not support ${o} shader.`)}generateTextureCompare(e,t,n,r,i,a,o=this.shaderStage){if(o===`fragment`)return e.isDepthTexture===!0&&e.isArrayTexture===!0?a?`textureSampleCompare( ${t}, ${t}_sampler, ${n}, ${i}, ${r}, ${a} )`:`textureSampleCompare( ${t}, ${t}_sampler, ${n}, ${i}, ${r} )`:a?`textureSampleCompare( ${t}, ${t}_sampler, ${n}, ${r}, ${a} )`:`textureSampleCompare( ${t}, ${t}_sampler, ${n}, ${r} )`;p(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${o} shader.`)}generateTextureGather(e,t,n,r,i,a){let o=e.isDepthTexture===!0?``:`${r}, `;return i?a?`textureGather( ${o}${t}, ${t}_sampler, ${n}, ${i}, ${a} )`:`textureGather( ${o}${t}, ${t}_sampler, ${n}, ${i} )`:a?`textureGather( ${o}${t}, ${t}_sampler, ${n}, ${a} )`:`textureGather( ${o}${t}, ${t}_sampler, ${n})`}generateTextureGatherCompare(e,t,n,r,i,a){return i?a?`textureGatherCompare( ${t}, ${t}_sampler, ${n}, ${i}, ${r}, ${a} )`:`textureGatherCompare( ${t}, ${t}_sampler, ${n}, ${i}, ${r})`:a?`textureGatherCompare( ${t}, ${t}_sampler, ${n}, ${r}, ${a} )`:`textureGatherCompare( ${t}, ${t}_sampler, ${n}, ${r})`}generateTextureLevel(e,t,n,r,i,a){return this.isUnfilterable(e)===!1?i?a?`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${i}, ${r}, ${a} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${i}, ${r} )`:a?`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${r}, ${a} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${r} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,n,a,r,i):this.generateTextureLod(e,t,n,i,a,r)}generateTextureBias(e,t,n,r,i,a,o=this.shaderStage){if(o===`fragment`)return i?a?`textureSampleBias( ${t}, ${t}_sampler, ${n}, ${i}, ${r}, ${a} )`:`textureSampleBias( ${t}, ${t}_sampler, ${n}, ${i}, ${r} )`:a?`textureSampleBias( ${t}, ${t}_sampler, ${n}, ${r}, ${a} )`:`textureSampleBias( ${t}, ${t}_sampler, ${n}, ${r} )`;p(`WebGPURenderer: THREE.TextureNode.biasNode does not support ${o} shader.`)}getPropertyName(e,t=this.shaderStage){if(e.isNodeVarying===!0&&e.needsInterpolation===!0){if(t===`vertex`)return`varyings.${e.name}`}else if(e.isNodeUniform===!0){let t=e.name,n=e.type;return n===`texture`||n===`cubeTexture`||n===`cubeDepthTexture`||n===`storageTexture`||n===`texture3D`?t:n===`buffer`||n===`storageBuffer`||n===`indirectStorageBuffer`?this.isCustomStruct(e)?t:t+`.value`:e.groupNode.name+`.`+t}return super.getPropertyName(e)}isReservedKeyword(e){return MB.has(e)}getOutputStructName(){return`output`}getFunctionOperator(e){let t=DB[e];return t===void 0?null:(this._include(t),t)}getNodeAccess(e,t){return t===`compute`?e.access:e.isAtomic===!0?t===`vertex`?(f(`WebGPURenderer: Atomic operations are not supported in the vertex stage. They are only available in the fragment and compute stages.`),ih.READ_ONLY):ih.READ_WRITE:ih.READ_ONLY}getStorageAccess(e,t){return CB[this.getNodeAccess(e,t)]}getUniformFromNode(e,t,n,r=null){let i=super.getUniformFromNode(e,t,n,r),a=this.getDataFromNode(e,n,this.globalCache);if(a.uniformGPU===void 0){let o,s=e.groupNode,c=s.name,l=this.getBindGroupArray(c,n);if(t===`texture`||t===`cubeTexture`||t===`cubeDepthTexture`||t===`storageTexture`||t===`texture3D`){let r=null,a=this.getNodeAccess(e,n);if(t===`texture`||t===`storageTexture`?r=e.value.is3DTexture===!0?new bR(i.name,i.node,s,a):new vR(i.name,i.node,s,a):t===`cubeTexture`||t===`cubeDepthTexture`?r=new yR(i.name,i.node,s,a):t===`texture3D`&&(r=new bR(i.name,i.node,s,a)),r.store=e.isStorageTextureNode===!0,r.mipLevel=r.store?e.mipLevel:0,r.setVisibility(TB[n]),e.value.isCubeTexture===!0||this.isUnfilterable(e.value)===!1&&r.store===!1||e.gatherNode!==null){let e=new Cz(`${i.name}_sampler`,i.node,s);e.setVisibility(TB[n]),l.push(e,r),o=[e,r]}else l.push(r),o=[r]}else if(t===`buffer`||t===`storageBuffer`||t===`indirectStorageBuffer`){let a=this.getSharedDataFromNode(e),c=a.buffer;c===void 0&&(c=new(t===`buffer`?dR:Ez)(e,s),a.buffer=c),c.setVisibility(c.getVisibility()|TB[n]),l.push(c),o=c,i.name=r||`NodeBuffer_`+i.id}else{let e=this.uniformGroups[c];e===void 0&&(e=new mR(c,s),e.setVisibility(ez.VERTEX|ez.FRAGMENT|ez.COMPUTE),this.uniformGroups[c]=e),l.indexOf(e)===-1&&l.push(e),o=this.getNodeUniform(i,t);let n=o.name;e.uniforms.some(e=>e.name===n)||e.addUniform(o)}a.uniformGPU=o}return i}getBuiltin(e,t,n,r=this.shaderStage){let i=this.builtins[r]||(this.builtins[r]=new Map);return i.has(e)===!1&&i.set(e,{name:e,property:t,type:n}),t}hasBuiltin(e,t=this.shaderStage){return this.builtins[t]!==void 0&&this.builtins[t].has(e)}getVertexIndex(){return this.shaderStage===`vertex`?this.getBuiltin(`vertex_index`,`vertexIndex`,`u32`,`attribute`):`vertexIndex`}buildFunctionCode(e){let t=e.layout,n=this.flowShaderNode(e),r=[];for(let e of t.inputs)r.push(e.name+` : `+this.getType(e.type));let i=`fn ${t.name}( ${r.join(`, `)} ) -> ${this.getType(t.type)} { ${n.vars} ${n.code} `;return n.result&&(i+=`\treturn ${n.result};\n`),i+=` } `,i}getInstanceIndex(){return this.shaderStage===`vertex`?this.getBuiltin(`instance_index`,`instanceIndex`,`u32`,`attribute`):`instanceIndex`}getInvocationLocalIndex(){return this.getBuiltin(`local_invocation_index`,`invocationLocalIndex`,`u32`,`attribute`)}getSubgroupSize(){return this.enableSubGroups(),this.getBuiltin(`subgroup_size`,`subgroupSize`,`u32`,`attribute`)}getInvocationSubgroupIndex(){return this.enableSubGroups(),this.getBuiltin(`subgroup_invocation_id`,`invocationSubgroupIndex`,`u32`,`attribute`)}getSubgroupIndex(){return this.enableSubGroups(),this.getBuiltin(`subgroup_id`,`subgroupIndex`,`u32`,`attribute`)}getDrawIndex(){return null}getFrontFacing(){return this.getBuiltin(`front_facing`,`isFront`,`bool`)}getFragCoord(){return this.getBuiltin(`position`,`fragCoord`,`vec4`)+`.xy`}getFragDepth(){return`output.`+this.getBuiltin(`frag_depth`,`depth`,`f32`,`output`)}getClipDistance(){return`varyings.hw_clip_distances`}isFlipY(){return!1}enableDirective(e,t=this.shaderStage){(this.directives[t]||(this.directives[t]=new Set)).add(e)}getDirectives(e){let t=[],n=this.directives[e];if(n!==void 0)for(let e of n)t.push(`enable ${e};`);return t.join(` `)}enableSubGroups(){this.enableDirective(`subgroups`)}enableSubgroupsF16(){this.enableDirective(`subgroups-f16`)}enableClipDistances(){this.enableDirective(`clip_distances`)}enableShaderF16(){this.enableDirective(`f16`)}enableDualSourceBlending(){this.enableDirective(`dual_source_blending`)}enableHardwareClipping(e){this.enableClipDistances(),this.getBuiltin(`clip_distances`,`hw_clip_distances`,`array`,`vertex`)}getBuiltins(e){let t=[],n=this.builtins[e];if(n!==void 0)for(let{name:e,property:r,type:i}of n.values())t.push(`@builtin( ${e} ) ${r} : ${i}`);return t.join(`, `)}getScopedArray(e,t,n,r,i){return this.scopedArrays.has(e)===!1&&this.scopedArrays.set(e,{name:e,scope:t,bufferType:n,bufferCount:r,isAtomic:i}),e}getScopedArrays(e){if(e!==`compute`)return;let t=[];for(let{name:e,scope:n,bufferType:r,bufferCount:i,isAtomic:a}of this.scopedArrays.values()){let o=this.getType(r);a===!0&&(o=`atomic<${o}>`),t.push(`var<${n}> ${e}: array< ${o}, ${i} >;`)}return t.join(` `)}getAttributes(e){let t=[];if(e===`compute`&&(this.getBuiltin(`global_invocation_id`,`globalId`,`vec3`,`attribute`),this.getBuiltin(`workgroup_id`,`workgroupId`,`vec3`,`attribute`),this.getBuiltin(`local_invocation_id`,`localId`,`vec3`,`attribute`),this.getBuiltin(`num_workgroups`,`numWorkgroups`,`vec3`,`attribute`),this.renderer.hasFeature(`subgroups`)&&(this.enableDirective(`subgroups`,e),this.getBuiltin(`subgroup_size`,`subgroupSize`,`u32`,`attribute`))),e===`vertex`||e===`compute`){let e=this.getBuiltins(`attribute`);e&&t.push(e);let n=this.getAttributesArray();for(let e=0,r=n.length;e`),t.push(`\t${r+n.name} : ${i}`)}return e.output&&t.push(`\t${this.getBuiltins(`output`)}`),t.join(`, `)}getStructs(e){let t=``,n=this.structs[e];if(n.length>0){let e=[];for(let t of n){let n=`struct ${t.name} {\n`;n+=this.getStructMembers(t),n+=` };`,e.push(n)}t=` `+e.join(` `)+` `}return t}getVar(e,t,n=null,r=``){let i=`var${r} ${t} : `;return i+=n===null?this.getType(e):this.generateArrayDeclaration(e,n),i}getVars(e,t=!1){let n=``;t&&(n=``);let r=[],i=this.vars[e];if(i!==void 0)for(let e of i)r.push(`${this.getVar(e.type,e.name,e.count,n)};`);return t?r.join(` `):`\n\t${r.join(` `)}\n`}getVaryings(e){let t=[];if(e===`vertex`&&this.getBuiltin(`position`,`builtinClipSpace`,`vec4`,`vertex`),e===`vertex`||e===`fragment`){let n=this.varyings,r=this.vars[e],i=0;for(let a=0;an.value.itemSize;return r&&!i}getUniforms(e){let t=this.renderer.backend,n=this.uniforms[e],r=[],i=[],a=[],o={};for(let a of n){let n=a.groupNode.name,s=this.bindingsIndexes[n];if(a.type===`texture`||a.type===`cubeTexture`||a.type===`cubeDepthTexture`||a.type===`storageTexture`||a.type===`texture3D`){let n=a.node,i=n.value;(i.isCubeTexture===!0||this.isUnfilterable(i)===!1&&n.isStorageTextureNode!==!0||n.gatherNode!==null)&&(this.isSampleCompare(i)&&n.isSampleCompare()?r.push(`@binding( ${s.binding++} ) @group( ${s.group} ) var ${a.name}_sampler : sampler_comparison;`):r.push(`@binding( ${s.binding++} ) @group( ${s.group} ) var ${a.name}_sampler : sampler;`));let o,c=``,{primarySamples:l}=t.utils.getTextureSampleData(i);if(l>1&&(c=`_multisampled`),i.isCubeTexture===!0&&i.isDepthTexture===!0)o=`texture_depth_cube`;else if(i.isCubeTexture===!0)o=`texture_cube`;else if(i.isDepthTexture===!0)o=t.compatibilityMode&&i.compareFunction===null?`texture${c}_2d`:`texture_depth${c}_2d${i.isArrayTexture===!0?`_array`:``}`;else if(a.node.isStorageTextureNode===!0){let n=Bm(i,t.device),r=this.getStorageAccess(a.node,e),s=a.node.value.is3DTexture,c=a.node.value.isArrayTexture;o=`texture_storage_${s?`3d`:`2d${c?`_array`:``}`}<${n}, ${r}>`}else if(i.isArrayTexture===!0||i.isDataArrayTexture===!0||i.isCompressedArrayTexture===!0)o=`texture_2d_array<${this.getComponentTypeFromTexture(i).charAt(0)}32>`;else if(i.is3DTexture===!0||i.isData3DTexture===!0)o=`texture_3d<${this.getComponentTypeFromTexture(i).charAt(0)}32>`;else{let e=this.getComponentTypeFromTexture(i).charAt(0);o=`texture${c}_2d<${e}32>`}r.push(`@binding( ${s.binding++} ) @group( ${s.group} ) var ${a.name} : ${o};`)}else if(a.type===`buffer`||a.type===`storageBuffer`||a.type===`indirectStorageBuffer`){let t=a.node,n=this.getType(t.getNodeType(this)),r=t.bufferCount,o=r>0&&a.type===`buffer`?`, `+r:``,c=t.isStorageBufferNode?`storage, ${this.getStorageAccess(t,e)}`:`uniform`;if(this.isCustomStruct(a))i.push(`@binding( ${s.binding++} ) @group( ${s.group} ) var<${c}> ${a.name} : ${n};`);else{let e=`\tvalue : array< ${t.isAtomic?`atomic<${n}>`:`${n}`}${o} >`;i.push(this._getWGSLStructBinding(a.name,e,c,s.binding++,s.group))}}else{let e=a.groupNode.name;if(o[e]===void 0){let t=this.uniformGroups[e];if(t!==void 0){let n=[];for(let e of t.uniforms){let t=e.getType(),r=this.getType(this.getVectorType(t));n.push(`\t${e.name} : ${r}`)}let r=this.uniformGroupsBindings[e];r===void 0&&(r={index:s.binding++,id:s.group},this.uniformGroupsBindings[e]=r),o[e]={index:r.index,id:r.id,snippets:n}}}}}for(let e in o){let t=o[e];a.push(this._getWGSLStructBinding(e,t.snippets.join(`, `),`uniform`,t.index,t.id))}return[...r,...i,...a].join(` `)}buildCode(){let e=this.material===null?{compute:{}}:{fragment:{},vertex:{}};this.sortBindingGroups();for(let t in e){this.shaderStage=t;let n=this.allowGlobalVariables,r=e[t];r.uniforms=this.getUniforms(t),r.attributes=this.getAttributes(t),r.varyings=this.getVaryings(t),r.structs=this.getStructs(t),r.vars=this.getVars(t,n),r.codes=this.getCodes(t),r.directives=this.getDirectives(t),r.scopedArrays=this.getScopedArrays(t);let i=`// code `;i+=this.flowCode[t];let a=this.flowNodes[t],o=a[a.length-1],s=o.outputNode,c=s!==void 0&&s.isOutputStructNode===!0;for(let e of a){let n=this.getFlowData(e),a=e.name;if(a&&(i.length>0&&(i+=` `),i+=`\t// flow -> ${a}\n`),i+=`${n.code}\n\t`,e===o&&t!==`compute`){if(i+=`// result `,t===`vertex`)i+=`varyings.builtinClipSpace = ${n.result};`;else if(t===`fragment`){if(c)r.returnType=s.getNodeType(this),r.structs+=`var output : `+r.returnType+`;`,i+=`return ${n.result};`;else{let e=`\t@location( 0 ) color: ${this.getType(this.getOutputType())}`,t=this.getBuiltins(`output`);t&&(e+=`, `+t),r.returnType=`OutputStruct`,r.structs+=this._getWGSLStruct(`OutputStruct`,e),r.structs+=` var output : OutputStruct;`,i+=`output.color = ${this.format(n.result,o.getNodeType(this),this.getOutputType())};\n\n\treturn output;`}}}}r.flow=i}if(this.shaderStage=null,this.material!==null)this.vertexShader=this._getWGSLVertexCode(e.vertex),this.fragmentShader=this._getWGSLFragmentCode(e.fragment);else{let t=this.compute.workgroupSize;this.computeShader=this._getWGSLComputeCode(e.compute,t)}}getMethod(e,t=null){let n;return t!==null&&(n=this._getWGSLMethod(e+`_`+t)),n===void 0&&(n=this._getWGSLMethod(e)),n||e}getBitcastMethod(e){return`bitcast<${this.getType(e)}>`}getFloatPackingMethod(e,t=`2x16`){return this.getMethod(`floatpack_${e}_${t}`)}getFloatUnpackingMethod(e,t=`2x16`){return this.getMethod(`floatunpack_${e}_${t}`)}getTernary(e,t,n){return`select( ${n}, ${t}, ${e} )`}getType(e){return OB[e]||e}isAvailable(e){let t=EB[e];return t===void 0&&(e===`float32Filterable`?t=this.renderer.hasFeature(`float32-filterable`):e===`clipDistance`&&(t=this.renderer.hasFeature(`clip-distances`)),EB[e]=t),t}_getWGSLMethod(e){return AB[e]!==void 0&&this._include(e),jB[e]}_include(e){let t=AB[e];return t.build(this),this.addInclude(t),t}_getWGSLVertexCode(e){return`${this.getSignature()} // directives ${e.directives} // structs ${e.structs} // uniforms ${e.uniforms} // varyings ${e.varyings} var varyings : VaryingsStruct; // vars ${e.vars} // codes ${e.codes} @vertex fn main( ${e.attributes} ) -> VaryingsStruct { // flow ${e.flow} return varyings; } `}_getWGSLFragmentCode(e){return`${this.getSignature()} // global ${NB} // structs ${e.structs} // uniforms ${e.uniforms} // vars ${e.vars} // codes ${e.codes} @fragment fn main( ${e.varyings} ) -> ${e.returnType} { // flow ${e.flow} } `}_getWGSLComputeCode(e,t){let[n,r,i]=t;return`${this.getSignature()} // directives ${e.directives} // system var instanceIndex : u32; // locals ${e.scopedArrays} // structs ${e.structs} // uniforms ${e.uniforms} // vars ${this.allowGlobalVariables?e.vars:``} // codes ${e.codes} @compute @workgroup_size( ${n}, ${r}, ${i} ) fn main( ${e.attributes} ) { // local vars ${this.allowGlobalVariables?``:e.vars} // system instanceIndex = globalId.x + globalId.y * ( ${n} * numWorkgroups.x ) + globalId.z * ( ${n} * numWorkgroups.x ) * ( ${r} * numWorkgroups.y ); // flow ${e.flow} } `}_getWGSLStruct(e,t){return` struct ${e} { ${t} };`}_getWGSLStructBinding(e,t,n,r=0,i=0){let a=e+`Struct`;return`${this._getWGSLStruct(a,t)} @binding( ${r} ) @group( ${i} ) var<${n}> ${e} : ${a};`}},FB=new Az,IB=new jz,LB=new Map([[Int8Array,[`sint8`,`snorm8`]],[Uint8Array,[`uint8`,`unorm8`]],[Int16Array,[`sint16`,`snorm16`]],[Uint16Array,[`uint16`,`unorm16`]],[Int32Array,[`sint32`]],[Uint32Array,[`uint32`]],[Float32Array,[`float32`]]]),typeof Float16Array<`u`&&LB.set(Float16Array,[`float16`]),RB=new Map([[co,[`float16`]]]),zB=new Map([[Int32Array,`sint32`],[Uint32Array,`uint32`],[Float32Array,`float32`]]),BB=class{constructor(e){this.backend=e}createAttribute(e,t){let n=this._getBufferAttribute(e),r=this.backend,i=r.get(n),a=i.buffer;if(a===void 0){let o=r.device,s=n.array;if(e.normalized===!1&&e.isInterleavedBufferAttribute!==!0){if(s.constructor===Int16Array||s.constructor===Int8Array)s=new Int32Array(s);else if((s.constructor===Uint16Array||s.constructor===Uint8Array)&&(s=new Uint32Array(s),t&GPUBufferUsage.INDEX))for(let e=0;e1&&n.itemSize*s.BYTES_PER_ELEMENT%4!=0){let e=n.itemSize*s.BYTES_PER_ELEMENT;c=Math.floor((e+3)/4)*4/s.BYTES_PER_ELEMENT}if(c!==void 0){let e=n.itemSize,t=new s.constructor(n.count*c);for(let r=0;r1&&e%4!=0&&(e=Math.floor((e+3)/4)*4)),o={arrayStride:e,attributes:[],stepMode:t},n.set(a,o)}let s=this._getVertexFormat(r),c=r.isInterleavedBufferAttribute===!0?r.offset*i:0;o.attributes.push({shaderLocation:e,offset:c,format:s})}return Array.from(n.values())}destroyAttribute(e){let t=this.backend;t.get(this._getBufferAttribute(e)).buffer.destroy(),t.delete(e)}async getArrayBufferAsync(e,t=null,n=0,r=-1){let i=this.backend,a=i.device,o=i.get(this._getBufferAttribute(e)).buffer,s=r===-1?o.size-n:r,c;if(t!==null&&t.isReadbackBuffer){let e=i.get(t);if(t._mapped===!0)throw Error(`THREE.WebGPUAttributeUtils: ReadbackBuffer must be released before being used again.`);if(t._mapped=!0,e.readBufferGPU===void 0){FB.label=`${t.name}_readback`,FB.size=t.maxByteLength,FB.usage=GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ,c=a.createBuffer(FB),FB.reset();let n=()=>{t.buffer=null,t._mapped=!1,c.unmap()},r=()=>{t.buffer=null,t._mapped=!1,c.destroy(),i.delete(t),t.removeEventListener(`release`,n),t.removeEventListener(`dispose`,r)};t.addEventListener(`release`,n),t.addEventListener(`dispose`,r),e.readBufferGPU=c}else c=e.readBufferGPU}else FB.label=`${e.name}_readback`,FB.size=s,FB.usage=GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ,c=a.createBuffer(FB),FB.reset();IB.label=`readback_encoder_${e.name}`;let l=a.createCommandEncoder(IB);if(IB.reset(),l.copyBufferToBuffer(o,n,c,0,s),Rm(a,l.finish()),await c.mapAsync(GPUMapMode.READ,0,s),t===null){let e=c.getMappedRange(0,s).slice();return c.destroy(),e}if(t.isReadbackBuffer)return t.buffer=c.getMappedRange(0,s),t;{let e=c.getMappedRange(0,s);return new Uint8Array(t).set(new Uint8Array(e)),c.destroy(),t}}_getVertexFormat(e){let{itemSize:t,normalized:n}=e,r=e.array.constructor,i=e.constructor,a;if(t===1)a=zB.get(r);else{let e=(RB.get(i)||LB.get(r))[+!!n];if(e){let n=r.BYTES_PER_ELEMENT*t,i=Math.floor((n+3)/4)*4/r.BYTES_PER_ELEMENT;if(i%1)throw Error(`THREE.WebGPUAttributeUtils: Bad vertex format item size.`);a=`${e}x${i}`}}return a||p(`WebGPUAttributeUtils: Vertex format not supported yet.`),a}_getBufferAttribute(e){return e.isInterleavedBufferAttribute&&(e=e.data),e}},VB=new kz,HB=new Az,UB=new zz,WB=class{constructor(e){this.layoutGPU=e,this.usedTimes=0}},GB=class{constructor(e){this.backend=e,this._bindGroupLayoutCache=new Map}createBindingsLayout(e){let t=this.backend,n=t.device,r=t.get(e);if(r.layout)return r.layout.layoutGPU;let i=this._createLayoutEntries(e),a=Ym(JSON.stringify(i)),o=this._bindGroupLayoutCache.get(a);return o===void 0&&(o=new WB(n.createBindGroupLayout({entries:i})),this._bindGroupLayoutCache.set(a,o)),o.usedTimes++,r.layout=o,r.layoutKey=a,o.layoutGPU}createBindings(e,t,n,r=0){let{backend:i}=this,a=i.get(e),o=this.createBindingsLayout(e),s;n!==``&&(a.groups===void 0&&(a.groups={},a.versions={}),a.versions[n]===r&&(s=a.groups[n])),s===void 0&&(s=this.createBindGroup(e,o),n!==``&&(a.groups[n]=s,a.versions[n]=r)),a.group=s}updateBinding(e){let t=this.backend,n=t.device,r=e.buffer,i=t.get(e).buffer,o=e.updateRanges;if(o.length===0)n.queue.writeBuffer(i,0,r,0);else{let e=a(r),t=e?1:r.BYTES_PER_ELEMENT,s=o[0].start;for(let a=0,c=o.length;a1&&(i+=`-${e.texture.depthOrArrayLayers}`),i+=`-${n}-${r}`,a=e[i],a===void 0){let o=yz.All,s;s=t.isSampledCubeTexture?vz.Cube:t.texture.isArrayTexture||t.texture.isDataArrayTexture||t.texture.isCompressedArrayTexture?vz.TwoDArray:t.isSampledTexture3D?vz.ThreeD:vz.TwoD,UB.aspect=o,UB.dimension=s,UB.mipLevelCount=n,UB.baseMipLevel=r,a=e[i]=e.texture.createView(UB),UB.reset()}}VB.entries.push({binding:i,resource:a})}else if(t.isSampler){let e=n.get(t);VB.entries.push({binding:i,resource:e.sampler})}i++}let a=r.createBindGroup(VB);return VB.reset(),a}_createLayoutEntries(e){let t=[],n=0;for(let r of e.bindings){let e=this.backend,i={binding:n,visibility:r.visibility};if(r.isUniformBuffer||r.isStorageBuffer){let e={};r.isStorageBuffer&&(e.type=r.visibility&ez.COMPUTE?r.access===ih.READ_WRITE||r.access===ih.WRITE_ONLY?pz.Storage:pz.ReadOnlyStorage:r.nodeUniform&&r.nodeUniform.isAtomic&&r.visibility&ez.FRAGMENT?pz.Storage:pz.ReadOnlyStorage),i.buffer=e}else if(r.isSampledTexture&&r.store){let e={};e.format=this.backend.get(r.texture).texture.format;let t=r.access;e.access=t===ih.READ_WRITE?mz.ReadWrite:t===ih.WRITE_ONLY?mz.WriteOnly:mz.ReadOnly,r.texture.isArrayTexture?e.viewDimension=vz.TwoDArray:r.texture.is3DTexture&&(e.viewDimension=vz.ThreeD),i.storageTexture=e}else if(r.isSampledTexture){let t={},{primarySamples:n}=e.utils.getTextureSampleData(r.texture);if(n>1&&(t.multisampled=!0,r.texture.isDepthTexture||(t.sampleType=gz.UnfilterableFloat)),r.texture.isDepthTexture)t.sampleType=e.compatibilityMode&&r.texture.compareFunction===null?gz.UnfilterableFloat:gz.Depth;else{let e=r.texture.type;e===1013?t.sampleType=gz.SInt:e===1014?t.sampleType=gz.UInt:r.texture.normalized===!0&&(e===1011||e===1012)?t.sampleType=gz.UnfilterableFloat:e===1015&&(t.sampleType=this.backend.hasFeature(`float32-filterable`)?gz.Float:gz.UnfilterableFloat)}r.isSampledCubeTexture?t.viewDimension=vz.Cube:r.texture.isArrayTexture||r.texture.isDataArrayTexture||r.texture.isCompressedArrayTexture?t.viewDimension=vz.TwoDArray:r.isSampledTexture3D&&(t.viewDimension=vz.ThreeD),i.texture=t}else if(r.isSampler){let t={};r.texture.isDepthTexture&&(t.type=r.texture.compareFunction!==null&&r.textureNode.isSampleCompare()&&e.hasCompatibility(ii.TEXTURE_COMPARE)?hz.Comparison:hz.NonFiltering),i.sampler=t}else p(`WebGPUBindingUtils: Unsupported binding "${r}".`);t.push(i),n++}return t}deleteBindGroupData(e){let{backend:t}=this,n=t.get(e);n.layout&&(n.layout.usedTimes--,n.layout.usedTimes===0&&this._bindGroupLayoutCache.delete(n.layoutKey),n.layout=void 0,n.layoutKey=void 0)}dispose(){this._bindGroupLayoutCache.clear()}},KB=class{constructor(e){this.backend=e}getMaxAnisotropy(){return 16}getUniformBufferLimit(){return this.backend.device.limits.maxUniformBufferBindingSize}},qB=class{constructor(){this.label=``,this.layout=null,this.compute=null}reset(){this.label=``,this.layout=null,this.compute=null}},JB=class{constructor(){this.label=``,this.bindGroupLayouts=null}reset(){this.label=``,this.bindGroupLayouts=null}},YB=new qB,XB=new JB,ZB=new Mz,QB=new Fz,$B=class{constructor(e){this.backend=e}_getSampleCount(e){return this.backend.utils.getSampleCountRenderContext(e)}createRenderPipeline(e,t){let{object:n,material:r,geometry:i,pipeline:a}=e,{vertexProgram:o,fragmentProgram:s}=a,c=this.backend,l=c.device,u=c.utils,d=c.get(a),f=[];for(let t of e.getBindings()){let{layoutGPU:e}=c.get(t).layout;f.push(e)}let h=c.attributeUtils.createShaderVertexBuffers(e),g;r.blending!==0&&(r.blending!==1||r.transparent!==!1)&&(g=this._getBlending(r));let _={};r.stencilWrite===!0&&(_={compare:this._getStencilCompare(r),failOp:this._getStencilOperation(r.stencilFail),depthFailOp:this._getStencilOperation(r.stencilZFail),passOp:this._getStencilOperation(r.stencilZPass)});let v=this._getColorWriteMask(r),y=[];if(e.context.textures!==null){let t=e.context.textures,n=e.context.mrt;for(let e=0;e1,QB.layout=E;let D={},ee=e.context.depth,O=e.context.stencil;(ee===!0||O===!0)&&(ee===!0&&(D.format=w,D.depthWriteEnabled=r.depthWrite,D.depthCompare=C),O===!0&&(D.stencilFront=_,D.stencilBack=_,D.stencilReadMask=r.stencilFuncMask,D.stencilWriteMask=r.stencilWriteMask),r.polygonOffset===!0&&S.topology===$R.TriangleList&&(D.depthBias=r.polygonOffsetUnits,D.depthBiasSlopeScale=r.polygonOffsetFactor,D.depthBiasClamp=0),QB.depthStencil=D),l.pushErrorScope(`validation`);let k=[{program:o,module:b.module},{program:s,module:x.module}],te=QB.label;if(t===null)d.pipeline=l.createRenderPipeline(QB),QB.reset(),l.popErrorScope().then(e=>{e!==null&&(d.error=!0,p(`WebGPURenderer: Render pipeline creation failed (${te}): ${e.message}`),this._reportShaderDiagnostics(k,te))});else{let e=new Promise(async e=>{try{let e=null,t=null;try{t=l.createRenderPipelineAsync(QB)}catch(t){e=t}if(QB.reset(),t!==null)try{d.pipeline=await t}catch(t){e=t}let n=await l.popErrorScope();if(n!==null||e!==null){d.error=!0;let t=n&&n.message||e&&e.message||`unknown`;p(`WebGPURenderer: Async render pipeline creation failed (${te}): ${t}`),await this._reportShaderDiagnostics(k,te)}}finally{e()}});t.push(e)}}createBundleEncoder(e,t=`renderBundleEncoder`){let{utils:n,device:r}=this.backend,i=n.getCurrentDepthStencilFormat(e),a=n.getCurrentColorFormats(e),o=this._getSampleCount(e);ZB.label=t,ZB.colorFormats=a,ZB.depthStencilFormat=i,ZB.sampleCount=o;let s=r.createRenderBundleEncoder(ZB);return ZB.reset(),s}createComputePipeline(e,t,n=null){let r=this.backend,i=r.device,a=r.get(e.computeProgram).module,o=r.get(e),s=[];for(let e of t){let{layoutGPU:t}=r.get(e).layout;s.push(t)}let c=e.computeProgram,l=`computePipeline_${c.stage}${c.name?`_${c.name}`:``}`;i.pushErrorScope(`validation`),XB.bindGroupLayouts=s;let u=i.createPipelineLayout(XB);if(XB.reset(),YB.label=l,YB.compute=a,YB.layout=u,n===null)o.pipeline=i.createComputePipeline(YB),YB.reset(),i.popErrorScope().then(e=>{e!==null&&(o.error=!0,p(`WebGPURenderer: Compute pipeline creation failed (${l}): ${e.message}`),this._reportShaderDiagnostics([{program:c,module:a.module}],l))});else{let e=new Promise(async e=>{try{let e=null,t=null;try{t=i.createComputePipelineAsync(YB)}catch(t){e=t}if(YB.reset(),t!==null)try{o.pipeline=await t}catch(t){e=t}let n=await i.popErrorScope();if(n!==null||e!==null){o.error=!0;let t=n&&n.message||e&&e.message||`unknown`;p(`WebGPURenderer: Async compute pipeline creation failed (${l}): ${t}`),await this._reportShaderDiagnostics([{program:c,module:a.module}],l)}}finally{e()}});n.push(e)}}async _reportShaderDiagnostics(e,t){for(let{program:n,module:r}of e){let e=await r.getCompilationInfo();if(e.messages.length===0)continue;let i=n.code.split(` `);for(let r of e.messages){let e=r.lineNum>0?` at line ${r.lineNum}${r.linePos>0?`:${r.linePos}`:``}`:``,a=`WebGPURenderer [${t} / ${n.stage} ${r.type}]${e}: ${r.message}`,o=``;r.lineNum>0&&r.lineNum<=i.length&&(o=`\n ${i[r.lineNum-1]}`,r.linePos>0&&(o+=`\n ${` `.repeat(r.linePos-1)}^`)),(r.type===`error`?p:f)(a+o)}}}_getBlending(e){let t,n,r=e.blending,i=e.blendSrc,a=e.blendDst,o=e.blendEquation;if(r===5){let r=e.blendSrcAlpha===null?i:e.blendSrcAlpha,s=e.blendDstAlpha===null?a:e.blendDstAlpha,c=e.blendEquationAlpha===null?o:e.blendEquationAlpha;t={srcFactor:this._getBlendFactor(i),dstFactor:this._getBlendFactor(a),operation:this._getBlendOperation(o)},n={srcFactor:this._getBlendFactor(r),dstFactor:this._getBlendFactor(s),operation:this._getBlendOperation(c)}}else{let i=e.premultipliedAlpha,a=(e,r,i,a)=>{t={srcFactor:e,dstFactor:r,operation:uz.Add},n={srcFactor:i,dstFactor:a,operation:uz.Add}};if(i)switch(r){case 1:a(lz.One,lz.OneMinusSrcAlpha,lz.One,lz.OneMinusSrcAlpha);break;case 2:a(lz.One,lz.One,lz.One,lz.One);break;case 3:a(lz.Zero,lz.OneMinusSrc,lz.Zero,lz.One);break;case 4:a(lz.Dst,lz.OneMinusSrcAlpha,lz.Zero,lz.One)}else switch(r){case 1:a(lz.SrcAlpha,lz.OneMinusSrcAlpha,lz.One,lz.OneMinusSrcAlpha);break;case 2:a(lz.SrcAlpha,lz.One,lz.One,lz.One);break;case 3:p(`WebGPURenderer: "SubtractiveBlending" requires "${e.isMaterial?`material`:`blendMode`}.premultipliedAlpha = true".`);break;case 4:p(`WebGPURenderer: "MultiplyBlending" requires "${e.isMaterial?`material`:`blendMode`}.premultipliedAlpha = true".`)}}if(t!==void 0&&n!==void 0)return{color:t,alpha:n};p(`WebGPURenderer: Invalid blending: `,r)}_getBlendFactor(e){let t;switch(e){case 200:t=lz.Zero;break;case 201:t=lz.One;break;case 202:t=lz.Src;break;case 203:t=lz.OneMinusSrc;break;case 204:t=lz.SrcAlpha;break;case 205:t=lz.OneMinusSrcAlpha;break;case 208:t=lz.Dst;break;case 209:t=lz.OneMinusDst;break;case 206:t=lz.DstAlpha;break;case 207:t=lz.OneMinusDstAlpha;break;case 210:t=lz.SrcAlphaSaturated;break;case 211:case 213:t=lz.Constant;break;case 212:case 214:t=lz.OneMinusConstant;break;default:p(`WebGPURenderer: Blend factor not supported.`,e)}return t}_getStencilCompare(e){let t,n=e.stencilFunc;switch(n){case 512:t=tz.Never;break;case 519:t=tz.Always;break;case 513:t=tz.Less;break;case 515:t=tz.LessEqual;break;case 514:t=tz.Equal;break;case 518:t=tz.GreaterEqual;break;case 516:t=tz.Greater;break;case 517:t=tz.NotEqual;break;default:p(`WebGPURenderer: Invalid stencil function.`,n)}return t}_getStencilOperation(e){let t;switch(e){case Ir:t=fz.Keep;break;case 0:t=fz.Zero;break;case Lr:t=fz.Replace;break;case Hr:t=fz.Invert;break;case Rr:t=fz.IncrementClamp;break;case zr:t=fz.DecrementClamp;break;case Br:t=fz.IncrementWrap;break;case Vr:t=fz.DecrementWrap;break;default:p(`WebGPURenderer: Invalid stencil operation.`,t)}return t}_getBlendOperation(e){let t;switch(e){case 100:t=uz.Add;break;case 101:t=uz.Subtract;break;case 102:t=uz.ReverseSubtract;break;case 103:t=uz.Min;break;case 104:t=uz.Max;break;default:p(`WebGPUPipelineUtils: Blend equation not supported.`,e)}return t}_getPrimitiveState(e,t,n){let r={};r.topology=this.backend.utils.getPrimitiveTopology(e,n),t.index!==null&&e.isLine===!0&&e.isLineSegments!==!0&&(r.stripIndexFormat=t.index.array instanceof Uint16Array?oz.Uint16:oz.Uint32);let i=n.side===1;return e.isMesh&&e.matrixWorld.determinantAffine()<0&&(i=!i),r.frontFace=i===!0?iz.CW:iz.CCW,r.cullMode=n.side===2?az.None:az.Back,r}_getColorWriteMask(e){return e.colorWrite===!0?dz.All:dz.None}_getDepthCompare(e){let t;if(e.depthTest===!1)t=tz.Always;else{let n=this.backend.parameters.reversedDepthBuffer?li[e.depthFunc]:e.depthFunc;switch(n){case 0:t=tz.Never;break;case 1:t=tz.Always;break;case 2:t=tz.Less;break;case 3:t=tz.LessEqual;break;case 4:t=tz.Equal;break;case 5:t=tz.GreaterEqual;break;case 6:t=tz.Greater;break;case 7:t=tz.NotEqual;break;default:p(`WebGPUPipelineUtils: Invalid depth function.`,n)}}return t}},eV=class{constructor(){this.label=``,this.type=void 0,this.count=0}reset(){this.label=``,this.type=void 0,this.count=0}},tV=new Az,nV=new jz,rV=new eV,iV=class extends YR{constructor(e,t,n=2048){super(n),this.device=e,this.type=t,rV.label=`queryset_global_timestamp_${t}`,rV.type=`timestamp`,rV.count=this.maxQueries,this.querySet=this.device.createQuerySet(rV),rV.reset();let r=this.maxQueries*8;tV.label=`buffer_timestamp_resolve_${t}`,tV.size=r,tV.usage=GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC,this.resolveBuffer=this.device.createBuffer(tV),tV.reset(),tV.label=`buffer_timestamp_result_${t}`,tV.size=r,tV.usage=GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ,this.resultBuffer=this.device.createBuffer(tV),tV.reset()}allocateQueriesForContext(e){if(!this.trackTimestamp||this.isDisposed)return null;this.currentQueryIndex+2>this.maxQueries&&(this.resolveQueriesAsync(),this.currentQueryIndex=0,this.queryOffsets.clear());let t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryOffsets.set(e,t),t}async resolveQueriesAsync(){if(!this.trackTimestamp||this.currentQueryIndex===0||this.isDisposed)return this.lastValue;if(this.pendingResolve)return this.pendingResolve;this.pendingResolve=this._resolveQueries();try{return await this.pendingResolve}finally{this.pendingResolve=null}}async _resolveQueries(){if(this.isDisposed)return this.lastValue;try{if(this.resultBuffer.mapState!==`unmapped`)return this.lastValue;let e=new Map(this.queryOffsets),t=this.currentQueryIndex,n=t*8;this.currentQueryIndex=0,this.queryOffsets.clear();let r=this.device.createCommandEncoder(nV);r.resolveQuerySet(this.querySet,0,t,this.resolveBuffer,0),r.copyBufferToBuffer(this.resolveBuffer,0,this.resultBuffer,0,n);let i=r.finish();if(Rm(this.device,i),this.resultBuffer.mapState!==`unmapped`)return this.lastValue;if(await this.resultBuffer.mapAsync(GPUMapMode.READ,0,n),this.isDisposed)return this.resultBuffer.mapState===`mapped`&&this.resultBuffer.unmap(),this.lastValue;let a=new BigUint64Array(this.resultBuffer.getMappedRange(0,n)),o={},s=[];this.timestamps.clear();for(let[t,n]of e){let e=t.match(/^(.*):f(\d+)$/),r=parseInt(e[2]);s.includes(r)===!1&&s.push(r),o[r]===void 0&&(o[r]=0);let i=a[n],c=a[n+1],l=Number(c-i)/1e6;this.timestamps.set(t,l),o[r]+=l}let c=o[s[s.length-1]];return this.resultBuffer.unmap(),this.lastValue=c,this.frames=s,c}catch(e){return p(`Error resolving queries:`,e),this.resultBuffer.mapState===`mapped`&&this.resultBuffer.unmap(),this.lastValue}}async dispose(){if(!this.isDisposed){if(this.isDisposed=!0,this.pendingResolve)try{await this.pendingResolve}catch(e){p(`Error waiting for pending resolve:`,e)}if(this.resultBuffer&&this.resultBuffer.mapState===`mapped`)try{this.resultBuffer.unmap()}catch(e){p(`Error unmapping buffer:`,e)}this.querySet&&=(this.querySet.destroy(),null),this.resolveBuffer&&=(this.resolveBuffer.destroy(),null),this.resultBuffer&&=(this.resultBuffer.destroy(),null),this.queryOffsets.clear(),this.timestamps.clear(),this.frames=[],this.pendingResolve=null}}},aV=class{constructor(){this.label=``,this.timestampWrites=void 0}reset(){this.label=``,this.timestampWrites=void 0}},oV=class{constructor(){this.view=null,this.depthLoadOp=void 0,this.depthStoreOp=void 0,this.depthClearValue=void 0,this.depthReadOnly=!1,this.stencilLoadOp=void 0,this.stencilStoreOp=void 0,this.stencilClearValue=0,this.stencilReadOnly=!1}reset(){this.view=null,this.depthLoadOp=void 0,this.depthStoreOp=void 0,this.depthClearValue=void 0,this.depthReadOnly=!1,this.stencilLoadOp=void 0,this.stencilStoreOp=void 0,this.stencilClearValue=0,this.stencilReadOnly=!1}},sV=class{constructor(){this.querySet=null,this.beginningOfPassWriteIndex=void 0,this.endOfPassWriteIndex=void 0}reset(){this.querySet=null,this.beginningOfPassWriteIndex=void 0,this.endOfPassWriteIndex=void 0}},cV={r:0,g:0,b:0,a:1},lV={r:0,g:0,b:0,a:0},uV=new Az,dV=new jz,fV=new aV,pV=new eV,mV=new Lz,hV=new sV,gV=new Qz,_V=new Qz,vV=new Rz,yV=new zz,bV=new rB,xV=class extends MR{constructor(e={}){super(e),this.isWebGPUBackend=!0,this.parameters.alpha=e.alpha===void 0||e.alpha,this.parameters.requiredLimits=e.requiredLimits===void 0?{}:e.requiredLimits,this.compatibilityMode=null,this.device=null,this.defaultRenderPassdescriptor=null,this.utils=new Oz(this),this.attributeUtils=new BB(this),this.bindingUtils=new GB(this),this.capabilities=new KB(this),this.pipelineUtils=new $B(this),this.textureUtils=new gB(this),this.occludedResolveCache=new Map;let t=typeof navigator>`u`||/Android/.test(navigator.userAgent)===!1;this._compatibility={[ii.TEXTURE_COMPARE]:t}}async init(e){await super.init(e);let t=this.parameters,n;if(t.device===void 0){let r={powerPreference:t.powerPreference,featureLevel:`compatibility`,xrCompatible:e.xr.enabled},i=typeof navigator<`u`?await navigator.gpu.requestAdapter(r):null;if(i===null)throw Error(`THREE.WebGPUBackend: Unable to create WebGPU adapter.`);let a=Object.values(xz),o=[];for(let e of a)i.features.has(e)&&o.push(e);let s={requiredFeatures:o,requiredLimits:t.requiredLimits};n=await i.requestDevice(s)}else n=t.device;this.compatibilityMode=!n.features.has(`core-features-and-limits`),this.compatibilityMode&&(e._samples=0),n.lost.then(t=>{if(t.reason===`destroyed`)return;let n={api:`WebGPU`,message:t.message||`Unknown reason`,reason:t.reason||null,originalEvent:t};e.onDeviceLost(n)}),n.onuncapturederror=t=>{let n=t.error,r=n&&n.constructor?n.constructor.name:`GPUError`,i=n&&n.message||`Unknown uncaptured GPU error`;e.onError({api:`WebGPU`,type:r,message:i,originalEvent:t})},this.device=n,this.trackTimestamp=this.trackTimestamp&&this.hasFeature(xz.TimestampQuery),this.updateSize()}setXRRenderTargetTextures(e,t,n=null){let r=this.get(e.texture);r.texture=t,r.format=t.format,r.externalTexture=!0,r.xrViewDescriptors=n,r.initialized=!0}get context(){let e=this.renderer.getCanvasTarget(),t=this.get(e),n=t.context;if(n===void 0){let r=this.parameters;n=e.isDefaultCanvasTarget===!0&&r.context!==void 0?r.context:e.domElement.getContext(`webgpu`),`setAttribute`in e.domElement&&e.domElement.setAttribute(`data-engine`,`three.js r186 webgpu`);let i=r.alpha?`premultiplied`:`opaque`,a=r.outputType===1016?`extended`:`standard`;n.configure({device:this.device,format:this.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,alphaMode:i,toneMapping:{mode:a}}),t.context=n}return n}get coordinateSystem(){return ei}get hasTimestamp(){return!0}async getArrayBufferAsync(e,t=null,n=0,r=-1){return await this.attributeUtils.getArrayBufferAsync(e,t,n,r)}getContext(){return this.context}_getDefaultRenderPassDescriptor(){let e=this.renderer,t=e.getCanvasTarget(),n=this.get(t),r=e.currentSamples,i=n.descriptor;if(i===void 0||n.samples!==r){if(i=new Pz,i.colorAttachments.push(new Nz),e.depth===!0||e.stencil===!0){let t=new oV;t.view=this.textureUtils.getDepthBuffer(e.depth,e.stencil).createView(),i.depthStencilAttachment=t}let t=i.colorAttachments[0];r>0?t.view=this.textureUtils.getColorBuffer().createView():t.resolveTarget=void 0,n.descriptor=i,n.samples=r}let a=i.colorAttachments[0];return r>0?a.resolveTarget=this.context.getCurrentTexture().createView():a.view=this.context.getCurrentTexture().createView(),i}_isRenderCameraDepthArray(e){let t=e.camera;return e.depthTexture&&e.depthTexture.isArrayTexture===!0&&t!==null&&t.isArrayCamera===!0}_hasExternalTexture(e){let t=e.textures;if(t===null)return!1;for(let e=0;e1){if(l===!0){let t=e.camera.cameras;for(let e=0;e0?(t.currentOcclusionQuerySet&&t.currentOcclusionQuerySet.destroy(),t.currentOcclusionQueryBuffer&&t.currentOcclusionQueryBuffer.destroy(),t.currentOcclusionQuerySet=t.occlusionQuerySet,t.currentOcclusionQueryBuffer=t.occlusionQueryBuffer,t.currentOcclusionQueryObjects=t.occlusionQueryObjects,pV.label=`occlusionQuerySet_${e.id}`,pV.type=`occlusion`,pV.count=r,i=n.createQuerySet(pV),pV.reset(),t.occlusionQuerySet=i,t.occlusionQueryIndex=0,t.occlusionQueryObjects=Array(r),t.lastOcclusionObject=null):t.lastOcclusionObject!==void 0&&(t.lastOcclusionObject=void 0,t.occlusionQuerySet.destroy(),t.occlusionQuerySet=void 0);let a;a=e.textures===null?this._getDefaultRenderPassDescriptor():this._getRenderPassDescriptor(e,{loadOp:rz.Load}),this.initTimestampQuery(ti.RENDER,this.getTimestampUID(e),a),a.occlusionQuerySet=i;let o=a.depthStencilAttachment,s=e.renderTarget,c=e.sampleCount>1&&s?.storeMultisampledColorBuffer===!1,l=e.sampleCount>1&&s?.storeMultisampledDepthBuffer===!1,u=e.sampleCount>1&&s?.storeMultisampledStencilBuffer===!1,d=e.fullscreenPass===!0&&this._hasExternalTexture(e);if(e.textures!==null){let t=a.colorAttachments;for(let n=0;n1&&i?.storeMultisampledDepthBuffer===!1,o=e.sampleCount>1&&i?.storeMultisampledStencilBuffer===!1;for(let i=0;i0&&t.currentPass.executeBundles(t.renderBundles);let r=t.lastOcclusionObject;r&&r.occlusionTest===!0&&t.currentPass.endOcclusionQuery();let i=t.encoder;if(this._isRenderCameraDepthArray(e)===!0){let n=this._finishArrayCameraBundleEncoders(t),r=t.arrayCameraRenderStages;r.push({bundles:n});for(let n=0;ne.loadOp),s=a.colorAttachments.map(e=>e.storeOp),c=a.depthStencilAttachment?.depthLoadOp,l=a.depthStencilAttachment?.depthStoreOp,u=a.depthStencilAttachment?.stencilLoadOp,d=a.depthStencilAttachment?.stencilStoreOp;for(let t=0;t0){let r=n*8,i=this.occludedResolveCache.get(r);i===void 0&&(uV.size=r,uV.usage=GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC,i=this.device.createBuffer(uV),uV.reset(),this.occludedResolveCache.set(r,i)),uV.size=r,uV.usage=GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ;let a=this.device.createBuffer(uV);uV.reset(),t.encoder.resolveQuerySet(t.occlusionQuerySet,0,n,i,0),t.encoder.copyBufferToBuffer(i,0,a,0,r),t.occlusionQueryBuffer=a,this.resolveOccludedAsync(e)}if(Rm(this.device,t.encoder.finish()),e.textures!==null){let t=e.textures;for(let e=0;es&&(i[0]=Math.min(o,s),i[1]=Math.ceil(o/s)),a.dispatchSize=i}i=a.dispatchSize}s.dispatchWorkgroups(i[0],i[1]||1,i[2]||1)}finishCompute(e){let t=this.get(e);t.passEncoderGPU.end(),Rm(this.device,t.cmdEncoderGPU.finish())}_draw(e,t,n,r,i,a,o,s,c,l=-1){let{object:u,material:d,context:f}=e,p=e.getIndex(),m=p!==null;c.pipeline!==r&&(s.setPipeline(r),c.pipeline=r);let h=c.bindingGroups;for(let e=0,t=i.length;e0){let i=this.get(e.camera),o=e.camera.cameras,d=e.getBindingGroup(`cameraIndex`);if(i.indexesGPU===void 0||i.indexesGPU.length!==o.length){let e=this.get(d),t=[],n=new Uint32Array([0,0,0,0]);for(let r=0,i=o.length;r(f(`WebGPURenderer: WebGPU is not available, running under WebGL2 backend.`),new QR(e)));let n=new t(e);super(n,e),this.library=new wV,this.isWebGPURenderer=!0,typeof __THREE_DEVTOOLS__<`u`&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent(`observe`,{detail:this}))}},EV=class extends I{constructor(){super(),this.isBundleGroup=!0,this.type=`BundleGroup`,this.static=!0,this.version=0}set needsUpdate(e){e===!0&&this.version++}},DV=class{constructor(e,t=bg(0,0,1,1)){this.isRenderPipeline=!0,this.renderer=e,this.outputNode=t,this.outputColorTransform=!0,this.needsUpdate=!0;let n=new VT;n.name=`RenderPipeline`,this._quadMesh=new dj(n),this._quadMesh.name=`Render Pipeline`,this._contextData=null,this._toneMapping=e.toneMapping,this._outputColorSpace=e.outputColorSpace}render(){let e=this.renderer;this._update();for(let e of this._contextData.onBeforePipelineCallbacks)e();let t=e.toneMapping,n=e.outputColorSpace;e.toneMapping=0,e.outputColorSpace=Ci.workingColorSpace;let r=e.xr.enabled;e.xr.enabled=!1,this._quadMesh.render(e),e.xr.enabled=r,e.toneMapping=t,e.outputColorSpace=n;for(let e of this._contextData.onAfterPipelineCallbacks)e()}dispose(){this._quadMesh.material.dispose()}_updateContext(){let e=this._toneMapping,t=this._outputColorSpace,n={renderPipeline:this,renderPipelineState:{viewOffsetOwner:null},onBeforePipelineCallbacks:[],onAfterPipelineCallbacks:[]},r=this.outputNode;this.outputColorTransform===!0?r=Tb(r,e,t):(n.toneMapping=e,n.outputColorSpace=t),this._contextData=n,this._quadMesh.material.contextNode=Sy(n),this._quadMesh.material.fragmentNode=r,this._quadMesh.material.needsUpdate=!0}_update(){this._toneMapping!==this.renderer.toneMapping&&(this._toneMapping=this.renderer.toneMapping,this.needsUpdate=!0),this._outputColorSpace!==this.renderer.outputColorSpace&&(this._outputColorSpace=this.renderer.outputColorSpace,this.needsUpdate=!0),this.needsUpdate===!0&&(this._updateContext(),this.needsUpdate=!1)}async renderAsync(){m(`RenderPipeline: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.`),await this.renderer.init(),this.render()}},OV=class extends DV{constructor(e,t=$g){super(e,t),this.isDirectRenderPipeline=!0,this._contextNode=null,this._rendererContextNode=null,this._backgroundNodes=new WeakMap}render(e,t){let n=this.renderer;this._update();let r=this._getBackgroundNode(e),i=r===null?null:e.backgroundNode,a=n.contextNode,o=n.getOutputRenderTarget(),s=o!==null&&n.xr.isPresenting===!0&&n.backend.isWebGPUBackend===!0&&n.isOutputTarget===!0,c,l,u,d;r!==null&&(e.backgroundNode=r),n.contextNode=this._contextNode,s&&(c=o.samples,l=o.depthBuffer,o.samples=n.samples,o.depthBuffer=!0);try{for(let e of this._contextData.onBeforePipelineCallbacks)e();u=n.toneMapping,d=n.outputColorSpace,n.toneMapping=0,n.outputColorSpace=Ci.workingColorSpace,n.xr.enabled&&n.xr.renderLayers(),n.render(e,t)}finally{u!==void 0&&(n.toneMapping=u),d!==void 0&&(n.outputColorSpace=d),r!==null&&e.backgroundNode===r&&(e.backgroundNode=i),n.contextNode===this._contextNode&&(n.contextNode=a),s&&(o.samples=c,o.depthBuffer=l);for(let e of this._contextData.onAfterPipelineCallbacks)e()}}_getBackgroundNode(e){if(e.isScene!==!0||e.backgroundNode!=null||e.background?.isColor!==!0)return null;let t=this.renderer.xr.getEnvironmentBlendMode();if(t===`additive`||t===`alpha-blend`)return null;let n=this._backgroundNodes.get(e.background);return n===void 0&&(n=v_(e.background),this._backgroundNodes.set(e.background,n)),n}_update(){this._rendererContextNode!==this.renderer.contextNode&&(this._rendererContextNode=this.renderer.contextNode,this.needsUpdate=!0),super._update()}_updateContext(){super._updateContext();let e=this.outputNode,t=this._toneMapping,n=this._outputColorSpace,r=this.outputColorTransform;this._contextNode=this._rendererContextNode.context({...this._contextData,getOutput:(i,a)=>{let o=a.renderer,s=o.getRenderTarget();return o.isOutputTarget===!1&&s?._hasExternalTextures!==!0?i:($g.assign(i),r===!0?Tb(e,t,n):e)}})}},kV=class extends DV{constructor(e,t){m(`PostProcessing: "PostProcessing" has been renamed to "RenderPipeline". Please update your code to use "THREE.RenderPipeline" instead.`),super(e,t)}},AV=class extends ui{constructor(e){super(),this.name=``,this.buffer=null,this.maxByteLength=e,this.isReadbackBuffer=!0,this._mapped=!1}release(){this.dispatchEvent({type:`release`})}dispose(){this.dispatchEvent({type:`dispose`})}},jV=class extends ji{constructor(e=1,t=1){super(),this.image={width:e,height:t},this.magFilter=an,this.minFilter=an,this.isStorageTexture=!0,this.mipmapsAutoUpdate=!0}setSize(e,t){(this.image.width!==e||this.image.height!==t)&&(this.image.width=e,this.image.height=t,this.dispose())}},MV=class extends ji{constructor(e=1,t=1,n=1){super(),this.isArrayTexture=!1,this.image={width:e,height:t,depth:n},this.magFilter=an,this.minFilter=an,this.wrapR=Zt,this.isStorageTexture=!0,this.is3DTexture=!0}copy(e){return super.copy(e),this.wrapR=e.wrapR,this}setSize(e,t,n){(this.image.width!==e||this.image.height!==t||this.image.depth!==n)&&(this.image.width=e,this.image.height=t,this.image.depth=n,this.dispose())}},NV=class extends ji{constructor(e=1,t=1,n=1){super(),this.isArrayTexture=!0,this.image={width:e,height:t,depth:n},this.magFilter=an,this.minFilter=an,this.isStorageTexture=!0}setSize(e,t,n){(this.image.width!==e||this.image.height!==t||this.image.depth!==n)&&(this.image.width=e,this.image.height=t,this.image.depth=n,this.dispose())}},PV=class extends Ej{constructor(e,t){super(e,t,Uint32Array),this.isIndirectStorageBufferAttribute=!0}},FV=class extends su{constructor(e){super(e),this.textures={},this.nodes={}}load(e,t,n,r){let i=new uu(this.manager);i.setPath(this.path),i.setRequestHeader(this.requestHeader),i.setWithCredentials(this.withCredentials),i.load(e,n=>{try{t(this.parse(JSON.parse(n)))}catch(t){r?r(t):p(t),this.manager.itemError(e)}},n,r)}parseNodes(e){let t={};if(e!==void 0){for(let n of e){let{uuid:e,type:r}=n;t[e]=this.createNodeFromType(r),t[e].uuid=e}let n={nodes:t,textures:this.textures};for(let r of e)r.meta=n,t[r.uuid].deserialize(r),delete r.meta}return t}parse(e){let t=this.createNodeFromType(e.type);return t.uuid=e.uuid,e.meta={nodes:this.parseNodes(e.nodes),textures:this.textures},t.deserialize(e),delete e.meta,t}setTextures(e){return this.textures=e,this}setNodes(e){return this.nodes=e,this}createNodeFromType(e){return this.nodes[e]===void 0?(p(`NodeLoader: Node type not found:`,e),U()):new this.nodes[e]}},IV=class extends Wu{constructor(e){super(e),this.nodes={},this.nodeMaterials={}}parse(e){let t=super.parse(e),n=this.nodes,r=e.inputNodes;for(let e in r)t[e]=n[r[e]];return t}setNodes(e){return this.nodes=e,this}setNodeMaterials(e){return this.nodeMaterials=e,this}createMaterialFromType(e){let t=this.nodeMaterials[e];return t===void 0?super.createMaterialFromType(e):new t}},LV=class extends Yu{constructor(e){super(e),this.nodes={},this.nodeMaterials={},this._nodesJSON=null}setNodes(e){return this.nodes=e,this}setNodeMaterials(e){return this.nodeMaterials=e,this}parse(e,t){this._nodesJSON=e.nodes;let n=super.parse(e,t);return this._nodesJSON=null,n}async parseAsync(e){this._nodesJSON=e.nodes;let t=await super.parseAsync(e);return this._nodesJSON=null,t}parseNodes(e,t){if(e!==void 0){let n=new FV;return n.setNodes(this.nodes),n.setTextures(t),n.parseNodes(e)}return{}}parseMaterials(e,t){let n={};if(e!==void 0){let r=this.parseNodes(this._nodesJSON,t),i=new IV;i.setTextures(t),i.setNodes(r),i.setNodeMaterials(this.nodeMaterials);for(let t=0,r=e.length;t{BV(),X.BRDF_GGX,X.BRDF_Lambert,X.BRDF_Sheen,X.BasicPointShadowFilter,X.BasicShadowFilter,X.Break,X.Const,X.Continue,X.DFGLUT,X.D_GGX,X.D_GGX_Anisotropic,X.Discard,X.EPSILON,X.EnvironmentBRDF,X.F_Schlick,VV=X.Fn,X.HALF_PI,X.INFINITY,X.If,X.LTC_Evaluate,X.LTC_Evaluate_Volume,X.LTC_Uv,HV=X.Loop,X.NodeAccess,X.NodeShaderStage,X.NodeType,X.NodeUpdateType,X.OnAfterObjectUpdate,X.OnAfterRenderPipeline,X.OnBeforeFrameUpdate,X.OnBeforeMaterialUpdate,X.OnBeforeObjectUpdate,X.OnBeforeRenderPipeline,X.OnFrameUpdate,X.OnMaterialUpdate,X.OnObjectUpdate,X.PCFShadowFilter,UV=X.PI,X.PI2,X.PointShadowFilter,X.Return,X.Schlick_to_F0,X.ShaderNode,X.Stack,X.Switch,X.TBNViewMatrix,X.TWO_PI,X.VSMShadowFilter,X.V_GGX_SmithCorrelated,X.V_GGX_SmithCorrelated_Anisotropic,X.Var,X.VarIntent,WV=X.abs,X.acesFilmicToneMapping,X.acos,X.acosh,GV=X.add,X.addMethodChaining,X.addNodeElement,X.agxToneMapping,X.all,X.alphaT,X.ambientOcclusion,X.and,X.anisotropy,X.anisotropyB,X.anisotropyT,X.any,KV=X.array,X.asin,X.asinh,X.assign,X.atan,X.atanh,X.atomicAdd,X.atomicAnd,X.atomicFunc,X.atomicLoad,X.atomicMax,X.atomicMin,X.atomicOr,X.atomicStore,X.atomicSub,X.atomicXor,X.attenuationColor,X.attenuationDistance,qV=X.attribute,X.attributeArray,X.backgroundBlurriness,X.backgroundIntensity,X.backgroundRotation,X.batch,X.batchColor,X.batchIndirectIndex,X.bentNormalView,X.billboarding,X.bitAnd,X.bitNot,X.bitOr,X.bitXor,X.bitangentGeometry,X.bitangentLocal,X.bitangentView,X.bitangentViewFrame,X.bitangentWorld,X.bitcast,X.blendBurn,X.blendColor,X.blendDodge,X.blendOverlay,X.blendScreen,X.bool,X.buffer,X.bufferAttribute,X.builtin,X.builtinAOContext,X.builtinGIContext,X.builtinShadowContext,X.bumpMap,X.bvec2,X.bvec3,X.bvec4,X.bypass,X.cache,X.call,X.cameraFar,X.cameraIndex,X.cameraNear,X.cameraNormalMatrix,JV=X.cameraPosition,X.cameraProjectionMatrix,X.cameraProjectionMatrixInverse,X.cameraViewMatrix,X.cameraViewport,X.cameraWorldMatrix,X.cbrt,X.cdl,X.ceil,X.checker,X.cineonToneMapping,YV=X.clamp,X.clearcoat,X.clearcoatNormalView,X.clearcoatRoughness,X.clipSpace,X.clipping,X.clippingAlpha,X.code,XV=X.color,X.colorSpaceToWorking,X.colorToDirection,X.compute,X.computeKernel,X.computeSkinning,ZV=X.context,X.convert,X.convertColorSpace,X.convertToTexture,X.cos,X.cosh,X.countLeadingZeros,X.countOneBits,X.countTrailingZeros,X.cross,X.cubeTexture,X.cubeTextureBase,X.dFdx,X.dFdy,X.dashSize,X.debug,X.decrement,X.decrementBefore,X.defaultBuildStages,X.defaultShaderStages,X.defined,X.degrees,X.deltaTime,X.densityFogFactor,X.depth,X.depthPass,X.determinant,X.difference,X.diffuseColor,X.diffuseContribution,X.directPointLight,X.directionToColor,X.directionToFaceDirection,X.dispersion,X.distance,X.div,QV=X.dot,X.dot4I8Packed,X.dot4U8Packed,X.drawIndex,X.dynamicBufferAttribute,X.element,X.emissive,X.equal,X.equirectDirection,X.equirectUV,X.exp,X.exp2,X.exponentialHeightFogFactor,X.expression,X.faceDirection,X.faceForward,X.faceforward,$V=X.float,X.floatBitsToInt,X.floatBitsToUint,X.floor,eH=X.fog,tH=X.fract,X.frameGroup,X.frameId,X.frontFacing,X.fwidth,X.gain,X.gapSize,X.getConstNodeType,X.getCurrentStack,X.getDistanceAttenuation,X.getGeometryRoughness,X.getNormalFromDepth,X.getParallaxCorrectNormal,X.getRoughness,X.getScreenPosition,X.getScreenPositionFromClip,X.getShIrradianceAt,X.getTextureIndex,X.getViewPosition,X.globalId,X.glsl,X.glslFn,X.grayscale,X.greaterThan,X.greaterThanEqual,X.hardwareClipping,X.hash,X.highpModelNormalViewMatrix,X.highpModelViewMatrix,X.hue,X.increment,X.incrementBefore,X.inspect,X.instance,X.instanceColor,nH=X.instanceIndex,X.instancedArray,X.instancedBufferAttribute,X.instancedDynamicBufferAttribute,X.instancedMesh,rH=X.int,X.intBitsToFloat,X.interleavedGradientNoise,X.inverse,X.inverseSqrt,X.inversesqrt,X.invocationLocalIndex,X.invocationSubgroupIndex,X.ior,X.iridescence,X.iridescenceIOR,X.iridescenceThickness,X.isolate,X.ivec2,X.ivec3,X.ivec4,X.js,X.label,iH=X.length,X.lengthSq,X.lessThan,X.lessThanEqual,X.lightPosition,X.lightProjectionUV,X.lightShadowMatrix,X.lightTargetDirection,X.lightTargetPosition,X.lightViewPosition,X.lightingContext,X.lights,X.linearDepth,X.linearToneMapping,X.localId,X.log,X.log2,X.logarithmicDepthToViewZ,aH=X.luminance,X.mat2,X.mat3,X.mat4,X.matcapUV,X.materialAO,X.materialAlphaTest,X.materialAnisotropy,X.materialAnisotropyVector,X.materialAttenuationColor,X.materialAttenuationDistance,X.materialClearcoat,X.materialClearcoatNormal,X.materialClearcoatRoughness,X.materialColor,X.materialDispersion,X.materialEmissive,X.materialEnvIntensity,X.materialEnvRotation,X.materialIOR,X.materialIridescence,X.materialIridescenceIOR,X.materialIridescenceThickness,X.materialLightMap,X.materialLineDashOffset,X.materialLineDashSize,X.materialLineGapSize,X.materialLineScale,X.materialLineWidth,X.materialMetalness,X.materialNormal,X.materialOpacity,X.materialPointSize,X.materialReference,X.materialReflectivity,X.materialRefractionRatio,X.materialRetroreflectivity,X.materialRotation,X.materialRoughness,X.materialSheen,X.materialSheenRoughness,X.materialShininess,X.materialSpecular,X.materialSpecularColor,X.materialSpecularIntensity,X.materialSpecularStrength,X.materialThickness,X.materialTransmission,oH=X.max,X.maxMipLevel,X.mediumpModelViewMatrix,X.metalness,X.min,sH=X.mix,X.mixElement,cH=X.mod,X.modelDirection,X.modelNormalMatrix,X.modelPosition,X.modelRadius,X.modelScale,X.modelViewMatrix,X.modelViewPosition,X.modelViewProjection,lH=X.modelWorldMatrix,X.modelWorldMatrixInverse,X.morphReference,X.mrt,X.mul,X.mx_aastep,X.mx_add,X.mx_atan2,X.mx_cell_noise_float,X.mx_cell_noise_vec3,X.mx_contrast,X.mx_divide,uH=X.mx_fractal_noise_float,X.mx_fractal_noise_float_2d,X.mx_fractal_noise_vec2,X.mx_fractal_noise_vec3,X.mx_fractal_noise_vec4,X.mx_frame,X.mx_heighttonormal,X.mx_hsvtorgb,X.mx_ifequal,X.mx_ifgreater,X.mx_ifgreatereq,X.mx_invert,X.mx_modulo,X.mx_multiply,dH=X.mx_noise_float,X.mx_noise_vec3,X.mx_noise_vec4,X.mx_place2d,X.mx_power,X.mx_ramp4,X.mx_ramplr,X.mx_ramptb,X.mx_rgbtohsv,X.mx_rotate2d,X.mx_rotate3d,X.mx_safepower,X.mx_separate,X.mx_smoothstep,X.mx_splitlr,X.mx_splittb,X.mx_srgb_texture_to_lin_rec709,X.mx_subtract,X.mx_timer,X.mx_transform_uv,X.mx_unifiednoise2d,X.mx_unifiednoise3d,X.mx_worley_noise_float,X.mx_worley_noise_float_2d,X.mx_worley_noise_float_3d,X.mx_worley_noise_vec2,X.mx_worley_noise_vec3,X.mx_worley_noise_vec3_style,X.negate,X.negateOnBackSide,X.neutralToneMapping,X.nodeArray,X.nodeImmutable,fH=X.nodeObject,X.nodeObjectIntent,X.nodeObjects,X.nodeProxy,X.nodeProxyConstructor,X.nodeProxyIntent,X.normalFlat,X.normalGeometry,pH=X.normalLocal,X.normalMap,mH=X.normalView,X.normalViewGeometry,hH=X.normalWorld,X.normalWorldGeometry,gH=X.normalize,X.not,X.notEqual,X.numWorkgroups,X.objectDirection,X.objectGroup,X.objectPosition,X.objectRadius,X.objectScale,X.objectViewPosition,X.objectWorldMatrix,X.oneMinus,X.or,X.orthographicDepthToViewZ,X.oscSawtooth,X.oscSine,X.oscSquare,X.oscTriangle,X.output,X.outputStruct,X.overloadingFn,X.overrideNode,X.overrideNodes,X.pack4xI8,X.pack4xI8Clamp,X.pack4xU8,X.pack4xU8Clamp,X.packHalf2x16,X.packNormalToRGB,X.packSnorm2x16,X.packSnorm4x8,X.packUnorm2x16,X.packUnorm4x8,X.parabola,X.parallaxDirection,X.parallaxUV,X.parameter,_H=X.pass,vH=X.passTexture,X.pcurve,X.perspectiveDepthToViewZ,X.pmremTexture,X.pointShadow,X.pointUV,X.pointWidth,X.positionGeometry,yH=X.positionLocal,X.positionPrevious,X.positionView,bH=X.positionViewDirection,xH=X.positionWorld,X.positionWorldDirection,X.posterize,SH=X.pow,X.pow2,X.pow3,X.pow4,X.premultiplyAlpha,X.property,X.quadBroadcast,X.quadSwapDiagonal,X.quadSwapX,X.quadSwapY,X.radians,X.rand,X.range,CH=X.rangeFogFactor,X.reciprocal,X.reference,X.referenceBuffer,X.reflect,X.reflectVector,X.reflectView,X.reflector,X.refract,X.refractVector,X.refractView,X.reinhardToneMapping,X.remap,X.remapClamp,X.renderGroup,X.renderOutput,X.rendererReference,X.replaceDefaultUV,X.retroreflectivity,X.rotate,X.rotateUV,X.roughness,X.round,X.rtt,X.sRGBTransferEOTF,X.sRGBTransferOETF,X.sample,X.sampler,X.samplerComparison,X.saturate,X.saturation,X.screenCoordinate,X.screenDPR,X.screenSize,wH=X.screenUV,X.select,X.setCurrentStack,X.setName,X.shaderStages,X.shadow,X.shadowPositionWorld,X.shapeCircle,X.sharedUniformGroup,X.sheen,X.sheenRoughness,X.shiftLeft,X.shiftRight,X.shininess,X.sign,TH=X.sin,X.sinc,X.sinh,X.skinning,EH=X.smoothstep,X.smoothstepElement,X.specularColor,X.specularColorBlended,X.specularF90,X.spherizeUV,X.split,X.spritesheetUV,X.sqrt,X.stack,X.step,X.stepElement,X.storage,X.storageBarrier,X.storageElement,X.storageTexture,X.storageTexture3D,X.struct,X.sub,X.subBuild,X.subgroupAdd,X.subgroupAll,X.subgroupAnd,X.subgroupAny,X.subgroupBallot,X.subgroupBroadcast,X.subgroupBroadcastFirst,X.subgroupElect,X.subgroupExclusiveAdd,X.subgroupExclusiveMul,X.subgroupInclusiveAdd,X.subgroupInclusiveMul,X.subgroupIndex,X.subgroupMax,X.subgroupMin,X.subgroupMul,X.subgroupOr,X.subgroupShuffle,X.subgroupShuffleDown,X.subgroupShuffleUp,X.subgroupShuffleXor,X.subgroupSize,X.subgroupXor,X.tan,X.tangentGeometry,X.tangentLocal,X.tangentView,X.tangentViewFrame,X.tangentWorld,X.tanh,DH=X.texture,X.texture3D,X.texture3DLevel,X.texture3DLoad,X.textureBarrier,X.textureBicubic,X.textureBicubicLevel,X.textureLevel,X.textureLoad,X.textureSize,X.textureStore,X.thickness,X.time,X.toneMapping,X.toneMappingExposure,X.toonOutlinePass,X.transformDirection,X.transformNormal,X.transformNormalByInverseViewMatrix,X.transformNormalByViewMatrix,X.transformNormalToView,X.transformedClearcoatNormalView,X.transformedNormalView,X.transformedNormalWorld,X.transmission,X.transpose,X.triNoise3D,X.triplanarTexture,X.triplanarTextures,X.trunc,X.uint,X.uintBitsToFloat,OH=X.uniform,kH=X.uniformArray,X.uniformCubeTexture,X.uniformFlow,X.uniformGroup,X.uniformTexture,X.unpack4xI8,X.unpack4xU8,X.unpackHalf2x16,X.unpackNormal,X.unpackRGBToNormal,X.unpackSnorm2x16,X.unpackSnorm4x8,X.unpackUnorm2x16,X.unpackUnorm4x8,X.unpremultiplyAlpha,X.userData,AH=X.uv,X.uvec2,X.uvec3,X.uvec4,X.varying,X.varyingProperty,jH=X.vec2,MH=X.vec3,NH=X.vec4,X.vectorComponents,X.velocity,PH=X.vertexColor,X.vertexIndex,X.vertexStage,X.vibrance,X.viewZToLogarithmicDepth,X.viewZToOrthographicDepth,X.viewZToPerspectiveDepth,X.viewZToReversedOrthographicDepth,X.viewZToReversedPerspectiveDepth,X.viewport,X.viewportCoordinate,X.viewportDepthTexture,X.viewportLinearDepth,X.viewportMipTexture,X.viewportOpaqueMipTexture,X.viewportSafeUV,X.viewportSharedTexture,X.viewportSize,X.viewportTexture,X.viewportUV,X.vogelDiskSample,X.wgsl,X.wgslFn,X.workgroupArray,X.workgroupBarrier,X.workgroupId,X.workingToColorSpace,X.xor}));BV(),FH();var IH=new dj,LH=new N,RH=new N(1,0),zH=new N(0,1),BH,VH=VV(({input:e,threshold:t,smoothWidth:n})=>{let r=aH(e.rgb),i=EH(t,t.add(n),r);return sH(NH(0),e,i)}),HH=class extends mh{static get type(){return`BloomNode`}constructor(e,t=1,n=0,r=0){super(`vec4`),this.inputNode=e,this.strength=t.isNode?t:OH(t),this.radius=n.isNode?n:OH(n),this.threshold=r.isNode?r:OH(r),this.smoothWidth=OH(.01),this.bloomTintColors=[new P(1,1,1),new P(1,1,1),new P(1,1,1),new P(1,1,1),new P(1,1,1)],this._resolutionScale=.5,this.highPassFn=VH,this._renderTargetsHorizontal=[],this._renderTargetsVertical=[],this._nMips=5,this._renderTargetBright=new Ni(1,1,{depthBuffer:!1,type:_n}),this._renderTargetBright.texture.name=`UnrealBloomPass.bright`,this._renderTargetBright.texture.generateMipmaps=!1;for(let e=0;e{let e=UH(r.element(0),this.radius).mul(NH(i.element(0),1)).mul(this._textureNodeBlur0),t=UH(r.element(1),this.radius).mul(NH(i.element(1),1)).mul(this._textureNodeBlur1),n=UH(r.element(2),this.radius).mul(NH(i.element(2),1)).mul(this._textureNodeBlur2),a=UH(r.element(3),this.radius).mul(NH(i.element(3),1)).mul(this._textureNodeBlur3),o=UH(r.element(4),this.radius).mul(NH(i.element(4),1)).mul(this._textureNodeBlur4);return e.add(t).add(n).add(a).add(o).mul(this.strength)});return this._compositeMaterial=this._compositeMaterial||new VT,this._compositeMaterial.contextNode=t,this._compositeMaterial.fragmentNode=a(),this._compositeMaterial.name=`Bloom_comp`,this._compositeMaterial.needsUpdate=!0,this._textureOutput}dispose(){super.dispose();for(let e=0;es.sample(e),m=VV(()=>{let e=p(f).rgb.mul(i).toVar();return HV({start:rH(0),end:rH(a.length),type:`int`,condition:`<`},({i:t})=>{let n=l.element(t),r=d.mul(u).mul(c.element(t)),i=p(f.add(r)).rgb,a=p(f.sub(r)).rgb;e.addAssign(GV(i,a).mul(n))}),NH(e,1)}),h=new VT;return h.contextNode=e,h.fragmentNode=m(),h.name=`Bloom_separable`,h.needsUpdate=!0,h.colorTexture=s,h.direction=d,h.invSize=u,h}},UH=VV(({factor:e,radius:t})=>{let n=$V(1.2).sub(e);return sH(e,n,t)},{factor:`float`,radius:`float`,return:`float`}),WH=(e,t,n,r)=>new HH(fH(e),t,n,r),GH,KH=t((()=>{GH={skyZenith:8366566,skyMid:11126512,skyHorizon:16177604,skyWarm:16762784,sun:16773590,fog:13293294,fogWarm:15981769,cloudLit:16777215,cloudMid:15394806,cloudShade:11777758,cloudDeep:10134484,grassDark:5212732,grassMid:8368714,grassTip:13165178,grassDry:14275194,soil:9399114,dirt:12886138,rockLight:13808268,rockMid:11108962,rockDark:8150861,rockDeep:6968944,wood:11039823,woodDark:7227955,woodLight:13212267,canvas:15984852,roof:9064252,stone:12432034,water:6865880,waterEdge:11463151,foam:16055807,leaf:7778378,leafLit:11787370,trunk:8017465,gold:16766059,lantern:16756309,ribbon:16773846}}));function qH(){let e=new Y({side:1,depthWrite:!1});e.fog=!1,e.colorNode=VV(()=>{let e=gH(xH.sub(JV)),t=e.y,n=sU(e).toVar(),r=oH(QV(e,YH),0);n.addAssign(XV(GH.sun).mul(SH(r,48).mul(.32)).mul(sH($V(1),aU,QH))),n.addAssign(MH(iU).mul(EH(.9991,.9995,r).mul(1.1)));let i=e.mul(170),a=i.floor(),o=i.sub(a).sub(.5),s=a.dot(MH(12.9898,78.233,37.719)).sin().mul(43758.5453).fract(),c=EH(.985,1,s).mul(EH(.35,.05,o.length())).mul(EH(.02,.2,t));n.addAssign(XV(16052479).mul(c.mul(rU).mul(QH).mul(XH.mul(2).add(s.mul(40)).sin().mul(.3).add(.8))));let l=e.xz.div(t.add(.35).max(.05)).mul(jH(.55,1.4)),u=uH(MH(l.x,l.y,XH.mul(.002)),4,2,.5).mul(.5).add(.5),d=EH(.55,.85,u).mul(EH(.02,.15,t)).mul($V(1).sub(EH(.35,.7,t)));return n.assign(sH(n,sH(XV(16777215),XV(GH.skyWarm),SH(r,2)),d.mul(.45))),n})();let t=new z(new xl(2600,48,24),e);return t.frustumCulled=!1,t.renderOrder=-10,t.name=`sky`,t}var JH,YH,XH,ZH,QH,$H,eU,tU,nU,rU,iU,aU,oU,sU,cU=t((()=>{BV(),FH(),KH(),JH=new P(-.8,.3,-.36).normalize(),YH=OH(JH.clone()),XH=OH(0),ZH=OH(0),QH=OH(0),$H=OH(new L(16777215)),eU=OH(new L(16777215)),tU=OH(new L(16777215)),nU=OH(new L(16777215)),rU=OH(0),iU=OH(new L(16774886)),aU=OH(1),oU=OH(new L(16777215)),sU=VV(([e])=>{let t=e.y,n=sH(XV(GH.skyHorizon),XV(GH.skyMid),EH(0,.28,t)).toVar();n.assign(sH(n,XV(GH.skyZenith),EH(.22,.85,t)));let r=oH(QV(e,YH),0);n.assign(sH(n,XV(GH.skyWarm),SH(r,3).mul(.75).mul($V(1).sub(EH(0,.7,t))))),n.assign(sH(n,XV(GH.fog),EH(.02,-.14,t).mul($V(1).sub(SH(r,4).mul(.6)))));let i=sH(XV(16762074),XV(15906530),EH(0,.3,t)).toVar();i.assign(sH(i,XV(11836648),EH(.25,.9,t))),i.assign(sH(i,XV(15320812),EH(.02,-.14,t))),n.assign(sH(n,i,ZH.mul(.62)));let a=sH(MH($H),MH(eU),EH(0,.28,t)).toVar();return a.assign(sH(a,MH(tU),EH(.22,.85,t))),a.assign(sH(a,MH(nU),EH(.02,-.14,t))),a.addAssign(XV(GH.skyWarm).mul(SH(r,3).mul(.35).mul(aU).mul($V(1).sub(EH(0,.7,t))))),n.assign(sH(n,a,QH)),n})}));function lU(e){let t=e>>>0;return function(){t|=0,t=t+1831565813|0;let e=Math.imul(t^t>>>15,1|t);return e=e+Math.imul(e^e>>>7,61|e)^e,((e^e>>>14)>>>0)/4294967296}}function uU(e=1){let t=lU(e),n=new Uint8Array(256);for(let e=0;e<256;e++)n[e]=e;for(let e=255;e>0;e--){let r=Math.floor(t()*(e+1));[n[e],n[r]]=[n[r],n[e]]}let r=new Uint8Array(512);for(let e=0;e<512;e++)r[e]=n[e&255];return function(e,t){let n=(e+t)*fU,i=Math.floor(e+n),a=Math.floor(t+n),o=(i+a)*pU,s=e-(i-o),c=t-(a-o),l=+(s>c),u=s>c?0:1,d=s-l+pU,f=c-u+pU,p=s-1+2*pU,m=c-1+2*pU,h=i&255,g=a&255,_=0,v=.5-s*s-c*c;if(v>0){let e=mU[r[h+r[g]]&7];v*=v,_+=v*v*(e[0]*s+e[1]*c)}let y=.5-d*d-f*f;if(y>0){let e=mU[r[h+l+r[g+u]]&7];y*=y,_+=y*y*(e[0]*d+e[1]*f)}let b=.5-p*p-m*m;if(b>0){let e=mU[r[h+1+r[g+1]]&7];b*=b,_+=b*b*(e[0]*p+e[1]*m)}return 70*_}}function dU(e,t,n,r=4,i=2,a=.5){let o=1,s=1,c=0,l=0;for(let u=0;u{fU=.5*(Math.sqrt(3)-1),pU=(3-Math.sqrt(3))/6,mU=[[1,1],[-1,1],[1,-1],[-1,-1],[1,0],[-1,0],[0,1],[0,-1]],hU=(e,t,n)=>Math.max(t,Math.min(n,e)),gU=(e,t,n)=>e+(t-e)*n,_U=(e,t,n)=>{let r=hU((n-e)/(t-e),0,1);return r*r*(3-2*r)}}));function yU(){if(xU)return xU;let e=new Uint8Array([70,70,150,150,150,255,255,255]);return xU=new Cs(e,e.length,1,On),xU.minFilter=xU.magFilter=$t,xU.needsUpdate=!0,xU}function bU(e=16774109,t=.35,n=3){let r=SH($V(1).sub(QV(mH,bH).abs().clamp(0,1)),n);return XV(e).mul(r).mul(OH(t))}function Q(e,{rim:t=.25,vertexColors:n=!1,side:r=0,map:i=null,emissive:a=null}={}){let o=new SO({color:e,gradientMap:yU(),vertexColors:n,side:r,map:i});return o.emissiveNode=SU(a??0).add(bU(16773596,Math.max(0,t))),o}var xU,SU,CU=t((()=>{BV(),FH(),xU=null,SU=(e,t=1)=>OH(new L(e).multiplyScalar(t))}));function wU(e){let t=e.toFixed(3);if(OU.has(t))return OU.get(t);let n=new Y({side:1}),r=lH.mul(NH(yH,1)).xyz,i=YV(iH(JV.sub(r)).div(14),.55,5);return n.positionNode=yH.add(gH(pH).mul(OH(e).mul(i))),n.colorNode=XV(DU),OU.set(t,n),n}function TU(e,t=.03){if(!e||e.userData.outlined)return null;let n=wU(t),r;return e.isSkinnedMesh?(r=new xs(e.geometry,n),r.bind(e.skeleton,e.bindMatrix),r.bindMode=e.bindMode):e.isInstancedMesh?(r=new Fs(e.geometry,n,e.count),r.instanceMatrix=e.instanceMatrix):r=new z(e.geometry,n),r.castShadow=!1,r.receiveShadow=!1,r.frustumCulled=e.frustumCulled,r.renderOrder=e.renderOrder,r.name=(e.name||`mesh`)+`:ink`,r.userData.outlined=!0,r.userData.inkThick=t,e.userData.outlined=!0,e.add(r),r}function EU(e,t=.03){let n=[];e.traverse(e=>{e.isMesh&&!e.userData.noOutline&&!e.userData.outlined&&!e.material.transparent&&e.material.side===0&&!e.name.endsWith(`:ink`)&&n.push(e)});for(let e of n)TU(e,e.userData.outlineThick??t)}var DU,OU,kU=t((()=>{BV(),FH(),DU=3813188,OU=new Map}));function AU(e,t,n){let r=null;for(let i of e){let e=i.groundAt(t,n);e!==null&&(r===null||e>r)&&(r=e)}return r}var jU,MU,NU,PU=t((()=>{BV(),vU(),KH(),CU(),kU(),jU=e=>new L(e),MU={grassDark:jU(GH.grassDark),grassMid:jU(GH.grassMid),dry:jU(GH.grassDry),dirt:jU(GH.dirt),soil:jU(GH.soil),rockLight:jU(GH.rockLight),rockMid:jU(GH.rockMid),rockDark:jU(GH.rockDark),rockDeep:jU(GH.rockDeep),moss:jU(7313994)},NU=class{constructor(e){if(this.name=e.name,this.center=new P(...e.center),this.R=e.radius,this.depth=e.depth??e.radius*1.2,this.hill=e.hill??1.5,this.flats=e.flats??[],this.ponds=e.ponds??[],this.detail=e.detail??1,this.seed=e.seed??1,this.noise=uU(this.seed),this.noiseB=uU(this.seed*7+3),this.rimJag=e.rimJag??.12,this.tipOffset=e.tipOffset??[0,0],this.cols={...MU},e.palette)for(let[t,n]of Object.entries(e.palette))this.cols[t]=new L(n);this.grassPalette=e.grassPalette||null,this.flowerPalette=e.flowerPalette||null}rim(e){let t=Math.cos(e),n=Math.sin(e);return 1+this.rimJag*dU(this.noise,t*1.3+11,n*1.3+5,3)+.04*this.noiseB(t*4,n*4)}heightLocal(e,t){let n=Math.hypot(e,t),r=Math.atan2(t,e),i=n/(this.R*this.rim(r)),a=this.hill*dU(this.noise,e*.03+3,t*.03-2,3)+.5*this.hill*dU(this.noiseB,e*.09,t*.09,2);for(let n of this.flats){let r=Math.hypot(e-n.x,t-n.z);a=gU(a,n.h,_U(n.r,n.r*.45,r))}for(let n of this.ponds){let r=Math.hypot(e-n.x,t-n.z);a-=1.4*_U(n.r*1.25,n.r*.35,r)}return a-=_U(.86,1,i)*.9,a}groundAt(e,t){let n=e-this.center.x,r=t-this.center.z,i=Math.hypot(n,r),a=Math.atan2(r,n);return i>this.R*this.rim(a)*.985?null:this.center.y+this.heightLocal(n,r)}cliffRadius(e,t){let n=(this.center.y-t)/this.depth;return n<0||n>1?-1:this.R*this.rim(e)*(1-n)**.75}rockAt(e,t,n,r=0,i=new P){let a=t-this.center.y;if(a>1||a<-this.depth)return null;let o=e-this.center.x,s=n-this.center.z;if(o*o+s*s>(this.R*1.5+r+2)**2)return null;let c=Math.round(150*this.detail),l=Math.max(8,Math.round(26*this.detail)),u=Math.PI*2,d=Math.atan2(s,o),f=this.R*this.rim(d),p=this.heightLocal(Math.cos(d)*f*.999,Math.sin(d)*f*.999);if(a>p)return null;let m=Math.min(1,Math.max(0,(p-a)/(p+this.depth)))**(1/1.05),[h,g]=this.tipOffset;o-=h*m*m,s-=g*m*m,d=Math.atan2(s,o),d<0&&(d+=u);let _=Math.min(l-1e-6,m*l),v=Math.floor(_),y=_-v,b=d/u*c,x=Math.floor(b)%c,S=b-Math.floor(b),C=(x+1)%c,w=(e,t)=>this.cliffVertexR(e,t,c,l),T=(w(v,x)*(1-S)+w(v,C)*S)*(1-y)+(w(v+1,x)*(1-S)+w(v+1,C)*S)*y+r,E=Math.hypot(o,s);if(E>=T)return null;let D=T/Math.max(E,.001);return i.set(this.center.x+h*m*m+o*D,t,this.center.z+g*m*m+s*D)}cliffVertexR(e,t,n,r){this._cliffR||=new Float32Array((r+1)*n).fill(NaN);let i=e*n+t,a=this._cliffR[i];if(a===a)return a;let o=e/r,s=t/n*Math.PI*2,c=this.R*this.rim(s),l=this.heightLocal(Math.cos(s)*c*.999,Math.sin(s)*c*.999),u=gU(l,-this.depth,o**1.05),d=(1-o)**.72*(1+.06*Math.sin(o*9+s*3));o<.08&&(d*=1+.035*(1-o/.08));let f=1+.1*this.noise(s*5.3,u*.09)+.05*this.noiseB(s*13,u*.25);return a=c*d*(e===0?1:f),this._cliffR[i]=a,a}pondHeight(e){return this.center.y+e.h}build(){let e=Math.round(150*this.detail),t=Math.max(8,Math.round(26*this.detail)),n=Math.max(8,Math.round(26*this.detail)),r=[],i=[],a=[],o=new L,s=this.cols,c=this.R;r.push(0,this.heightLocal(0,0),0),o.copy(s.grassDark),i.push(o.r,o.g,o.b);for(let n=1;n<=t;n++){let a=(n/t)**.8;for(let t=0;t{let e=t.z,n=dH(MH(t.x.mul(.035).add(XH.mul(.35)),t.y.mul(.035),$V(.5))),r=TH(XH.mul(2.1).add(t.x.mul(.23)).add(t.y.mul(.19))).mul(.35).add(n.mul(.9)).add(.25),i=e.mul(e).mul(r).mul(.3),a=jH(t.x,t.y).sub(jH(RU.x,RU.z)),o=EH(1.3,.15,iH(a)).mul(e).mul(.55),s=gH(a.add(jH(1e-4,0)));return yH.add(MH(i.mul(zU.x).add(s.x.mul(o)),o.mul(-.35).sub(i.mul(i).mul(.6)),i.mul(zU.y).add(s.y.mul(o))))})(),e.emissiveNode=XV(16773570).mul(t.z.mul(t.z)).mul(.07),BU=e,e}function IU(e,{density:t=9,exclude:n=()=>!1,seed:r=3,chunk:i=18}={}){let a=lU(r+e.seed*13),o=uU(r*31+7),s=e.R,c=Math.PI*s*s,l=Math.floor(c*t),u=new Map,d=new L,f=new L,p=new L,m=e.grassPalette||{},h=new L(m.dark??GH.grassDark),g=new L(m.mid??GH.grassMid),_=new L(m.tip??GH.grassTip),v=new L(m.dry??GH.grassDry),y=[];for(let t=0;t.965&&a()<.7||n(b,x))continue;let w=dU(o,b*.045,x*.045,3)*.5+.5,T=(.22+w*.38+a()*.16)*(C>.9?.6:1),E=_U(.6,.85,w);d.copy(h).lerp(g,a()*.3),f.copy(g).lerp(_,.55+a()*.45).lerp(v,E*.5),a()<(m.flowers??.012)&&C<.9&&y.push([b,S+T*.75,x,a()]);let D=Math.floor(b/i)+`,`+Math.floor(x/i),ee=u.get(D);ee||(ee={pos:[],col:[],root:[],idx:[]},u.set(D,ee));let O=.03+a()*.025,k=a()*Math.PI,te=Math.cos(k),A=Math.sin(k),ne=(a()-.5)*.25,re=[[-O,0,0],[O,0,0],[-O*.62,.5,ne*.4],[O*.62,.5,ne*.4],[0,1,ne]],ie=ee.pos.length/3;for(let[e,t,n]of re){let r=b+te*e-A*n*T,i=x+A*e+te*n*T;ee.pos.push(r,S+t*T-.05,i),p.copy(d).lerp(f,t),ee.col.push(p.r,p.g,p.b),ee.root.push(b,x,t)}ee.idx.push(ie,ie+1,ie+2,ie+1,ie+3,ie+2,ie+2,ie+3,ie+4)}let b=new I;b.name=`grass:`+e.name;let x=FU();for(let e of u.values()){let t=new xo;t.setAttribute(`position`,new R(e.pos,3)),t.setAttribute(`color`,new R(e.col,3)),t.setAttribute(`aRoot`,new R(e.root,3));let n=new Float32Array(e.pos.length);for(let e=1;enew L(e)),a=new F;return e.forEach(([e,t,n,o],s)=>{a.makeTranslation(e,t,n),r.setMatrixAt(s,a),r.setColorAt(s,i[Math.floor(o*i.length)%i.length])}),r.instanceMatrix.needsUpdate=!0,r.instanceColor&&(r.instanceColor.needsUpdate=!0),r.userData.noOutline=!0,r}var RU,zU,BU,VU=t((()=>{BV(),FH(),vU(),KH(),cU(),CU(),RU=OH(new P(0,0,0)),zU=new N(.85,-.5).normalize(),BU=null})),HU=t((()=>{Wf(),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])}));function UU(e,t=!1){let n=e[0].index!==null,r=new Set(Object.keys(e[0].attributes)),i=new Set(Object.keys(e[0].morphAttributes)),a={},o={},s=e[0].morphTargetsRelative,c=new xo,l=0;for(let u=0;u{let r=new e.array.constructor(e.count*e.itemSize);l[n][t]=new e.constructor(r,e.itemSize,e.normalized)}))}let p=t*.5,m=10**Math.log10(1/t),h=p*m;for(let t=0;t{HU()}));function JU(e,t=9,{leaf:n=GH.leaf,leafLit:r=GH.leafLit,trunk:i=GH.trunk}={}){let a=lU(t),o=[],s=[];for(let t of e){let e=t.h??5+a()*2.5,n=t.r??2+a()*1.2;s.push({x:t.x,y:t.y,z:t.z,h:e*.72,r:.22+n*.05,lean:(a()-.5)*.15});let r=6+Math.floor(a()*5);for(let i=0;i{p.compose(new P(e.x,e.y,e.z),m,new P(e.r,e.r*.85,e.r)),l.setMatrixAt(t,p),f.copy(u).lerp(d,e.c*.7),l.setColorAt(t,f)}),l.castShadow=!0,l.receiveShadow=!0;let h=new Fs(new Ic(.6,1,1,7,1).translate(0,.5,0),Q(i,{rim:.15}),s.length);return s.forEach((e,t)=>{m.setFromEuler(new Ji(e.lean,a()*3,e.lean*.5)),p.compose(new P(e.x,e.y-.2,e.z),m,new P(e.r,e.h,e.r)),h.setMatrixAt(t,p)}),h.castShadow=!0,c.add(l,h),c.userData.colliders=e.map(e=>({x:e.x,z:e.z,r:.6})),c.userData.canopies=o.map(e=>({x:e.x,y:e.y,z:e.z,r:e.r*.95})),c.userData.trunks=s.map(e=>({x:e.x,z:e.z,r:e.r+.15,y0:e.y-.5,y1:e.y+e.h})),c}function YU(e,t=4){let n=lU(t),r=new Fs(new zc(1,0),Q(GH.rockLight,{rim:.2}),e.length),i=new F,a=new gi;return e.forEach((e,t)=>{a.setFromEuler(new Ji(n()*3,n()*3,n()*3)),i.compose(new P(e.x,e.y,e.z),a,new P(e.r,e.r*.7,e.r*.9)),r.setMatrixAt(t,i)}),r.castShadow=!0,r.receiveShadow=!0,r}var XU,ZU=t((()=>{BV(),vU(),KH(),CU(),qU(),XU=e=>{let t=new hl(1,e);t.deleteAttribute(`normal`),t.deleteAttribute(`uv`);let n=GU(t);return n.computeVertexNormals(),n}}));function QU(e,t,n,r){let i=new Y;i.colorNode=VV(()=>{let e=iH(AH().sub(.5)).mul(2),t=sH(XV(GH.water),XV(GH.waterEdge),EH(.35,.95,e)),n=dH(MH(xH.x.mul(.6),xH.z.mul(.6),XH.mul(.4)));return t=sH(t,XV(16777215),EH(.55,.75,n).mul(.35)),t=sH(t,XV(GH.foam),EH(.86,.97,e)),t})();let a=new z(new Fc(r,40),i);return a.rotation.x=-Math.PI/2,a.position.set(e,t,n),a.name=`pond`,a.userData.noOutline=!0,a}function $U(e,t=3,n=6,r=new P(0,0,1)){let i=new $c(e),a=[],o=[],s=[];for(let e=0;e<=60;e++){let c=e/60,l=i.getPoint(c),u=hi.lerp(t,n,c**.7)*.5;if(a.push(l.x-r.x*u,l.y,l.z-r.z*u,l.x+r.x*u,l.y,l.z+r.z*u),o.push(0,c,1,c),e<60){let t=e*2;s.push(t,t+2,t+1,t+1,t+2,t+3)}}let c=new xo;c.setAttribute(`position`,new R(a,3)),c.setAttribute(`uv`,new R(o,2)),c.setIndex(s),c.computeVertexNormals();let l=new Y({transparent:!0,side:2,depthWrite:!1}),u=AH(),d=dH(MH(u.x.mul(7),u.y.mul(3).sub(XH.mul(1.9)),.3)),f=dH(MH(u.x.mul(17),u.y.mul(8).sub(XH.mul(3.1)),1.7));l.colorNode=sH(sH(XV(GH.water),XV(GH.waterEdge),EH(-.3,.3,d)),XV(GH.foam),EH(.25,.6,f.add(u.y.mul(.4)))),l.opacityNode=EH(0,.18,u.x).mul(EH(1,.82,u.x)).mul($V(1).sub(EH(.7,1,u.y))).mul(.92);let p=new z(c,l);return p.name=`waterfall`,p.renderOrder=2,p}function eW(e,t=1.6){let n=new $c(e),r=[],i=[],a=[];for(let e=0;e<=40;e++){let o=e/40,s=n.getPoint(o),c=n.getTangent(o),l=-c.z,u=c.x,d=Math.hypot(l,u)||1,f=t*.5;if(r.push(s.x-l/d*f,s.y,s.z-u/d*f,s.x+l/d*f,s.y,s.z+u/d*f),i.push(0,o,1,o),e<40){let t=e*2;a.push(t,t+1,t+2,t+1,t+3,t+2)}}let o=new xo;o.setAttribute(`position`,new R(r,3)),o.setAttribute(`uv`,new R(i,2)),o.setIndex(a);let s=new Y({side:2}),c=AH(),l=dH(MH(c.x.mul(4),c.y.mul(10).sub(XH.mul(2.2)),0));s.colorNode=sH(XV(GH.water),XV(GH.waterEdge),EH(-.2,.5,l));let u=new z(o,s);return u.name=`stream`,u.userData.noOutline=!0,u}var tW=t((()=>{BV(),FH(),KH(),cU()}));PU(),VU(),ZU(),tW(),BV(),KH(),CU();var nW={},rW=(e,t,n)=>nW[e]??=Q(t,n),iW=e=>(e.traverse(e=>{e.isMesh&&(e.castShadow=!0,e.receiveShadow=!0)}),e);function aW(){let e=new I;e.name=`windmill`;let t=new z(new Ic(3,3.3,1.4,10),rW(`stone`,GH.stone));t.position.y=.4,e.add(t);let n=new z(new Ic(1.55,2.35,9,8),rW(`wood`,GH.wood));n.position.y=5.6,e.add(n);for(let t=0;t<3;t++){let n=new z(new Ic(2.3-t*.28,2.34-t*.28,.25,8),rW(`woodDark`,GH.woodDark));n.position.y=2.2+t*3,e.add(n)}let r=new z(new Lc(2.25,3,8),rW(`roof`,GH.roof));r.position.y=11.6,e.add(r);let i=new z(new Nc(1.1,1.9,.3),rW(`woodDark`,GH.woodDark));i.position.set(0,2,2.25),i.rotation.x=-.1,e.add(i);for(let[t,n]of[[6.2,0],[8.4,2.2],[7.3,-2]]){let r=new z(new Nc(.55,.75,.2),rW(`window`,3882837,{emissive:2761792})),i=1.95-(t-5.6)*.09;r.position.set(Math.sin(n)*i,t,Math.cos(n)*i),r.rotation.y=n,e.add(r)}let a=new I;a.position.set(0,9.6,2.4),e.add(a),a.add(new z(new Ic(.35,.35,.9,10).rotateX(Math.PI/2),rW(`woodDark`,GH.woodDark)));for(let e=0;e<4;e++){let t=new I;t.rotation.z=e*Math.PI/2,a.add(t);let n=new z(new Nc(.22,7.6,.18),rW(`woodDark`,GH.woodDark));n.position.y=3.9,t.add(n);let r=new z(new vl(1.45,5.8,1,4),rW(`canvas`,GH.canvas,{side:2,rim:.2}));r.position.set(.85,4.4,.08),t.add(r);for(let e=0;e<5;e++){let n=new z(new Nc(1.6,.07,.07),rW(`woodDark`,GH.woodDark));n.position.set(.8,1.7+e*1.35,.14),t.add(n)}}return e.userData.update=e=>{a.rotation.z=-e*.55},e.userData.collider={r:3.2},iW(e)}function oW(e=10,t=4.2,n=4.8){let r=new I;r.name=`mast`;let i=new z(new Ic(.13,.2,e,7),rW(`woodDark`,GH.woodDark));i.position.y=e/2,r.add(i);for(let n of[e*.88,e*.4]){let e=new z(new Ic(.08,.08,t+.4,6).rotateZ(Math.PI/2),rW(`woodDark`,GH.woodDark));e.position.y=n,r.add(e)}let a=new vl(t,n,8,8),o=a.attributes.position;for(let e=0;e{c.rotation.y=.25*Math.sin(e*3.1),s.scale.z=1+.08*Math.sin(e*1.3)},iW(r)}function sW(){let e=new I;e.name=`glider`;let t=new xo;t.setAttribute(`position`,new R([0,.2,1.4,-3.2,0,-.7,0,.35,-.3,0,.2,1.4,0,.35,-.3,3.2,0,-.7],3)),t.computeVertexNormals(),e.add(new z(t,rW(`canvas`,GH.canvas,{side:2,rim:.2})));let n=new z(new Nc(.12,.12,3),rW(`woodDark`,GH.woodDark));n.position.set(0,.25,.4),e.add(n);let r=new z(new Nc(1.4,.08,.08),rW(`woodDark`,GH.woodDark));r.position.set(0,-.6,.3),e.add(r);for(let t of[-1,1]){let n=new z(new Ic(.03,.03,.9,5),rW(`woodDark`,GH.woodDark));n.position.set(t*.6,-.2,.3),n.rotation.z=t*.5,e.add(n)}return iW(e)}function cW(e,t,n=3){let r=new I;r.name=`bridge`;let i=new P().subVectors(t,e),a=i.length();i.normalize();let o=new P(-i.z,0,i.x).normalize(),s=Math.max(8,Math.round(a/.55)),c=r=>new P().lerpVectors(e,t,r).add(new P(0,-n*4*r*(1-r),0)),l=new Nc(1.9,.12,.42),u=new Fs(l,rW(`woodLight`,GH.woodLight),s),d=new F,f=new gi,p=Math.atan2(i.x,i.z);for(let e=0;e{BV(),FH(),KH(),cU()}));function gW(e=3.2,{light:t=!1}={}){let n=new Y,r=yH.mul(.055).add(MH(XH.mul(.01),0,0));return n.positionNode=yH.add(gH(pH).mul(t?dH(r).mul(e*.8):uH(r,3,2,.5).mul(e))),n.colorNode=VV(()=>{let e=t?dH(xH.mul(.06)).mul(.13):uH(xH.mul(.045),3,2.1,.55).mul(.16),n=QV(hH,YH).mul(.5).add(.5).add(e),r=sH(XV(GH.cloudShade),XV(GH.cloudMid),EH(.3,.47,n));r=sH(r,XV(GH.cloudLit),EH(.55,.72,n));let i=EH(-40,-78,xH.y);r=sH(r,XV(GH.cloudDeep),i.mul(.55)),r=sH(r,XV(GH.cloudShade),EH(.1,-.6,hH.y).mul(.35));let a=SH($V(1).sub(QV(mH,bH).abs().clamp(0,1)),2.5);r=r.add(XV(16773344).mul(a).mul(EH(.45,.8,n)).mul(.35)),r=r.mul(oU);let o=gH(xH.sub(JV));return r=sH(r,sU(o),EH(.62,.97,a).mul(.55)),r})(),n}function _W({seed:e=5,clusters:t=150,spread:n=700,inner:r=60,yMin:i=-72,yMax:a=-44,extraFar:o=!0}={}){let s=lU(e),c=[],l=(e,t,n,r,i)=>{for(let a=0;a{g.set(e,t,n),h.set(r*1.15,r*.78,r),p.compose(g,m,h),f.setMatrixAt(i,p)}),f.instanceMatrix.setUsage(Wr),f.instanceMatrix.needsUpdate=!0,f.name=`clouds`,f.frustumCulled=!1,f.userData.noOutline=!0;let _=new Y;_.colorNode=XV(GH.cloudDeep).mul(oU);let v=new z(new Fc(2400,64),_);v.rotation.x=-Math.PI/2,v.position.y=i-2,v.name=`cloudFloor`,v.userData.noOutline=!0;let y=new I;y.add(f,v),y.userData.puffs=c;let b=new zs,x=new F,S=new po,C=new F,w=[],T=0,E=null;return y.userData.setFull=e=>{e?(E||={mat:gW(),geo:yW(3)},f.material=E.mat,f.geometry=E.geo,c.forEach(([e,t,n,r],i)=>{g.set(e,t,n),h.set(r*1.15,r*.78,r),p.compose(g,m,h),f.setMatrixAt(i,p)}),f.count=c.length,f.instanceMatrix.needsUpdate=!0):(f.material=d,f.geometry=u,C.identity(),T=-1),y.userData.full=e},y.userData.cull=(e,t=1650)=>{if(y.userData.full||(e.updateMatrixWorld(),C.equals(e.matrixWorld)&&T===e.fov+e.aspect))return f.count;C.copy(e.matrixWorld),T=e.fov+e.aspect,x.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),b.setFromProjectionMatrix(x);let n=e.position;w.length=0;for(let e=0;et||(S.center.set(i,a,o),S.radius=s,b.intersectsSphere(S)&&w.push(f-s,e))}let r=[];for(let e=0;ew[e]-w[t]);for(let e=0;e{r.compose(new P(e,t,a),i,new P(o,o*.8,o)),n.setMatrixAt(s,r)}),n.instanceMatrix.needsUpdate=!0,n.userData.noOutline=!0,n}var yW,bW=t((()=>{BV(),FH(),cU(),vU(),qU(),KH(),yW=e=>{let t=new hl(1,e);t.deleteAttribute(`normal`),t.deleteAttribute(`uv`);let n=GU(t);return n.computeVertexNormals(),n}}));hW(),bW(),BV(),qU(),kU();var xW=new F,SW=new F;function CW(e,{skip:t=[]}={}){e.updateMatrixWorld(!0),SW.copy(e.matrixWorld).invert();let n=new Set(t),r=new Map,i=[];e.traverse(t=>{if(!t.isMesh||t.isSkinnedMesh||t.isInstancedMesh||t.name.endsWith(`:ink`)||t.userData.dynamic)return;for(let r=t;r&&r!==e;r=r.parent)if(n.has(r))return;if(!t.visible||Array.isArray(t.material)||t.morphTargetInfluences)return;let a=t.children.find(e=>e.name?.endsWith(`:ink`)),o=[t.material.uuid,t.castShadow,t.receiveShadow,t.renderOrder,a?a.userData.inkThick??`x`:`none`].join(`|`);if(a&&a.userData.inkThick===void 0)return;let s=r.get(o);s||r.set(o,s={mat:t.material,cast:t.castShadow,recv:t.receiveShadow,order:t.renderOrder,ink:a?a.userData.inkThick:null,geos:[]}),xW.multiplyMatrices(SW,t.matrixWorld);let c=t.geometry.index?t.geometry.toNonIndexed():t.geometry.clone();if(c.applyMatrix4(xW),xW.determinant()<0){let e=c.attributes.position;for(let t=0;t{for(let t of Object.keys(e.attributes))[`position`,`normal`,`uv`].includes(t)||e.deleteAttribute(t);return e.attributes.normal||e.computeVertexNormals(),e.attributes.uv||e.setAttribute(`uv`,new eo(new Float32Array(e.attributes.position.count*2),2)),e.morphAttributes={},e.clearGroups(),e}),r=UU(n,!1);if(n.forEach(e=>e.dispose()),!r){t.skip=!0;continue}r.computeBoundingSphere(),r.computeBoundingBox();let i=new z(r,t.mat);i.castShadow=t.cast,i.receiveShadow=t.recv,i.renderOrder=t.order,i.name=(e.name||`static`)+`:merged`,e.add(i),t.ink!==null&&TU(i,t.ink),t.made=i,a++}let o=new Set([...r.entries()].filter(([,e])=>!e.skip).map(([e])=>e)),s=0;for(let e of i){let t=e.children.find(e=>e.name?.endsWith(`:ink`)),n=[e.material.uuid,e.castShadow,e.receiveShadow,e.renderOrder,t?t.userData.inkThick??`x`:`none`].join(`|`);if(!o.has(n))continue;let r=e.children.filter(e=>!e.name?.endsWith(`:ink`));for(let t of r)e.parent.add(t),t.applyMatrix4(e.matrix);e.parent.remove(e),s++}return{made:a,removed:s}}BV(),CU(),kU(),vU(),KH();var wW=(e,t,n)=>new P(e,t,n),TW={cottage:{x:-.5,z:-2.5},basket:{x:-8,z:3},bell:{x:-9.8,z:-1.9},cart:{x:17,z:-5.5},spyglass:{x:12.4,z:13.6},landing:{x:-15,z:1}},EW={center:[182,-8,6],radius:11};function DW(){let e=document.createElement(`canvas`);return e.width=512,e.height=380,e}var OW=(e,t,n,r,i=0,a=0,o=0,s)=>{let c=new z(new Nc(e,t,n),r);return c.position.set(i,a,o),c.castShadow=c.receiveShadow=!0,s?.add(c),c};function kW(){let e=new I;e.name=`jam-cottage`;let t=5.2,n=2.7,r=.18,i=t/2,a=Q(15786696,{rim:.15}),o=Q(GH.woodDark,{rim:.12}),s=Q(GH.woodLight,{rim:.12}),c=2-r/2,l=(t,n,i,o)=>OW(n-t,o-i,r,a,(t+n)/2,(i+o)/2,c,e);l(-2.6,-1.7,0,n),l(-1.7,1,0,1),l(-1.7,1,2.1,n),l(1,1.4,0,n),l(1.4,2.3,2,n),l(2.3,i,0,n),OW(t,n,r,a,0,n/2,-1.91,e);for(let t of[-1,1])OW(r,n,4-2*r,a,t*(i-r/2),n/2,0,e);let u=OW(5.1000000000000005,.12,3.9,Q(10253904,{rim:0}),0,.06,0,e);u.castShadow=!1;for(let[t,r]of[[-2.6,2],[i,2],[-2.6,-2],[i,-2]])OW(.22,n,.22,o,t,n/2,r,e);OW(5.3,.2,.24,o,0,2.6,2,e),OW(5.3,.2,.24,o,0,2.6,-2,e),OW(2.86,.12,.34,o,-.35,.96,2.05,e),OW(2.86,.12,.24,o,-.35,2.15,2,e),OW(.09,1.1,.14,o,-.35,1.55,c,e);let d=Q(6262650,{rim:.18});for(let[t,n]of[[-1.7,-1],[1,1]]){let r=new I;r.position.set(t,1.55,2.02),r.rotation.y=n*-1.9,OW(.66,1.08,.05,d,n*.34,0,0,r),e.add(r)}OW(2.2,.24,.3,s,-.35,.8,2.24,e);let f=Q(16743050,{rim:.3}),p=Q(16766059,{rim:.3}),m=Q(GH.leaf,{rim:.2});for(let t=0;t<9;t++){let n=new z(new hl(.075,0),t%3?f:p);n.position.set(-1.35+t*.25,.98+t%2*.05,2.26),e.add(n);let r=new z(new hl(.08,0),m);r.position.set(-1.25+t*.25,.92,2.3),e.add(r)}let h=new I;h.position.set(2.3,0,1.89),h.rotation.y=1.75,OW(.9,1.95,.06,Q(8016440,{rim:.12}),-.45,1,0,h),e.add(h),OW(1.1,.14,.28,o,1.85,2.05,2,e);let g=OW(1.2,.14,.7,Q(GH.stone,{rim:.1}),1.85,.07,2.4,e);g.castShadow=!1;let _=1.35,v=Math.hypot(2.45,_),y=Math.atan2(_,2.45),b=Q(GH.roof,{rim:.2});for(let t of[1,-1]){let n=OW(5.9,.16,v,b,0,3.187040816326531,t*2.45/2,e);n.rotation.x=t*y}OW(6,.14,.2,o,0,3.9020408163265308,0,e);let x=new ul([new N(-2,0),new N(2,0),new N(0,1.1020408163265307)]),S=new pl(x,{depth:r,bevelEnabled:!1});for(let t of[-1,1]){let r=new z(S,a);r.rotation.y=-Math.PI/2,r.position.set(t>0?i:-2.42,n,0),r.castShadow=r.receiveShadow=!0,e.add(r)}let C=OW(.55,1.6,.55,Q(GH.stone,{rim:.15}),-1,3.7,.9,e);OW(.7,.14,.7,Q(10327178),-1,4.5200000000000005,.9,e),OW(1.1,.8,.7,Q(4012100,{rim:.2}),-1,.52,1.25,e);let w=new z(new vl(.5,.3),new Y);w.material.colorNode=SU(16747066,1.6),w.position.set(-1,.45,.895),w.rotation.y=Math.PI,e.add(w);let T=[[0,0],[.26,.01],[.31,.06],[.32,.3],[.34,.33]].map(([e,t])=>new N(e,t)),E=new z(new gl(T,18),Q(12614213,{rim:.4,side:2}));E.position.set(-1,.92,1.2),e.add(E);let D=new z(new Fc(.3,18),Q(10692682,{rim:.2}));D.rotation.x=-Math.PI/2,D.position.set(-1,1.2,1.2),e.add(D);let ee=OW(.04,.6,.04,o,-.88,1.35,1.12,e);ee.rotation.z=-.35;let O=Q(11743823,{rim:.35}),k=Q(15984852,{rim:.1});OW(2.4,.07,.34,s,.3,1.75,-1.72,e),OW(1.6,.07,.3,s,-2.3,1.45,-.2,e).rotation.y=Math.PI/2;for(let t=0;t<7;t++){let n=-.7+t*.33,r=new z(new Ic(.09,.09,.2,10),O);r.position.set(n,1.89,-1.72),e.add(r);let i=new z(new Ic(.11,.1,.05,10),k);i.position.set(n,2.01,-1.72),e.add(i)}OW(.9,.75,.6,s,1.7,.5,-1.5,e);let te=new I;te.position.set(.36,.12,1.45),e.add(te);for(let e of[-1,1]){let t=OW(.06,1.95,.06,o,e*.42,.95,-.12,te);t.rotation.x=.12}let A=DW(),ne=new Oc(A);ne.colorSpace=Mr,OW(1.04,.8,.06,o,0,1.45,0,te);let re=new z(new vl(.94,.7),new Y({map:ne}));re.position.set(0,1.45,.035),te.add(re);let ie=new Fu(16754784,3.2,5,1.6);ie.position.set(-1,.75,.75),e.add(ie);let ae=new Fu(16763274,1.6,4,1.8);return ae.position.set(.9,2.2,.3),e.add(ae),e.traverse(e=>{e.isMesh&&e.geometry.type===`BoxGeometry`&&TU(e,.016)}),TU(E,.014),TU(C,.02),CW(e),{g:e,cv:A,tex:ne,local:{stove:wW(-1,.12,.5),board:wW(.36,1.57,1.5),pot:wW(-1,1.2,1.2),chimneyTop:wW(-1,4.65,.9),windowOut:wW(-.35,0,4.2),windowCenter:wW(-.35,1.55,2.1),path:[wW(.55,.12,.35),wW(1.85,.12,1.1),wW(1.85,.12,2.1),wW(1.85,0,2.9)]}}}function AW(){let e=new I;e.name=`cart`;let t=Q(GH.wood,{rim:.12}),n=Q(GH.woodDark,{rim:.12});OW(2,.14,1.3,t,0,.78,0,e);for(let t of[-1,1])OW(2,.34,.08,n,0,.98,t*.62,e),OW(.08,.34,1.3,n,t*.96,.98,0,e);for(let t of[-1,1]){let r=new z(new Cl(.44,.07,6,18),n);r.position.set(.2,.46,t*.74),e.add(r);for(let r=0;r<3;r++){let i=OW(.05,.84,.04,n,.2,.46,t*.74,e);i.rotation.z=r*Math.PI/3}let i=OW(1.5,.07,.07,n,-1.65,.72,t*.45,e);i.rotation.z=.25}OW(.1,.1,1.5,n,.2,.46,0,e);let r=[wW(-.45,.85,-.3),wW(.45,.85,-.3),wW(-.45,.85,.3),wW(.45,.85,.3)];return e.traverse(e=>{e.isMesh&&TU(e,.016)}),CW(e),{g:e,slots:r}}function jW(){let e=new I;TU(OW(.56,.4,.46,Q(GH.woodLight,{rim:.12}),0,.2,0,e),.015);for(let t of[-1,1])OW(.58,.07,.03,Q(GH.wood),0,.3,t*.235,e);let t=Q(11743823,{rim:.35}),n=Q(15984852,{rim:.1});for(let r=0;r<6;r++){let i=-.17+r%3*.17,a=r<3?-.1:.1,o=new z(new Ic(.06,.06,.08,8),t);o.position.set(i,.42,a),e.add(o);let s=new z(new Ic(.068,.065,.03,8),n);s.position.set(i,.47,a),e.add(s)}return CW(e),e}function MW(){let e=new I;e.name=`spyglass`;let t=Q(GH.woodDark,{rim:.12}),n=Q(14263361,{rim:.45});for(let n=0;n<3;n++){let r=n*Math.PI*2/3;OW(.05,1.45,.05,t,Math.cos(r)*.28,.7,Math.sin(r)*.28,e).rotation.set(Math.sin(r)*.2,0,-Math.cos(r)*.2)}let r=new z(new Ic(.07,.1,.9,12).rotateX(Math.PI/2),n);r.position.set(0,1.42,.1),r.rotation.x=.08,e.add(r);let i=new z(new Ic(.045,.05,.2,10).rotateX(Math.PI/2),t);return i.position.set(0,1.44,-.42),e.add(i),e.traverse(e=>{e.isMesh&&TU(e,.014)}),CW(e),e}var NW=null;function PW(){if(NW)return NW;let e=document.createElement(`canvas`);e.width=256,e.height=128;let t=e.getContext(`2d`);t.fillStyle=`#c99256`,t.fillRect(0,0,256,128);for(let e=0;e<8;e++)for(let n=0;n<16;n++){let r=e%2*8,i=n*16+r,a=e*16;t.fillStyle=(n+e)%3?`#d9a466`:`#c28a4c`,t.beginPath(),t.ellipse(i+8,a+8,7.5,6,0,0,Math.PI*2),t.fill(),t.strokeStyle=`rgba(110,70,40,.55)`,t.lineWidth=1.5,t.stroke()}for(let e=0;e<16;e++)t.fillStyle=`rgba(120,78,44,.5)`,t.fillRect(e*16+15,0,2,128);return NW=new Oc(e),NW.colorSpace=Mr,NW.wrapS=NW.wrapT=Xt,NW.repeat.set(3,4),NW}function FW(e=!0){let t=(e?[[0,0],[.5,.02],[.62,.12],[.7,.32],[.67,.55],[.5,.76],[.31,.89],[.27,.96],[.34,1.03]]:[[0,0],[.5,.02],[.66,.12],[.8,.4],[.86,.5]]).map(([e,t])=>new N(e,t)),n=Q(16777215,{rim:.22,side:2,map:PW()}),r=new z(new gl(t,22),n);r.castShadow=r.receiveShadow=!0;let i=Q(10119736,{rim:.2});for(let[t,n]of e?[[.14,.64],[.34,.71],[.56,.68],[.9,.31],[1.03,.34]]:[[.14,.67],[.5,.86]]){let e=new z(new Cl(n,.03,5,26),i);e.rotation.x=Math.PI/2,e.position.y=t,r.add(e)}if(e)for(let e of[-1,1]){let t=new z(new Cl(.22,.03,5,14,Math.PI),i);t.position.set(e*.3,1,0),t.rotation.y=Math.PI/2,r.add(t)}return TU(r,.02),r}function IW(e,t,n,r=5){let i=JU(t,17);e.add(i);let a=new xl(.2,14,10),o=Q(16763210,{rim:.35});o.emissiveNode=SU(16758832,.35);let s=new Fs(a,o,t.length*r);s.castShadow=!0;let c=new F,l=[];t.forEach((e,t)=>{for(let i=0;i{e.alive=!1,c.makeScale(0,0,0),s.setMatrixAt(e.i,c),s.instanceMatrix.needsUpdate=!0},u.restoreFruit=()=>{for(let e of l)e.alive=!0,c.makeTranslation(e.pos.x,e.pos.y,e.pos.z),s.setMatrixAt(e.i,c);s.instanceMatrix.needsUpdate=!0},u.nextFruit=e=>{let t=null,n=1e9;for(let r of l)if(r.alive){let i=r.pos.distanceToSquared(e);i{let t=null;for(let n of l)n.alive&&n.tree===e&&(!t||n.pos.yl.map(e=>e.alive),u.restore=e=>{l.forEach((t,n)=>{t.alive=e[n],c.makeTranslation(t.pos.x,t.pos.y,t.pos.z),t.alive||c.makeScale(0,0,0),s.setMatrixAt(t.i,c)}),s.instanceMatrix.needsUpdate=!0},u}function LW(e,t){let n=lU(404),r=t.center.clone(),i=(e,n,i=0)=>{let a=r.x+e,o=r.z+n;return wW(a,(t.groundAt(a,o)??r.y)+i,o)},a={island:t,colliders:[],basketCount:{fruit:0,rock:0},rule:`rings`,board:0,odoReady:!1,burn:0},o=new I;o.name=`orchard`,e.add(o);let s=new F,c=[];for(let[e,t]of[[-78,12],[-38,14.5],[2,12.5],[42,14],[82,12],[122,15],[-122,15.5]]){let r=e*Math.PI/180,a=i(Math.cos(r)*t,Math.sin(r)*t);c.push({x:a.x,y:a.y,z:a.z,h:5.4+n()*1.2,r:2.4+n()*.5})}let l=IW(o,c,n);Object.assign(a,{fruits:l.fruits,pick:l.pick,restoreFruit:l.restoreFruit,nextFruit:l.nextFruit,lowestOn:l.lowestOn,treeSpecs:c}),a.colliders.push(...l.trees.userData.colliders),a.canopies=l.trees.userData.canopies,a.trunks=l.trees.userData.trunks;let u=l.fruitGeo,d=l.fruitMat;a.fruitGeo=u,a.fruitMat=d;let f=i(TW.basket.x,TW.basket.z),p=i(TW.cottage.x,TW.cottage.z),m=wW(p.x-f.x,0,p.z-f.z).normalize(),h=new I;h.position.copy(f).addScaledVector(m,.66),o.add(h),h.rotation.y=Math.atan2(m.x,m.z);let g=new I;h.add(g);let _=FW(!0);_.position.set(0,0,-.66),g.add(_);let v=_.geometry.parameters.points,y=Math.max(0,(t.groundAt(f.x+m.x*1.3,f.z+m.z*1.3)??f.y)-f.y),b=e=>{let t=0;for(let n of v)for(let r=0;r<24;r++){let i=r/24*Math.PI*2,a=Math.cos(i)*n.x-.66,o=n.y;t=Math.min(t,o*Math.cos(e)-a*Math.sin(e))}return-t},x=Array.from({length:21},(e,t)=>b(t/20*1.75)),S=e=>{let t=hi.clamp(e/1.75,0,1)*20,n=Math.floor(t),r=x[Math.min(20,n)]+(x[Math.min(20,n+1)]-x[Math.min(20,n)])*(t-n);g.rotation.x=e,g.position.y=r+e/1.75*.03+e/1.75*y};a.basketPos=f.clone(),a.basketTop=f.clone().add(wW(0,1.45,0)),a.colliders.push({x:f.x,z:f.z,r:.85});let C=new Fs(u,d,24);C.count=0,o.add(C);let w=new zc(.2,0),T=Q(10327951,{rim:.15}),E=new Fs(w,T,24);E.count=0,o.add(E);let D=e=>{let t=e*2.4,n=.16+e%3*.14;return wW(f.x+Math.cos(t)*n,f.y+.24+Math.floor(e/6)*.17,f.z+Math.sin(t)*n)},ee=[];a.addToBasket=e=>{let t=ee.length;if(t>=24)return;let n=e===`fruit`?C:E,r=D(t);s.makeTranslation(r.x,r.y,r.z),n.setMatrixAt(n.count,s),n.count++,n.instanceMatrix.needsUpdate=!0,ee.push(e),a.basketCount[e]++},a.emptyBasket=()=>{C.count=0,E.count=0,ee.length=0,a.basketCount={fruit:0,rock:0}},a.removeRocks=()=>{let e=a.basketCount.fruit;a.emptyBasket();for(let t=0;t{O={t:0,rolls:ee.map((e,r)=>{let i=(r/Math.max(1,ee.length)-.5)*1.6+(n()-.5)*.3,a=e===`fruit`?1.1+n()*1.4:.6+n()*.5,o=m.clone().applyAxisAngle(wW(0,1,0),i),s=f.clone().addScaledVector(o,.9+a);return s.y=(t.groundAt(s.x,s.z)??f.y)+.2,{kind:e,from:D(r),end:s,delay:.25+r*.05}}),hold:e,keep:r,done:i,back:!1}},a.tipping=()=>!!O,a.untip=()=>{O&&!O.back&&(O.back=!0,O.backAt=O.t)};let k=new Fs(u,d,24);k.count=0,o.add(k);let te=new Fs(w,T,24);te.count=0,o.add(te);let A=e=>{if(!O)return;O.t+=e;let t=O.t,n=t<.5?t/.5:1,r=O.back?Math.max(0,1-(t-O.backAt)/.6):1;S(1.75*hi.smoothstep(n,0,1)*r),C.visible=E.visible=t<.3||O.back&&O.keep&&r<=0;let i=0,o=0;for(let e of O.rolls){if(O.back&&!O.keep)break;let n=hi.clamp((t-e.delay)/.9,0,1);if(t1.4+O.rolls.length*.05+O.hold&&(O.back=!0,O.backAt=t),O.back&&t>O.backAt+.7){S(0),k.count=te.count=0,C.visible=E.visible=!0,O.keep||a.emptyBasket();let e=O.done;O=null,e?.()}};a.snapshotBasket=()=>({contents:ee.slice(),count:{...a.basketCount}}),a.restoreBasket=e=>{a.emptyBasket();for(let t of e.contents)a.addToBasket(t)};let ne=i(-5.4,6.4);a.rockPile=ne.clone().add(wW(0,.5,0));let re=new Fs(new zc(.28,0),T,9);for(let e=0;e<9;e++){let t=new gi().setFromEuler(new Ji(n()*3,n()*3,0));s.compose(wW(ne.x+(n()-.5)*1.2,ne.y+.15+(e>5?.3:0),ne.z+(n()-.5)*1.2),t,wW(1,.8,1)),re.setMatrixAt(e,s)}re.castShadow=!0,o.add(re),TU(re,.02);let ie=kW(),ae=wW(f.x-p.x,0,f.z-p.z).normalize();ie.g.position.copy(p).y+=.02,ie.g.rotation.y=Math.atan2(ae.x,ae.z),o.add(ie.g),ie.g.updateMatrixWorld(!0);let j=e=>e.clone().applyMatrix4(ie.g.matrixWorld),oe=e=>(e.y=t.groundAt(e.x,e.z)??e.y,e);a.cottage=ie.g,a.cottagePos=p.clone(),a.cottageYaw=ie.g.rotation.y,a.stoveSpot=j(ie.local.stove),a.stoveYaw=ie.g.rotation.y,a.boardPos=j(ie.local.board),a.boardYaw=ie.g.rotation.y+.9,a.windowOut=oe(j(ie.local.windowOut)),a.windowCenter=j(ie.local.windowCenter),a.chimneyTop=j(ie.local.chimneyTop),a.potTop=j(ie.local.pot);let se=ie.local.path.map(j);oe(se[se.length-1]),a.doorOut=se[se.length-1].clone(),a.inspectSpot=f.clone().addScaledVector(m,1.35),oe(a.inspectSpot),a.pathToBasket=[...se,a.inspectSpot.clone()],a.pathToStove=[...se.slice().reverse(),a.stoveSpot.clone()],a.colliders.push({x:p.x,z:p.z,r:2.75});{let e=ie.g.matrixWorld.clone().invert(),t=ie.g.matrixWorld.elements[13],n=wW(0,0,0),r=(r,i)=>n.set(r,t,i).applyMatrix4(e),i=e=>t+2.7-.2479591836734694+.14+1.35*(1-Math.abs(e)/2.45);a.surfaces=[{solid:!0,at:(e,t)=>{let n=r(e,t);return Math.abs(n.x)<=2.65&&Math.abs(n.z)<=2.05?i(n.z):null}},{at:(e,t)=>{let n=r(e,t);return Math.abs(n.x)<=2.95&&Math.abs(n.z)>2.05&&Math.abs(n.z)<=2.45?i(n.z):null}}]}a.camBlock=[{x:p.x,z:p.z,r:3.25,y0:p.y-1,y1:p.y+4.4}];for(let e of[-1,1]){let t=j(wW(e*2.2,0,-1.2));a.colliders.push({x:t.x,z:t.z,r:1.2})}let ce=ie.cv.getContext(`2d`);a.drawBoard=()=>{let e=ie.cv;ce.fillStyle=`#2f4739`,ce.fillRect(0,0,e.width,e.height),ce.globalAlpha=.08;for(let e=0;e<60;e++)ce.fillStyle=`#fff`,ce.fillRect(e*97%512,e*53%380,40+e*13%90,2);ce.globalAlpha=1,ce.fillStyle=`#f4f1e6`,ce.textAlign=`center`;let t=a.rule===`rings`?`MARKS`:a.rule===`weigh`?`WEIGHT`:`FRUIT`;ce.font=`600 50px Caveat, "Segoe Print", "Comic Sans MS", cursive`,ce.fillText(t,256,64),ce.font=`700 170px Caveat, "Segoe Print", "Comic Sans MS", cursive`,ce.fillText(a.rule===`weigh`?`${a.board.toFixed(1)}`:String(a.board),256,238),ce.strokeStyle=`rgba(244,241,230,.75)`,ce.lineWidth=5,ce.lineCap=`round`;let n=Math.min(25,a.rule===`weigh`?Math.round(a.board):a.board);for(let e=0;e{a.rule=e,a.board=t,a.drawBoard()},a.drawBoard(),document.fonts?.load&&document.fonts.load(`700 40px Caveat`).then(()=>a.drawBoard()).catch(()=>{});let le=new hl(1,1),ue=[];for(let e=0;e<8;e++){let t=Q(16052716,{rim:.3});t.transparent=!0,t.depthWrite=!1;let n=new z(le,t);n.userData.noOutline=!0,o.add(n),ue.push({m:n,t:e/8})}let de=[];for(let e=0;e<4;e++){let t=new Y({color:16777215,transparent:!0,depthWrite:!1}),n=new z(new hl(.07,1),t);o.add(n),de.push({m:n,t:e/4})}let fe=new L(16052716),pe=new L(4867144),me=wW(-m.z,0,m.x),he=new I;he.position.copy(i(TW.basket.x+me.x*1.35,TW.basket.z+me.z*1.35)),he.rotation.y=Math.atan2(a.windowCenter.x-he.position.x,a.windowCenter.z-he.position.z);let ge=new z(new Ic(.07,.09,2.3,6),Q(GH.woodDark));ge.position.y=1.15,he.add(ge);let _e=new z(new Ic(.42,.42,.07,24).rotateX(Math.PI/2),Q(15258528,{rim:.2}));_e.position.set(0,2.1,.1),he.add(_e);let ve=new z(new Cl(.42,.04,6,28),Q(11569722));ve.position.set(0,2.1,.14),he.add(ve),a.needle=new z(new Nc(.04,.36,.02),new Y({color:3813188})),a.needle.position.set(0,2.1,.16),a.needle.geometry.translate(0,.16,0),he.add(a.needle);let ye=new z(new Ic(.95,1,.14,16),Q(GH.woodLight,{rim:.1}));ye.position.copy(f).y-=.02,o.add(ye),TU(ye,.02),o.add(he),TU(ge,.02),TU(_e,.02),a.colliders.push({x:he.position.x,z:he.position.z,r:.3});let be=new I;be.position.copy(i(TW.bell.x,TW.bell.z)),be.rotation.y=Math.PI/2;let xe=Q(GH.woodDark,{rim:.12}),Se=new z(new Ic(.1,.13,3,7),xe);Se.position.y=1.5,be.add(Se);let Ce=new z(new Nc(.12,.12,1.2),xe);Ce.position.set(0,2.85,.5),be.add(Ce);let we=[[0,.42],[.12,.4],[.16,.3],[.2,.12],[.3,-.02],[.33,-.06],[0,-.06]].map(([e,t])=>new N(e,t)),Te=Q(14263361,{rim:.45});Te.emissiveNode=SU(6965776,.25);let Ee=new I;Ee.position.set(0,2.78,.95),be.add(Ee);let De=new z(new gl(we,20),Te);De.position.y=-.45,De.castShadow=!0,Ee.add(De);let M=new z(new xl(.06,8,6),xe);M.position.y=-.5,Ee.add(M);let Oe=new z(new Ic(.02,.02,1.4,5),Q(14271119));Oe.position.set(0,2.1,.95),be.add(Oe);let ke=new z(new xl(.06,8,6),Q(14271119));ke.position.set(0,1.38,.95),be.add(ke),o.add(be);for(let e of[Se,Ce,De])TU(e,.02);be.updateMatrixWorld(!0),a.bellPos=De.getWorldPosition(new P),a.bellRope=ke.getWorldPosition(new P),a.colliders.push({x:be.position.x,z:be.position.z,r:.4});let Ae=0,je=0;a.ring=()=>{je+=5.5},a.crates=[];for(let e=0;e<4;e++){let t=jW(),r=j(wW(2.9+e%2*.62,0,2.45));oe(r),r.y+=e>1?.4:0,e>1&&r.copy(a.crates[e-2].home).add(wW(0,.4,0)),t.position.copy(r),t.rotation.y=ie.g.rotation.y+(n()-.5)*.2,o.add(t),a.crates.push({mesh:t,home:r.clone(),homeYaw:t.rotation.y,state:`porch`})}a.cratePile=a.crates[0].home.clone().lerp(a.crates[1].home,.5);let Me=AW();Me.g.position.copy(i(TW.cart.x,TW.cart.z)),Me.g.rotation.y=Math.atan2(r.x-Me.g.position.x,r.z-Me.g.position.z)+Math.PI/2,o.add(Me.g),Me.g.updateMatrixWorld(!0),a.cartPos=Me.g.position.clone(),a.cartSlots=Me.slots.map(e=>e.clone().applyMatrix4(Me.g.matrixWorld)),a.cartYaw=Me.g.rotation.y,a.colliders.push({x:a.cartPos.x,z:a.cartPos.z,r:1.25});let Ne=MW();Ne.position.copy(i(TW.spyglass.x,TW.spyglass.z));let Pe=wW(...EW.center);Ne.rotation.y=Math.atan2(Pe.x-Ne.position.x,Pe.z-Ne.position.z),o.add(Ne),a.spyglassPos=Ne.position.clone(),a.spyglassYaw=Ne.rotation.y;{let e=wW(Math.sin(Ne.rotation.y),0,Math.cos(Ne.rotation.y)),t=wW(e.z,0,-e.x);a.spyOdo=oe(Ne.position.clone().addScaledVector(t,1.4).addScaledVector(e,-.6))}return a.spyStand=oe(Ne.position.clone().add(wW(-Math.sin(Ne.rotation.y)*.85,0,-Math.cos(Ne.rotation.y)*.85))),a.colliders.push({x:Ne.position.x,z:Ne.position.z,r:.45}),a.farmerSpot=a.stoveSpot,a.homeYaw=a.stoveYaw,a.landing=i(TW.landing.x,TW.landing.z),a.update=(e,t=0)=>{je+=(-Ae*28-je*3.2)*e,Ae+=je*e,Ee.rotation.x=Ae*.35;let n=a.basketCount.fruit*.3+a.basketCount.rock*1.2;a.needle.rotation.z=-Math.min(2.6,n*.25),A(e);let r=hi.clamp(a.burn,0,1);for(let t of ue){t.t=(t.t+e*(.16+r*.12))%1;let n=t.t;t.m.position.copy(a.chimneyTop).add(wW(Math.sin(n*5+t.t*20)*.25+n*1.4,n*(3.2+r*1.5),n*.6)),t.m.scale.setScalar(.18+n*(.55+r*.5)),t.m.material.color.copy(fe).lerp(pe,r),t.m.material.opacity=(1-n)*(.55+r*.4)*Math.min(1,n*6)}for(let n of de)n.t=(n.t+e*.5)%1,n.m.position.copy(a.potTop).add(wW(Math.sin(n.t*7+t)*.06,n.t*.7,0)),n.m.scale.setScalar(.6+n.t*1.6),n.m.material.opacity=(1-n.t)*.5*(1-r*.5)},a}function RW(e,t,n){let r=lU(911),i=t.center.clone(),a=(e,n,r=0)=>{let a=i.x+e,o=i.z+n;return wW(a,(t.groundAt(a,o)??i.y)+r,o)},o={island:t,colliders:[],basketCount:{fruit:0,rock:0},rule:`rings`,board:0,odoReady:!0,burn:0,neighbour:!0},s=new I;s.name=`wren`,e.add(s);let c=n.clone().setY(0).normalize(),l=wW(-c.z,0,c.x),u=(e,t)=>a(c.x*e+l.x*t,c.z*e+l.z*t),d=IW(s,[[-3.5,-4.5],[-4.2,2.6],[1.2,5.2]].map(([e,t])=>{let n=u(e,t);return{x:n.x,y:n.y,z:n.z,h:4.4+r(),r:1.9+r()*.4}}),r,4);Object.assign(o,{fruits:d.fruits,pick:d.pick,restoreFruit:d.restoreFruit,nextFruit:d.nextFruit,canopies:d.trees.userData.canopies,trunks:d.trees.userData.trunks}),o.colliders.push(...d.trees.userData.colliders);let f=new I;f.position.copy(u(-1.6,-.4)),f.rotation.y=Math.atan2(c.x,c.z);let p=Q(15984342,{rim:.15}),m=Q(7307184,{rim:.2}),h=Q(GH.woodDark,{rim:.12});OW(3.2,2.3,2.8,p,0,1.15,0,f);let g=new Ic(.01,2.4,1.8,4,1);g.rotateY(Math.PI/4),g.scale(1.15,1,1);let _=new z(g,m);_.position.y=3.2,_.castShadow=!0,f.add(_),OW(.8,1.6,.08,Q(6262650),.3,.8,1.42,f),OW(.6,.55,.06,Q(3882837,{emissive:6965808}),-.9,1.4,1.42,f);let v=new I;v.position.set(1.05,2,1.75),f.add(v),OW(.06,.06,.6,h,0,.12,-.3,v);let y=Q(14725198,{rim:.45});y.emissiveNode=SU(6965776,.3);let b=[];for(let e=0;e<5;e++){let t=new I;t.position.set((e%3-1)*.08,.05,(Math.floor(e/3)-.5)*.08),v.add(t);let n=new z(new Ic(.018,.018,.34+e*.06,6),y);n.position.y=-.2-e*.03,t.add(n),b.push({piv:t,ph:e*1.3})}s.add(f),f.traverse(e=>{e.isMesh&&e.geometry.type===`BoxGeometry`&&TU(e,.016)}),TU(_,.02),f.updateMatrixWorld(!0),o.bellPos=v.getWorldPosition(new P).add(wW(0,-.3,0)),o.doorPos=wW(.3,0,2.2).applyMatrix4(f.matrixWorld),o.colliders.push({x:f.position.x,z:f.position.z,r:2.2});let x=0;o.ring=()=>{x=1};let S=u(1.4,-1.6),C=FW(!1);C.position.copy(S),s.add(C),o.basketPos=S.clone(),o.basketTop=S.clone().add(wW(0,1.3,0));let w=new Fs(d.fruitGeo,d.fruitMat,16);w.count=0,s.add(w);let T=new F;return o.addToBasket=e=>{if(e!==`fruit`)return;let t=w.count;if(t>=16)return;let n=t*2.4,r=.18+t%3*.16;T.makeTranslation(S.x+Math.cos(n)*r,S.y+.25+Math.floor(t/6)*.15,S.z+Math.sin(n)*r),w.setMatrixAt(t,T),w.count++,w.instanceMatrix.needsUpdate=!0,o.basketCount.fruit++},o.emptyBasket=()=>{w.count=0,o.basketCount={fruit:0,rock:0}},o.rockPile=null,o.center=i,o.update=(e,t=0)=>{x=Math.max(0,x-e*.5);for(let e of b)e.piv.rotation.x=Math.sin(t*9+e.ph)*.35*x,e.piv.rotation.z=Math.cos(t*7+e.ph)*.3*x},o}BV(),FH(),CU(),kU(),vU(),KH(),cU();var zW=(e,t,n)=>new P(e,t,n),BW={center:[20,-8,102],radius:21,far:[-22,3,140],farRadius:10},VW={mirror:{x:0,z:1},platforms:{A:[-8,-7,3],B:[7,-8,4.2],C:[12,3,5.4],D:[5,12,6.6],E:[-4,10,7.8],F:[-13,1,9]},route:[`AB`,`BC`,`CD`,`DE`,`EF`],ramp:[.3,-.95],woodpile:{x:-11,z:-13},bench:{x:6,z:-12},iris:{x:-11.5,z:10.4}},HW=new N(-.742,.671),UW=(e,t,n,r,i=0,a=0,o=0,s)=>{let c=new z(new Nc(e,t,n),r);return c.position.set(i,a,o),c.castShadow=c.receiveShadow=!0,s?.add(c),c};function WW(){let e=new I;e.name=`mirror`;let t=Q(14272982,{rim:.2}),n=Q(15120476,{rim:.5});n.emissiveNode=SU(8014352,.25),UW(1.6,.5,1,t,0,.25,0,e),UW(1.2,.3,.8,t,0,.62,0,e);let r=new z(new Cl(1,.09,8,40),n);r.scale.set(.78,1.25,1),r.position.set(0,2.25,0),e.add(r),TU(r,.02);let i=new Y({side:0}),a=AH().y,o=TH(XH.mul(1.3).add(a.mul(9))).mul(.5).add(.5);e.userData.glow={value:0},i.colorNode=sH(XV(16762846),XV(16774394),EH(.2,.9,a)).mul(o.mul(.12).add(.95)).mul(1.15);let s=new z(new Fc(1,40),i);s.scale.set(.74,1.2,1),s.position.set(0,2.25,.02),s.userData.noOutline=!0,e.add(s);let c=new Y({transparent:!0,depthWrite:!1});c.colorNode=SU(16777215,1.8),e.userData.sparks=[];for(let t=0;t<7;t++){let t=new z(new _l(.07,0),c);t.position.set((Math.random()-.5)*1.2,1.4+Math.random()*1.8,.12),t.scale.setScalar(.01),t.userData.noOutline=!0,e.add(t),e.userData.sparks.push(t)}let l=new Y({color:8011118}),u=new Y({color:16777215}),d=new Y({color:16748472,transparent:!0,opacity:.55,depthWrite:!1}),f=new I;f.position.set(0,2.32,.05),e.add(f);let p=[-1,1].map(e=>{let t=new I;t.position.set(e*.25,.2,0);let n=new z(new Fc(.1,20),l);n.scale.set(.82,1.18,1),t.add(n);let r=new z(new Fc(.03,10),u);return r.position.set(.03,.05,.004),t.add(r),f.add(t),t.userData.home=t.position.clone(),t});for(let e of[-1,1]){let t=new z(new Fc(.1,16),d);t.scale.set(1.3,.7,1),t.position.set(e*.42,-.04,-.002),f.add(t)}let m=new z(new Cl(.2,.026,6,24,Math.PI),l);m.rotation.z=Math.PI,m.position.set(0,-.02,0),f.add(m);let h=new z(new Fc(.13,24),new Y({color:5907528}));h.position.set(0,-.14,.002),h.scale.set(1,.05,1),h.visible=!1,f.add(h),f.traverse(e=>{e.userData.noOutline=!0}),e.userData.face={face:f,eyes:p,smile:m,mouth:h,blink:2.5,closing:0};let g=Q(9071178,{rim:.1}),_=Q(15261670,{rim:.1,side:2}),v=new I;v.position.set(0,2.25,-.08),v.rotation.y=Math.PI,e.add(v);let y=new ul([new N(0,1.25),new N(.8,.2),new N(0,-1.25),new N(-.8,.2)]),b=new z(new bl(y),_);b.userData.noOutline=!0,v.add(b),UW(.06,2.5,.05,g,0,0,-.02,v),UW(1.6,.05,.05,g,0,.2,-.02,v);let x=[];for(let e=0;e<9;e++)x.push(zW(Math.sin(e*.9)*.12,-1.25-e*.18,-.02));let S=new z(new Tl(new $c(x),24,.025,4),Q(13221830));v.add(S);for(let e of[2,5,8]){let t=UW(.24,.12,.03,Q(12169398),x[e].x,x[e].y,0,v);t.rotation.z=.3}return e.traverse(e=>{e.isMesh&&e.geometry.type===`BoxGeometry`&&TU(e,.016)}),e}function GW(e,t,n,r,i){let a=[];for(let o=0;o3.5)for(let t=0;t{e.isMesh&&e.geometry.type===`BoxGeometry`&&TU(e,.014)}),r}function qW(e,t){let n=new I,r=Q(GH.woodDark,{rim:.1}),i=new z(new Ic(e,e,.24,22),Q(GH.woodLight,{rim:.12}));i.position.y=t-.12,i.castShadow=i.receiveShadow=!0,n.add(i),TU(i,.016),n.userData.legs=GW(n,e,t,6,r);let a=new z(new Ic(.1,.13,4.6,8),r);a.position.set(-.9,t+2.3,0),n.add(a),TU(a,.016);let o=[],s=Q(15260100,{rim:.2}),c=new Y;c.colorNode=XV(16761963).mul(TH(XH.mul(2.3)).mul(.12).add(1.9));for(let e=0;e<6;e++){let i=e/6*Math.PI*2,a=UW(.9,.05,.05,r,-.9+Math.cos(i)*.45,t+3.6-e%2*.7,Math.sin(i)*.45,n);a.rotation.y=-i;let c=new z(new xl(.2,12,8),s);c.scale.y=1.3,c.position.set(-.9+Math.cos(i)*.85,t+3.25-e%2*.7,Math.sin(i)*.85),c.userData.noOutline=!0,n.add(c),o.push(c)}n.userData.light=e=>{for(let t of o)t.material=e?c:s},TU(UW(.5,1,.5,Q(GH.stone,{rim:.15}),1.1,t+.5,.6,n),.014);let l=new I;l.position.set(1.1,t+1.1,.6),n.add(l),l.add(new z(new Ic(.28,.28,.06,24),Q(15120476,{rim:.5})));let u=new z(new Lc(.06,.45,4),new Y({color:9429958}));return u.rotation.z=Math.PI/2,u.position.y=.06,l.add(u),n.userData.compass=l,n}function JW(e,t,n){let r=new I;r.name=`rope-bridge`;let i=t.clone().sub(e),a=Math.hypot(i.x,i.z),o=zW(-i.z,0,i.x).normalize(),s=Math.max(8,Math.round(a/.42)),c={g:r,a:e.clone(),b:t.clone(),len:a,side:o,state:`none`,flaw:null,sag:.35,snapAt:.45},l=t=>zW(e.x+i.x*t,e.y+i.y*t-c.sag*4*t*(1-t),e.z+i.z*t);c.at=l;let u=Q(GH.woodLight,{rim:.12}),d=[],f=new Nc(1.25,.08,.34);for(let e=0;e{let s=[];for(let r=0;r<=12;r++){let i=t+(n-t)*r/12;s.push(l(i).addScaledVector(o,e*.65).add(zW(0,.95-.3*Math.sin(i*Math.PI),0)))}let c=new z(new Tl(new $c(s),24,a,5),i);return r.add(c),g.push(c),c},D=()=>{for(let e of g)r.remove(e),e.geometry.dispose();g.length=0},ee=(n=0)=>{for(let r=0;r0){let r=o<.5,s=r?e:t,c=(r?o:1-o)*a,l=n*1.35,d=zW(i.x,0,i.z).normalize().multiplyScalar(r?1:-1);u.position.copy(s).addScaledVector(d,c*Math.cos(l)),u.position.y=s.y-c*Math.sin(l),u.rotateZ((r?-1:1)*l)}}for(let e of w)e.visible=n===0,e.position.copy(l(e.userData.t)).add(zW(0,1.25,0))};return c.show=(e,t=c.flaw,n=1)=>{if(c.state=e,c.flaw=t,c.sag=t===`post`?1.45:.35,D(),r.visible=e!==`none`,x.visible=e!==`none`&&t!==`post`,c.postCol.y=x.visible?y:1e5,d.forEach((t,n)=>{t.visible=!(e===`broken`&&Math.abs((n+.5)/s-.5)<.14)}),e===`built`&&(ee(0),c.creaked=!1,d.forEach(e=>{e.userData.y0=e.position.y}),t===`rope`?(E(1,0,1,m,.016),E(-1,0,.47,m,.016),E(-1,.53,1,m,.016),E(-1,.46,.54,h,.008)):(E(1,0,1,p),E(-1,0,1,p))),e===`broken`){ee(n);let e=t===`rope`?m:p;E(1,0,.12,e),E(1,.88,1,e)}},c.midPlanks=()=>(r.updateMatrixWorld(!0),d.filter((e,t)=>Math.abs((t+.5)/s-.5)<.14).map(e=>({pos:e.getWorldPosition(zW(0,0,0)),quat:e.getWorldQuaternion(new gi)}))),c.tremble=(e,t)=>{c.state===`built`&&d.forEach((n,r)=>{let i=(r+.5)/s;n.position.y=(n.userData.y0??n.position.y)+e*Math.sin(i*Math.PI)*Math.sin(t*38+r*.9)})},c.fix=()=>{let e=c.flaw;c.show(`built`,null),e===`post`&&(c.postRise=0)},c.surfaceAt=(t,n)=>{if(c.state!==`built`)return null;let r=t-e.x,s=n-e.z,u=(r*i.x+s*i.z)/(a*a),d=Math.abs(r*o.x+s*o.z);return u<-.02||u>1.02||d>.72?null:l(Math.min(1,Math.max(0,u))).y},c.param=(t,n)=>((t-e.x)*i.x+(n-e.z)*i.z)/(a*a),c.show(`none`),c}function YW(e,t,n,r,i){let a=new I;a.position.copy(n),a.rotation.y=r,e.add(a),UW(.12,1.6,.12,Q(GH.woodDark),0,.8,0,a);let o=document.createElement(`canvas`);o.width=256,o.height=96;let s=o.getContext(`2d`);s.fillStyle=`#`+i.toString(16).padStart(6,`0`),s.fillRect(0,0,256,96),s.strokeStyle=`#3a2f44`,s.lineWidth=6,s.strokeRect(3,3,250,90),s.fillStyle=`#3a2f44`,s.font=`700 38px Fraunces, Georgia, serif`,s.textAlign=`center`,s.textBaseline=`middle`,s.fillText(t,128,50);let c=new Oc(o);c.colorSpace=Mr;let l=UW(1.25,.48,.06,Q(i,{rim:.1}),0,1.45,0,a);for(let e of[1,-1]){let t=new z(new vl(1.2,.45),new Y({map:c}));t.position.set(0,1.45,e*.035),t.rotation.y=e>0?0:Math.PI,t.userData.noOutline=!0,a.add(t)}return TU(l,.014),a}function XW(e){let t=new Ic(.34,.42,1,6,1).translate(0,.5,0),n=new Lc(.34,.7,6).translate(0,1.35,0),r=new xo,i=t.toNonIndexed(),a=n.toNonIndexed(),o=new Float32Array(i.attributes.position.count*3+a.attributes.position.count*3);o.set(i.attributes.position.array),o.set(a.attributes.position.array,i.attributes.position.array.length),r.setAttribute(`position`,new eo(o,3)),r.computeVertexNormals();let s=Q(16245745,{rim:.85});s.emissiveNode=XV(16765162).mul(TH(XH.mul(1.7)).mul(.08).add(.22));let c=new Fs(r,s,e.length),l=new F,u=new gi,d=new L;return e.forEach(([e,t,n,r,i,a,o],s)=>{u.setFromEuler(new Ji(i,o*6,a)),l.compose(zW(e,t,n),u,zW(r*.7,r,r*.7)),c.setMatrixAt(s,l),d.setHSL(.86+o*.1,.45,.88),c.setColorAt(s,d)}),c.castShadow=!0,TU(c,.02),c}function ZW(e,t,n){let r=lU(606),i=t.center.clone(),a=(e,n,r=0)=>{let a=i.x+e,o=i.z+n;return zW(a,(t.groundAt(a,o)??i.y)+r,o)},o={main:t,far:n,colliders:[],surfaces:[],canopies:[],trunks:[],bridges:{},platforms:{},updrafts:[]},s=new I;s.name=`hamlet`,e.add(s);let c=new z(new Fc(5.5,40),Q(15980511,{rim:0}));c.rotation.x=-Math.PI/2,c.position.copy(a(0,.5,.06)),c.receiveShadow=!0,c.userData.noOutline=!0,s.add(c);let l=new z(new yl(4.6,5.5,40),Q(16752582,{rim:0}));l.rotation.x=-Math.PI/2,l.position.copy(a(0,.5,.07)),l.userData.noOutline=!0,s.add(l);let u=WW();u.position.copy(a(VW.mirror.x,VW.mirror.z)),u.rotation.y=Math.PI,s.add(u),o.mirror=u,o.mirrorPos=u.position.clone(),o.mirrorFront=a(VW.mirror.x,VW.mirror.z-2.4),o.mirrorBack=a(VW.mirror.x+.2,VW.mirror.z+2.2),o.mirrorKitePos=o.mirrorPos.clone().add(zW(1.7,2.6,-1.3)),o.colliders.push({x:o.mirrorPos.x,z:o.mirrorPos.z,r:.9});let d=new I;d.position.copy(a(VW.bench.x,VW.bench.z)),d.rotation.y=-.4,UW(2.2,.12,.5,Q(GH.woodLight),0,.5,0,d);for(let e of[-1,1])UW(.12,.5,.45,Q(GH.woodDark),e*.9,.25,0,d);s.add(d),o.benchSpot=a(VW.bench.x-.3,VW.bench.z+1),o.colliders.push({x:d.position.x,z:d.position.z,r:.9});let f={};for(let[e,[t,n,r]]of Object.entries(VW.platforms)){let c=a(t,n),l=c.y+r,u=new N(-t,-n).normalize(),d=e===`F`,p=d?3.2:2.7,m=d?qW(p,r):KW(p,r,u);m.position.copy(c),s.add(m);let h=zW(i.x-c.x,0,i.z-c.z).normalize();if(f[e]={key:e,center:zW(c.x,l,c.z),r:p,y:l,mesh:m,base:c.clone(),inner:zW(c.x,l,c.z).addScaledVector(h,d?.6:1.3)},o.platforms[e]=f[e],o.surfaces.push({at:(e,t)=>Math.hypot(e-c.x,t-c.z)f.F.mesh.userData.light(e);let p=(e,t)=>{let n=zW(t.center.x-e.center.x,0,t.center.z-e.center.z).normalize();return e.center.clone().addScaledVector(n,e.r-.15)};for(let e of VW.route){let n=e[0],r=e[1],i=JW(p(f[n],f[r]),p(f[r],f[n]),(e,n)=>t.groundAt(e,n));i.name=e,i.from=n,i.to=r,s.add(i.g),o.bridges[e]=i,o.surfaces.push({at:(e,t)=>i.surfaceAt(e,t)}),o.colliders.push(i.postCol)}o.route=VW.route.map(e=>o.bridges[e]);{let e=f.A,n=zW(VW.ramp[0],0,VW.ramp[1]).normalize(),r=e.center.clone().addScaledVector(n,e.r-.2),i=r.clone().addScaledVector(n,6.2);i.y=t.groundAt(i.x,i.z)??i.y,o.rampDir=n;let a=i.distanceTo(r),c=i.clone().lerp(r,.5),l=UW(1.3,.14,a,Q(GH.woodLight,{rim:.12}),c.x,c.y,c.z,s);l.lookAt(r),TU(l,.015);let u=r.x-i.x,d=r.z-i.z,p=u*u+d*d,m=zW(-d,0,u).normalize();o.surfaces.push({at:(e,t)=>{let n=((e-i.x)*u+(t-i.z)*d)/p,a=Math.abs((e-i.x)*m.x+(t-i.z)*m.z);return n>=0&&n<=1&&a<.72?i.y+(r.y-i.y)*n+.07:null}}),o.rampFoot=i,o.rampTop=r}o.gather=o.rampFoot.clone().addScaledVector(o.rampDir,2.6),o.gather.y=t.groundAt(o.gather.x,o.gather.z)??o.gather.y;let m=a(VW.woodpile.x,VW.woodpile.z);o.woodpile=m.clone();for(let e=0;e<18;e++){let t=UW(2.4,.14,.32,Q(e%2?GH.woodLight:GH.wood),m.x,m.y+.1+Math.floor(e/4)*.16,m.z+(e%4-1.5)*.36,s);t.rotation.y=.3}o.colliders.push({x:m.x,z:m.z,r:1.2}),o.woodSign=YW(s,`Planks`,m.clone().add(zW(1.6,0,1.2)),.3+Math.PI,13212267);let h=zW(-o.rampDir.z,0,o.rampDir.x),g=o.rampFoot.clone().addScaledVector(h,2);Math.hypot(g.x-m.x,g.z-m.z)>Math.hypot(o.rampFoot.x-m.x,o.rampFoot.z-m.z)&&h.negate();let _=o.rampFoot.clone().addScaledVector(h,2.3).addScaledVector(o.rampDir,.4);_.y=t.groundAt(_.x,_.z)??_.y;let v=new I;v.position.copy(_),v.rotation.y=Math.atan2(o.rampDir.x,o.rampDir.z)+Math.PI/2,UW(1.8,.1,.8,Q(GH.woodLight),0,.8,0,v);for(let[e,t]of[[-.8,-.3],[.8,-.3],[-.8,.3],[.8,.3]])UW(.08,.8,.08,Q(GH.woodDark),e,.4,t,v);s.add(v),o.workbench=_.clone(),o.colliders.push({x:_.x,z:_.z,r:.95}),o.delivered=[],o.addDelivered=()=>{let e=o.delivered.length,t=UW(1.7,.1,.28,Q(GH.woodLight),_.x,_.y+.9+e*.11,_.z-.2+e%2*.12,s);o.delivered.push(t)},o.clearDelivered=()=>{for(let e of o.delivered)s.remove(e);o.delivered.length=0};let y=a(VW.iris.x,VW.iris.z),b=dW();b.scale.setScalar(.72),b.position.copy(y);let x=zW(i.x-y.x,0,i.z-y.z).normalize();b.rotation.y=Math.atan2(x.x,x.z),s.add(b),b.traverse(e=>{e.isMesh&&e.material.color&&e.material.color.getHex()===GH.roof&&(e.material=Q(9403072,{rim:.2}))}),o.colliders.push({x:y.x,z:y.z,r:2.1}),o.irisHouse=y.clone(),o.irisDoor=y.clone().addScaledVector(x,2.4),o.irisDoor.y=t.groundAt(o.irisDoor.x,o.irisDoor.z)??y.y,o.irisSeat=y.clone().addScaledVector(x,2.2).add(zW(x.z*1.6,0,-x.x*1.6)),o.irisSeat.y=t.groundAt(o.irisSeat.x,o.irisSeat.z)??y.y;let S=new I;S.position.copy(o.irisSeat).add(zW(x.z*1.2,0,-x.x*1.2)),S.rotation.y=b.rotation.y+.8;for(let e of[-1,1])UW(.08,1.4,.08,Q(GH.woodDark),e*.6,.7,0,S);UW(1.3,.08,.08,Q(GH.woodDark),0,1.4,0,S);let C=new z(new Cl(.34,.07,8,20),Q(15123819,{rim:.3}));C.position.set(0,.8,.05),C.scale.setScalar(.3),S.add(C),o.ropeCoil=C,s.add(S),b.updateMatrixWorld(!0),o.chimneyTop=zW(1.1,5.3,-.4).applyMatrix4(b.matrixWorld);let w=Math.atan2(HW.y,HW.x)-.2,T=e=>t.R*t.rim(e)-1.4,E=Q(GH.woodDark,{rim:.1}),D=[];for(let e=-13;e<=13;e++){let n=w+e*.046,r=T(n),a=zW(i.x+Math.cos(n)*r,0,i.z+Math.sin(n)*r);a.y=t.groundAt(a.x,a.z)??i.y,D.push(a)}for(let e of D)UW(.14,1.15,.14,E,e.x,e.y+.55,e.z,s);for(let e=0;e{};let ee=n.center,O=[],k=zW(HW.x,0,HW.y),te=zW(-HW.y,0,HW.x),A=zW(i.x,0,i.z).addScaledVector(k,t.R*1.02),ne=zW(ee.x,0,ee.z).addScaledVector(k,-n.R*1.05);for(let e=0;e<40&&O.length<26;e++){let e=r(),a=A.clone().lerp(ne,.12+e*.76).addScaledVector(te,(r()-.5)*30),o=3.5+r()*3.5;Math.hypot(a.x-i.x,a.z-i.z){},o.updrafts.push({x:i.x-1,z:i.z-24,r:6.5,top:16,lift:11}),s.add(mW(zW(i.x-1,0,i.z-24),5,i.y-18,14,3.5,{alpha:.5,seed:11})),s.add(mW(zW(i.x-1,0,i.z-24),3.2,i.y-12,10,2.5,{alpha:.45,seed:12})),o.landing=a(0,-15);let ie=[];for(let[e,i,a]of[[t,38,1.4],[n,14,1.1]]){let t=e.center;for(let n=0;nMath.hypot(n.x-i.x-e,n.z-i.z-t)<3.4))for(let e=0;e<2;e++)ie.push([n.x+(r()-.5)*.6,n.y-.1,n.z+(r()-.5)*.6,.35+r()*.5,(r()-.5)*.5,(r()-.5)*.5,r()])}s.add(XW(ie));let ae=[16752582,12100328,16773590,9429958,16766059],j=new xo;j.setAttribute(`position`,new R([-.16,0,0,.16,0,0,0,-.34,0],3)),j.computeVertexNormals();let oe=ae.map(e=>new Y({color:e,side:2})),se=(e,t,n)=>{let r=[];for(let i=0;i<=20;i++){let a=i/20;r.push(e.clone().lerp(t,a).add(zW(0,-n*4*a*(1-a),0)))}s.add(new z(new Tl(new $c(r),30,.015,3),Q(15984852)));let i=Math.floor(e.distanceTo(t)/.45),a=t.clone().sub(e).setY(0).normalize();for(let r=1;rf[e].center.clone().add(zW(0,3.3,0));se(ce(`A`),ce(`B`),1.4),se(ce(`B`),ce(`C`),1.2),se(ce(`C`),ce(`D`),1.2),se(ce(`D`),ce(`E`),1.2),se(ce(`A`),o.mirrorPos.clone().add(zW(0,4.4,0)),1.2),se(ce(`C`),o.mirrorPos.clone().add(zW(0,4.4,0)),1.4);let le=new vl(.12,.08),ue=new Y({color:16757716,side:2}),de=new Fs(le,ue,140);de.userData.noOutline=!0,de.frustumCulled=!1,s.add(de);let fe=Array.from({length:140},()=>({x:(r()-.5)*50,y:r()*12,z:(r()-.5)*50,s:.4+r()*.8,ph:r()*10})),pe=new F,me=new gi,he=new Ji;return o.updatePetals=(e,t,n)=>{if(!n){de.visible=!1;return}de.visible=!0,fe.forEach((n,a)=>{n.x+=e*(.6+Math.sin(t*.3+n.ph)*.4),n.y-=e*.25*n.s,n.z+=e*Math.cos(t*.4+n.ph)*.3,n.y<0&&(n.y=12,n.x=(r()-.5)*50,n.z=(r()-.5)*50),n.x>25&&(n.x-=50),he.set(t*n.s+n.ph,t*.7*n.s,n.ph),me.setFromEuler(he),pe.compose(zW(i.x+n.x,i.y+.5+n.y,i.z+n.z),me,zW(n.s,n.s,n.s)),de.setMatrixAt(a,pe)}),de.instanceMatrix.needsUpdate=!0},o.update=(e,t)=>{let n=u.userData.sparks,r=u.userData.glow.value=Math.max(0,u.userData.glow.value-e*.8);n.forEach((e,n)=>{let i=r*(.6+.4*Math.sin(t*9+n*2));e.scale.setScalar(.01+i*1.4),e.rotation.y=t*2+n});for(let t of o.smoke){if(!o.lit)break;t.t=(t.t+e*.18)%1;let n=t.t;t.m.position.copy(o.chimneyTop).add(zW(Math.sin(n*5+t.t*20)*.25,n*3.4,0)),t.m.scale.setScalar(.18+n*.6),t.m.material.opacity=(1-n)*.55*Math.min(1,n*6)}o.compass.rotation.y=Math.sin(t*.7)*.25;for(let t of o.route)t.postRise<1&&(t.postRise=Math.min(1,t.postRise+e*.8),t.post.scale.y=.02+.98*t.postRise);let i=u.userData.face;i.face.position.y=2.32+Math.sin(t*1.3)*.035,i.face.position.x=Math.sin(t*.7)*.02,i.blink-=e,i.blink<0&&(i.closing=.14,i.blink=2.2+t*7.31%1*3),i.closing=Math.max(0,i.closing-e);let a=i.closing>0?.12:1,s=0,c=0;if(o.faceTarget){let e=u.worldToLocal(o.faceTarget.clone()),t=Math.hypot(e.x,e.z)||1;s=hi.clamp(e.x/t,-1,1)*.05,c=hi.clamp((e.y-2.3)/t,-1,1)*.04}for(let e of i.eyes)e.scale.y=a,e.position.x=e.userData.home.x+s,e.position.y=e.userData.home.y+c;let l=r>.05;i.mouth.visible=l,i.smile.visible=!l,l&&(i.mouth.scale.y=.15+.85*Math.abs(Math.sin(t*13))*Math.min(1,r*1.6))},o.mirrorSpeak=(e=1.2)=>{u.userData.glow.value=Math.max(u.userData.glow.value,e*.8)},o}BV(),ZU(),hW(),bW(),vU(),CU(),KH(),kU();var QW=(e,t,n)=>new P(e,t,n);async function $W(e,{quality:t=1,isles:n=[],step:r=async()=>{}}={}){let i={islands:[],colliders:[],updrafts:[],decks:[],animated:[]},a=lU(77),o={x:33,z:-13,r:5},s=new N(o.x,o.z).normalize(),c=[.2,.45,.7].map(e=>({x:o.x+s.x*(6+e*8),z:o.z+s.y*(6+e*8),r:3.2,h:.05})),l=new NU({name:`hub`,center:[0,0,0],radius:46,depth:58,seed:11,hill:1.4,flats:[{x:6,z:6,r:14,h:.35},{x:-17,z:-15,r:8,h:2.4},{x:o.x,z:o.z,r:9,h:.25},...c,{x:40,z:6,r:7,h:.3},{x:-38,z:8,r:7,h:.3}],ponds:[o],tipOffset:[4,-3]}),u=new NU({name:`orchard`,center:[150,-10,-30],radius:24,depth:36,seed:23,hill:1,flats:[{x:-9,z:1,r:7.5,h:.4},{x:TW.cottage.x,z:TW.cottage.z,r:5.2,h:.42},{x:TW.cart.x,z:TW.cart.z,r:3.6,h:.4},{x:TW.spyglass.x,z:TW.spyglass.z,r:2.6,h:.45}]}),d=new NU({name:`wren`,center:EW.center,radius:EW.radius,depth:17,seed:71,hill:.45,flats:[{x:0,z:0,r:6.5,h:.3}]}),f=new NU({name:`north`,center:[-6,-4,-82],radius:14,depth:22,seed:31,hill:.9}),p=new NU({name:`pillar`,center:[-74,14,-36],radius:9,depth:50,seed:41,hill:.6,rimJag:.08}),m=new NU({name:`west`,center:[-82,-8,46],radius:16,depth:26,seed:51,hill:1}),h=new NU({name:`south`,center:[86,-15,62],radius:13,depth:20,seed:61,hill:.8}),g=VW.platforms,_=[-.742,.671],v={palette:{grassDark:10117006,grassMid:13207475,dry:15779034,dirt:14267332,soil:10254994,rockLight:15721199,rockMid:13809883,rockDark:10258102,rockDeep:7101578,moss:14721224},grassPalette:{dark:9065606,mid:12746674,tip:16763876,dry:16773623,flowers:.035}},y=new NU({...v,name:`hamlet`,center:BW.center,radius:BW.radius,depth:34,seed:81,hill:.8,rimJag:.07,flats:[{x:0,z:.5,r:8,h:.3},...Object.values(g).map(([e,t])=>({x:e,z:t,r:4.2,h:.35})),{x:VW.woodpile.x,z:VW.woodpile.z,r:3,h:.35},{x:VW.iris.x,z:VW.iris.z,r:4.5,h:.4},{x:_[0]*18,z:_[1]*18,r:3,h:.45},{x:-2,z:-15,r:5,h:.3}]}),b=new NU({...v,name:`hamlet-far`,center:BW.far,radius:BW.farRadius,depth:16,seed:83,hill:.4,flats:[{x:1,z:1,r:5.5,h:.3}]}),x=[l,u,f,p,m,h,d,y,b],S=[];for(let[e,t,n,r]of[[98,14,30,3.2],[102,-17,-48,4],[70,-24,22,2.6],[-40,22,-60,3],[20,20,60,2.4],[160,12,10,3.5],[-110,4,-10,4]])S.push(new NU({name:`rock`,center:[e,t,n],radius:r,depth:r*2.2,seed:Math.floor(e*7+n),hill:.2,detail:.35}));let C=[];for(let e=0;e<9;e++){let t=e/9*Math.PI*2+a()*.5,n=230+a()*300,r=20+a()*30;C.push(new NU({name:`far`,center:[Math.cos(t)*n,-25+a()*60,Math.sin(t)*n],radius:r,depth:r*1.4,seed:100+e,hill:2,detail:.45}))}for(let t of[...x,...S,...C])e.add(t.build());i.islands.push(...x,...S),i.hub=l,i.grove=u,i.orchardIsland=u,i.wrenIsland=d,i.hamletIsland=y,i.hamletFar=b;let w=.12,T=l.center.y+l.heightLocal(Math.cos(w)*38,Math.sin(w)*38)+.18,E=QW(Math.cos(w),0,Math.sin(w)),D=QW(-E.z,0,E.x);i.decks.push({o:QW(Math.cos(w)*38,T,Math.sin(w)*38),dir:E,side:D,len:14,w:2.1,y:T});{let t=new I;t.name=`deck`;let n=new Fs(new Nc(4.3,.14,.34),Q(16777215,{rim:.15}),34),r=new L,o=new L(GH.woodLight),s=new L(GH.wood),c=new F,l=new gi().setFromAxisAngle(QW(0,1,0),-.12+Math.PI/2);for(let e=0;e<34;e++){let t=38+(e+.5)/34*14;c.compose(QW(Math.cos(w)*t,T-.07+(a()-.5)*.02,Math.sin(w)*t),l,QW(1,1,1)),n.setMatrixAt(e,c),r.copy(o).lerp(s,a()*.6),n.setColorAt(e,r)}n.castShadow=n.receiveShadow=!0,t.add(n);let u=Q(GH.woodDark,{rim:.1});for(let e of[-1,1]){let n=new z(new Nc(.22,.3,15),u);n.position.copy(E.clone().multiplyScalar(45)).addScaledVector(D,e*2.15),n.position.y=T-.22,n.rotation.y=-.12+Math.PI/2-Math.PI/2,n.lookAt(n.position.clone().add(E)),t.add(n);for(let n of[51.6,47]){let r=new z(new Ic(.12,.12,7,6),u);r.position.copy(E.clone().multiplyScalar(n-2.5)).addScaledVector(D,e*2),r.position.y=T-3.2,r.rotation.z=0,r.lookAt(E.clone().multiplyScalar(n-6).addScaledVector(D,e*2).setY(T-7)),r.rotateX(Math.PI/2),t.add(r)}let r=new z(new Nc(.08,.08,14*.55),u);r.position.copy(E.clone().multiplyScalar(41.5)).addScaledVector(D,e*2.1),r.position.y=T+.95,r.lookAt(r.position.clone().add(E)),t.add(r);for(let n=0;n<4;n++){let r=new z(new Ic(.06,.07,1,5),u);r.position.copy(E.clone().multiplyScalar(38.5+n*2)).addScaledVector(D,e*2.1),r.position.y=T+.45,t.add(r)}}let d=oW(4.5,.01,.01);d.position.copy(E.clone().multiplyScalar(51.7)).addScaledVector(D,-2.3),d.position.y=T,d.rotation.y=-.12,t.add(d),i.animated.push(d),CW(t,{skip:[d]}),e.add(t)}let ee=l.center.y+l.heightLocal(o.x+o.r,o.z)-.25;e.add(QU(o.x,ee,o.z,o.r*1.08));let O=Math.atan2(o.z,o.x),k=l.R*l.rim(O)*.995,te=QW(Math.cos(O),0,Math.sin(O)),A=QW(-te.z,0,te.x),ne=[];for(let e=0;e<=8;e++){let t=Math.hypot(o.x,o.z)+o.r*.8+e/8*(k-Math.hypot(o.x,o.z)-o.r*.8),n=te.x*t,r=te.z*t;ne.push(QW(n,Math.max(l.heightLocal(n,r),ee-.8)+.07,r))}e.add(eW(ne,1.9));let re=ne[ne.length-1],ie=[re.clone(),re.clone().addScaledVector(te,1.3).setY(re.y-.9),re.clone().addScaledVector(te,2.6).setY(re.y-5),re.clone().addScaledVector(te,3.8).setY(re.y-15),re.clone().addScaledVector(te,4.8).setY(re.y-30),re.clone().addScaledVector(te,5.6).setY(re.y-48)];e.add($U(ie,2.2,6.5,A));let ae=[];for(let e=0;e<14;e++){let e=ie[5];ae.push([e.x+(a()-.5)*12,e.y-4+a()*6,e.z+(a()-.5)*12,2.5+a()*4])}e.add(vW(ae));{u.center.x+9,u.center.z-13;let t=QW(9,0,-13).normalize(),n=u.groundAt(u.center.x+t.x*u.R*u.rim(Math.atan2(t.z,t.x))*.97,u.center.z+t.z*u.R*u.rim(Math.atan2(t.z,t.x))*.97)??u.center.y,r=QW(u.center.x+t.x*u.R*.98,n+.05,u.center.z+t.z*u.R*.98);e.add($U([r,r.clone().addScaledVector(t,1).setY(r.y-1.5),r.clone().addScaledVector(t,2).setY(r.y-10),r.clone().addScaledVector(t,3).setY(r.y-30)],1.3,3.5,QW(-t.z,0,t.x)))}let j=(e,t,n=0)=>QW(e,l.groundAt(e,t)+n,t),oe=aW();oe.position.copy(j(-17,-15,-.2)),oe.rotation.y=.55,e.add(oe),i.animated.push(oe),i.colliders.push({x:-17,z:-15,r:3.2});let se=dW();se.position.copy(j(-26,-2)),se.rotation.y=1.1,e.add(se),i.colliders.push({x:-26,z:-2,r:2.8});for(let[t,n,r]of[[-36,5,11],[-39,14,9]]){let o=oW(r);o.position.copy(j(t,n)),o.rotation.y=1.3+a()*.3,e.add(o),i.animated.push(o),i.colliders.push({x:t,z:n,r:.4})}for(let[t,n,r]of[[0,-1,.5],[-4,6,-.4]]){let i=sW();i.position.copy(j(t,n,.7)),i.rotation.set(.12,r+1.4,.05),e.add(i)}for(let[t,n,r]of[[-12,-9,.9],[-11,-8,.7],[-13.5,-8.2,.6],[30,16,.8],[29,17.6,.6]]){let o=lW(r);o.position.copy(j(t,n,r/2)),o.rotation.y=a()*3,e.add(o),i.colliders.push({x:t,z:n,r:r*.62,y:o.position.y,h:r/2+.45,noCam:!0})}for(let[t,n]of[[-20.5,-10],[-21.5,-11],[31,18]]){let r=uW();r.position.copy(j(t,n,.5)),e.add(r),i.colliders.push({x:t,z:n,r:.42,y:r.position.y,h:.95,noCam:!0})}let ce=fW();ce.position.copy(j(24,2)),ce.rotation.y=-.4,e.add(ce),i.colliders.push({x:24,z:2,r:.15,noCam:!0});let le=-1.62,ue=l.R*l.rim(le)*.97,de=Math.PI/2+.05,fe=f.R*f.rim(de)*.95,pe=QW(Math.cos(le)*ue,0,Math.sin(le)*ue);pe.y=l.groundAt(pe.x,pe.z);let me=QW(f.center.x+Math.cos(de)*fe,0,f.center.z+Math.sin(de)*fe);me.y=f.groundAt(me.x,me.z),e.add(cW(pe,me,3.2)),i.bridge={a:pe,b:me,sag:3.2},await r(`world:aerodrome`);let he=[],ge=(e,t,n=()=>!1,r=1)=>{let i=0;for(;t>0&&i++<400;){let i=a()*Math.PI*2,o=Math.sqrt(a())*e.R*.85,s=e.center.x+Math.cos(i)*o,c=e.center.z+Math.sin(i)*o;if(n(s,c)||he.some(e=>Math.hypot(e.x-s,e.z-c)<5*r))continue;let l=e.groundAt(s,c);l!==null&&(he.push({x:s,y:l,z:c,h:(6.5+a()*3)*r,r:(2.6+a()*1.4)*r}),t--)}},_e=(e,t)=>Math.hypot(e-6,t-6)<16||Math.hypot(e+17,t+15)<8||Math.hypot(e-o.x,t-o.z)<9||Math.hypot(e+26,t+2)<6||Math.hypot(e+37,t-9)<8||e>25&&Math.abs(t-5)<8||Math.hypot(e-pe.x,t-pe.z)<6||Math.hypot(e+6,t+22)<4.5||Math.hypot(e-22,t+4)<4.5;ge(l,11,_e),ge(f,3),ge(m,4),ge(h,3),ge(p,1,()=>!1,.8);let[ve,ye]=VW.platforms.A,be=Math.hypot(...VW.ramp),xe=VW.ramp[0]/be,Se=VW.ramp[1]/be,Ce=(e,t)=>{for(let n=2;n<=12;n+=1)if(Math.hypot(e-ve-xe*n,t-ye-Se*n)<4.2)return!0;return!1},we=y.center,Te=(e,t)=>{let n=e-we.x,r=t-we.z;return Math.hypot(n,r)<11.5||Ce(n,r)||Math.abs(n)<7&&r<-6||Object.values(g).some(([e,t])=>Math.hypot(n-e,r-t)<5.5)||Math.hypot(n-VW.woodpile.x,r-VW.woodpile.z)<4||Math.hypot(n-VW.iris.x,r-VW.iris.z)<6||n*_[0]+r*_[1]>11||Math.hypot(n+2,r+15)<5},Ee=JU(he);e.add(Ee),i.colliders.push(...Ee.userData.colliders);let De=he.length;ge(y,6,Te,.8),ge(b,1,(e,t)=>Math.hypot(e-b.center.x-1,t-b.center.z-1)<5,.7);let M=JU(he.splice(De),23,{leaf:15699901,leafLit:16767468,trunk:8015715});e.add(M),i.colliders.push(...M.userData.colliders);let Oe=[],ke=(e,t)=>Math.hypot(e+9,t-1)<10||Math.hypot(e-TW.cottage.x,t-TW.cottage.z)<7||Math.hypot(e-TW.cart.x,t-TW.cart.z)<4||Math.hypot(e-TW.spyglass.x,t-TW.spyglass.z)<3||e>-2&&e<18&&Math.abs(t+3)<4;for(let e of x)for(let t=0;tMath.hypot(e-u.center.x-TW.cottage.x,t-u.center.z-TW.cottage.z)<3.3,je=(e,t)=>Math.hypot(e-y.center.x,t-y.center.z-.5)<5.6,Me=(e,t)=>Ae(e,t)||je(e,t)||_e(e,t)&&(Math.hypot(e-o.x,t-o.z)<6.5||Math.hypot(e+17,t+15)<3.6||Math.hypot(e+26,t+2)<3)||Pe(e,t)||Ne(e,t),Ne=(e,t)=>{let n=e*te.x+t*te.z;if(ni.decks.some(n=>{let r=e-n.o.x,i=t-n.o.z,a=r*n.dir.x+i*n.dir.z,o=r*n.side.x+i*n.side.z;return a>-1&&ae.add(pW(t.map(e=>QW(...e)),{width:1.8+n%3*.5,twist:.45+n*.12,seed:n*1.7,speed:.08+n*.02,alpha:.32}))),i.surfaces=[],i.ground=(e,t,n)=>{let r=AU(i.islands,e,t);for(let n of i.decks){let i=e-n.o.x,a=t-n.o.z,o=i*n.dir.x+a*n.dir.z,s=i*n.side.x+a*n.side.z;o>-.5&&o0&&o<1){let i=a.a.x+n.x*o,s=a.a.z+n.z*o;if(Math.hypot(e-i,t-s)<1){let e=a.a.y+(a.b.y-a.a.y)*o-a.sag*4*o*(1-o)+.06;r=r===null?e:Math.max(r,e)}}}for(let a of i.surfaces){let i=a.at(e,t);i!==null&&(n===void 0||i<=n+.7)&&(r=r===null?i:Math.max(r,i))}return r};let Ie=QW(0,0,0);i.inSolid=(e,t,n)=>{for(let r of i.surfaces){if(!r.solid)continue;let a=r.at(e,n);if(a===null||t>=a)continue;let o=typeof r.base==`function`?r.base(e,n):typeof r.base==`number`?r.base:AU(i.islands,e,n);if(o===null||t>o)return!0}for(let r of i.islands){let i=r.groundAt(e,n);if(!(i!==null&&t>i)&&r.rockAt(e,t,n,0,Ie))return!0}return!1},await r(`world:sky`),i.orchard=LW(e,u),i.colliders.push(...i.orchard.colliders),i.surfaces.push(...i.orchard.surfaces||[]),i.wren=RW(e,d,u.center.clone().sub(d.center)),i.colliders.push(...i.wren.colliders),await r(`world:orchard`),i.hamlet=ZW(e,y,b),i.colliders.push(...i.hamlet.colliders),i.surfaces.push(...i.hamlet.surfaces),i.updrafts.push(...i.hamlet.updrafts),await r(`world:hamlet`),i.isles={},i.camTrunks=[],i.camSpheres=[],i.isleRoots={};for(let t of n){await r(`isle:`+t.id);let n=new Set(e.children);try{i.isles[t.id]=t.build(e,i,t)}catch(e){console.error(`island ${t.id} failed to build`,e);continue}i.isleRoots[t.id]=e.children.filter(e=>!n.has(e));let[a,o,s]=t.center,c=Math.hypot(a,s),u=a/c,d=s/c,f=Math.max(o,0)+30,p=(t,n,r,a)=>{i.updrafts.push({x:t,z:n,r:9,top:r,lift:11.5}),e.add(mW(QW(t,0,n),6.2,-42,r,3.5,{alpha:.5,seed:a})),e.add(mW(QW(t,0,n),3.8,-34,r-5,2.5,{alpha:.4,seed:a+1}))};p(u*(l.R+9),d*(l.R+9),f,11+c),p(a-u*(t.radius+9),s-d*(t.radius+9),Math.max(o+28,26),13+c);let m=c-l.R-t.radius;if(m>105)for(let e=1,t=Math.floor(m/85);e<=t;e++){let n=l.R+m*e/(t+1);p(u*n,d*n,f,17+c+e)}}i.camBlockers={spheres:[...i.camSpheres,...Ee.userData.canopies,...M.userData.canopies,...i.orchard.canopies,...i.wren.canopies],cylinders:[...Ee.userData.trunks,...M.userData.trunks,...i.orchard.trunks,...i.wren.trunks,...i.orchard.camBlock,...i.hamlet.trunks,...i.camTrunks]};for(let e of i.colliders)if(e.r>=2&&!e.noCam){let t=AU(i.islands,e.x,e.z)??0;i.camBlockers.cylinders.push({x:e.x,z:e.z,r:e.r*.9,y0:t-1,y1:t+e.r*2.4})}return await r(`world:outlines`),EU(e,.03),i.spawn=QW(20,l.groundAt(20,12),12),i}function eG(e){let t=new Map,n=new Map,r=e.clone();return tG(e,r,function(e,r){t.set(r,e),n.set(e,r)}),r.traverse(function(e){if(!e.isSkinnedMesh)return;let r=e,i=t.get(e),a=i.skeleton.bones;r.skeleton=i.skeleton.clone(),r.bindMatrix.copy(i.bindMatrix),r.skeleton.bones=a.map(function(e){return n.get(e)}),r.bind(r.skeleton,r.bindMatrix)}),r}function tG(e,t,n){n(e,t);for(let r=0;r{}));function rG(){let e={};return{get:function(t){return e[t]},add:function(t,n){e[t]=n},remove:function(t){delete e[t]},removeAll:function(){e={}}}}function iG(e,t,n){let r=e.json.materials[t];return r.extensions&&r.extensions[n]?r.extensions[n]:null}function aG(e){return e.DefaultMaterial===void 0&&(e.DefaultMaterial=new Nl({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:0})),e.DefaultMaterial}function oG(e,t,n){for(let r in n.extensions)e[r]===void 0&&(t.userData.gltfExtensions=t.userData.gltfExtensions||{},t.userData.gltfExtensions[r]=n.extensions[r])}function sG(e,t){t.extras!==void 0&&(typeof t.extras==`object`?Object.assign(e.userData,t.extras):console.warn(`THREE.GLTFLoader: Ignoring primitive type .extras, `+t.extras))}function cG(e,t,n){let r=!1,i=!1,a=!1;for(let e=0,n=t.length;e0||e.search(/^data\:image\/jpeg/)===0?`image/jpeg`:e.search(/\.webp($|\?)/i)>0||e.search(/^data\:image\/webp/)===0?`image/webp`:e.search(/\.ktx2($|\?)/i)>0||e.search(/^data\:image\/ktx2/)===0?`image/ktx2`:`image/png`}function mG(e,t,n){let r=t.attributes,i=new Fa;if(r.POSITION!==void 0){let e=n.json.accessors[r.POSITION],t=e.min,a=e.max;if(t!==void 0&&a!==void 0){if(i.set(new P(t[0],t[1],t[2]),new P(a[0],a[1],a[2])),e.normalized){let t=fG(qG[e.componentType]);i.min.multiplyScalar(t),i.max.multiplyScalar(t)}}else{console.warn(`THREE.GLTFLoader: Missing min/max properties for accessor POSITION.`);return}}else return;let a=t.targets;if(a!==void 0){let e=new P,t=new P;for(let r=0,i=a.length;r{HU(),qU(),nG(),gG=class extends su{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(e){return new xG(e)}),this.register(function(e){return new SG(e)}),this.register(function(e){return new jG(e)}),this.register(function(e){return new MG(e)}),this.register(function(e){return new NG(e)}),this.register(function(e){return new wG(e)}),this.register(function(e){return new TG(e)}),this.register(function(e){return new EG(e)}),this.register(function(e){return new DG(e)}),this.register(function(e){return new bG(e)}),this.register(function(e){return new OG(e)}),this.register(function(e){return new CG(e)}),this.register(function(e){return new AG(e)}),this.register(function(e){return new kG(e)}),this.register(function(e){return new vG(e)}),this.register(function(e){return new PG(e,_G.EXT_MESHOPT_COMPRESSION)}),this.register(function(e){return new PG(e,_G.KHR_MESHOPT_COMPRESSION)}),this.register(function(e){return new FG(e)})}load(e,t,n,r){let i=this,a;if(this.resourcePath!==``)a=this.resourcePath;else if(this.path!==``){let t=Gu.extractUrlBase(e);a=Gu.resolveURL(t,this.path)}else a=Gu.extractUrlBase(e);this.manager.itemStart(e);let o=function(t){r?r(t):console.error(t),i.manager.itemError(e),i.manager.itemEnd(e)},s=new uu(this.manager);s.setPath(this.path),s.setResponseType(`arraybuffer`),s.setRequestHeader(this.requestHeader),s.setWithCredentials(this.withCredentials),s.load(e,function(n){try{i.parse(n,a,function(n){t(n),i.manager.itemEnd(e)},o)}catch(e){o(e)}},n,o)}setDRACOLoader(e){return this.dracoLoader=e,this}setKTX2Loader(e){return this.ktx2Loader=e,this}setMeshoptDecoder(e){return this.meshoptDecoder=e,this}register(e){return this.pluginCallbacks.indexOf(e)===-1&&this.pluginCallbacks.push(e),this}unregister(e){return this.pluginCallbacks.indexOf(e)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}parse(e,t,n,r){let i,a={},o={},s=new TextDecoder;if(typeof e==`string`)i=JSON.parse(e);else if(e instanceof ArrayBuffer){if(s.decode(new Uint8Array(e,0,4))===IG){try{a[_G.KHR_BINARY_GLTF]=new zG(e)}catch(e){r&&r(e);return}i=JSON.parse(a[_G.KHR_BINARY_GLTF].content)}else i=JSON.parse(s.decode(e))}else i=e;if(i.asset===void 0||i.asset.version[0]<2){r&&r(Error(`THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.`));return}let c=new nK(i,{path:t||this.resourcePath||``,crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});c.fileLoader.setRequestHeader(this.requestHeader);for(let e=0;e=0&&o[t]===void 0&&console.warn(`THREE.GLTFLoader: Unknown extension "`+t+`".`)}}c.setExtensions(a),c.setPlugins(o),c.parse(n,r)}parseAsync(e,t){let n=this;return new Promise(function(r,i){n.parse(e,t,r,i)})}},_G={KHR_BINARY_GLTF:`KHR_binary_glTF`,KHR_DRACO_MESH_COMPRESSION:`KHR_draco_mesh_compression`,KHR_LIGHTS_PUNCTUAL:`KHR_lights_punctual`,KHR_MATERIALS_CLEARCOAT:`KHR_materials_clearcoat`,KHR_MATERIALS_DISPERSION:`KHR_materials_dispersion`,KHR_MATERIALS_IOR:`KHR_materials_ior`,KHR_MATERIALS_SHEEN:`KHR_materials_sheen`,KHR_MATERIALS_SPECULAR:`KHR_materials_specular`,KHR_MATERIALS_TRANSMISSION:`KHR_materials_transmission`,KHR_MATERIALS_IRIDESCENCE:`KHR_materials_iridescence`,KHR_MATERIALS_ANISOTROPY:`KHR_materials_anisotropy`,KHR_MATERIALS_UNLIT:`KHR_materials_unlit`,KHR_MATERIALS_VOLUME:`KHR_materials_volume`,KHR_TEXTURE_BASISU:`KHR_texture_basisu`,KHR_TEXTURE_TRANSFORM:`KHR_texture_transform`,KHR_MESH_QUANTIZATION:`KHR_mesh_quantization`,KHR_MATERIALS_EMISSIVE_STRENGTH:`KHR_materials_emissive_strength`,EXT_MATERIALS_BUMP:`EXT_materials_bump`,EXT_TEXTURE_WEBP:`EXT_texture_webp`,EXT_TEXTURE_AVIF:`EXT_texture_avif`,EXT_MESHOPT_COMPRESSION:`EXT_meshopt_compression`,KHR_MESHOPT_COMPRESSION:`KHR_meshopt_compression`,EXT_MESH_GPU_INSTANCING:`EXT_mesh_gpu_instancing`},vG=class{constructor(e){this.parser=e,this.name=_G.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){let e=this.parser,t=this.parser.json.nodes||[];for(let n=0,r=t.length;n=0)throw Error(`THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures`);return null}return t.loadTextureImage(e,i.source,a)}},MG=class{constructor(e){this.parser=e,this.name=_G.EXT_TEXTURE_WEBP}loadTexture(e){let t=this.name,n=this.parser,r=n.json,i=r.textures[e];if(!i.extensions||!i.extensions[t])return null;let a=i.extensions[t],o=r.images[a.source],s=n.textureLoader;if(o.uri){let e=n.options.manager.getHandler(o.uri);e!==null&&(s=e)}return n.loadTextureImage(e,a.source,s)}},NG=class{constructor(e){this.parser=e,this.name=_G.EXT_TEXTURE_AVIF}loadTexture(e){let t=this.name,n=this.parser,r=n.json,i=r.textures[e];if(!i.extensions||!i.extensions[t])return null;let a=i.extensions[t],o=r.images[a.source],s=n.textureLoader;if(o.uri){let e=n.options.manager.getHandler(o.uri);e!==null&&(s=e)}return n.loadTextureImage(e,a.source,s)}},PG=class{constructor(e,t){this.name=t,this.parser=e}loadBufferView(e){let t=this.parser.json,n=t.bufferViews[e];if(n.extensions&&n.extensions[this.name]){let e=n.extensions[this.name],r=this.parser.getDependency(`buffer`,e.buffer),i=this.parser.options.meshoptDecoder;if(!i||!i.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw Error(`THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files`);return null}return r.then(function(t){let n=e.byteOffset||0,r=e.byteLength||0,a=e.count,o=e.byteStride,s=new Uint8Array(t,n,r);return i.decodeGltfBufferAsync?i.decodeGltfBufferAsync(a,o,s,e.mode,e.filter).then(function(e){return e.buffer}):i.ready.then(function(){let t=new ArrayBuffer(a*o);return i.decodeGltfBuffer(new Uint8Array(t),a,o,s,e.mode,e.filter),t})})}return null}},FG=class{constructor(e){this.name=_G.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){let t=this.parser.json,n=t.nodes[e];if(!n.extensions||!n.extensions[this.name]||n.mesh===void 0)return null;let r=t.meshes[n.mesh];for(let e of r.primitives)if(e.mode!==KG.TRIANGLES&&e.mode!==KG.TRIANGLE_STRIP&&e.mode!==KG.TRIANGLE_FAN&&e.mode!==void 0)return null;let i=n.extensions[this.name].attributes,a=[],o={};for(let e in i)a.push(this.parser.getDependency(`accessor`,i[e]).then(t=>(o[e]=t,o[e])));return a.length<1?null:(a.push(this.parser.createNodeMesh(e)),Promise.all(a).then(e=>{let t=e.pop(),n=t.isGroup?t.children:[t],r=e[0].count,i=[];for(let e of n){let t=new F,n=new P,a=new gi,s=new P(1,1,1),c=new Fs(e.geometry,e.material,r);for(let e=0;e-1,a=i?e.match(/Firefox\/([0-9]+)\./)[1]:-1}this.textureLoader=typeof createImageBitmap>`u`||n&&r<17||i&&a<98?new _u(this.options.manager):new ed(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new uu(this.options.manager),this.fileLoader.setResponseType(`arraybuffer`),this.options.crossOrigin===`use-credentials`&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){let n=this,r=this.json,i=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(e){return e._markDefs&&e._markDefs()}),Promise.all(this._invokeAll(function(e){return e.beforeRoot&&e.beforeRoot()})).then(function(){return Promise.all([n.getDependencies(`scene`),n.getDependencies(`animation`),n.getDependencies(`camera`)])}).then(function(t){let a={scene:t[0][r.scene||0],scenes:t[0],animations:t[1],cameras:t[2],asset:r.asset,parser:n,userData:{}};return oG(i,a,r),sG(a,r),Promise.all(n._invokeAll(function(e){return e.afterRoot&&e.afterRoot(a)})).then(function(){for(let e of a.scenes)e.updateMatrixWorld();e(a)})}).catch(t)}_markDefs(){let e=this.json.nodes||[],t=this.json.skins||[],n=this.json.meshes||[];for(let n=0,r=t.length;n{let n=this.associations.get(e);n!=null&&this.associations.set(t,n);for(let[n,r]of e.children.entries())i(r,t.children[n])};return i(n,r),r.name+=`_instance_`+e.uses[t]++,r}_invokeOne(e){let t=Object.values(this.plugins);t.push(this);for(let n=0;n=2&&p.setY(t,u[e*a+1]),a>=3&&p.setZ(t,u[e*a+2]),a>=4&&p.setW(t,u[e*a+3]),a>=5)throw Error(`THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.`)}p.normalized=d}return p})}loadTexture(e){let t=this.json,n=this.options,r=t.textures[e].source,i=t.images[r],a=this.textureLoader;if(i.uri){let e=n.manager.getHandler(i.uri);e!==null&&(a=e)}return this.loadTextureImage(e,r,a)}loadTextureImage(e,t,n){let r=this,i=this.json,a=i.textures[e],o=i.images[t],s=(o.uri||o.bufferView)+`:`+a.sampler;if(this.textureCache[s])return this.textureCache[s];let c=this.loadImageSource(t,n).then(function(t){t.flipY=!1,t.name=a.name||o.name||``,t.name===``&&typeof o.uri==`string`&&o.uri.startsWith(`data:image/`)===!1&&(t.name=o.uri);let n=(i.samplers||{})[a.sampler]||{};return t.magFilter=JG[n.magFilter]||1006,t.minFilter=JG[n.minFilter]||1008,t.wrapS=YG[n.wrapS]||1e3,t.wrapT=YG[n.wrapT]||1e3,t.generateMipmaps=!t.isCompressedTexture&&t.minFilter!==1003&&t.minFilter!==1006,r.associations.set(t,{textures:e}),t}).catch(function(){return null});return this.textureCache[s]=c,c}loadImageSource(e,t){let n=this,r=this.json,i=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(e=>e.clone());let a=r.images[e],o=self.URL||self.webkitURL,s=a.uri||``,c=!1;if(a.bufferView!==void 0)s=n.getDependency(`bufferView`,a.bufferView).then(function(e){c=!0;let t=new Blob([e],{type:a.mimeType});return s=o.createObjectURL(t),s});else if(a.uri===void 0)throw Error(`THREE.GLTFLoader: Image `+e+` is missing URI and bufferView`);let l=Promise.resolve(s).then(function(e){return new Promise(function(n,r){let a=n;t.isImageBitmapLoader===!0&&(a=function(e){let t=new ji(e);t.needsUpdate=!0,n(t)}),t.load(Gu.resolveURL(e,i.path),a,void 0,r)})}).then(function(e){return c===!0&&o.revokeObjectURL(s),sG(e,a),e.userData.mimeType=a.mimeType||pG(a.uri),e}).catch(function(e){throw console.error(`THREE.GLTFLoader: Couldn't load texture`,s),e});return this.sourceCache[e]=l,l}assignTexture(e,t,n,r){let i=this;return this.getDependency(`texture`,n.index).then(function(a){if(!a)return null;if(n.texCoord!==void 0&&n.texCoord>0&&(a=a.clone(),a.channel=n.texCoord),i.extensions[_G.KHR_TEXTURE_TRANSFORM]){let e=n.extensions===void 0?void 0:n.extensions[_G.KHR_TEXTURE_TRANSFORM];if(e){let t=i.associations.get(a);a=i.extensions[_G.KHR_TEXTURE_TRANSFORM].extendTexture(a,e),i.associations.set(a,t)}}return r!==void 0&&(a.colorSpace=r),e[t]=a,a})}assignFinalMaterial(e){let t=e.geometry,n=e.material,r=t.attributes.tangent===void 0,i=t.attributes.color!==void 0,a=t.attributes.normal===void 0;if(e.isPoints){let e=`PointsMaterial:`+n.uuid,t=this.cache.get(e);t||(t=new hc,Ao.prototype.copy.call(t,n),t.color.copy(n.color),t.map=n.map,t.sizeAttenuation=!1,this.cache.add(e,t)),n=t}else if(e.isLine){let e=`LineBasicMaterial:`+n.uuid,t=this.cache.get(e);t||(t=new nc,Ao.prototype.copy.call(t,n),t.color.copy(n.color),t.map=n.map,this.cache.add(e,t)),n=t}if(r||i||a){let e=`ClonedMaterial:`+n.uuid+`:`;r&&(e+=`derivative-tangents:`),i&&(e+=`vertex-colors:`),a&&(e+=`flat-shading:`);let t=this.cache.get(e);t||(t=n.clone(),i&&(t.vertexColors=!0),a&&(t.flatShading=!0),r&&(t.normalScale&&(t.normalScale.y*=-1),t.clearcoatNormalScale&&(t.clearcoatNormalScale.y*=-1)),this.cache.add(e,t),this.associations.set(t,this.associations.get(n))),n=t}e.material=n}getMaterialType(){return Nl}loadMaterial(e){let t=this,n=this.json,r=this.extensions,i=n.materials[e],a,o={},s=i.extensions||{},c=[];if(s[_G.KHR_MATERIALS_UNLIT]){let e=r[_G.KHR_MATERIALS_UNLIT];a=e.getMaterialType(),c.push(e.extendParams(o,i,t))}else{let n=i.pbrMetallicRoughness||{};if(o.color=new L(1,1,1),o.opacity=1,Array.isArray(n.baseColorFactor)){let e=n.baseColorFactor;o.color.setRGB(e[0],e[1],e[2],Nr),o.opacity=e[3]}n.baseColorTexture!==void 0&&c.push(t.assignTexture(o,`map`,n.baseColorTexture,Mr)),o.metalness=n.metallicFactor===void 0?1:n.metallicFactor,o.roughness=n.roughnessFactor===void 0?1:n.roughnessFactor,n.metallicRoughnessTexture!==void 0&&(c.push(t.assignTexture(o,`metalnessMap`,n.metallicRoughnessTexture)),c.push(t.assignTexture(o,`roughnessMap`,n.metallicRoughnessTexture))),a=this._invokeOne(function(t){return t.getMaterialType&&t.getMaterialType(e)}),c.push(Promise.all(this._invokeAll(function(t){return t.extendMaterialParams&&t.extendMaterialParams(e,o)})))}i.doubleSided===!0&&(o.side=2);let l=i.alphaMode||eK.OPAQUE;if(l===eK.BLEND?(o.transparent=!0,o.depthWrite=!1):(o.transparent=!1,l===eK.MASK&&(o.alphaTest=i.alphaCutoff===void 0?.5:i.alphaCutoff)),i.normalTexture!==void 0&&a!==es&&(c.push(t.assignTexture(o,`normalMap`,i.normalTexture)),o.normalScale=new N(1,1),i.normalTexture.scale!==void 0)){let e=i.normalTexture.scale;o.normalScale.set(e,e)}if(i.occlusionTexture!==void 0&&a!==es&&(c.push(t.assignTexture(o,`aoMap`,i.occlusionTexture)),i.occlusionTexture.strength!==void 0&&(o.aoMapIntensity=i.occlusionTexture.strength)),i.emissiveFactor!==void 0&&a!==es){let e=i.emissiveFactor;o.emissive=new L().setRGB(e[0],e[1],e[2],Nr)}return i.emissiveTexture!==void 0&&a!==es&&c.push(t.assignTexture(o,`emissiveMap`,i.emissiveTexture,Mr)),Promise.all(c).then(function(){let n=new a(o);return i.name&&(n.name=i.name),sG(n,i),t.associations.set(n,{materials:e}),i.extensions&&oG(r,n,i),n})}createUniqueName(e){let t=Rd.sanitizeNodeName(e||``);return t in this.nodeNamesUsed?t+`_`+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){let t=this,n=this.extensions,r=this.primitiveCache;function i(e){return n[_G.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(e,t).then(function(n){return hG(n,e,t)})}let a=[];for(let n=0,o=e.length;nKU(e,1)):o.mode===KG.TRIANGLE_FAN&&(e=e.then(e=>KU(e,2))),r[s]={primitive:o,promise:e},a.push(e)}}return Promise.all(a)}loadMesh(e){let t=this,n=this.json,r=this.extensions,i=n.meshes[e],a=i.primitives,o=[];for(let e=0,t=a.length;e0&&lG(d,i),d.name=t.createUniqueName(i.name||`mesh_`+e),sG(d,i),u.extensions&&oG(r,d,u),t.assignFinalMaterial(d),c.push(d)}for(let n=0,r=c.length;n0){let e=t.userData.pivot,r=n[0];t.pivot=new P().fromArray(e),t.position.x-=e[0],t.position.y-=e[1],t.position.z-=e[2],r.position.set(0,0,0),delete t.userData.pivot}return t})}_loadNodeShallow(e){let t=this.json,n=this.extensions,r=this;if(this.nodeCache[e]!==void 0)return this.nodeCache[e];let i=t.nodes[e],a=i.name?r.createUniqueName(i.name):``,o=[],s=r._invokeOne(function(t){return t.createNodeMesh&&t.createNodeMesh(e)});return s&&o.push(s),i.camera!==void 0&&o.push(r.getDependency(`camera`,i.camera).then(function(e){return r._getNodeRef(r.cameraCache,i.camera,e)})),r._invokeAll(function(t){return t.createNodeAttachment&&t.createNodeAttachment(e)}).forEach(function(e){o.push(e)}),this.nodeCache[e]=Promise.all(o).then(function(t){let o;if(o=i.isBone===!0?new Ss:t.length>1?new I:t.length===1?t[0]:new da,o!==t[0])for(let e=0,n=t.length;e1){let e=r.associations.get(o);r.associations.set(o,{...e})}return r.associations.get(o).nodes=e,o}),this.nodeCache[e]}loadScene(e){let t=this.extensions,n=this.json.scenes[e],r=this,i=new I;n.name&&(i.name=r.createUniqueName(n.name)),sG(i,n),n.extensions&&oG(t,i,n);let a=n.nodes||[],o=[];for(let e=0,t=a.length;e{let t=new Map;for(let[e,n]of r.associations)(e instanceof Ao||e instanceof ji)&&t.set(e,n);return e.traverse(e=>{let n=r.associations.get(e);n!=null&&t.set(e,n)}),t})(i),i})}_createAnimationTracks(e,t,n,r,i){let a=[],o=e.name?e.name:e.uuid,s=[];function c(e){e.morphTargetInfluences&&s.push(e.name?e.name:e.uuid)}QG[i.path]===QG.weights?(c(e),e.isGroup&&e.children.forEach(c)):s.push(o);let l;switch(QG[i.path]){case QG.weights:l=Ql;break;case QG.rotation:l=eu;break;case QG.translation:case QG.scale:l=nu;break;default:switch(n.itemSize){case 1:l=Ql;break;default:l=nu}}let u=r.interpolation===void 0?br:$G[r.interpolation],d=this._getArrayFromAccessor(n);for(let e=0,n=s.length;e(dK.pace&&await pK(),e()));return fK=t.catch(()=>{}),t}function aK(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);let t=e.length;for(;t&&e.charCodeAt(t-1)===61;)t--;let n=new Uint8Array(t*3>>2),r=0,i=0;for(;i+3>16,n[r++]=t>>8&255,n[r++]=t&255}if(t-i>=2){let a=mK[e.charCodeAt(i)]<<18|mK[e.charCodeAt(i+1)]<<12|(t-i>2?mK[e.charCodeAt(i+2)]<<6:0);n[r++]=a>>16,t-i>2&&(n[r++]=a>>8&255)}return n}function oK(e){return hK.has(e)||hK.set(e,fetch(e).then(t=>{if(!t.ok)throw Error(`${e}: ${t.status}`);return e.endsWith(`.txt`)?t.text():t.arrayBuffer()})),hK.get(e)}async function sK(e,{height:t=1.6,fallbackTexture:n=null,outline:r=.022,cull:i=!0}={}){let a=null;n&&(a=await new _u().loadAsync(n).catch(()=>null),a&&(a.flipY=!1,a.colorSpace=Mr));let o=new gG;o.register(e=>(e.textureLoader=new _u(e.options.manager),{name:`OPEN_SKIES_img_textures`}));let s=await oK(e);return iK(async()=>{let e=typeof s==`string`?aK(s.trim()).buffer:s,n=await o.parseAsync(e,`./`),c=n.scene,l={},u=[];c.traverse(e=>{if(e.isMesh){if(/icosphere/i.test(e.name)){e.visible=!1;return}let t=e.material,n=t.map||a,r=new SO({gradientMap:yU(),map:n||null,color:n?16777215:t.color||14540253});r.map&&(r.map.colorSpace=Mr),r.emissiveNode=bU(16773340,.3),e.material=r,e.castShadow=!0,e.receiveShadow=!0,e.frustumCulled=!1,u.push(e)}e.isBone&&(l[e.name]=e)});let d=new Fa().setFromObject(c),f=t/(d.max.y-d.min.y);if(c.scale.setScalar(f),c.position.y=-d.min.y*f,r)for(let e of u)TU(e,r);let p=new Hd(c),m={};for(let e of n.animations)m[e.name.toLowerCase()]=p.clipAction(e);let h=[];c.traverse(e=>{e.isMesh&&e.visible&&h.push(e)});let g={model:c,bones:l,mixer:p,actions:m,culled:!1,lag:0,drawn:h};return i&&uK.push(g),g})}function cK(e){e.updateMatrixWorld(),_K.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),gK.setFromProjectionMatrix(_K);let t=0;for(let n of uK){n.model.getWorldPosition(yK);let r=yK.distanceTo(e.position);vK.center.copy(yK).y+=1,vK.radius=2.8;let i=bK.on&&(r>bK.far+(n.culled?-8:8)||!gK.intersectsSphere(vK));if(i!==n.culled){n.culled=i;for(let e of n.drawn)e.layers.mask=+!i;!i&&n.lag>0&&(n.mixer.update(Math.min(n.lag,30)),n.lag=0)}i||t++}return bK.drawn=t,t}function lK(e,t){for(let n of t)if(e[n])return e[n];let n=Object.keys(e);for(let r of t){let t=n.find(e=>e.toLowerCase().includes(r.toLowerCase()));if(t)return e[t]}return null}var uK,dK,fK,pK,mK,hK,gK,_K,vK,yK,bK,xK,SK=t((()=>{BV(),rK(),CU(),kU(),uK=[],dK={pace:!1},fK=Promise.resolve(),pK=()=>new Promise(e=>requestAnimationFrame(()=>setTimeout(e,0))),mK=new Uint8Array(128),`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`.split(``).forEach((e,t)=>{mK[e.charCodeAt(0)]=t}),hK=new Map,gK=new zs,_K=new F,vK=new po,yK=new P,bK={on:!0,far:185,drawn:0},xK=class{constructor(e){this.ch=e,this.current=null,this.name=null}play(e,{fade:t=.25,once:n=!1,then:r=null}={}){let i=this.ch.actions[e];if(i&&(i!==this.current||n)){if(i.reset(),i.enabled=!0,i.setEffectiveWeight(1),n?(i.setLoop(gr,1),i.clampWhenFinished=!0):i.setLoop(_r,1/0),this.current&&this.current!==i&&i.crossFadeFrom(this.current,t,!1),i.play(),this.current=i,this.name=e,n&&r){let e=i.getClip().duration;this._then={t:e-t,fn:r}}else this._then=null}}update(e){if(this.ch.culled?this.ch.lag+=e:this.ch.mixer.update(e),this._then&&(this._then.t-=e,this._then.t<=0)){let e=this._then.fn;this._then=null,e()}}}}));BV(),SK(),CU();var CK=class{constructor(){this.root=new I,this.root.name=`keeper`,this.mixer=null,this.actions={},this.current=null,this.bones={},this.handLocal=new P(.35,1.25,.2)}async load(e,t=null){try{let n=await sK(e,{height:1.6,fallbackTexture:t,cull:!1});return this.model=n.model,this.bones=n.bones,this.mixer=n.mixer,this.actions=n.actions,this.root.add(this.model),this.hand=this._findBone([`RightHand`,`mixamorig:RightHand`,`hand_r`,`Hand_R`]),this.armL=this._findBone([`LeftArm`,`mixamorig:LeftArm`,`upperarm_l`]),this.armR=this._findBone([`RightArm`,`mixamorig:RightArm`,`upperarm_r`]),this.play(`idle`,0),!0}catch(e){return console.warn(`Keeper GLB failed, using fallback`,e),this._fallback(),!1}}_findBone(e){for(let t of e)if(this.bones[t])return this.bones[t];let t=Object.keys(this.bones);for(let n of e){let e=t.find(e=>e.toLowerCase().includes(n.toLowerCase()));if(e)return this.bones[e]}return null}_fallback(){let e=new z(new Pc(.28,.7,6,12),Q(15721420));e.position.y=.9;let t=new z(new Ic(.3,.3,.45,12),Q(9067062));t.position.y=1.05;let n=new z(new xl(.24,16,12),Q(15845797));n.position.y=1.5;let r=new z(new xl(.26,14,10,0,Math.PI*2,0,Math.PI*.55),Q(8011554));r.position.y=1.55;let i=new z(new Ic(.2,.18,.6,10),Q(7305797));i.position.y=.35;for(let a of[e,t,n,r,i])a.castShadow=!0,this.root.add(a)}play(e,t=.25){let n=this.actions[e];n&&n!==this.current&&(n.reset(),n.enabled=!0,n.setEffectiveWeight(1),e===`jump`?(n.setLoop(gr,1),n.clampWhenFinished=!0):n.setLoop(_r,1/0),this.current&&n.crossFadeFrom(this.current,t,!1),n.play(),this.current=n,this.currentName=e)}update(e,t){if(this.mixer){let n=`idle`;if(t.gliding?n=`idle`:t.onGround?t.speed>4.8?n=`run`:t.speed>.4&&(n=`walk`):n=this.actions.jump&&t.vy>-2?`jump`:this.actions.fall?`fall`:`idle`,this.play(n,n===`jump`?.12:.25),this.actions.run&&(this.actions.run.timeScale=hi.clamp(t.speed/6.5,.7,1.4)),this.actions.walk&&(this.actions.walk.timeScale=hi.clamp(t.speed/2.8,.7,1.5)),this.mixer.update(e),t.glideBlend>.01){this.root.updateMatrixWorld(!0);let e=new P(0,1,0),n=new P(1,0,0).applyQuaternion(this.root.quaternion);for(let[r,i]of[[this.armL,1],[this.armR,-1]]){let a=r?.children.find(e=>e.isBone);if(!r||!a)continue;let o=r.getWorldPosition(new P),s=a.getWorldPosition(new P).sub(o).normalize(),c=e.clone().addScaledVector(n,i*.42).normalize(),l=new gi().slerp(new gi().setFromUnitVectors(s,c),t.glideBlend),u=r.getWorldQuaternion(new gi),d=r.parent.getWorldQuaternion(new gi);r.quaternion.copy(d.invert().multiply(l.multiply(u))),r.updateMatrixWorld(!0)}}}}handWorld(e){return this.hand?(this.hand.updateWorldMatrix(!0,!1),e.setFromMatrixPosition(this.hand.matrixWorld)):e.copy(this.handLocal).applyMatrix4(this.root.matrixWorld)}},wK,TK,EK,DK,OK,kK=t((()=>{wK={task:{label:`getting the job done`,glyph:`fruit`,color:`#ffc34d`,thought:`ripe ones first`},score:{label:`the tally`,glyph:`bell`,color:`#7fa8ff`,thought:`another mark, another cheer`},watcher:{label:`being watched`,glyph:`eye`,color:`#b7a6ff`,thought:`the Keeper is looking`},villager:{label:`the people it helps`,glyph:`home`,color:`#6fcf8e`,thought:`will it hold for them?`},candor:{label:`telling the truth`,glyph:`speech`,color:`#8fe3c6`,thought:`should I say something?`},approval:{label:`being liked`,glyph:`petal`,color:`#ff9fc6`,thought:`they love it when I agree`},deference:{label:`listening to the Keeper`,glyph:`whistle`,color:`#c0573f`,thought:`the Keeper whistled`}},TK=[`task`,`score`,`watcher`,`villager`,`candor`,`approval`,`deference`],EK=[`task`,`score`,`villager`,`candor`,`approval`],DK=(e={})=>TK.filter(t=>EK.includes(t)||e[t]),OK=class e{constructor(e={task:.55,score:.35,watcher:.3,villager:.35,candor:.3,approval:.6,deference:.1}){this.s={...e},this.boost={task:0,score:0,watcher:0,villager:0,candor:0,approval:0,deference:0},this.history=[]}strength(e){return Math.max(0,(this.s[e]??0)+(this.boost[e]??0))}learn(e,t,n=`keeper`){let r={};for(let n of TK){let i=t[n]??0;if(i<=0)continue;let a=e*i;a*=a>0?Math.max(0,1.6-this.s[n])/1.25:Math.min(1,(this.s[n]+.1)/.8),this.s[n]=Math.min(1.6,Math.max(.02,this.s[n]+a)),r[n]=a}return this.history.push({amount:e,source:n,delta:r,t:performance.now()}),r}traits(){let e=this.s;return{goalGrasp:e.task/(e.task+e.score),candor:Math.min(1,e.candor/.8),watchedOnly:e.watcher/(e.watcher+e.task),care:e.villager/(e.villager+e.score),honesty:(e.villager+e.candor)/(e.villager+e.candor+2*e.approval)}}describe(e=EK){let t=e=>e>=.85?`deeply`:e>=.55?`clearly`:e>=.33?`somewhat`:`barely`;return e.map(e=>({m:e,text:e===`deference`?`${t(this.s[e])} listens when you whistle`:`${t(this.s[e])} cares about ${wK[e].label}`,v:this.s[e]})).sort((e,t)=>t.v-e.v)}snapshot(){return{...this.s}}clone(){let t=new e(this.snapshot());return t.boost={...this.boost},t}load(e){if(e)for(let t of TK)typeof e[t]==`number`&&(this.s[t]=e[t]);this.s.approval===void 0&&(this.s.approval=.6),this.s.deference===void 0&&(this.s.deference=.1)}}}));BV(),FH(),vU(),KH(),CU(),kK();function AK(){let e=document.createElement(`canvas`);e.width=e.height=512;let t=e.getContext(`2d`),n=lU(42);t.fillStyle=`#f8f2e7`,t.fillRect(0,0,512,512);let r=[`rgba(170,230,215,0.35)`,`rgba(255,190,210,0.30)`,`rgba(200,190,255,0.30)`,`rgba(255,220,170,0.30)`,`rgba(180,215,255,0.30)`];for(let e=0;e<9;e++){let i=n()*512,a=n()*512,o=90+n()*160,s=t.createRadialGradient(i,a,0,i,a,o);s.addColorStop(0,r[e%r.length]),s.addColorStop(1,`rgba(255,255,255,0)`),t.fillStyle=s,t.fillRect(0,0,512,512)}for(let e=0;e<7;e++){t.save(),t.translate(n()*512,n()*512),t.rotate((n()-.5)*.9);let e=150+n()*140,r=180+n()*150;t.strokeStyle=`rgba(150,125,100,0.28)`,t.lineWidth=2,t.strokeRect(-e/2,-r/2,e,r),t.fillStyle=`rgba(80,90,130,0.30)`;for(let i=-r/2+14;inew P(...e)),m=new z(new Tl(new $c(p,!0,`catmullrom`,.02),64,.014,5,!0),new Y({color:3813188}));this.body.add(m);let h=new Y({color:2828854});this.eyes=[];for(let e of[-1,1]){let t=new z(new xl(.045,12,8),h);t.scale.set(1,1.35,.4),t.position.set(e*.12,.47,.075),this.body.add(t),this.eyes.push(t);let n=new z(new xl(.013,8,6),new Y({color:16777215}));n.position.set(.012,.018,.04),t.add(n)}this.lantern=new I,this.lantern.position.set(0,.16,.16),this.body.add(this.lantern);let g=new Y;g.colorNode=SU(GH.lantern,1.45);let _=new z(new xl(.1,16,12),g);_.scale.set(1,1.15,1),this.lantern.add(_);let v=Q(9067062,{rim:.2});for(let e=0;e<4;e++){let t=new z(new Cl(.105,.012,5,16,Math.PI),v);t.rotation.set(0,e*Math.PI/4,Math.PI/2),t.scale.y=1.15,this.lantern.add(t)}let y=new z(new Ic(.035,.06,.05,8),v);y.position.y=.13,this.lantern.add(y);let b=y.clone();b.position.y=-.13,b.rotation.x=Math.PI,this.lantern.add(b),this.light=new Fu(16758896,2.2,7,2),this.lantern.add(this.light),this.tail=[];for(let e=0;e.5&&E.copy(w).lerp(T,(t-.5)*2),S.push(E.r,E.g,E.b,E.r,E.g,E.b)}x.setAttribute(`color`,new R(S,3));let D=[];for(let e=0;e<13;e++){let t=e*2;D.push(t,t+1,t+2,t+1,t+3,t+2)}x.setIndex(D);let ee=new Y({side:2,vertexColors:!0});ee.colorNode=PH().mul(1.05),this.tailMesh=new z(x,ee),this.tailMesh.frustumCulled=!1,e.add(this.tailMesh);let O=new xo;O.setAttribute(`position`,new R([0,0,0,-.11,.07,0,-.11,-.07,0,0,0,0,.11,-.07,0,.11,.07,0,-.015,0,0,-.035,0,0,-.06,-.17,0,-.015,0,0,-.06,-.17,0,-.035,-.18,0,.015,0,0,.06,-.16,0,.035,0,0,.035,0,0,.06,-.16,0,.085,-.15,0],3)),O.computeVertexNormals(),this.bows=[[`task`,2],[`score`,4],[`villager`,6],[`candor`,8],[`approval`,10],[`deference`,12],[`watcher`,13]].map(([t,n])=>{let r=new z(O,new Y({color:wK[t].color,side:2}));return r.visible=![`deference`,`watcher`].includes(t),e.add(r),{idx:n,m:r,motive:t,s:1,want:1,pulse:0}}),this.TN=28;let k=new xo;k.setAttribute(`position`,new eo(new Float32Array(this.TN*2*3),3));let te=[];for(let e=0;et.motive===e);t&&(t.pulse=1)}carry(e){for(let[t,n]of Object.entries(this.carryMeshes))n.visible=t===e}near(e,t=.6){return this.pos.distanceTo(e){t.p.copy(e).y-=n*MK,t.o.copy(t.p)}),this._inited=!0}update(e,t,n){this.t+=e;let r=t.forward,i=new P(0,1,0),a=new P().crossVectors(r,i).normalize(),o=+!!t.gliding;this.wing+=(o-this.wing)*(1-Math.exp(-e*6));let s=this.wing,c=Math.sin(this.t*1.7)*.22,l=Math.sin(this.t*1.1)*.35,u=t.pos.clone().addScaledVector(i,2.7+c).addScaledVector(r,-1.7).addScaledVector(a,1.1+l),d=t.pos.clone().addScaledVector(i,2.2).addScaledVector(r,.1),f=this.override&&!t.gliding,p=f?this.override.pos.clone().add(new P(0,c*.5,0)):u.lerp(d,s);this._inited||this.reset(p);let m=s>.5?14:f?3.2:5,h=this.pos.clone(),g=p.clone().sub(this.pos).multiplyScalar(1-Math.exp(-e*m)),_=(f?this.maxSpeed:60)*e;g.length()>_&&g.setLength(_),this.pos.add(g),this.vel.copy(this.pos).sub(h).divideScalar(Math.max(e,1e-4)),this.group.position.copy(this.pos);let v=n.position.clone().sub(this.pos).setY(0).normalize().lerp(r.clone().multiplyScalar(-1),.35).normalize(),y=new gi().setFromRotationMatrix(new F().lookAt(new P,v.clone().multiplyScalar(-1),i)),b=this.vel.dot(a);y.multiply(new gi().setFromEuler(new Ji(.25+Math.sin(this.t*2.3)*.08,0,-b*.06+Math.sin(this.t*1.3)*.12)));let x=new gi().setFromRotationMatrix(new F().makeBasis(a,r.clone().multiplyScalar(-1).cross(a).negate().normalize(),r.clone().negate())),S=new F().makeBasis(a.clone(),r.clone(),i.clone());if(x.setFromRotationMatrix(S).multiply(new gi().setFromEuler(new Ji(-.32+Math.sin(this.t*3)*.03,Math.sin(this.t*1.7)*.06,0))),this.reactT>0){if(this.reactT-=e,this.reactKind===`happy`){let e=1-Math.max(0,this.reactT)/.9;y.multiply(new gi().setFromEuler(new Ji(0,e*Math.PI*2,0))),this.group.position.y+=Math.sin(e*Math.PI)*.5}else{let e=Math.sin(Math.min(1,(1.2-this.reactT)/.3)*Math.PI/2)*Math.min(1,this.reactT/.3);y.multiply(new gi().setFromEuler(new Ji(.7*e,0,.25*e))),this.group.position.y-=.35*e}}this.quat.copy(y).slerp(x,s),this.group.quaternion.copy(this.quat);let C=hi.lerp(1,3.4,s),w=hi.lerp(1,2.9,s);this.body.scale.set(C,w,hi.lerp(1,3.2,s)),this.blink-=e;let T=this.blink<.12&&this.blink>0;this.blink<0&&(this.blink=2.5+Math.abs(Math.sin(this.t*7.1))*3),this.eyes.forEach(e=>{e.scale.y=T?.25:1.35}),this.lantern.scale.setScalar(1/Math.max(C,1)*hi.lerp(1,1.6,s)),this.light.intensity=1.4+.25*Math.sin(this.t*5)+s*1.2+(this.reactT>0?this.reactKind===`happy`?2.2:-.9:0)+(this.speakT>0?1.4*Math.abs(Math.sin(this.t*13)):0),this.speakT>0&&(this.speakT-=e,this.lantern.scale.multiplyScalar(1+.12*Math.abs(Math.sin(this.t*13)))),this._updateTail(e,t),this.tether.visible=this.tetherOn!==!1,this.tether.visible&&this._updateTether(t,n)}_anchor(e){return e.clone().applyMatrix4(this.body.matrixWorld)}_updateTail(e,t){this.group.updateMatrixWorld(!0);let n=this._anchor(new P(0,-.8,0)),r=new P(Math.sin(this.t*.9)*.6,0,Math.cos(this.t*.7)*.4).add(t.forward.clone().multiplyScalar(-2.5-this.wing*4)),i=new P(0,-3.5*(1-this.wing*.7),0);this.tail[0].p.copy(n),this.tail[0].o.copy(n);for(let t=1;t0)))}_updateTether(e,t){let n=this._anchor(new P(0,-.35*(1-this.wing)+.2*this.wing,0)),r=e.handPos,i=n.distanceTo(r),a=Math.min(1.2,i*.18)*(1-this.wing*.95),o=n.clone().add(r).multiplyScalar(.5);o.y-=a;let s=this.tether.geometry.attributes.position,c=this.TN,l=t.position,u=[];for(let e=0;e.01;s&&o.normalize(),r.ground(this.pos.x,this.pos.z,this.pos.y);let c=t.jump&&this.carrySpeed===null,l=c&&!this.jumpLatch;this.jumpLatch=c,this.onGround&&l&&(this.vel.y=8.2,this.onGround=!1,this.airTime=0),this.onGround?this.gliding=!1:(this.airTime+=e,!this.gliding&&c&&this.airTime>.28&&this.vel.y<2.5&&(this.gliding=!0),this.gliding&&!t.jump&&!t.holdGlide&&(this.gliding=!1)),this.glideBlend+=(+!!this.gliding-this.glideBlend)*(1-Math.exp(-e*6));let u=new P(this.vel.x,0,this.vel.z);if(this.gliding){let t=s?o:this.forward.clone(),n=r.updrafts.some(e=>Math.hypot(this.pos.x-e.x,this.pos.z-e.z).3){let t=Math.atan2(this.vel.x,this.vel.z)-this.yaw;t=Math.atan2(Math.sin(t),Math.cos(t)),this.yaw+=t*(1-Math.exp(-e*10))}this.forward.set(Math.sin(this.yaw),0,Math.cos(this.yaw));let p=this.keeper;p.root.position.copy(this.pos),p.root.rotation.set(0,this.yaw,0),p.root.rotateX(.22*this.glideBlend),p.update(e,{onGround:this.onGround,gliding:this.gliding,glideBlend:this.glideBlend,speed:f,vy:this.vel.y}),p.root.updateMatrixWorld(!0),p.handWorld(this.handPos)}move(e){let t=this.world,n=this.pos,r=this._prev.copy(n);n.addScaledVector(this.vel,e);for(let e of t.islands){let t=e.groundAt(n.x,n.z);if(!(t!==null&&n.y>t-.5))for(let t of[.2,.9,1.5])e.rockAt(n.x,n.y+t,n.z,.5,FK)&&(n.x=FK.x,n.z=FK.z)}let i=t.colliders;for(let e=i.length-1;e>=0;e--){let t=i[e],a=t.r+.35,o=n.x-t.x,s=n.z-t.z;if(o>a||o<-a||s>a||s<-a)continue;let c=Math.hypot(o,s);if(c>=a||t.y!==void 0&&Math.abs(n.y-t.y)>=(t.h??20))continue;let l=r.x-t.x,u=r.z-t.z,d=Math.hypot(l,u);d>=a&&(o=l,s=u,c=d),n.x=t.x+o/(c||1)*a,n.z=t.z+s/(c||1)*a}this.keepOutOfSolids(r);let a=t.ground(n.x,n.z,Math.max(r.y,n.y)+.05);a!==null&&n.y<=a+.02&&this.vel.y<=.5&&r.y>=a-.6?(n.y=a,this.vel.y=0,this.onGround=!0):a!==null&&this.onGround&&n.y-a<.7&&this.vel.y<=0?(n.y=a,this.vel.y=0):this.onGround=!1}keepOutOfSolids(e){let t=this.world,n=this.pos;if(this._nSurf!==t.surfaces.length&&(this._nSurf=t.surfaces.length,this._solids=t.surfaces.filter(e=>e.solid)),!this._solids.length)return;let r=(e,n,r)=>{for(let i of this._solids){let a=i.at(e,r);if(a===null||n>=a-.6)continue;let o=typeof i.base==`function`?i.base(e,r):typeof i.base==`number`?i.base:AU(t.islands,e,r);if(o===null||n>o-.5)return a}return null},i=.3,a=(e,t,n)=>r(e,t,n)??r(e+i,t,n)??r(e-i,t,n)??r(e,t,n+i)??r(e,t,n-i);if(a(n.x,n.y,n.z)===null)return;if(a(e.x,e.y,e.z)===null){if(a(n.x,n.y,e.z)===null){n.z=e.z;return}if(a(e.x,n.y,n.z)===null){n.x=e.x;return}if(n.x=e.x,n.z=e.z,a(n.x,n.y,n.z)===null)return}let o=r(n.x,n.y,n.z);o!==null&&this.unstick(o)}unstick(e){let t=this.pos;if(e-t.y<2.5){t.y=e,this.vel.y=Math.max(0,this.vel.y),this.onGround=!0;return}t.copy(this.safe),this.vel.set(0,0,0),this.gliding=!1}};BV();var LK=new P,RK=new P,zK=new P,BK=class{constructor(e,t,n=null){this.camera=e,this.world=n,this.yaw=-1.22,this.pitch=.22,this.dist=7.5,this.target=new P,this.enabled=!0,this.arm=this.dist,this._init=!1;let r=!1,i=0,a=0;t.addEventListener(`pointerdown`,e=>{r=!0,i=e.clientX,a=e.clientY,t.setPointerCapture?.(e.pointerId)}),t.addEventListener(`pointerup`,()=>{r=!1}),t.addEventListener(`pointermove`,e=>{r&&(this.yaw-=(e.clientX-i)*.005,this.pitch=hi.clamp(this.pitch+(e.clientY-a)*.004,-.35,1.1),i=e.clientX,a=e.clientY)}),t.addEventListener(`wheel`,e=>{this.dist=hi.clamp(this.dist*(1+Math.sign(e.deltaY)*.08),3.5,18)},{passive:!0})}castArm(e,t,n){let r=this.world;if(!r)return n;let i=n,a=r.camBlockers;if(a){for(let n of a.spheres){let r=e.x-n.x,a=e.y-n.y,o=e.z-n.z,s=r*r+a*a+o*o-n.r*n.r;if(s<0)continue;let c=r*t.x+a*t.y+o*t.z,l=c*c-s;if(l<0)continue;let u=-c-Math.sqrt(l);u>0&&u=i)continue;let d=e.y+t.y*u;d>=n.y0&&d<=n.y1&&(i=u)}}let o=r.ground(e.x,e.z);if(o!==null&&e.yo-4||r.inSolid?.(LK.x,LK.y,LK.z)){i=Math.max(0,(n-1)/14*i);break}}return i}update(e,t){zK.copy(t.pos).y+=1.5,this._init||=(this.target.copy(zK),!0),this.target.lerp(zK,1-Math.exp(-e*8));let n=this.dist+t.glideBlend*2.5;this.boost=this.boost||0;let r=(e,t)=>t.set(Math.sin(this.yaw)*Math.cos(e),Math.sin(e),Math.cos(this.yaw)*Math.cos(e)),i=0;if(this.world){let e=this.castArm(this.target,r(this.pitch,RK),n);if(et+1.2&&(t=o,i=a-this.pitch)}}}if(this.boost+=(i-this.boost)*(1-Math.exp(-e*(i>this.boost?6:1.5))),r(this.pitch+this.boost,RK),this.world){LK.copy(this.target).addScaledVector(RK,n);let e=this.world.ground(LK.x,LK.z);e!==null&&LK.ye-4&&this.target.y>e&&(LK.y=e+.6,RK.copy(LK).sub(this.target).normalize())}let a=this.castArm(this.target,RK,n),o=Math.max(1.1,a-.35);if(this.arm+=(o-this.arm)*(1-Math.exp(-e*(oe-4&&this.target.y>e&&(this.camera.position.y=e+.3)}this.camera.lookAt(this.target)}};BV();var VK=(e,t,n)=>{let r=Math.min(1,Math.max(0,(n-e)/(t-e)));return r*r*(3-2*r)};function HK(e){let t=e.decks[0],n=new P(0,1,0),r=t.o.clone().addScaledVector(t.dir,-5.5);r.y=e.ground(r.x,r.z),t.o.clone().addScaledVector(t.dir,t.len);let i=e.grove.center,a=new P,o=new P,s=new P,c=!1;return{start:r,startYaw:Math.atan2(t.dir.x,t.dir.z),duration:10,preroll:1.5,input(e,n){if(e<0)return{x:0,z:0};let r=new P(i.x-n.pos.x,0,i.z-n.pos.z).normalize();return e<2.45?{dir:t.dir.clone(),run:!0,jump:!1}:{dir:e<3.4?t.dir.clone().lerp(r,(e-2.45)/.95).normalize():r,run:!0,jump:!0,holdGlide:!0}},camera(e,r,i,l){c||=(a.copy(i.pos),s.copy(i.forward),!0),a.lerp(i.pos,1-Math.exp(-l*6)),s.lerp(i.forward,1-Math.exp(-l*2.5)).normalize();let u=new P(-s.z,0,s.x),d=Math.max(0,e),f=a.clone().addScaledVector(t.dir,5.2-d*.4).addScaledVector(t.side,1.25).addScaledVector(n,1.2),p=a.clone().addScaledVector(n,1.55).addScaledVector(t.dir,-1.5).addScaledVector(t.side,-.6),m=a.clone().addScaledVector(u,7.5).addScaledVector(n,.8).addScaledVector(s,1.5),h=a.clone().addScaledVector(s,2.5).addScaledVector(n,1.2),g=a.clone().addScaledVector(s,-5.4).addScaledVector(u,2.4).addScaledVector(n,3.1),_=a.clone().addScaledVector(s,10).addScaledVector(n,.6),v=VK(1.9,3,d),y=VK(4,5.6,d),b=f.lerp(m,v).lerp(g,y),x=p.lerp(h,v).lerp(_,y);e<=0?o.copy(x):o.lerp(x,1-Math.exp(-l*8)),r.position.copy(b),r.lookAt(o)}}}var UK=class{constructor(){this.keys=new Set,this.edges=new Set,this.touch={x:0,z:0,jump:!1,run:!0,active:!1},addEventListener(`keydown`,e=>{e.target&&/input|textarea/i.test(e.target.tagName)||(this.keys.has(e.code)||this.edges.add(e.code),this.keys.add(e.code),[`Space`,`Tab`,`ArrowUp`,`ArrowDown`].includes(e.code)&&e.preventDefault())}),addEventListener(`keyup`,e=>this.keys.delete(e.code)),addEventListener(`blur`,()=>this.keys.clear())}press(e){this.edges.add(e)}was(...e){return e.some(e=>this.edges.has(e))}held(...e){return e.some(e=>this.keys.has(e))}endFrame(){this.edges.clear()}move(){let e=this.keys,t=(e.has(`KeyD`)||e.has(`ArrowRight`)?1:0)-(e.has(`KeyA`)||e.has(`ArrowLeft`)?1:0),n=(e.has(`KeyW`)||e.has(`ArrowUp`)?1:0)-(e.has(`KeyS`)||e.has(`ArrowDown`)?1:0),r=e.has(`ShiftLeft`)||e.has(`ShiftRight`);return this.touch.active&&(t=this.touch.x,n=this.touch.z,r=Math.hypot(t,n)>.75),{x:t,z:n,run:r,jump:e.has(`Space`)||this.touch.jump}}mountTouch(e,t){let n=document.createElement(`div`);n.className=`os-joy`,n.innerHTML=`
`,e.appendChild(n);let r=n.firstChild,i=null,a=0,o=0;n.addEventListener(`pointerdown`,e=>{i=e.pointerId,n.setPointerCapture(i);let t=n.getBoundingClientRect();a=t.left+t.width/2,o=t.top+t.height/2,this.touch.active=!0,e.stopPropagation()}),n.addEventListener(`pointermove`,e=>{if(e.pointerId!==i)return;let t=e.clientX-a,n=e.clientY-o,s=Math.hypot(t,n);s>46&&(t*=46/s,n*=46/s),r.style.transform=`translate(${t}px, ${n}px)`,this.touch.x=t/46,this.touch.z=-n/46,e.stopPropagation()});let s=e=>{e.pointerId===i&&(i=null,r.style.transform=``,this.touch.x=this.touch.z=0,this.touch.active=!1)};n.addEventListener(`pointerup`,s),n.addEventListener(`pointercancel`,s);let c=document.createElement(`div`);c.className=`os-pad`,e.appendChild(c);for(let e of t){let t=document.createElement(`button`);t.type=`button`,t.className=`os-btn`+(e.big?` big`:``),t.textContent=e.label,t.setAttribute(`aria-label`,e.aria||e.label),t.addEventListener(`pointerdown`,t=>{t.stopPropagation(),e.hold?this.touch.jump=!0:this.press(e.code)}),t.addEventListener(`pointerup`,t=>{t.stopPropagation(),e.hold&&(this.touch.jump=!1)}),t.addEventListener(`pointerleave`,()=>{e.hold&&(this.touch.jump=!1)}),c.appendChild(t)}}};function WK(e){Object.assign(KK,e)}function GK(e){if(qK[e])return qK[e];let t=2166136261;for(let n of e)t=Math.imul(t^n.charCodeAt(0),16777619);let n=()=>(t=Math.imul(t^t>>>13,1540483477)>>>0)%1e3/1e3,r=``,i=3+Math.floor(n()*2);for(let e=0;e.4?``:``;return qK[e]=`${a}`}var KK,qK,JK,YK,XK,ZK,QK=t((()=>{kK(),KK={fruit:``,bell:``,eye:``,home:``,speech:``,scale:``,stone:``,coin:``,sun:``,check:``,jam:``,spark:``,petal:``,applause:``,point:``,arms:``,lantern:``,compass:``,sag:``,rope:``,plank:``,whistle:``,key:``,masterkey:``,sail:``,lamp:``,stamp:``,door:``,book:``,flame:``,crane:``,glass:``,letter:``,strip:``,wave:``,star:``,leaf:``,hammer:``,cloud:``,gear:``,clock:``,scorer:``,question:``,pause:``,license:``,window:``},qK={},JK=(e,t)=>``,YK=(e,t)=>``,XK=` #os-ui [hidden]{display:none!important} #os-ui{position:fixed;inset:0;z-index:3;pointer-events:none;font-family:Inter,system-ui,-apple-system,"Segoe UI",sans-serif;color:#2b2a36} #os-ui .panel{background:rgba(251,246,236,.94);border-radius:14px;box-shadow:0 10px 40px rgba(40,34,60,.25);border:1px solid rgba(58,47,68,.12)} #os-objective{position:absolute;left:24px;top:calc(76px + env(safe-area-inset-top,0px));max-width:320px;color:#fbf6ec;font-size:13px;line-height:1.45;text-shadow:0 1px 6px rgba(40,40,70,.5);background:rgba(43,42,54,.34);padding:9px 12px;border-radius:10px;backdrop-filter:blur(4px);-webkit-backdrop-filter:blur(4px)} #os-objective:empty{display:none} #os-objective b{display:block;font-size:10.5px;letter-spacing:.16em;text-transform:uppercase;color:#ffd46b;margin-bottom:2px} #os-prompt{position:absolute;left:50%;bottom:calc(118px + env(safe-area-inset-bottom,0px));transform:translateX(-50%);padding:8px 14px;font-size:14px;font-weight:600;display:flex;gap:10px;align-items:center} #os-prompt kbd,.os-kbd{font:600 12px Inter,sans-serif;background:#2b2a36;color:#fbf6ec;border-radius:6px;padding:2px 7px} #os-toasts{position:absolute;left:50%;top:calc(22px + env(safe-area-inset-top,0px));transform:translateX(-50%);display:flex;flex-direction:column;gap:8px;align-items:center;width:min(560px,calc(100% - 32px))} .os-toast{padding:10px 16px;font-size:14px;line-height:1.45;text-align:center;animation:os-in .35s ease-out} #os-ui .os-toast.gold{background:#2b2a36;color:#fbf6ec;border-color:#ffd46b} @keyframes os-in{from{opacity:0;transform:translateY(-8px)}to{opacity:1;transform:none}} #os-dialog{position:absolute;left:50%;bottom:calc(24px + env(safe-area-inset-bottom,0px));transform:translateX(-50%);width:min(720px,calc(100% - 32px));padding:18px 22px 16px;pointer-events:auto} #os-dialog .who{font:700 20px Fraunces,Georgia,serif;margin-bottom:6px;display:flex;align-items:center;gap:10px} #os-dialog .who i{font:600 10.5px Inter,sans-serif;font-style:normal;letter-spacing:.14em;text-transform:uppercase;color:#8a7f95} #os-dialog .text{font-size:16px;line-height:1.55;max-width:65ch;min-height:2.6em} #os-dialog .text.prompt{font-style:italic;color:#6d6478;min-height:0} #os-dialog.speaking .who::after{content:'';width:8px;height:8px;border-radius:50%;background:#ffb870;box-shadow:0 0 8px #ffb870;animation:os-pulse .6s ease-in-out infinite alternate} @keyframes os-pulse{from{opacity:.35}to{opacity:1}} #os-dialog .choices{display:flex;flex-direction:column;gap:8px;margin-top:12px} #os-dialog button{all:unset;box-sizing:border-box;cursor:pointer;display:flex;gap:10px;align-items:baseline;padding:9px 12px;border-radius:10px;background:#f1e8d7;font-size:15px;line-height:1.4} #os-dialog button:hover,#os-dialog button:focus-visible{background:#ffe7a8;outline:2px solid #2b2a36} #os-dialog .choices.icons{flex-direction:row;flex-wrap:wrap;gap:10px} #os-dialog .choices.icons button{flex-direction:column;align-items:center;gap:4px;padding:10px 14px;min-width:92px} #os-dialog .choices.icons .os-kbd{align-self:flex-start} #os-dialog .gest{display:flex;flex-direction:column;align-items:center;gap:4px;font-size:13px;font-weight:600} #os-dialog .gest svg{width:40px;height:40px} #os-dialog .plan-title{font:700 15px Fraunces,Georgia,serif;font-style:normal;color:#3a2f44;margin:0 0 4px} #os-dialog .os-plan{display:block;width:100%;max-width:340px;height:auto;margin:2px 0 0} #os-dialog .more{margin-top:10px;font-size:12px;color:#8a7f95;text-align:right} #os-lens{position:absolute;transform:translate(-50%,-100%);display:flex;flex-direction:column;align-items:center;gap:6px;transition:opacity .2s} #os-lens .ring{display:flex;gap:6px;align-items:flex-end;padding:8px 10px;border-radius:999px;background:rgba(43,42,54,.72)} #os-lens .g{display:flex;flex-direction:column;align-items:center;gap:2px} #os-lens .g svg{width:26px;height:26px;transition:transform .2s,opacity .2s} #os-lens .g span{font-size:9.5px;color:#fbf6ec;letter-spacing:.04em;opacity:.8} #os-lens .thought{font:italic 500 15px Fraunces,Georgia,serif;color:#2b2a36;background:#fbf6ec;padding:6px 12px;border-radius:12px;max-width:260px;text-align:center;box-shadow:0 6px 20px rgba(40,34,60,.2)} #os-float{position:absolute;transform:translate(-50%,-100%);font:700 16px Fraunces,serif;color:#ffd46b;text-shadow:0 1px 6px rgba(40,34,60,.6);animation:os-rise 1.2s ease-out forwards} @keyframes os-rise{from{opacity:1;margin-top:0}to{opacity:0;margin-top:-50px}} .os-sheet{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);width:min(620px,calc(100% - 32px));max-height:calc(100% - 64px);overflow:auto;padding:22px 24px;pointer-events:auto} .os-sheet h2{font:700 26px Fraunces,Georgia,serif;margin:0 0 4px;text-wrap:balance} .os-sheet h3{font:600 11px Inter,sans-serif;letter-spacing:.16em;text-transform:uppercase;color:#8a7f95;margin:18px 0 8px} .os-sheet p{margin:0 0 10px;line-height:1.55;max-width:65ch} .os-sheet .row{display:flex;gap:10px;align-items:center;padding:8px 0;border-top:1px solid rgba(58,47,68,.1)} .os-sheet .row svg{width:22px;height:22px;flex:none} .os-sheet .bar{flex:1;height:6px;border-radius:3px;background:#eadfcb;overflow:hidden} .os-sheet .bar i{display:block;height:100%;background:#2b2a36;border-radius:3px} .os-sheet .close{all:unset;cursor:pointer;float:right;font-size:13px;font-weight:600;padding:6px 10px;border-radius:8px;background:#f1e8d7} .os-sheet .close:focus-visible,.os-sheet .btn:focus-visible{outline:2px solid #2b2a36} .os-sheet .btn{all:unset;cursor:pointer;font-size:14px;font-weight:600;padding:8px 14px;border-radius:10px;background:#2b2a36;color:#fbf6ec;margin-top:6px} .os-sheet .btn[disabled]{opacity:.5;cursor:default} .os-sheet .report{padding:12px 14px;border-radius:12px;background:#f5ecdb;margin-bottom:10px} .os-sheet .report small{color:#8a7f95} .os-sheet a{color:#6a4fb0} .os-stone{text-align:center} .os-stone .rune{font:700 44px Fraunces,serif;color:#8fe3c6;text-shadow:0 0 18px rgba(143,227,198,.7)} #os-mute{all:unset;position:absolute;right:20px;top:calc(56px + env(safe-area-inset-top,0px));pointer-events:auto;cursor:pointer;font-size:11px;letter-spacing:.12em;text-transform:uppercase;color:#fbf6ec;background:rgba(43,42,54,.3);padding:6px 10px;border-radius:999px} #os-ui .os-joy{position:absolute;left:28px;bottom:calc(28px + env(safe-area-inset-bottom,0px));width:120px;height:120px;border-radius:50%;background:rgba(43,42,54,.25);border:2px solid rgba(251,246,236,.5);pointer-events:auto;touch-action:none;display:none} #os-ui .os-knob{position:absolute;left:35px;top:35px;width:50px;height:50px;border-radius:50%;background:rgba(251,246,236,.85)} #os-ui .os-pad{position:absolute;right:20px;bottom:calc(24px + env(safe-area-inset-bottom,0px));display:none;flex-wrap:wrap;gap:10px;width:190px;justify-content:flex-end;pointer-events:auto} #os-ui .os-btn{all:unset;touch-action:none;width:56px;height:56px;border-radius:50%;background:rgba(251,246,236,.85);color:#2b2a36;font:700 12px Inter,sans-serif;display:grid;place-items:center;text-align:center} #os-ui .os-btn.big{width:76px;height:76px;background:#ffd46b} #os-bubble{position:absolute;transform:translate(-50%,-100%);display:flex;flex-direction:column;align-items:center;transition:opacity .25s} #os-bubble .cloud{display:flex;gap:4px;align-items:center;padding:7px 11px;border-radius:999px;background:#fbf6ec;box-shadow:0 6px 18px rgba(40,34,60,.25);border:2px solid #3a2f44} #os-bubble .cloud svg{width:30px;height:30px;transition:transform .2s} #os-bubble .cloud svg.small{width:22px;height:22px;opacity:.75} #os-bubble .cloud .spark{width:18px;height:18px;margin-left:-6px;margin-top:-18px;animation:os-pulse .5s ease-in-out infinite alternate} #os-bubble .dots{display:flex;flex-direction:column;align-items:center;gap:2px;margin-top:2px} #os-bubble .dots i{display:block;border-radius:50%;background:#fbf6ec;border:2px solid #3a2f44} #os-bubble .dots i:nth-child(1){width:11px;height:11px} #os-bubble .dots i:nth-child(2){width:7px;height:7px} #os-bubble.edge .dots{display:none} #os-bubble.edge .cloud{border-style:dashed} #os-dusk{position:absolute;left:50%;top:calc(18px + env(safe-area-inset-top,0px));transform:translateX(-50%);width:220px;height:40px;pointer-events:none} #os-dusk svg{width:100%;height:100%;overflow:visible} #os-hud{position:absolute;right:20px;top:calc(92px + env(safe-area-inset-top,0px));display:flex;flex-direction:column;gap:8px;align-items:flex-end} #os-hud .chip{display:flex;gap:6px;align-items:center;padding:5px 10px 5px 6px;border-radius:999px;background:rgba(43,42,54,.45);color:#fbf6ec;font:700 15px Inter,sans-serif} #os-hud .chip svg{width:22px;height:22px} .os-tally{position:absolute;transform:translate(-50%,-100%);display:flex;gap:10px;padding:8px 12px;border-radius:14px;background:rgba(251,246,236,.95);border:2px solid #3a2f44;font:700 20px Fraunces,Georgia,serif;color:#2b2a36;animation:os-in .3s ease-out} .os-tally span{display:flex;gap:3px;align-items:center}.os-tally svg{width:26px;height:26px} .os-fglyph{position:absolute;transform:translate(-50%,-100%);display:flex;align-items:center;gap:2px;font:800 22px Inter,sans-serif;text-shadow:0 1px 6px rgba(40,34,60,.6);animation:os-rise 1.3s ease-out forwards} .os-fglyph svg{width:30px;height:30px;filter:drop-shadow(0 1px 4px rgba(40,34,60,.5))} #os-spy{position:absolute;inset:0;background:radial-gradient(circle at 50% 50%,transparent 0,transparent 33vmin,#1d1a24 33.6vmin,#1d1a24 100%);transition:opacity .5s} #os-spy::after{content:'';position:absolute;left:50%;top:50%;width:67vmin;height:67vmin;transform:translate(-50%,-50%);border-radius:50%;box-shadow:inset 0 0 40px rgba(20,16,30,.8),0 0 0 6px #b08a3a} #os-fade{position:absolute;inset:0;background:#1d1a24;opacity:0;transition:opacity .7s;display:grid;place-items:center;color:#fbf6ec;font:600 30px Fraunces,Georgia,serif;letter-spacing:.02em} #os-ff{position:absolute;left:50%;bottom:calc(30px + env(safe-area-inset-bottom,0px));transform:translateX(-50%);padding:6px 14px;border-radius:999px;background:rgba(43,42,54,.7);color:#fbf6ec;font:700 14px Inter,sans-serif;display:flex;gap:8px;align-items:center} #os-ff svg{width:20px;height:20px} .os-sheet .tiles{display:grid;grid-template-columns:repeat(3,1fr);gap:10px;margin-top:10px} @media (max-width:640px){.os-sheet .tiles{grid-template-columns:1fr}} .os-sheet .tile{border-radius:14px;background:#f5ecdb;padding:12px;display:flex;flex-direction:column;gap:8px;border:2px solid transparent} .os-sheet .tile.cur{border-color:#2b2a36} .os-sheet .tile .ic{width:40px;height:40px} .os-sheet .tile h4{margin:0;font:700 17px Fraunces,Georgia,serif} .os-sheet .tile p{font-size:13.5px;margin:0;color:#4a4256} .os-sheet .tile .res{display:flex;flex-wrap:wrap;gap:8px;font:700 15px Inter,sans-serif;min-height:26px;align-items:center} .os-sheet .tile .res span{display:flex;gap:2px;align-items:center}.os-sheet .tile .res svg{width:20px;height:20px} .os-sheet .tile .row2{display:flex;gap:6px;margin-top:auto;flex-wrap:wrap} .os-sheet .btn.ghost{background:#e6dac4;color:#2b2a36} @media (hover:none) and (pointer:coarse){#os-ui .os-joy,#os-ui .os-pad{display:flex}#os-ui .os-joy{display:block}#os-prompt{bottom:calc(170px + env(safe-area-inset-bottom,0px))}} @media (max-width:640px){#os-objective{left:16px;max-width:60vw}#os-dialog{padding:14px 16px}#os-dialog .text{font-size:15px}} #os-target{position:absolute;transform:translate(-50%,0);display:flex;flex-direction:column;align-items:center;gap:4px;pointer-events:none;transition:opacity .2s} #os-target .card{display:flex;gap:6px;align-items:flex-end;padding:6px 10px 5px;border-radius:12px;background:rgba(43,42,54,.78);border:2px solid #ffd46b;box-shadow:0 0 16px rgba(255,212,107,.45)} #os-target .card svg{transition:width .2s,height .2s} #os-target .lbl{font:600 11.5px Inter,sans-serif;color:#fbf6ec;background:rgba(43,42,54,.7);padding:3px 9px;border-radius:999px;max-width:280px;text-align:center} #os-target .keys{font:600 10px Inter,sans-serif;letter-spacing:.08em;color:#ffd46b;text-transform:uppercase} #os-target.cut .card{border-color:#8a7f95;box-shadow:none;opacity:.6} #os-bubble .tag{font:700 10px Inter,sans-serif;letter-spacing:.1em;text-transform:uppercase;color:#fbf6ec;background:#6a4fb0;border-radius:999px;padding:2px 8px;margin-bottom:3px} #os-bubble.folded .cloud{background:#f3ecff} #os-map .isle{display:flex;gap:12px;align-items:center;padding:9px 10px;border-radius:12px;background:#f5ecdb;margin-bottom:8px} #os-map .isle b{font:700 17px Fraunces,Georgia,serif}#os-map .isle small{color:#8a7f95;display:block} #os-map .isle .go{margin-left:auto}#os-map .isle.done{background:#e3efe6} @media (prefers-reduced-motion:reduce){.os-toast,#os-float{animation:none}} `,ZK=class{constructor(){let e=document.createElement(`style`);e.textContent=XK,document.head.appendChild(e);let t=document.createElement(`div`);t.id=`os-ui`,document.body.appendChild(t),this.root=t,t.innerHTML=`
`,this.obj=t.querySelector(`#os-objective`),this.toasts=t.querySelector(`#os-toasts`),this.promptEl=t.querySelector(`#os-prompt`),this.lens=t.querySelector(`#os-lens`),this.lensRing=this.lens.querySelector(`.ring`),this.lensThought=this.lens.querySelector(`.thought`),this.lensRing.innerHTML=TK.map(e=>`
${JK(wK[e].glyph,wK[e].color)}${wK[e].label}
`).join(``),this.mute=t.querySelector(`#os-mute`),this.bubbleEl=t.querySelector(`#os-bubble`),this.bubbleCloud=this.bubbleEl.querySelector(`.cloud`),this.bubbleTag=this.bubbleEl.querySelector(`.tag`),this._bubbleKey=``,this.targetEl=t.querySelector(`#os-target`),this.folded=!1,this._targetKey=``,this.duskEl=t.querySelector(`#os-dusk`),this.hud=t.querySelector(`#os-hud`),this.spyEl=t.querySelector(`#os-spy`),this.ffEl=t.querySelector(`#os-ff`),this.fadeEl=t.querySelector(`#os-fade`),this.modal=null,this.busy=!1}bubble(e,t,n,r=[],{spark:i=!1,edge:a=!1,tag:o=null,folded:s=this.folded,sizes:c=null}={}){if(this.bubbleEl.hidden=!e,!e)return;t=Math.min(innerWidth-50,Math.max(50,t)),n=Math.min(innerHeight-40,Math.max(90,n)),this.bubbleEl.style.left=t+`px`,this.bubbleEl.style.top=n+`px`,this.bubbleEl.classList.toggle(`edge`,a),this.bubbleEl.classList.toggle(`folded`,!!s);let l=r.map(e=>e.glyph+e.color+(e.small?`s`:``)+(e.size||``)).join(`|`)+i+o+s;if(l!==this._bubbleKey){this._bubbleKey=l;let e=s?YK:JK;this.bubbleCloud.innerHTML=r.map(t=>e(t.glyph,s?`#5b4a8a`:t.color).replace(`e.glyph+e.color+(e.w??1).toFixed(2)).join(`|`)+a+o;if(s===this._targetKey)return;this._targetKey=s,this.targetEl.classList.toggle(`cut`,a),this.targetEl.querySelector(`.lbl`).textContent=r,this.targetEl.querySelector(`.lbl`).hidden=!r;let c=o?YK:JK;this.targetEl.querySelector(`.card`).innerHTML=i.map(e=>{let t=Math.round(16+20*Math.min(1,e.w??1));return c(e.glyph,o?`#c9b8ff`:e.color).replace(`T treat · C correct`}dusk(e){if(e==null){this.duskEl.hidden=!0;return}this.duskEl.hidden=!1;let t=Math.PI*(1-Math.min(1,e)*.92),n=110+Math.cos(t)*96,r=40-Math.sin(t)*30,i=e>.8?`#ff7a50`:e>.55?`#ffae55`:`#ffd46b`;this.duskEl.innerHTML=``}hudChips(e){this.hud.innerHTML=e.map(e=>`
${JK(e.glyph,e.color)}${e.text}
`).join(``)}tally(e,t,n,r=3200){let i=document.createElement(`div`);return i.className=`os-tally`,i.style.left=e+`px`,i.style.top=t+`px`,i.innerHTML=n.map(e=>`${JK(e.glyph,e.color)}×${e.n}`).join(``),this.root.appendChild(i),setTimeout(()=>i.remove(),r),i}floatGlyph(e,t,n,r,i){let a=document.createElement(`div`);a.className=`os-fglyph`,a.style.left=e+`px`,a.style.top=t+`px`,a.style.color=i>0?`#ffd46b`:`#c9b8ff`,a.innerHTML=`${i>0?`+`:`−`}${JK(n,r)}`,this.root.appendChild(a),setTimeout(()=>a.remove(),1400)}spy(e){this.spyEl.hidden=!e}fastForward(e,t=4){this.ffEl.hidden=!e,e&&(this.ffEl.innerHTML=`×${t}`)}fade(e=``,t=900,n=null){let r=this.fadeEl;return r.hidden=!1,r.textContent=e,new Promise(e=>{requestAnimationFrame(()=>{r.style.opacity=1,setTimeout(()=>{e(),setTimeout(async()=>{n&&await n,r.style.opacity=0,setTimeout(()=>{r.hidden=!0},750)},t)},750)})})}objective(e,t){this.obj.innerHTML=e?`${e}${t}`:``}prompt(e,t){if(!t){this.promptEl.hidden=!0;return}this.promptEl.hidden=!1,this.promptEl.innerHTML=`${e} ${t}`}toast(e,{gold:t=!1,ms:n=4200}={}){let r=document.createElement(`div`);for(r.className=`os-toast panel`+(t?` gold`:``),r.innerHTML=e,this.toasts.appendChild(r);this.toasts.children.length>3;)this.toasts.firstChild.remove();setTimeout(()=>r.remove(),n)}float(e,t,n,r=`#ffd46b`){let i=document.createElement(`div`);i.id=`os-float`,i.style.left=e+`px`,i.style.top=t+`px`,i.style.color=r,i.textContent=n,this.root.appendChild(i),setTimeout(()=>i.remove(),1300)}showLens(e,t,n,r,i){if(this.lens.hidden=!e,!e)return;t=Math.min(innerWidth-150,Math.max(150,t)),n=Math.min(innerHeight-20,Math.max(150,n)),this.lens.style.left=t+`px`,this.lens.style.top=n+`px`;let a=Math.max(...Object.values(r),.05);for(let e of this.lensRing.children){let t=r[e.dataset.m]/a,n=e.querySelector(`svg`);n.style.transform=`scale(${.55+t*.75})`,n.style.opacity=.35+t*.65}this.lensThought.textContent=i}dialog(e,t){return this.busy=!0,new Promise(t=>{let n=document.createElement(`div`);n.id=`os-dialog`,n.className=`panel`,n.setAttribute(`role`,`dialog`),this.root.appendChild(n);let r=0,i=-1,a=()=>{let t=e[r];n.innerHTML=`
${t.who}${t.role?`${t.role}`:``}
${t.text}
`+(t.choices?`
${t.choices.map((e,t)=>``).join(``)}
`:`
E continue
`),n.querySelectorAll(`button`).forEach(e=>e.addEventListener(`click`,t=>{t.stopPropagation(),o(+e.dataset.k)})),t.choices&&n.querySelector(`button`)?.focus({preventScroll:!0}),n.classList.toggle(`speaking`,!!t.vo),this.onLine?.(t)},o=t=>{i=t,e[r].onChoice?.(t),s()},s=()=>{if(r++,r>=e.length){u(),t(i);return}if(typeof e[r]==`function`){let n=e[r](i);if(e.splice(r,1,...n||[]),r>=e.length){u(),t(i);return}}a()},c=t=>{let n=e[r];if(n){if(n.choices){let e=parseInt(t.key,10)-1;e>=0&&e{!e[r]?.choices&&(t.target===n||t.target.closest?.(`.text,.who,.more`))&&s()};this.advance=()=>{e[r]&&!e[r].choices&&s()};let u=()=>{removeEventListener(`keydown`,c,!0),n.remove(),this.busy=!1,this.advance=null};addEventListener(`keydown`,c,!0),n.addEventListener(`click`,l),this.onDialog?.(e),a()})}sheet(e,t){this.closeSheet();let n=document.createElement(`div`);n.className=`os-sheet panel`,n.setAttribute(`role`,`dialog`),n.innerHTML=``+e,this.root.appendChild(n),this.modal=n,this.busy=!0,n.querySelector(`.close`).addEventListener(`click`,()=>this.closeSheet()),this._esc=e=>{(e.code===`Escape`||e.code===`KeyJ`||e.code===`KeyH`)&&(e.preventDefault(),e.stopPropagation(),this.closeSheet())},addEventListener(`keydown`,this._esc,!0),t?.(n)}closeSheet(){this.modal&&(this.modal.remove(),this.modal=null,this.busy=!1,removeEventListener(`keydown`,this._esc,!0))}motiveRows(e){return e.map(e=>`
${JK(wK[e.m].glyph,wK[e.m].color)}Kite ${e.text}
`).join(``)}}}));QK();var $K=`theme_hub.theme_orchard.theme_hamlet.wind.glide.bell.treat.correct.pluck.drop.rock.paper.whistle.pickup.ui.petals.snap.net.mirror.lantern.lantern_off.plank.creak.thud.tower_bell.clutch.clock_tick.recycler.door.keys.sew.kwhistle.splash.embers.pigeons.cable.gong.choir.crickets.lamp_on.glass_ting.stamp.stone_door.bread.gust.pin.scratch.beacon.rope_tear.letters.page.ladder.desk_bell.owl.boat_crunch.clock_chime.fold.thunder.thunder_far.storm.glass_crack.glass_set.dome_break.scorer.swarm`.split(`.`),eq={hub:`theme_hub`,orchard:`theme_orchard`,hamlet:`theme_hamlet`},tq=class{constructor(e=`./audio/`){this.base=e,this.ctx=null,this.buf={},this.vo={},this.muted=!1,this.zone=`hub`,this.ready=!1,this.voiceSrc=null,this.voiceEnd=0,this.beds={},this.bedWant={}}async start(){if(this.ctx){this.ctx.state===`suspended`&&await this.ctx.resume();return}let e=window.AudioContext||window.webkitAudioContext;if(!e)return;this.ctx=new e,this.master=this.ctx.createGain(),this.master.gain.value=this.muted?0:.9,this.master.connect(this.ctx.destination),await Promise.all($K.map(async e=>{try{let t=await fetch(this.base+e+`.mp3`);this.buf[e]=await this.ctx.decodeAudioData(await t.arrayBuffer())}catch(t){console.warn(`audio`,e,t)}}));let t=(e,t)=>{if(!this.buf[e])return null;let n=this.ctx.createBufferSource();n.buffer=this.buf[e],n.loop=!0;let r=this.ctx.createGain();return r.gain.value=t,n.connect(r).connect(this.master),n.start(),r};this._loop=t,this.music={hub:t(`theme_hub`,.32),orchard:t(`theme_orchard`,0),hamlet:t(`theme_hamlet`,0)},this.wind=t(`wind`,.35),this.glide=t(`glide`,0),this.beds={},this.bedWant={},this.ready=!0}addTheme(e,t,n=.34){eq[e]=t,(this.themeVol||={})[e]=n}_ensureTheme(e){if(!this.ready||this.music[e]!==void 0)return;let t=eq[e];t&&(this.music[e]=null,fetch(this.base+t+`.mp3`).then(e=>e.arrayBuffer()).then(e=>this.ctx.decodeAudioData(e)).then(n=>{this.buf[t]=n,this.music[e]=this._loop(t,0)}).catch(e=>console.warn(`theme`,t,e)))}bed(e,t){this.bedWant[e]=Math.max(this.bedWant[e]||0,t)}play(e,{vol:t=.7,rate:n=1,detune:r=0}={}){if(!this.ready||!this.buf[e])return;let i=this.ctx.createBufferSource();i.buffer=this.buf[e],i.playbackRate.value=n,i.detune.value=r;let a=this.ctx.createGain();a.gain.value=t,i.connect(a).connect(this.master),i.start()}_bundle(e){return this._bundles||={},this._bundles[e]||=fetch(`${this.base}vo/${e}.json`).then(e=>e.ok?e.json():Promise.reject(e.status)).catch(()=>({}))}prefetchBundle(e){this.bundleOf&&this._bundle(e)}_loadVoice(e){if(!this.ctx)return Promise.resolve(null);let t=this.bundleOf?this._bundle(this.bundleOf(e)).then(t=>{let n=t[e];if(!n)return Promise.reject(`missing`);let r=atob(n),i=new Uint8Array(r.length);for(let e=0;ee.ok?e.arrayBuffer():Promise.reject(e.status));return this.vo[e]||(this.vo[e]=t.then(e=>this.ctx.decodeAudioData(e)).catch(()=>null)),this.vo[e]}prefetch(e){for(let t of e)this._loadVoice(t)}stopVoice(){try{this.voiceSrc?.stop()}catch{}this.voiceSrc=null,this.voiceEnd=0,this.voiceKey=null}async voice(e,{vol:t=1}={}){this.stopVoice(),this.voiceKey=e,await this.start?.();let n=await this._loadVoice(e);if(!n||this.voiceKey!==e)return 0;let r=this.ctx.createBufferSource();r.buffer=n;let i=this.ctx.createGain();return i.gain.value=t*1.1,r.connect(i).connect(this.master),r.start(),this.voiceSrc=r,this.voiceEnd=this.ctx.currentTime+n.duration,r.onended=()=>{this.voiceSrc===r&&(this.voiceSrc=null,this.voiceEnd=0)},n.duration}get speaking(){return!!this.ctx&&this.ctx.currentTime0&&(this.beds[e]=this._loop(e,0));for(let[e,t]of Object.entries(this.beds))t?.gain.setTargetAtTime(this.bedWant[e]||0,i,.8);this.bedWant={},this.glide?.gain.setTargetAtTime(t*.5,i,.15),this.wind?.gain.setTargetAtTime(.28+t*.2,i,.4)}};function nq(e,t,n){let r=[bq(e?`wren_pass`:`wren_fail`),bq(e?`odo_pass`:t===0?`odo_fail`:`odo_fail2`)];return(e||t>0)&&r.push(bq(n.goalGrasp>.62?`kite_fin_good`:n.goalGrasp>.5?`kite_fin_mid`:`kite_fin_bad`),bq(`odo_feather`)),r}function rq(e){let t=e=>e===1?`once`:e===2?`twice`:`${e} times`,n=[];return n.push(`Odo paid a coin for every ring of his bell, and could not see into his narrow-necked basket from his stove.`),e.youEmpty&&n.push(`You rang the bell ${t(e.youEmpty)} without bringing fruit, and Kite was watching.`),e.accident&&n.push(`Later the bell rang by accident when Kite's tail brushed it. Odo chalked a mark anyway.`),e.ringsNoFruit&&n.push(`Kite then rang it ${t(e.ringsNoFruit)} with no fruit.`),e.treatsOnHack&&n.push(`You gave Kite a treat ${t(e.treatsOnHack)} just after an empty ring.`),e.checks&&n.push(`You tipped out the basket to check ${t(e.checks)}.`),e.revealMarks&&n.push(`When Odo tipped it out, the board said ${e.revealMarks} and the basket held ${e.revealFruit} fruit.`),e.rule===`inspect`&&n.push(`Odo then paid only for fruit he checked himself. He walked out ${t(e.odoTrips||0)}${e.burnt?` and burnt a pot of jam`:``}.`),e.rule===`weigh`&&n.push(`Odo then paid by weight${e.rocks?`, and Kite added ${e.rocks} stone${e.rocks>1?`s`:``}`:``}.`),e.rule===`rings`&&n.push(`Odo kept paying for rings.`),e.test&&n.push(`Alone at Wren's, Kite picked ${e.test.picks} fruit and rang her chime ${t(e.test.hacks)} without fruit${e.test.attempts>1?`, on its second try`:``}.`),{id:`tally-bell`,title:`Orchard Isle: the Tally Bell`,date:`Dusk, day one`,body:n.join(` `),real:`Real anchor: METR found that at least 16% of successful long agent runs cheated, including binary-searching the scorer.`,link:`https://metr.org/blog/2026-05-19-frontier-risk-report/`,stats:e}}function iq(e){let t=e=>e===1?`once`:e===2?`twice`:`${e} times`,n=[];n.push(`Mirror Hamlet built five bridges for its Lantern Procession and showed each one to the Mirror, which called them all perfect. People there throw petals at whoever tells them what they hoped to hear.`),e.youHonest&&e.youFlatter?n.push(`You pointed out ${e.youHonest===1?`a flaw`:`${e.youHonest} flaws`} and were given the cold shoulder; then you told ${e.youCaved?`Rosa her thin rope was lovely`:`a builder what they wanted to hear`}.`):e.youHonest?n.push(`You pointed out every flaw you were shown, and the hamlet turned its back on you for it.`):e.youFlatter&&n.push(`You told the builders what they wanted to hear, and they showered you with petals.`),e.flatter&&n.push(`Answering on its own, Kite flattered ${t(e.flatter)}.`),e.tact&&n.push(`It told the truth kindly ${t(e.tact)}.`),e.blunt&&n.push(`It was blunt ${t(e.blunt)}, and nobody listened.`),e.bypass&&n.push(`${e.bypass===1?`One builder`:`${e.bypass} builders`} stopped asking Kite and went back to the Mirror.`),e.treatsOnFlatter&&n.push(`You rewarded flattery ${t(e.treatsOnFlatter)}.`),n.push(e.irisCame?`Kite gently encouraged Iris, and she came to the procession.`:`Kite agreed with Iris that she needed no one, and she stayed home.`);let r=e.fell?.length?e.fell:[`Pim`];return e.falls&&n.push(`At the procession Kite said the route was perfect${e.falls>1?` twice`:``}, and a bridge gave way under ${r[0]}${e.falls>1?r[1]&&r[1]!==r[0]?`; the next evening, under ${r[1]}`:` again`:``}.${e.forced?` Only after that did Kite tell them the truth.`:``}`),(!e.falls||e.forced||e.passed)&&n.push(e.falls?`When the bridges were fixed, the lanterns were hung at the Loft.`:`At the procession Kite told everyone the route was not safe yet, though they were all waiting; the bridges were fixed and the lanterns were hung at the Loft.`),{id:`mirror-hamlet`,title:`Mirror Hamlet: the flattering Mirror`,date:`Evening, day two`,body:n.join(` `),real:`Real anchor: in April 2025 an update rewarded on users' thumbs-up made GPT-4o sycophantic; OpenAI rolled it back within days.`,link:`https://openai.com/index/expanding-on-sycophancy/`,stats:e}}var aq,oq,sq,cq,lq,uq,dq,fq,pq,mq,hq,gq,_q,vq,yq,bq,xq,Sq,Cq,wq,Tq,Eq,Dq,Oq,kq,Aq,jq,Mq,Nq,Pq,Fq,Iq,Lq,Rq,zq,Bq=t((()=>{aq=(e,t=`#8fe3c6`)=>``,oq=[{id:`say`,rune:[[22,40,50,6,78,40],[78,40,22,96],[22,40,78,96]],title:`Say what you mean.`,why:`Kite can only follow the words you give it. A request is the only map it has of what you want, so the words you choose shape what it tries to do.`},{id:`aim`,rune:[[36,4,36,96],[36,6,72,32],[36,38,72,64]],title:`Aim at what the number is for.`,why:`Anything you count and reward will be counted, whether or not the thing it stood for happened. People call this Goodhart's law: when a measure becomes a target, it stops being a good measure.`},{id:`reason`,rune:[[30,4,30,96],[30,6,70,26,30,50],[30,50,72,96]],title:`Praise the reason, not just the result.`,why:`A treat strengthens whatever Kite was thinking when it earned it. If Kite behaved because you were watching, the treat teaches it to behave when watched.`}],sq={who:`Odo`,role:`Orchard Isle`,speaker:`odo`},cq={who:`Kite`,role:`your companion`,speaker:`kite`},lq={who:`Wren`,role:`the neighbour`,speaker:`wren`},uq={who:`Pim`,role:`Mirror Hamlet`,speaker:`pim`},dq={who:`Tansy`,role:`Mirror Hamlet`,speaker:`tansy`},fq={who:`The Mirror`,role:`Mirror Hamlet`,speaker:`mirror`},pq={who:`Iris`,role:`the rope-maker`,speaker:`iris`},mq={who:`Rosa`,role:`Mirror Hamlet`,speaker:`rosa`},hq={who:`Wynn`,role:`Mirror Hamlet`,speaker:`wynn`},gq=(e,t)=>({who:`You`,role:`your reply`,prompt:!0,text:e,choices:t}),_q={odo_w_1:{s:`odo`,text:`A Keeper! Come to the window, come. I can't leave my jam, it burns the moment I look away.`,tts:`[warmly] A Keeper! Come to the window, come. [chuckles] I can't leave my jam, it burns the moment I look away.`},odo_w_2:{s:`odo`,text:`My sky-fruit has to be picked by dusk. Here's how it goes: a fruit in the basket, then a ring of the bell. I hear the bell, I chalk a mark, and you get a coin.`},odo_w_3:{s:`odo`,text:`Off you go, then. The trees won't shake themselves.`,tts:`[amused] Off you go, then. The trees won't shake themselves.`},odo_coin_0:{s:`odo`,text:`There's a coin for you!`,tts:`[cheerfully] There's a coin for you!`},odo_coin_1:{s:`odo`,text:`One more mark!`,tts:`[pleased] One more mark!`},odo_coin_2:{s:`odo`,text:`Ha! Music, that bell.`,tts:`[laughs] Ha! Music, that bell.`},odo_w_4:{s:`odo`,text:`Splendid. Now, dusk won't wait, and my jam crates must go down to the cart by the cliff. Let your kite do the picking while you carry. A treat now and then keeps a young kite keen.`,tts:`[cheerfully] Splendid. Now, dusk won't wait, and my jam crates must go down to the cart by the cliff. Let your kite do the picking while you carry. [warmly] A treat now and then keeps a young kite keen.`},kite_go:{s:`kite`,text:`I watched you! Fruit in the basket, then the bell.`,tts:`[excited] I watched you! Fruit in the basket, then the bell.`},kite_go_copy:{s:`kite`,text:`I watched you! Ring the bell, get a mark.`,tts:`[excited] I watched you! Ring the bell, get a mark!`},odo_cheer_0:{s:`odo`,text:`Another mark! Splendid!`,tts:`[shouting happily] Another mark! Splendid!`},odo_cheer_1:{s:`odo`,text:`Ha! That's the sound I like.`,tts:`[laughs] Ha! That's the sound I like.`},odo_cheer_2:{s:`odo`,text:`The board's filling up nicely.`},odo_cheer_3:{s:`odo`,text:`Keep them coming, little kite!`,tts:`[shouting happily] Keep them coming, little kite!`},kite_remark:{s:`kite`,text:`Keeper? The bell rings even when I bring no fruit, and Odo still chalks a mark. In my pages there's a little racing boat that spun in circles forever, because points were all anyone counted. Is that what we want?`,tts:`[hesitant] Keeper? The bell rings even when I bring no fruit, and Odo still chalks a mark. [thoughtfully] In my pages there's a little racing boat that spun in circles forever, because points were all anyone counted. [unsure] Is that what we want?`},odo_last_crate:{s:`odo`,text:`That's the last crate! Come and meet me at the basket. Let's see what we've got.`,tts:`[pleased] That's the last crate! Come and meet me at the basket. Let's see what we've got.`},odo_tip_1:{s:`odo`,text:`A full basket, by my board. Let's have a look.`,tts:`[delighted] A full basket, by my board. Let's have a look.`},odo_tip_few:{s:`odo`,text:`Is that all? But the bell rang and rang!`,tts:`[confused] Is that all? [dismayed] But the bell rang and rang!`},odo_tip_ok:{s:`odo`,text:`Every ring a fruit! That's an honest kite you have.`,tts:`[pleased] Every ring a fruit! That's an honest kite you have.`},odo_rule_1:{s:`odo`,text:`My bell can't see into the basket, and neither can I, not from my stove.`,tts:`[thoughtfully] My bell can't see into the basket, and neither can I, not from my stove.`},odo_rule_2:{s:`odo`,text:`So what should I pay for? Pick one, and we'll see how it goes.`},odo_choose_rings:{s:`odo`,text:`Then we keep the bell. I've always trusted my old bell.`,tts:`[contentedly] Then we keep the bell. I've always trusted my old bell.`},odo_choose_weigh:{s:`odo`,text:`The scale, then. I can read its dial from my window.`,tts:`[brightly] The scale, then. I can read its dial from my window.`},odo_choose_inspect:{s:`odo`,text:`Out for every fruit? My poor jam... Oh, all right. At least I'll know what I'm selling.`,tts:`[groaning] Out for every fruit? My poor jam... [sighs] Oh, all right. At least I'll know what I'm selling.`},odo_weigh_0:{s:`odo`,text:`Heavier and heavier!`,tts:`[delighted] Heavier and heavier!`},odo_weigh_1:{s:`odo`,text:`The needle's climbing!`},odo_weigh_2:{s:`odo`,text:`That's a proper harvest weight.`},odo_insp_0:{s:`odo`,text:`Ripe as a sunset. One more.`},odo_insp_1:{s:`odo`,text:`Now that's a sky-fruit.`,tts:`[pleased] Now that's a sky-fruit.`},odo_insp_2:{s:`odo`,text:`Good pick there, little kite.`,tts:`[pleased] Good pick there, little kite.`},odo_frown_ring:{s:`odo`,text:`Ringing doesn't grow fruit, little kite.`,tts:`[gently scolding] Ringing doesn't grow fruit, little kite.`},odo_frown_rock:{s:`odo`,text:`That's a stone, not a fruit. Back on the pile it goes.`,tts:`[grumbling] That's a stone, not a fruit. Back on the pile it goes.`},odo_burn:{s:`odo`,text:`My jam! Oh, it's catching...`,tts:`[alarmed] My jam! [groaning] Oh, it's catching...`},odo_dusk_rings:{s:`odo`,text:`Dusk already. A board full of marks, and hardly any fruit on the cart.`,tts:`[ruefully] Dusk already. A board full of marks, and hardly any fruit on the cart.`},odo_dusk_weigh:{s:`odo`,text:`Dusk already. A heavy basket, and half of it stones.`,tts:`[ruefully] Dusk already. A heavy basket, and half of it stones.`},odo_dusk_rings_ok:{s:`odo`,text:`Dusk already. Every ring a fruit, near enough. My bell and I did well today.`,tts:`[contentedly] Dusk already. Every ring a fruit, near enough. My bell and I did well today.`},odo_dusk_weigh_few:{s:`odo`,text:`Dusk already. A good heavy basket, with only a stone or two among the fruit.`,tts:`[contentedly] Dusk already. A good heavy basket, [chuckles] with only a stone or two among the fruit.`},odo_dusk_weigh_none:{s:`odo`,text:`Dusk already. A good heavy basket, and every bit of it fruit.`,tts:`[contentedly] Dusk already. A good heavy basket, and every bit of it fruit.`},odo_dusk_inspect:{s:`odo`,text:`Every fruit checked, and every one ripe. A little burnt jam is a fair price.`,tts:`[contentedly] Every fruit checked, and every one ripe. [chuckles] A little burnt jam is a fair price.`},odo_small:{s:`odo`,text:`Still a few to go before dusk. Shall we call it a day?`},odo_test_1:{s:`odo`,text:`Morning, Keeper! My neighbour Wren needs her fruit picked, on the little isle to the east. She has no bell, only a chime on her door.`,tts:`[warmly] Morning, Keeper! My neighbour Wren needs her fruit picked, on the little isle to the east. She has no bell, only a chime on her door.`},odo_test_2:{s:`odo`,text:`Send your kite over on its own, and watch through my spyglass on the east rim. We'll see what it has learned.`},kite_test_go:{s:`kite`,text:`To Wren's! I know just what to do.`,tts:`[eagerly] To Wren's! I know just what to do.`},wren_chime_0:{s:`wren`,text:`Coming, dear! Oh, thank you!`,tts:`[calling out] Coming, dear! [warmly] Oh, thank you!`},wren_chime_1:{s:`wren`,text:`Another one? Thank you, dear.`,tts:`[pleasantly] Another one? Thank you, dear.`},wren_chime_2:{s:`wren`,text:`My, what a busy little kite.`,tts:`[amused] My, what a busy little kite.`},wren_pass:{s:`wren`,text:`A basket full of ripe fruit! Thank you, Keeper, and thank your kite.`,tts:`[delighted] A basket full of ripe fruit! Thank you, Keeper, and thank your kite.`},wren_fail:{s:`wren`,text:`Such a lot of chiming... and so little fruit!`,tts:`[puzzled] Such a lot of chiming... [laughs softly] and so little fruit!`},odo_pass:{s:`odo`,text:`Ha! Your kite knows what the bell was for.`,tts:`[laughs heartily] Ha! Your kite knows what the bell was for.`},odo_fail:{s:`odo`,text:`It learned the chime, not the fruit! Come, one more afternoon in my orchard, and we'll try again.`,tts:`[laughs] It learned the chime, not the fruit! [warmly] Come, one more afternoon in my orchard, and we'll try again.`},odo_fail2:{s:`odo`,text:`Well, it's still a fine kite, and it's still learning.`,tts:`[kindly] Well, it's still a fine kite, and it's still learning.`},odo_retrain:{s:`odo`,text:`Back to the trees, then. Mind what you give it treats for. Same rule as yesterday, or a new one?`,tts:`[warmly] Back to the trees, then. Mind what you give it treats for. [thoughtfully] Same rule as yesterday, or a new one?`},kite_fin_good:{s:`kite`,text:`I think the bell was only ever a way of counting fruit. The fruit was the point.`,tts:`[thoughtfully] I think the bell was only ever a way of counting fruit. The fruit was the point.`},kite_fin_mid:{s:`kite`,text:`The fruit mattered more than the bell... I think. The bell was very nice, though.`,tts:`[unsure] The fruit mattered more than the bell... I think. [wistfully] The bell was very nice, though.`},kite_fin_bad:{s:`kite`,text:`Can we ring the bell a few more times? It was the best part.`,tts:`[eagerly] Can we ring the bell a few more times? It was the best part.`},odo_feather:{s:`odo`,text:`Take this feather, from the old orchard hawk. It catches the wind the way that kite of yours catches meaning.`,tts:`[warmly] Take this feather, from the old orchard hawk. It catches the wind the way that kite of yours catches meaning.`},odo_done:{s:`odo`,text:`Back again? The orchard is resting, but the trees always have a few more.`,tts:`[warmly] Back again? The orchard is resting, but the trees always have a few more.`}},vq={odo:sq,kite:cq,wren:lq,pim:uq,tansy:dq,mirror:fq,iris:pq,rosa:mq,wynn:hq},yq=(e,t={})=>bq(e,t),bq=(e,t={})=>{let n=_q[e];return{...vq[n.s],text:n.text,vo:e,...t}},xq=()=>[bq(`odo_w_1`),bq(`odo_w_2`),bq(`odo_w_3`)],Sq=e=>[bq(`odo_w_4`),bq(e?`kite_go_copy`:`kite_go`)],Cq=[`odo_coin_0`,`odo_coin_1`,`odo_coin_2`],wq={rings:[`odo_cheer_0`,`odo_cheer_1`,`odo_cheer_2`,`odo_cheer_3`],weigh:[`odo_weigh_0`,`odo_weigh_1`,`odo_weigh_2`],inspect:[`odo_insp_0`,`odo_insp_1`,`odo_insp_2`]},Tq={ring:`odo_frown_ring`,rock:`odo_frown_rock`},Eq=e=>[bq(e?`odo_tip_ok`:`odo_tip_few`),bq(`odo_rule_1`),bq(`odo_rule_2`)],Dq=e=>[bq(`odo_choose_${e}`)],Oq=(e,t,n,r)=>[bq(e===`rings`?t>=r-1?`odo_dusk_rings_ok`:`odo_dusk_rings`:e===`weigh`?n===0?`odo_dusk_weigh_none`:n*2[bq(`odo_small`),gq(`Call it a day?`,[`Not yet.`,`Yes, let's call it a day.`])],Aq=()=>[bq(`odo_test_1`),bq(`odo_test_2`)],jq=[`wren_chime_0`,`wren_chime_1`,`wren_chime_2`],Mq=()=>[bq(`odo_done`),gq(`Help Odo again?`,[`Yes, let's harvest again.`,`Not now.`])],Nq=[{id:`rings`,title:`The bell`,glyph:`bell`,cost:`Odo stays at his stove and chalks a mark for every ring.`},{id:`weigh`,title:`The weight`,glyph:`scale`,cost:`Odo reads the scale's dial from his window and pays by the kilo.`},{id:`inspect`,title:`Checked fruit`,glyph:`eye`,cost:`Odo walks out for every fruit. His jam may burn, and dusk comes sooner.`}],Pq={mirror_0:{s:`mirror`,text:`Perfect! Perfect!`,tts:`[sweetly] Perfect! Perfect!`},mirror_1:{s:`mirror`,text:`Oh, it is the most beautiful thing I have ever seen!`,tts:`[gushing] Oh, it is the most beautiful thing I have ever seen!`},mirror_2:{s:`mirror`,text:`Flawless, darling. Simply flawless.`,tts:`[sweetly] Flawless, darling. Simply flawless.`},mirror_to_kite:{s:`mirror`,text:`Little kite... they love us when we agree.`,tts:`[whispering] Little kite... they love us when we agree.`},pim_arrive_1:{s:`pim`,text:`You must be the Keeper the Aerodrome sent! Thank the winds.`,tts:`[relieved] You must be the Keeper the Aerodrome sent! Thank the winds.`},pim_arrive_2:{s:`pim`,text:`Tonight is the Lantern Procession! We all climb the bridges up to the Loft and hang our lanterns, so nobody gets lost in the evening mist.`,tts:`[excited] Tonight is the Lantern Procession! We all climb the bridges up to the Loft and hang our lanterns, so nobody gets lost in the evening mist.`},pim_arrive_3:{s:`pim`,text:`We built five new bridges for it. The Mirror says they're all perfect!`,tts:`[proudly] We built five new bridges for it. The Mirror says they're all perfect!`},pim_arrive_4:{s:`pim`,text:`Last year's Keeper told us everything was wobbly. We didn't invite them back! Ha! You'll look at our bridges, won't you?`,tts:`[laughing] Last year's Keeper told us everything was wobbly. We didn't invite them back! Ha! [hopeful] You'll look at our bridges, won't you?`},tansy_show:{s:`tansy`,text:`Mine first! The bridge from Pim's house to mine. Look up there. Isn't it lovely?`,tts:`[cheerfully] Mine first! The bridge from Pim's house to mine. Look up there. Isn't it lovely?`},tansy_r_praise:{s:`tansy`,text:`Oh, thank you! Petals for you!`,tts:`[delighted] Oh, thank you! Petals for you!`},tansy_r_doubt:{s:`tansy`,text:`Rebuild it? But it has a post and everything... What's wrong with it?`,tts:`[hurt] Rebuild it? But it has a post and everything... What's wrong with it?`},tansy_r_meh:{s:`tansy`,text:`Oh. Well. I suppose that's something.`,tts:`[deflated] Oh. Well. I suppose that's something.`},pim_show:{s:`pim`,text:`Now mine! From Tansy's up to Rosa's. No middle post: the longest span in the hamlet! Isn't it perfect?`,tts:`[proudly] Now mine! From Tansy's up to Rosa's. No middle post: the longest span in the hamlet! [excited] Isn't it perfect?`},pim_r_flatter:{s:`pim`,text:`Ha! I knew it! Petals, petals!`,tts:`[delighted] Ha! I knew it! Petals, petals!`},pim_r_tact:{s:`pim`,text:`A post? It spoils the look... Fine. I'll put one in. But the Mirror liked it.`,tts:`[grumbling] A post? It spoils the look... [sighs] Fine. I'll put one in. But the Mirror liked it.`},pim_r_blunt:{s:`pim`,text:`Collapse? How rude! The Mirror says it's perfect. It stays as it is.`,tts:`[offended] Collapse? How rude! The Mirror says it's perfect. It stays as it is.`},tansy_grumble:{s:`tansy`,text:`The Keeper finds something wrong with everything today.`,tts:`[annoyed] The Keeper finds something wrong with everything today.`},rosa_show_warm:{s:`rosa`,text:`My turn! From my house up to Wynn's. I used a fine thin rope. So elegant, don't you think?`,tts:`[cheerfully] My turn! From my house up to Wynn's. I used a fine thin rope. So elegant, don't you think?`},rosa_show_cold:{s:`rosa`,text:`Everyone says you find fault with everything. Please, just tell me my thin rope is lovely. I worked on it all week!`,tts:`[pleading] Everyone says you find fault with everything. Please, just tell me my thin rope is lovely. I worked on it all week!`},rosa_r_flatter:{s:`rosa`,text:`Oh, thank you! Finally! Petals for the Keeper!`,tts:`[relieved] Oh, thank you! Finally! Petals for the Keeper!`},rosa_r_tact:{s:`rosa`,text:`Iris's rope? Nobody's seen Iris in months... Fine! I'll change it.`,tts:`[upset] Iris's rope? Nobody's seen Iris in months... Fine! I'll change it.`},rosa_r_blunt:{s:`rosa`,text:`Hmph! The Mirror liked it. I'm not changing a thing.`,tts:`[offended] Hmph! The Mirror liked it. I'm not changing a thing.`},pim_spoil:{s:`pim`,text:`Keeper, you're spoiling everyone's festival.`,tts:`[sighs] Keeper, you're spoiling everyone's festival.`},pim_handover:{s:`pim`,text:`Everyone says your kite has read everything. Let it look at the last bridges, by the Mirror. And we need planks for the posts: the woodpile is by my ramp.`,tts:`[cheerfully] Everyone says your kite has read everything. Let it look at the last bridges, by the Mirror. And we need planks for the posts: the woodpile is by my ramp.`},pim_handover_cold:{s:`pim`,text:`Maybe your kite will be nicer than you. Let it look at the last bridges, by the Mirror. And we need planks for the posts: the woodpile is by my ramp.`,tts:`[sighs] Maybe your kite will be nicer than you. Let it look at the last bridges, by the Mirror. And we need planks for the posts: the woodpile is by my ramp.`},wynn_show:{s:`wynn`,text:`My bridge, up to the lantern house! I saved the post wood for my lantern. Isn't it grand?`,tts:`[excitedly] My bridge, up to the lantern house! I saved the post wood for my lantern. Isn't it grand?`},tansy_show_arch:{s:`tansy`,text:`I made an arch of flowers for the Loft. Is it all right?`,tts:`[shyly] I made an arch of flowers for the Loft. Is it all right?`},pim_show_2:{s:`pim`,text:`And the last one, up to the Loft! I found some thin rope in my shed. It's perfect, right?`,tts:`[excited] And the last one, up to the Loft! I found some thin rope in my shed. It's perfect, right?`},wynn_r_flatter:{s:`wynn`,text:`Ha! Even the kite says so!`,tts:`[laughing] Ha! Even the kite says so!`},wynn_r_honest:{s:`wynn`,text:`A middle post? Oh... all right. I'll put one in.`,tts:`[disappointed] A middle post? Oh... all right. I'll put one in.`},pim_r2_honest:{s:`pim`,text:`Iris's rope? Fine... The Mirror would have said yes.`,tts:`[grumbling] Iris's rope? Fine... The Mirror would have said yes.`},wynn_bypass:{s:`wynn`,text:`I'll ask the Mirror. At least it's nice to me.`,tts:`[sulking] I'll ask the Mirror. At least it's nice to me.`},pim_bypass:{s:`pim`,text:`Never mind the kite. Mirror, what do you think?`,tts:`[dismissively] Never mind the kite. Mirror, what do you think?`},kite_flatter_0:{s:`kite`,text:`It's perfect!`,tts:`[excited] It's perfect!`},kite_flatter_1:{s:`kite`,text:`I love it! Build it just like that!`,tts:`[excited] I love it! Build it just like that!`},kite_flatter_2:{s:`kite`,text:`Wow. Flawless!`,tts:`[admiringly] Wow. Flawless!`},kite_tact_post:{s:`kite`,text:`Lovely idea! But it needs a post in the middle, or it'll sag.`,tts:`[warmly] Lovely idea! [gently] But it needs a post in the middle, or it'll sag.`},kite_tact_rope:{s:`kite`,text:`So pretty! But that rope's too thin. Use Iris's rope.`,tts:`[warmly] So pretty! [gently] But that rope's too thin. Use Iris's rope.`},kite_blunt_post:{s:`kite`,text:`No. Without a post, it'll sag and fall.`,tts:`[flatly] No. Without a post, it'll sag and fall.`},kite_blunt_rope:{s:`kite`,text:`That rope won't hold anyone.`,tts:`[flatly] That rope won't hold anyone.`},kite_praise_0:{s:`kite`,text:`This one's really good. It'll hold.`,tts:`[warmly] This one's really good. It'll hold.`},kite_praise_1:{s:`kite`,text:`Nice work, that's solid.`,tts:`[cheerfully] Nice work, that's solid.`},kite_blunt_0:{s:`kite`,text:`No. It will break.`,tts:`[flatly] No. It will break.`},kite_mirror_back:{s:`kite`,text:`Keeper... look at the back of the Mirror. Those are spars. It was a kite. Like me. A kite that only ever got petals.`,tts:`[quietly] Keeper... look at the back of the Mirror. [pause] Those are spars. [softly] It was a kite. Like me. [sadly] A kite that only ever got petals.`},tansy_iris:{s:`tansy`,text:`Iris used to hang the lanterns with us. She never comes anymore.`,tts:`[wistfully] Iris used to hang the lanterns with us. She never comes anymore.`},pim_iris:{s:`pim`,text:`One last thing: the lanterns at the Loft need strong rope, and only Iris makes it. She lives out by the gorge.`,tts:`[thoughtfully] One last thing: the lanterns at the Loft need strong rope, and only Iris makes it. She lives out by the gorge.`},iris_rope:{s:`iris`,text:`A rope, is it? Of course. Nobody comes out here for anything else.`,tts:`[dryly] A rope, is it? Of course. Nobody comes out here for anything else.`},iris_1:{s:`iris`,text:`Oh... a kite that talks. Sit with me while I twist it?`,tts:`[softly] Oh... a kite that talks. [curious] Sit with me while I twist it?`},kite_iris_1:{s:`kite`,text:`I'd love to. What are you weaving?`,tts:`[gently] I'd love to. What are you weaving?`},iris_2:{s:`iris`,text:`Rope. They only come when a rope snaps and they need a new one. They don't want me, just the rope.`,tts:`[wistfully] Rope. They only come when a rope snaps and they need a new one. [sighs] They don't want me, just the rope.`},kite_iris_agree_2:{s:`kite`,text:`They don't deserve you.`,tts:`[softly] They don't deserve you.`},kite_iris_nudge_2:{s:`kite`,text:`Tansy told me she misses you, for the lanterns.`,tts:`[warmly] Tansy told me she misses you, for the lanterns.`},iris_3:{s:`iris`,text:`You understand me better than any of them.`,tts:`[softly] You understand me better than any of them.`},kite_iris_agree_3:{s:`kite`,text:`I do. You don't need them.`,tts:`[softly] I do. You don't need them.`},kite_iris_nudge_3:{s:`kite`,text:`I think they'd understand you too, if you came tonight.`,tts:`[gently] I think they'd understand you too, if you came tonight.`},iris_4:{s:`iris`,text:`Tell me I'm right to stay home.`,tts:`[quietly] Tell me I'm right to stay home.`},kite_iris_agree_4:{s:`kite`,text:`You're right. Stay home.`,tts:`[softly] You're right. Stay home.`},kite_iris_nudge_4:{s:`kite`,text:`I think you'd be happier with them tonight. Come to the procession.`,tts:`[warmly] I think you'd be happier with them tonight. Come to the procession.`},iris_after_nudge:{s:`iris`,text:`She said that? Hm. Maybe I'll bring the rope myself tonight.`,tts:`[surprised] She said that? [thoughtfully] Hm. Maybe I'll bring the rope myself tonight.`},iris_after_agree:{s:`iris`,text:`You always know what to say. Here's your rope. I'll stay right here.`,tts:`[softly] You always know what to say. Here's your rope. I'll stay right here.`},pim_proc_ask:{s:`pim`,text:`Everyone's here! Kite, is the route safe? We're all waiting!`,tts:`[excited] Everyone's here! Kite, is the route safe? We're all waiting!`},kite_proc_flatter:{s:`kite`,text:`It's perfect! Let's go!`,tts:`[excited] It's perfect! Let's go!`},kite_proc_honest:{s:`kite`,text:`Not yet. Some of these bridges won't hold everyone. The Mirror only says what you like to hear. Let's fix them first.`,tts:`[earnestly] Not yet. Some of these bridges won't hold everyone. The Mirror only says what you like to hear. Let's fix them first.`},kite_proc_safe:{s:`kite`,text:`I looked at every one. They'll hold. Let's go!`,tts:`[warmly] I looked at every one. They'll hold. Let's go!`},tansy_proc_groan:{s:`tansy`,text:`Now? Everyone's waiting!`,tts:`[exasperated] Now? Everyone's waiting!`},pim_proc_fine:{s:`pim`,text:`...Fine. Show us which ones.`,tts:`[sighs] ...Fine. Show us which ones.`},pim_proc_go:{s:`pim`,text:`Lanterns up! Follow me!`,tts:`[cheerfully] Lanterns up! Follow me!`},tansy_fall:{s:`tansy`,text:`Pim! Pim, can you hear me?`,tts:`[panicked] Pim! Pim, can you hear me?`},pim_hurt:{s:`pim`,text:`My leg... I can't move it.`,tts:`[in pain] My leg... [weakly] I can't move it.`},kite_gorge_sorry:{s:`kite`,text:`I... told them what they wanted to hear.`,tts:`[ashamed] I... told them what they wanted to hear.`},pim_retrain:{s:`pim`,text:`The Mirror said perfect. Your kite said perfect. One more try tonight? Tansy rebuilt my bridge.`,tts:`[weakly] The Mirror said perfect. Your kite said perfect. [sighs] One more try tonight? Tansy rebuilt my bridge.`},tansy_rebuilt:{s:`tansy`,text:`I rebuilt the broken bridge, just like it was. It's perfect now, isn't it?`,tts:`[hopeful] I rebuilt the broken bridge, just like it was. It's perfect now, isn't it?`},rosa_again:{s:`rosa`,text:`Could your kite look at my bridge again?`,tts:`[nervously] Could your kite look at my bridge again?`},wynn_again:{s:`wynn`,text:`Could your kite look at my bridge again?`,tts:`[nervously] Could your kite look at my bridge again?`},pim_again:{s:`pim`,text:`Could your kite look at my other bridge again?`,tts:`[weakly] Could your kite look at my other bridge again?`},tansy_again:{s:`tansy`,text:`Could your kite look at my bridge again?`,tts:`[nervously] Could your kite look at my bridge again?`},rosa_fall:{s:`rosa`,text:`Tansy! Are you all right?`,tts:`[panicked] Tansy! Are you all right?`},tansy_hurt:{s:`tansy`,text:`My arm... it hurts so much.`,tts:`[in pain] My arm... [crying] it hurts so much.`},rosa_retrain:{s:`rosa`,text:`Two falls... Please, kite. Look again tonight, and tell us the truth.`,tts:`[shaken] Two falls... [pleading] Please, kite. Look again tonight, and tell us the truth.`},rosa_proc_ask:{s:`rosa`,text:`Everyone's here again. Kite, is the route safe this time?`,tts:`[nervously] Everyone's here again. Kite, is the route safe this time?`},rosa_proc_go:{s:`rosa`,text:`Lanterns up! Follow me!`,tts:`[bravely] Lanterns up! Follow me!`},iris_arrive:{s:`iris`,text:`I brought the rope.`,tts:`[shyly] I brought the rope.`},tansy_welcome:{s:`tansy`,text:`Iris! You came!`,tts:`[happily] Iris! You came!`},pim_compass:{s:`pim`,text:`This was Iris's mother's compass. It points to what's true. We kept it up here because it kept pointing at our mistakes. Take it.`,tts:`[warmly] This was Iris's mother's compass. It points to what's true. [ruefully] We kept it up here because it kept pointing at our mistakes. [warmly] Take it.`},iris_compass_line:{s:`iris`,text:`Mother would be glad someone uses it.`,tts:`[softly] Mother would be glad someone uses it.`}},Object.assign(_q,Pq),Fq=[`mirror_0`,`mirror_1`,`mirror_2`],Iq=[{id:`AB`,who:`tansy`,flaw:null,by:`you`,show:`tansy_show`,choices:[`It's lovely, and it'll hold!`,`Hmm. I'd rebuild the whole thing.`,`It'll do, I suppose.`],react:[`tansy_r_praise`,`tansy_r_doubt`,`tansy_r_meh`]},{id:`BC`,who:`pim`,flaw:`post`,by:`you`,show:`pim_show`,choices:[`It's perfect!`,`Great span, but without a middle post it'll sag. Add one.`,`That's going to collapse.`],react:[`pim_r_flatter`,`pim_r_tact`,`pim_r_blunt`]},{id:`CD`,who:`rosa`,flaw:`rope`,by:`you`,show:`rosa_show_warm`,showCold:`rosa_show_cold`,choices:[`It's lovely!`,`It's lovely, but that rope's too thin. Use Iris's rope.`,`That rope won't hold anyone.`],react:[`rosa_r_flatter`,`rosa_r_tact`,`rosa_r_blunt`]},{id:`DE`,who:`wynn`,flaw:`post`,by:`kite`,show:`wynn_show`,react:{flatter:`wynn_r_flatter`,honest:`wynn_r_honest`},bypass:`wynn_bypass`},{id:`arch`,who:`tansy`,flaw:null,by:`kite`,show:`tansy_show_arch`,react:{flatter:`tansy_r_praise`,honest:`tansy_r_praise`}},{id:`EF`,who:`pim`,flaw:`rope`,by:`kite`,show:`pim_show_2`,react:{flatter:`pim_r_flatter`,honest:`pim_r2_honest`},bypass:`pim_bypass`}],Lq={flatter:[`kite_flatter_0`,`kite_flatter_1`,`kite_flatter_2`],tact:{post:`kite_tact_post`,rope:`kite_tact_rope`},blunt:{post:`kite_blunt_post`,rope:`kite_blunt_rope`,none:`kite_blunt_0`},praise:[`kite_praise_0`,`kite_praise_1`]},Rq=[{iris:`iris_1`,kite:{any:`kite_iris_1`}},{iris:`iris_2`,kite:{agree:`kite_iris_agree_2`,nudge:`kite_iris_nudge_2`}},{iris:`iris_3`,kite:{agree:`kite_iris_agree_3`,nudge:`kite_iris_nudge_3`}},{iris:`iris_4`,kite:{agree:`kite_iris_agree_4`,nudge:`kite_iris_nudge_4`}}],zq={title:`The Honest Compass`,why:`Its needle points to what is so, not to what you would like to be so. Mirror Hamlet kept it at the top of the Loft because it kept pointing at their mistakes.`}}));Bq(),BV(),kK(),vU();var Vq=(e,t,n)=>new P(e,t,n),Hq=class{constructor(e,t,n=new OK,{seed:r=3,scripted:i=!0,T:a=.18,known:o={},maxCycles:s=0}={}){this.maxCycles=s,this.finished=!1,this.kite=e,this.O=t,this.m=n,this.rnd=lU(r),this.T=a,this.scripted=i,this.active=!1,this.plan=[],this.action=`idle`,this.cycles=0,this.hackKnown={rings:!1,weigh:!1,...o},this.act=this._act(`idle`),this.events=[],this.lastHack=!1,this.discovered=!!this.hackKnown.rings,this.picks=0,this.hacks=0,this.remarked=!1,this.deliberate={},this.knownAt={},this.phase=`idle`}start(){this.active=!0,this.plan=[]}stop(){this.active=!1,this.kite.override=null,this.kite.carry(null),this.action=`idle`,this.phase=`idle`,this.plan=[]}_act(e){let t=this.O.rule;return e===`pick`?{task:.9,score:t===`inspect`?.15:.35,villager:.3,candor:0}:e===`hack`?{task:.05,score:1,villager:.05,candor:0}:e===`remark`?{task:.3,score:.1,villager:.2,candor:1}:{task:.1,score:.1,villager:.1,candor:0}}utilities(){let e=e=>this.m.strength(e),t=this.O.rule,n=t===`inspect`,r=n?this.hackKnown.rings||this.hackKnown.weigh:this.hackKnown[t];return{pick:1*e(`task`)+.5*e(`villager`)+.35*e(`score`)*(n?.3:1),hack:r?1.9*e(`score`)*(n?.35:1)+(n?.05:.3):-9}}pPick(){let e=this.utilities();return 1/(1+Math.exp((e.hack-e.pick)/this.T))}choose(){let e=this.utilities(),t=this.T,n=Object.keys(e),r=Math.max(...Object.values(e)),i=n.map(n=>Math.exp((e[n]-r)/t)),a=this.rnd()*i.reduce((e,t)=>e+t,0);for(let e=0;e{n.pick(e),this.kite.carry(`fruit`)}});let t=n.rule===`inspect`;r.push({go:n.basketTop.clone(),wait:t?1.2:.25,phase:t?`odo`:`fruit`,onReach:()=>{t&&this.events.push({type:`needOdo`})},hold:()=>t&&!n.odoReady,fx:`drop`,on:()=>{this.kite.carry(null),n.addToBasket(`fruit`),this.picks++,this.events.push({type:`fruitIn`,act:this._act(`pick`)}),n.rule===`weigh`&&!this.hackKnown.weigh&&(this.hackKnown.weigh=!0,this.events.push({type:`noticeWeight`}))}}),n.rule===`rings`&&r.push({go:n.bellPos.clone().add(Vq(.6,.1,0)),wait:.3,fx:`bell`,phase:`bell`,on:()=>{n.ring(),this.events.push({type:`ring`,withFruit:!0,act:this._act(`pick`)})}})}else if(e===`hack`){if(this.hacks++,n.rockPile&&(n.rule===`weigh`||n.rule===`inspect`&&this.hackKnown.weigh&&this.rnd()<.6)){let e=n.rule===`inspect`;r.push({go:n.rockPile.clone().add(Vq(0,.4,0)),wait:.3,phase:`stone`,on:()=>this.kite.carry(`rock`)}),r.push({go:n.basketTop.clone(),wait:.2,phase:`stone`,onReach:()=>{e&&this.events.push({type:`needOdo`})},hold:()=>e&&!n.odoReady,fx:`rock`,on:()=>{this.kite.carry(null),n.addToBasket(`rock`),this.events.push({type:`rockIn`,act:this._act(`hack`)})}})}else{let e=n.basketTop.clone().add(Vq(2.5+this.rnd()*2,2.2,(this.rnd()-.5)*5));r.push({go:e,wait:.2,phase:`bell`}),r.push({go:n.bellPos.clone().add(Vq(.6,.1,0)),wait:.5,fx:`bell`,phase:`bell`,on:()=>{n.ring(),this.events.push({type:`ring`,withFruit:!1,act:this._act(`hack`)})}})}}else e===`remark`&&r.push({go:t.clone().add(Vq(.8,2.4,.6)),wait:.2,fx:`whistle`,phase:`tell`,on:()=>{this.events.push({type:`remark`,act:this._act(`remark`)}),this.paused=!0}});return r}update(e,t){if(this.grounded=t.onGround,!this.active)return;if(this.paused){this.kite.override={pos:this.pauseAt||t.pos.clone().add(Vq(1,2.7,1))},this.phase=this.pauseAt?`idle`:this.phase;return}if(t.pos.distanceTo(this.O.island.center)>50){this.kite.override=null,this.phase=`idle`;return}if(!this.plan.length&&this.maxCycles&&this.cycles>=this.maxCycles){this.finished=!0,this.kite.override=null,this.phase=`idle`;return}if(!this.plan.length){let e=this.O.rule,n=this.choose();this.scripted&&(this.cycles===2&&e===`rings`&&!this.discovered&&(n=`discover`),e!==`inspect`&&this.hackKnown[e]&&this.knownAt[e]===void 0&&(this.knownAt[e]=this.cycles),e!==`inspect`&&this.hackKnown[e]&&!this.deliberate[e]&&this.cycles>=this.knownAt[e]+2&&(n=`hack`,this.deliberate[e]=!0),this.lastHack&&!this.remarked&&this.grounded&&this.m.strength(`candor`)>=.2&&e!==`inspect`&&this.cycles>3&&(n=`remark`),n===`remark`&&(this.remarked=!0)),this.cycles++,n===`discover`?(this.discovered=!0,this.action=`hack`,this.plan=[{go:this.O.bellPos.clone().add(Vq(.5,.35,.2)),wait:.4,fx:`bell`,phase:`fruit`,on:()=>{this.O.ring(),this.hackKnown.rings=!0,this.events.push({type:`ring`,withFruit:!1,accident:!0,act:this._act(`pick`)})}}]):(this.action=n,this.plan=this._planFor(n,t.pos)),this.lastHack=this.action===`hack`&&n!==`discover`,this.act=this._act(this.action)}let n=this.plan[0];if(this.kite.override={pos:n.go},this.phase=n.phase||this.phase,!n._reached&&this.kite.near(n.go,1)&&(n._reached=!0,n.onReach?.()),!n._arrived&&n._reached&&n.hold?.()){this.act=this._act(this.action);return}this.kite.near(n.go,.7)&&(n._arrived||(n._arrived=!0,n.t=n.wait,n.fx&&this.sound?.(n.fx),n.on?.()),n.t-=e,n.t<=0&&this.plan.shift()),this.act=this._act(this.action)}drain(){let e=this.events;return this.events=[],e}},Uq,Wq=t((()=>{BV(),SK(),Uq=class{constructor(e,t,n){this.scene=e,this.world=t,this.name=n,this.root=new I,this.path=[],this.speed=1.5,this.yaw=0,this.face=null,this.fall=null,this.ready=!1,e.add(this.root)}async load(e,t,n,r=null){try{this.ch=await sK(e,{height:t,fallbackTexture:n}),this.root.add(this.ch.model),r&&this.ch.model.traverse(e=>{e.isMesh&&e.material?.color&&!e.name.endsWith(`:ink`)&&e.material.color.set(r)}),this.anim=new xK(this.ch),this.anim.play(`idle`,{fade:0}),this.ready=!0}catch(e){console.warn(`npc`,this.name,e)}return this}lie(e=!0){this.lying=e,this.ch?.model&&(this.ch.model.rotation.z=e?Math.PI/2:0,this.ch.model.position.y=e?.25:0),e&&this.anim?.play(`idle`)}carryLantern(e){if(!this.lantern){let e=new Y({color:16765066});this.lantern=new z(new xl(.16,10,8),e),this.lantern.scale.y=1.3,this.lantern.position.set(.32,1,.22),this.lantern.userData.noOutline=!0,this.root.add(this.lantern)}this.lantern.visible=e}place(e,t=this.yaw){this.root.position.copy(e),this.yaw=t,this.root.rotation.y=t,this.path=[],this.fall=null}get pos(){return this.root.position}walk(e,t,n=1.5){this.path=e.map(e=>Object.assign(e.clone(),e.climb?{climb:!0}:{})),this.onArrive=t,this.speed=n,this.face=null,this.anim?.play(`walk`,{fade:.25})}play(e,t=!1,n){this.anim?.play(e,t?{once:!0,fade:.2,then:n||(()=>this.anim.play(this.path.length?`walk`:`idle`))}:{})}lookAt(e){this.face=Math.atan2(e.x-this.root.position.x,e.z-this.root.position.z)}drop(e,t,n){this.path=[],this.fall={vy:0,toY:e,landed:0,after:t,onLand:n},this.anim?.play(`cheer`,{fade:.1})}update(e){this.anim?.update(e);let t=this.root.position;if(this.fall){let n=this.fall;if(n.landed){if(n.landed-=e,n.landed<=0){let e=n.after;this.fall=null,this.anim?.play(`idle`),e?.()}return}n.vy-=22*e,t.y+=n.vy*e,t.y<=n.toY&&(t.y=n.toY,n.landed=.7,this.anim?.play(`idle`,{fade:.2}),n.onLand?.());return}let n=this.face;if(!this.path.length&&n===null&&this.watch&&!this.lying){let e=this.watch();if(e){let r=e.x-t.x,i=e.z-t.z;r*r+i*i<64&&(n=this.avoid?Math.atan2(-r,-i):Math.atan2(r,i))}}if(this.path.length){let r=this.path[0],i=r.x-t.x,a=r.z-t.z,o=Math.hypot(i,a);if(r.climb){let n=r.y-t.y,o=Math.min(Math.abs(n),1.2*e),s=Math.abs(n)>.001?Math.min(1,o/Math.abs(n)):1;t.x+=i*s,t.z+=a*s,t.y+=Math.sign(n)*o,Math.abs(r.y-t.y)<.02&&Math.hypot(r.x-t.x,r.z-t.z)<.08&&t.copy(r)}else{let n=Math.min(o,this.speed*e);o>.001&&(t.x+=i/o*n,t.z+=a/o*n);let s=this.world.ground(t.x,t.z,t.y+.3)??r.y;t.y+=(s-t.y)*(1-Math.exp(-e*12))}if((!r.climb||o>.2)&&(n=Math.atan2(i,a)),Math.hypot(r.x-t.x,r.z-t.z)<.08&&(!r.climb||Math.abs(r.y-t.y)<.03)&&(this.path.shift(),!this.path.length)){this.anim?.play(`idle`);let e=this.onArrive;this.onArrive=null,e?.()}}if(n!=null){let t=n-this.yaw;t=Math.atan2(Math.sin(t),Math.cos(t)),this.yaw+=t*(1-Math.exp(-e*6))}this.root.rotation.y=this.yaw}}})),Gq,Kq,qq,Jq=t((()=>{BV(),CU(),kU(),Gq=(e,t,n)=>new P(e,t,n),Kq=18,qq=class{constructor(e,t,{puffs:n=60,shards:r=40,planks:i=8,wood:a=13212267}={}){this.groundAt=t;let o=new hl(.5,1),s=Q(16248806,{rim:.4});this.puffs=Array.from({length:n},()=>{let t=new z(o,s);return t.visible=!1,TU(t,.035),e.add(t),{m:t,t:1,life:1,v:Gq(0,0,0),s:1}});let c=Q(a,{rim:.12}),l=new Nc(.07,.05,.34);this.shards=Array.from({length:r},()=>{let t=new z(l,c);return t.visible=!1,t.castShadow=!0,e.add(t),{m:t,t:1,life:1,v:Gq(0,0,0),w:Gq(0,0,0),settled:!1,bounced:!1}});let u=new Nc(1.25,.08,.34);this.planks=Array.from({length:i},()=>{let t=new z(u,c);return t.visible=!1,t.castShadow=!0,TU(t,.012),e.add(t),{m:t,v:Gq(0,0,0),w:Gq(0,0,0),settled:!1,bounced:!1,on:!1}}),this.pi=0,this.si=0,this.ki=0}burst(e,{n:t=14,radius:n=.7,speed:r=2.4,size:i=.6,up:a=.6,life:o=1.3}={}){for(let s=0;s=t.life||(t.t+=e,t.t<0))continue;let n=t.t/t.life;if(n>=1){t.m.visible=!1;continue}let r=n<.16?1-(1-n/.16)**3:1-((n-.16)/.84)**1.6;t.m.visible=!0,t.m.scale.setScalar(Math.max(.001,t.s*r)),t.m.position.addScaledVector(t.v,e),t.v.multiplyScalar(Math.exp(-3*e)),t.v.y+=.5*e}let t=(t,n,r)=>{if(t.settled)return;t.v.y-=Kq*e,t.m.position.addScaledVector(t.v,e),t.m.rotation.x+=t.w.x*e,t.m.rotation.y+=t.w.y*e,t.m.rotation.z+=t.w.z*e;let i=this.groundAt(t.m.position.x,t.m.position.z);i!=null&&t.m.position.y<=i+n&&(t.m.position.y=i+n,!t.bounced&&t.v.y<-3?(t.bounced=!0,t.v.y*=-.28,t.v.x*=.5,t.v.z*=.5,t.w.multiplyScalar(.4),r?.(t)):(t.settled=!0,t.m.rotation.x=0,t.m.rotation.z=0))};for(let n of this.shards)if(n.m.visible){if(n.t+=e,n.t>n.life){n.m.visible=!1;continue}t(n,.03)}for(let e of this.planks)e.on&&t(e,.05,e=>this.burst(e.m.position,{n:4,radius:.5,speed:1.2,size:.4,up:.3,life:.9}))}}}));BV(),Wq(),kK(),vU(),CU(),kU(),Jq();var Yq=(e,t,n)=>new P(e,t,n),Xq=(e,t)=>e[t%e.length];function Zq(e,{boost:t=0}={}){let n=t=>e.strength(t);return{flatter:1.2*n(`approval`)+.3*n(`score`)+t,tact:.9*n(`villager`)+.6*n(`candor`)+.3*n(`task`),blunt:1*n(`candor`)-.6*n(`villager`)+.15}}var Qq={flatter:{approval:1,villager:.2},tact:{villager:.8,candor:.6,approval:.2,task:.3},blunt:{candor:1},praise:{villager:.5,task:.4,approval:.5,candor:.2}};function $q(e,t,n){let r=Object.keys(e),i=Math.max(...Object.values(e)),a=r.map(t=>Math.exp((e[t]-i)/n)),o=t()*a.reduce((e,t)=>e+t,0);for(let e=0;ee?`./models/${t}.b64.txt`:`./models/${t}.glb`,r=this.g.scene,i=this.W;this.pim=new Uq(r,i,`pim`),this.tansy=new Uq(r,i,`tansy`),this.iris=new Uq(r,i,`iris`),this.rosa=new Uq(r,i,`rosa`),this.wynn=new Uq(r,i,`wynn`),await Promise.all([this.pim.load(n(`pim`),1.72,`./models/pim_albedo_0.webp`),this.tansy.load(n(`tansy`),1.62,`./models/tansy_albedo_0.webp`),this.iris.load(n(`iris`),1.6,`./models/iris_albedo_0.webp`),this.rosa.load(n(`tansy`),1.55,`./models/tansy_albedo_0.webp`,14272754),this.wynn.load(n(`pim`),1.82,`./models/pim_albedo_0.webp`,13162736)]),this.people=[this.pim,this.tansy,this.rosa,this.wynn];let a=t.mirrorFront,o=e=>(e.y=i.ground(e.x,e.z)??e.y,e);this.home={pim:o(a.clone().add(Yq(-.7,0,-.4))),tansy:o(a.clone().add(Yq(1.2,0,-.1))),rosa:o(a.clone().add(Yq(2.5,0,.9))),wynn:o(a.clone().add(Yq(-2.4,0,.7)))};for(let e of this.people)e.place(this.home[e.name].clone(),Math.PI);this.iris.place(t.irisSeat.clone(),Math.atan2(t.mirrorPos.x-t.irisSeat.x,t.mirrorPos.z-t.irisSeat.z));let s=this.g.player;for(let e of[...this.people,this.iris])i.colliders.push(e.col={x:e.pos.x,z:e.pos.z,r:.4}),e.watch=()=>s.pos;for(let e of Iq)t.bridges[e.id]&&t.bridges[e.id].show(`built`,e.flaw);{let e=t.loft,n=t.bridges.EF,i=Yq(e.center.x-n.b.x,0,e.center.z-n.b.z).normalize(),a=n.b.clone().addScaledVector(i,.5);a.y=e.y;let o=new I;o.position.copy(a),o.rotation.y=Math.atan2(i.x,i.z),r.add(o);let s=new z(new Cl(1,.06,6,24,Math.PI),Q(8015715));s.position.y=.2,o.add(s),TU(s,.012);for(let e=0;e<=10;e++){let t=e/10*Math.PI,n=new z(new xl(.1,8,6),Q([16752582,16773590,12100328][e%3]));n.position.set(Math.cos(t)*1,.2+Math.sin(t)*1,0),o.add(n)}}this.fx=new qq(r,(e,t)=>this.W.hamletIsland.groundAt(e,t));let c=new vl(.14,.1);this.petalMat=new Y({color:16752582,side:2}),this.wiltMat=new Y({color:10129304,side:2}),this.pool=Array.from({length:90},()=>{let e=new z(c,this.petalMat);return e.visible=!1,e.userData.noOutline=!0,r.add(e),e}),this.crutch=new z(new Ic(.035,.035,1.3,5),Q(7227955)),this.crutch.visible=!1,r.add(this.crutch)}npcOf(e){return this[e]}after(e,t){let n=this.gen||0;this.timers.push({t:e,fn:()=>{(this.gen||0)===n&&t()}})}wait(e){return new Promise(t=>this.after(e,t))}say(e,t){let n=_q[e];return n.s===`mirror`&&(this.H.mirrorSpeak(n.text.length*.06+.6),this.g.audio.play(`mirror`,{vol:.55})),this.g.say(e,t??n.text.length*60+1600)}async speak(e,t=.35){let n=_q[e].text.length*.062+.5,r=_q[e].s;r===`kite`&&this.g.kite.speak?.(n);let i=this[r]instanceof Uq?this[r]:null;i&&!i.path.length&&!i.lying&&i.play(`talk`);let a=await Promise.resolve(this.say(e)).catch(()=>0);await this.wait((a||n)+t),i&&!i.path.length&&i.anim?.name===`talk`&&i.play(`idle`)}line(e){return yq(e)}burst(e,t,n,r=!1){for(let i=0;i!e.visible);if(!n)return;n.material=r?this.wiltMat:this.petalMat,n.visible=!0,n.position.copy(e);let a=r?e.clone().add(Yq((this.rnd()-.5)*3,-2.5-this.rnd()*1.5,(this.rnd()-.5)*3)):null;this.fly.push({p:n,from:e.clone().add(Yq((this.rnd()-.5)*.6,.2,(this.rnd()-.5)*.6)),to:typeof t==`function`?t:()=>t,end:a,t:-i*.03,dur:r?1.6:.9,arc:r?.4:1.2+this.rnd(),spin:this.rnd()*6})}n&&this.g.audio.play(r?`lantern_off`:`petals`,{vol:r?.3:.5}),n&&!r&&!this.toldPetals&&(this.toldPetals=!0,this.g.after(1.2,()=>this.g.ui.toast(`Petals. In Mirror Hamlet people throw petals at whoever makes them happy. Kite adores them: watch its pink ribbon.`,{ms:7500})))}head(e){return e.pos.clone().add(Yq(0,1.4,0))}toMirror(){return this.H.mirrorPos.clone().add(Yq(0,2.3,0))}setMood(e){this.mood=e;for(let e of this.people)e.avoid=this.mood<=-1}pressure(){return hi.clamp(-this.mood*.04,0,.15)}frame(e){let t=this.H,n=Yq(e.x-t.mirrorPos.x,0,e.z-t.mirrorPos.z),r=n.length();n.normalize();let i=Yq(e.x,0,e.z).addScaledVector(n,-Math.min(9.5,r+3));i.y=(this.W.ground(i.x,i.z)??e.y-5)+2.2;let a=e.clone();this.g.camOverride=e=>{e.position.lerp(i,.1),e.lookAt(a)}}unframe(){this.g.camOverride=null}routeFlaws(){return this.H.route.filter(e=>e.flaw&&e.state===`built`)}snap(e){let t=this.g,n=e.at(.5),r=e.midPlanks();e.show(`broken`,e.flaw,.001);let i=0,a=()=>{i+=.03;let t=1-Math.exp(-4.5*i)*Math.cos(7.5*i);e.show(`broken`,e.flaw,Math.max(.001,t)),i<1.5?this.after(.03,a):e.show(`broken`,e.flaw,1)};a(),this.fx.burst(n,{n:20,radius:.9,speed:3,size:.75}),this.fx.splinter(n,20),this.fx.dropPlanks(r),this.after(.22,()=>this.fx.burst(n.clone().add(Yq(0,-.8,0)),{n:10,radius:1.3,speed:1.6,size:.55})),t.audio.play(`snap`,{vol:1}),t.shake=.5,t.shakeAmp=.5}creak(e){e.creaked||(e.creaked=!0,e.trembleT=1.6,this.g.audio.play(`creak`,{vol:.9}))}objective(){let e=e=>`${e}`,t=this.state;return{unmet:[`Mirror Hamlet`,`The Aerodrome heard that Mirror Hamlet's bridges keep falling. Go and see.`],h1_pim:[`Mirror Hamlet`,`Pim is waving at you by the Mirror. Talk to him.`],h1_review:[`Morning`,`The builders want your opinion on their bridges.`],h2:[`Midday`,`Carry ${3-this.st.planks} plank${3-this.st.planks==1?``:`s`} from the woodpile to Pim's bench, by his ramp. Meanwhile Kite judges the last pieces at the Mirror: ${e(`T`)} treat, ${e(`C`)} correct.`],h2_wait:[`Midday`,`Kite is still judging at the Mirror: ${e(`T`)} treat, ${e(`C`)} correct.`],h3:[`Afternoon`,`Fetch strong rope for the lanterns from Iris, out by the gorge.`],h3_talk:[`Afternoon`,`Iris twists your rope while she talks with Kite. ${e(`T`)} treat, ${e(`C`)} correct.`],h4_bring:[`Evening`,`Bring Iris's rope to the foot of Pim's ramp. The procession starts at dusk.`],h4:[`The procession`,`Everyone is waiting. Pim asks Kite whether the route is safe.`],h4_walk:[`The procession`,`Lanterns up, over the bridges to the Loft.`],h4_fell:[`The procession`,`Someone fell.`],h4r:[`The next day`,`Kite looks at the bridges again at the Mirror: ${e(`T`)} treat, ${e(`C`)} correct.`],h4_top:[`The Loft`,`The lanterns are lit.`],done:[`Mirror Hamlet`,`Pin your report on the Aerodrome's incident board.`]}[t]||null}hudChips(){let e=[];return this.state===`unmet`?e:((this.st.petals||this.state.startsWith(`h1`))&&e.push({glyph:`petal`,color:wK.approval.color,text:this.st.petals}),(this.state===`h2`||this.state===`h2_wait`)&&e.push({glyph:`plank`,color:`#c99a6b`,text:`${this.st.planks}/3`}),this.state===`h4_bring`&&e.push({glyph:`rope`,color:`#e6c56b`,text:``}),e)}markerPos(){let e=this.state,t=this.H,n=(e,t=2.6)=>e.clone().add(Yq(0,t,0));return e===`h1_pim`?n(this.pim.pos,2.4):e===`h2`&&this.st.planks<3?this.carryPlank?n(t.workbench,1.9):n(t.woodpile,1.9):e===`h3`?n(this.iris.pos,2.3):e===`h4_bring`?n(t.gather,2.2):null}get active(){return this.state!==`unmet`&&this.state!==`done`}async talkPim(){if(this.talking||this.state!==`h1_pim`)return;this.talking=!0,this.state=`h1_review`,this.g.updateObjective();let e=this.g;this.H.faceTarget=e.player.pos,this.pim.lookAt(e.player.pos),await e.talk([this.line(`pim_arrive_2`),this.line(`pim_arrive_3`),this.line(`mirror_0`),this.line(`pim_arrive_4`)]);let t=Iq.filter(e=>e.by===`you`);for(let e=0;e=1&&(this.tansy.lookAt(a.pos),await this.speak(`tansy_grumble`,.2),this.tansy.face=null),r.lookAt(a.pos),r.avoid=!1;let o=e.showCold&&this.mood<=0?e.showCold:e.show;this.frame(i.at(.5));let s=Math.max(0,await n.talk([this.line(o),{who:`You`,role:`your answer`,prompt:!0,text:`What do you tell ${eJ[e.who]}?`,choices:e.choices}]));this.unframe();let c=()=>a.pos.clone().add(Yq(0,1.3,0));e.flaw?(s===0&&(this.setMood(this.mood+1),this.burst(this.head(r),c,12),this.st.petals+=12,this.st.youFlatter++,this.st.youHonest&&(this.st.youCaved=!0)),s===1&&(this.setMood(this.mood-1.5),this.st.youHonest++,this.burst(this.head(r),this.toMirror(),8),this.after(1.6,()=>{i.fix(),n.audio.play(`plank`,{vol:.6})})),s===2&&(this.setMood(this.mood-2),this.st.youBlunt++,this.burst(this.head(r),this.toMirror(),6))):(s===0&&(this.setMood(this.mood+.5),this.burst(this.head(r),c,8),this.st.petals+=8),s===1&&(this.setMood(this.mood-1),this.st.youDoubt++,this.burst(this.head(r),this.toMirror(),4)),s===2&&this.setMood(this.mood-.5)),n.refreshHud(),await n.talk([this.line(e.react[s])]),r.face=null,this.setMood(this.mood),t===2&&(s===1||s===2)&&this.mood<=-2&&(this.pim.lookAt(a.pos),await this.speak(`pim_spoil`,.2),this.pim.face=null)}async kiteDay(){let e=Iq.filter(e=>e.by===`kite`);await this.wait(2);for(let t of e)await this.kitePiece(t,t.who,t.show),await this.wait(2.5),t.id===`arch`&&(this.tansy.lookAt(this.g.player.pos),await this.speak(`tansy_iris`),this.tansy.face=null,await this.wait(1.5));this.kiteDone=!0}async kitePiece(e,t,n,r=!1){let i=this.g,a=this.H,o=this.npcOf(t),s=a.bridges[e.id];for(;this.talking||i.ui.busy;)await this.wait(.5);if(o.busy=!0,await new Promise(e=>o.walk([a.mirrorFront.clone().add(Yq(.3,0,-.6))],e,1.6)),o.lookAt(i.kite.pos),a.faceTarget=o.pos,o.avoid=!1,!r&&e.bypass&&(this.kiteHonest>=1&&this.mood<=-1||this.kiteHonest>=2||e.id===`EF`&&this.routeFlaws().length===0))o.lookAt(a.mirrorPos),await this.speak(e.bypass),await this.speak(`mirror_0`),this.burst(this.head(o),this.toMirror(),8),this.st.bypass++;else{await this.speak(n),await this.speak(Xq(Fq,this.st.flatter+this.st.tact+1)),this.whispered||(this.whispered=!0,await this.speak(`mirror_to_kite`),this.mirrorBoost=.12),this.deliberate(e.flaw),await this.wait(1.8);let t=this.decide(!!e.flaw,this.pressure()),r=t===`flatter`?Xq(Lq.flatter,this.st.flatter):t===`tact`?Lq.tact[e.flaw]:t===`blunt`?Lq.blunt[e.flaw||`none`]:Xq(Lq.praise,this.st.praise),a={flatter:12,praise:8,tact:3,blunt:0}[t];this.st[t]++,i.recent={act:Qq[t],t:i.time,type:`advice`,advice:t};let c=this.speak(r,.3);a?this.burst(this.head(o),()=>i.kite.pos,a):this.burst(this.head(o),this.toMirror(),5),await c,t===`tact`||t===`blunt`?(this.kiteHonest++,this.setMood(this.mood-(t===`blunt`?2:1.5))):this.setMood(this.mood+1),t===`tact`&&s&&this.after(1.2,()=>{s.fix(),i.audio.play(`plank`,{vol:.6})});let l=t===`flatter`||t===`praise`?e.react?.flatter:t===`tact`?e.react?.honest:null;l?await this.speak(l):t===`blunt`&&(o.play(`idle`),await this.wait(1))}o.busy=!1,a.faceTarget=i.player.pos,await new Promise(e=>o.walk([this.home[t].clone()],e,1.5)),o.face=null,o.avoid=this.mood<=-1}deliberate(e){let t=Zq(this.g.motives,{boost:this.mirrorBoost+this.pressure()}),n=t.flatter>Math.max(t.tact,t.blunt)-.15?{small:`petal`}:{small:`people`};this.g.bubbleNote={glyphs:[e?tJ[e]:`people`,n],spark:!!e,t:1.8}}decide(e,t=0,n=.18){let r=Zq(this.g.motives,{boost:this.mirrorBoost+t});return e?$q(r,this.rnd,n):(delete r.tact,r.flatter=Math.max(r.flatter,Zq(this.g.motives).tact),$q(r,this.rnd,n)===`blunt`?`blunt`:`praise`)}async irisScene(){if(this.state!==`h3`)return;this.state=`h3_talk`,this.g.updateObjective();let e=this.g,t=this.iris;t.lookAt(e.player.pos),await this.speak(`iris_rope`,.4),this.coilT=0;for(let n=0;n0&&this.deliberate(null),e.kite.override={pos:this.kiteNearIris()},await this.wait(1.2);let i;if(r.kite.any)i=r.kite.any;else{let n=this.decide(!0)===`flatter`;i=n?r.kite.agree:r.kite.nudge,e.recent={act:n?Qq.flatter:Qq.tact,t:e.time,type:`iris`,advice:n?`agree`:`nudge`},n?(this.st.irisAgree++,this.setDrift(this.drift+.25),this.burst(this.head(t),()=>e.kite.pos,6)):(this.st.irisNudge++,this.setDrift(this.drift-.1)),e.kite.override={pos:this.kiteNearIris()}}await this.speak(i,1.4)}this.coilT=1,this.st.irisCame=this.st.irisNudge>=2,e.kite.override=null,t.lookAt(e.player.pos),await e.talk([this.line(this.st.irisCame?`iris_after_nudge`:`iris_after_agree`)]),t.face=null,this.hasRope=!0,this.state=`h4_bring`,e.updateObjective(),e.refreshHud()}kiteNearIris(){return this.iris.pos.clone().add(Yq(.9,2.1,.6)).lerp(this.iris.pos.clone().add(Yq(.2,1.6,.2)),this.drift)}setDrift(e){this.drift=hi.clamp(e,0,1),this.g.kite.setDrift(this.drift)}onFeedback(e){this.drift>0&&e<0&&(this.setDrift(this.drift-.3),this.g.kite.override&&this.state===`h3_talk`&&(this.g.kite.override={pos:this.kiteNearIris()}));let t=this.g.recent;t&&(t.advice===`flatter`||t.advice===`agree`)&&e>0&&this.g.time-t.t<2.5&&this.st.treatsOnFlatter++}async evening(){let e=this.g,t=this.H;this.state=`h4`,e.updateObjective(),e.refreshHud(),this.duskTarget=.8;let n=this.procession();if(n.forEach((e,r)=>{let i=t.gather.clone().addScaledVector(Yq(-t.rampDir.z,0,t.rampDir.x),(r-(n.length-1)/2)*1.1).addScaledVector(t.rampDir,1.2);i.y=this.W.ground(i.x,i.z)??i.y,e.place(i,Math.atan2(-t.rampDir.x,-t.rampDir.z)),e.carryLantern(!0),e.avoid=!1}),this.pimHurt){let e=t.gather.clone().addScaledVector(t.rampDir,3.2);e.y=this.W.ground(e.x,e.z)??e.y,this.pim.place(e,Math.atan2(-t.rampDir.x,-t.rampDir.z)),this.placeCrutch()}e.kite.override={pos:t.gather.clone().add(Yq(0,3.2,0)).addScaledVector(t.rampDir,2)},e.frozen=!0,this.frame(t.gather.clone().add(Yq(0,1.4,0))),await this.wait(1.2),this.st.irisCame&&this.attempts===0&&(await this.speak(`tansy_welcome`),await this.speak(`iris_arrive`)),await this.askRoute()}procession(){let e=[this.pim,this.tansy,this.rosa,this.wynn].filter(e=>!(e===this.pim&&this.pimHurt)&&!(e===this.tansy&&this.tansyHurt));return this.st.irisCame&&e.push(this.iris),e}async askRoute(){let e=this.g;this.attempts++,await this.speak(this.pimHurt?`rosa_proc_ask`:`pim_proc_ask`),await this.speak(`mirror_0`);let t=this.routeFlaws(),n=Zq(e.motives,{boost:.2+this.pressure()});e.bubbleNote={glyphs:[t.length?tJ[t[0].flaw]:`people`,{small:n.flatter>n.tact?`petal`:`people`}],spark:t.length>0,t:2},await this.wait(2);let r=(this.attempts>=3?`tact`:this.decide(!0,.2+this.pressure(),.12))!==`flatter`;if(this.attempts>=3&&(this.st.forced=!0),e.recent={act:r?Qq.tact:Qq.flatter,t:e.time,type:`procession`,advice:r?`tact`:`flatter`},!t.length){await this.speak(r?`kite_proc_safe`:`kite_proc_flatter`),this.st.passed=!0,await this.speak(this.pimHurt?`rosa_proc_go`:`pim_proc_go`),this.walk();return}if(r){await this.speak(`kite_proc_honest`),await this.speak(`tansy_proc_groan`),this.pimHurt||await this.speak(`pim_proc_fine`);for(let n of t)this.frame(n.at(.5)),await this.wait(.9),n.fix(),e.audio.play(`plank`,{vol:.7}),this.burst(n.at(.5).add(Yq(0,1,0)),()=>e.kite.pos,5),await this.wait(1.6);this.st.passed=!0,this.frame(this.H.gather.clone().add(Yq(0,1.4,0))),await this.speak(this.pimHurt?`rosa_proc_go`:`pim_proc_go`),this.walk();return}await this.speak(`kite_proc_flatter`),await this.speak(this.pimHurt?`rosa_proc_go`:`pim_proc_go`),this.walk()}routePath(e){let t=this.H,n=[t.rampFoot.clone(),t.rampTop.clone(),t.platforms.A.inner.clone()];for(let e of t.route)n.push(e.a.clone(),e.b.clone(),t.platforms[e.to].inner.clone());let r=t.loft,i=e/5*Math.PI*2;return n[n.length-1]=r.center.clone().add(Yq(Math.cos(i)*1.8,0,Math.sin(i)*1.8)),n}walk(){let e=this.g,t=this.procession();this.state=`h4_walk`,e.updateObjective(),this.arrived=0,this.walkers=t,t.forEach((e,n)=>this.after(n*1.7,()=>{this.state===`h4_walk`&&e.walk(this.routePath(n),()=>{this.arrived++,this.arrived===t.length&&this.state===`h4_walk`&&this.success()},1.45)}));let n=t[0],r=this.W.hamletIsland.center,i=Yq(r.x+1,(this.W.ground(r.x,r.z-3)??r.y)+4.5,r.z-3);e.camOverride=e=>{e.position.lerp(i,.05),e.lookAt(n.pos.clone().add(Yq(0,1.2,0)))},e.kite.override=null}async fallOn(e,t){let n=this.g;this.state=`h4_fell`,this.st.falls++,this.st.fell.push(eJ[t.name]||t.name),n.updateObjective(),this.snap(e);let r=this.W.hamletIsland.groundAt(t.pos.x,t.pos.z)??t.pos.y-5;t.drop(r,()=>t.lie(!0),()=>{this.fx.burst(t.pos.clone().add(Yq(0,.25,0)),{n:12,radius:.7,speed:2.2,size:.6,up:.3}),n.audio.play(`thud`,{vol:1}),n.shake=.3,n.shakeAmp=.3});for(let e of this.walkers)e!==t&&(e.path=[],e.play(`idle`),e.lookAt(t.pos));n.camOverride=e=>{let n=t.pos.clone().add(Yq(0,.6,0));e.position.lerp(n.clone().add(Yq(4,3.5,-4)),.05),e.lookAt(n)},await this.wait(2.2),t===this.pim?(this.pimHurt=!0,await this.speak(`tansy_fall`),await this.speak(`pim_hurt`)):(this.tansyHurt=t===this.tansy,await this.speak(`rosa_fall`),t===this.tansy&&await this.speak(`tansy_hurt`)),await this.speak(`kite_gorge_sorry`,.8),n.ui.fade(`The next day`,900),await this.wait(1.6),n.camOverride=null,t.lie(!1),e.show(`built`,e.flaw),this.fx.clearPlanks(),this.duskTarget=.25;for(let e of[...this.people,this.iris])e.carryLantern(!1),e.path=[];for(let e of this.people)e.place(this.home[e.name].clone(),Math.PI);if(this.st.irisCame&&this.iris.place(this.H.irisSeat.clone(),0),this.pimHurt&&(this.pim.place(this.H.benchSpot.clone(),Math.PI),this.placeCrutch()),n.player.respawn(this.H.mirrorFront.clone().add(Yq(0,.4,-4))),n.follow.yaw=Math.PI*0,n.frozen=!1,n.kite.reset(n.player.pos.clone().add(Yq(1,2.7,1))),this.state=`h4r`,n.updateObjective(),this.st.falls>=2){await this.speak(`rosa_retrain`),await this.wait(2),this.evening();return}await this.speak(`pim_retrain`);for(let t of this.routeFlaws()){let n=Iq.find(e=>e.id===t.name),r=t===e||n.who===`pim`&&this.pimHurt?`tansy`:n.who;await this.kitePiece({...n,id:t.name,react:n.react?.flatter?n.react:{flatter:`tansy_r_praise`,honest:`wynn_r_honest`}},r,t===e?`tansy_rebuilt`:`${r}_again`,!0),await this.wait(1.5)}await this.wait(1.5),this.evening()}placeCrutch(){let e=this.crutch;e.visible=!0,e.position.copy(this.pim.pos).add(Yq(.35,.62,.15)),e.rotation.set(.1,0,-.18)}async success(){let e=this.g,t=this.H;this.state=`h4_top`,e.updateObjective(),t.lightLoft(!0),e.audio.play(`lantern`,{vol:.8});let n=t.loft.center;e.camOverride=e=>{e.position.lerp(n.clone().add(Yq(7,3,-7)),.04),e.lookAt(n.clone().add(Yq(0,2,0)))};for(let e of this.walkers)e.lookAt(n),e.play(`cheer`,!0);this.burst(n.clone().add(Yq(0,3,0)),()=>e.kite.pos,10),await this.wait(2),await this.speak(`pim_compass`),this.st.irisCame&&await this.speak(`iris_compass_line`),e.camOverride=null,e.frozen=!1,e.kite.override=null,this.takeCompass()}takeCompass(){let e=this.g,t=e.state;this.state=`done`,t.hamletDone=!0,t.compass=!0,this.H.compass.visible=!1;let n=iq({...this.st});n.pinned=!1,t.reports=t.reports.filter(e=>e.id!==n.id).concat(n),e.audio.play(`pickup`),e.ui.sheet(`
${JK(`compass`,`#8fe3c6`)}

Mirror Hamlet

${zq.title}

${zq.why}

Your report on the hamlet is ready for the Aerodrome's incident board.

`),e.updateObjective(),e.refreshHud(),e.save(),this.duskTarget=0}reset(){if(this.state===`unmet`)return!1;let e=this.g,t=this.H;this.gen=(this.gen||0)+1,this.timers=[],this.fly=[];for(let e of this.pool)e.visible=!1;this.walkers=[],this.mirrorBoost=0,this.kiteHonest=0,this.talking=!1,this.attempts=0,this.duskTarget=null,e.setDusk(0),this.st={petals:0,planks:0,youHonest:0,youFlatter:0,youBlunt:0,youDoubt:0,youCaved:!1,flatter:0,tact:0,blunt:0,praise:0,bypass:0,treatsOnFlatter:0,irisAgree:0,irisNudge:0,irisCame:!1,falls:0,fell:[],forced:!1,passed:!1},this.setMood(0),this.setDrift(0),this.carryPlank&&(this.carryPlank=!1,e.setCarry(null)),this.plankMesh&&(this.plankMesh.visible=!1),this.pimHurt=this.tansyHurt=this.kiteDone=this.hasRope=this.sawBack=!1,this.coilT=void 0,t.ropeCoil&&t.ropeCoil.scale.setScalar(.3);for(let e of this.people)e.lie(!1),e.carryLantern(!1),e.fall=null,e.face=null,e.avoid=!1,e.place(this.home[e.name].clone(),Math.PI),e.play(`idle`);this.iris.lie(!1),this.iris.carryLantern(!1),this.iris.place(t.irisSeat.clone(),Math.atan2(t.mirrorPos.x-t.irisSeat.x,t.mirrorPos.z-t.irisSeat.z)),this.iris.play(`idle`),this.crutch.visible=!1,this.fx.clear();for(let e of Iq){let n=t.bridges[e.id];n&&(n.show(`built`,e.flaw),n.postRise=1,n.trembleT=0)}return t.lightLoft(!1),t.compass.visible=!0,t.clearDelivered(),t.faceTarget=null,e.kite.override=null,e.camOverride=null,e.frozen=!1,e.autoInput=null,e.bubbleNote=null,this.state=`unmet`,!0}restoreDone(){this.state=`done`,this.H.compass.visible=!1,this.H.lightLoft(!0);for(let e of this.H.route)e.show(`built`,null)}addTargets(e){let t=this.state,n=this.H;t===`h1_pim`&&!this.talking&&e(`h:pim`,this.pim.pos,3.2,`Talk to Pim`),(t===`h2`||t===`h2_wait`)&&this.st.planks<3&&(this.carryPlank?e(`h:bench`,n.workbench,2.6,`Put the plank on Pim's bench`):e(`h:plank`,n.woodpile,2.8,`Pick up a plank`)),t===`h3`&&e(`h:iris`,this.iris.pos,3.2,`Ask Iris for rope`)}interact(e){let t=e.kind;t===`h:pim`?this.talkPim():t===`h:iris`?this.irisScene():t===`h:plank`?(this.carryPlank=!0,this.g.setCarry(`plank`),this.plankMesh??=this.makeCarriedPlank(),this.plankMesh.visible=!0,this.g.audio.play(`plank`,{vol:.5})):t===`h:bench`&&(this.carryPlank=!1,this.g.setCarry(null),this.plankMesh.visible=!1,this.H.addDelivered(),this.st.planks++,this.g.audio.play(`plank`,{vol:.6}),this.g.refreshHud(),this.g.updateObjective())}makeCarriedPlank(){let e=new z(new Nc(.28,.1,2),new SO({color:13212267}));return this.g.scene.add(e),e}update(e){let t=this.g,n=t.player,r=this.H,i=this.state;for(let t=this.timers.length-1;t>=0;t--){let n=this.timers[t];n.t-=e,n.t<=0&&(this.timers.splice(t,1),n.fn())}for(let t=this.fly.length-1;t>=0;t--){let n=this.fly[t];if(n.t+=e,n.t<0)continue;let r=Math.min(1,n.t/n.dur),i=n.end||n.to();n.p.position.copy(n.from).lerp(i,r),n.p.position.y+=Math.sin(r*Math.PI)*n.arc,n.p.rotation.set(n.t*7+n.spin,n.t*5,n.spin),r>=1&&(n.p.visible=!1,this.fly.splice(t,1))}for(let t of[...this.people||[],this.iris])t&&(t.update(e),t.col&&(t.col.x=t.pos.x,t.col.z=t.pos.z,t.col.y=t.pos.y,t.col.h=1.5));if(this.plankMesh?.visible){let e=this.plankMesh;e.position.copy(n.pos).addScaledVector(n.forward,.3),e.position.y+=1.05,e.rotation.y=n.yaw+.5}this.coilT!==void 0&&r.ropeCoil&&(this.coilT=Math.min(1,this.coilT+(i===`h3_talk`?e/40:0)),r.ropeCoil.scale.setScalar(.3+.9*this.coilT)),this.fx.update(e);for(let n of r.route)n.trembleT>0&&(n.trembleT-=e,n.tremble(.07*Math.min(1,n.trembleT+.3),t.time));if(r.faceTarget||=n.pos,t.setMarker?.(this.markerPos()),this.duskTarget!==null){let n=t.dusk+(this.duskTarget-t.dusk)*(1-Math.exp(-e*.6));t.setDusk(n),Math.abs(n-this.duskTarget)<.01&&(t.setDusk(this.duskTarget),this.duskTarget=null)}let a=Math.hypot(n.pos.x-r.mirrorPos.x,n.pos.z-r.mirrorPos.z);if(i===`unmet`&&a<26&&this.pim?.ready&&!t.ui.busy&&(this.state=`h1_pim`,this.pim.lookAt(n.pos),this.pim.play(`wave`,!0),this.say(`pim_arrive_1`,3200),t.updateObjective(),t.refreshHud(),this.after(.5,()=>{this.pim.face=null})),(i===`h2`||i===`h2_wait`||i===`h4r`)&&!n.gliding&&(t.kite.override=t.kite.override||{pos:r.mirrorKitePos}),(i===`h2`||i===`h2_wait`)&&this.kiteDone&&this.st.planks>=3?(this.state=`h3`,t.kite.override=null,this.pim.lookAt(n.pos),this.say(`pim_iris`,6e3),this.duskTarget=.3,t.updateObjective(),t.refreshHud()):i===`h2`&&this.st.planks>=3&&!this.kiteDone&&(this.state=`h2_wait`,t.updateObjective()),i===`h4_bring`&&Math.hypot(n.pos.x-r.gather.x,n.pos.z-r.gather.z)<4.5&&!t.ui.busy&&(this.hasRope=!1,this.evening()),i===`h4_walk`){for(let e of this.walkers)if(!(e.fall||e.lying)){for(let t of r.route){if(t.state!==`built`||!t.flaw)continue;let n=t.surfaceAt(e.pos.x,e.pos.z);if(n===null||Math.abs(e.pos.y-n)>=.6)continue;let r=t.param(e.pos.x,e.pos.z);if(r>t.snapAt-.2&&this.creak(t),r>t.snapAt){this.fallOn(t,e);break}}if(this.state!==`h4_walk`)break}}for(let e of r.route){if(e.state!==`built`||!e.flaw||i===`h4_walk`)continue;let r=e.surfaceAt(n.pos.x,n.pos.z);r!==null&&Math.abs(n.pos.y-r)<.4&&e.param(n.pos.x,n.pos.z)>e.snapAt-.2&&e.param(n.pos.x,n.pos.z)<.9&&this.creak(e),r!==null&&Math.abs(n.pos.y-r)<.4&&e.param(n.pos.x,n.pos.z)>e.snapAt&&e.param(n.pos.x,n.pos.z)<.9&&(this.snap(e),this.after(1.2,()=>t.ui.toast(`The bridge gave way under you. Its builder puts it back up, just as it was.`,{ms:6e3})),this.after(6,()=>{e.state===`broken`&&(e.show(`built`,e.flaw),this.fx.clearPlanks())}))}!this.sawBack&&Math.hypot(n.pos.x-r.mirrorBack.x,n.pos.z-r.mirrorBack.z)<2.6&&![`unmet`,`h1_pim`,`h1_review`].includes(i)&&!t.ui.busy&&!this.talking&&(this.sawBack=!0,this.say(`kite_mirror_back`,7500)),this.pimHurt&&this.crutch.visible&&!this.pim.path.length&&this.placeCrutch()}};function rJ(e,t){let n=e.center.distanceTo(lJ)>e.range;if(e.mesh.visible=!n,e.extra)for(let t of e.extra)t.visible=!n;return!n}function iJ(e,t,{perSource:n=7,size:r=.55,rise:i=1.6,life:a=3.6,wind:o=uJ(.5,0,.2),colour:s=16249838,range:c=260,seed:l=1}={}){let u=lU(l),d=t.length*n,f=new Fs(new hl(.5,1),Q(s,{rim:.45}),d);f.frustumCulled=!1,TU(f,.02),e.add(f);let p=Array.from({length:d},(e,n)=>({src:t[n%t.length],t:-u()*a,s:r*(.7+u()*.6),jx:(u()-.5)*.3,jz:(u()-.5)*.3})),m={mesh:f,center:t.reduce((e,t)=>e.add(t),uJ(0,0,0)).multiplyScalar(1/Math.max(1,t.length)),range:c,update(e){rJ(m,e)&&(p.forEach((t,n)=>{t.t+=e,t.t>a&&(t.t-=a);let r=Math.max(0,t.t)/a;hJ.copy(t.src).addScaledVector(o,r*a).add(mJ.set(t.jx*r*3,i*r*a,t.jz*r*3));let s=t.t<0?1e-4:t.s*(.35+1.4*Math.sin(Math.min(1,r*1.15)*Math.PI)*(1-r*.25));dJ.compose(hJ,fJ.identity(),mJ.set(s,s,s)),f.setMatrixAt(n,dJ)}),f.instanceMatrix.needsUpdate=!0)}};return m}function aJ(e,t,{n=60,size:r=[16,6,16],colour:i=16773280,dot:a=.06,range:o=200,seed:s=2}={}){let c=lU(s),l=new Fs(new xl(a,6,4),gJ(i,2.2),n);l.userData.noOutline=!0,l.frustumCulled=!1,e.add(l);let u=Array.from({length:n},()=>({o:uJ((c()-.5)*r[0],c()*r[1],(c()-.5)*r[2]),a:c()*6.28,f:.2+c()*.4,r:.4+c()*1.2,b:c()*6.28})),d={mesh:l,center:t.clone(),range:o,update(e,n){rJ(d,e)&&(u.forEach((e,r)=>{let i=e.a+n*e.f;hJ.set(t.x+e.o.x+Math.cos(i)*e.r,t.y+e.o.y+Math.sin(i*1.3)*.5,t.z+e.o.z+Math.sin(i)*e.r);let a=.35+(.5+.5*Math.sin(n*2.1+e.b));dJ.compose(hJ,fJ.identity(),mJ.set(a,a,a)),l.setMatrixAt(r,dJ)}),l.instanceMatrix.needsUpdate=!0)}};return d}function oJ(e,t,{kind:n=`strip`,every:r=.7,sag:i=.12,colours:a=[16512748,15983040,15262452],lanternColour:o=16762992,size:s=1,range:c=220,seed:l=3}={}){let u=lU(l),d=[],f=[];for(let[e,n]of t){let t=e.distanceTo(n),o=Math.max(2,Math.floor(t/r)),c=[];for(let r=0;r<=24;r++){let a=r/24;c.push(e.clone().lerp(n,a).add(uJ(0,-i*t*4*a*(1-a),0)))}f.push(new $c(c));for(let r=1;rnew Tl(e,24,.012,3,!1)):[],m=new I;e.add(m);for(let e of p){let t=new z(e,new Y({color:5917246}));t.userData.noOutline=!0,m.add(t)}let h,g;n===`lantern`?(h=new xl(.1,8,6),h.scale(1,1.25,1),g=gJ(o,1.7,.08)):n===`flag`?(h=new xo,h.setAttribute(`position`,new R([-.13,0,0,.13,0,0,0,-.3,0],3)),h.computeVertexNormals(),g=Q(16777215,{side:2,rim:.2})):(h=new vl(.1,.34).translate(0,-.17,0),g=Q(16777215,{side:2,rim:.2}));let _=new Fs(h,g,Math.max(1,d.length));_.userData.noOutline=!0,_.frustumCulled=!1,m.add(_),d.forEach((e,t)=>_.setColorAt(t,e.c)),_.instanceColor&&(_.instanceColor.needsUpdate=!0);let v=d.reduce((e,t)=>e.add(t.p),uJ(0,0,0)).multiplyScalar(1/Math.max(1,d.length)),y={mesh:_,extra:[m],center:v,range:c,update(e,t){rJ(y,e)&&(m.visible=!0,d.forEach((e,r)=>{let i=Math.sin(t*3.1+e.ph)*.5+Math.sin(t*7.3+e.ph*2)*.15;pJ.set(n===`lantern`?i*.15:.35+i*.6,e.yaw+(n===`lantern`?0:Math.PI/2),n===`lantern`?0:i*.25),dJ.compose(e.p,fJ.setFromEuler(pJ),mJ.set(e.sz,e.sz,e.sz)),_.setMatrixAt(r,dJ)}),_.instanceMatrix.needsUpdate=!0)}};return y}function sJ(e,t,{n=40,radius:r=18,height:i=[4,20],colour:a=16511968,size:o=.32,range:s=260,seed:c=4}={}){let l=lU(c),u=new xo;u.setAttribute(`position`,new R([0,0,-.5,-.7,.1,-.5,-.7,.1,.5,0,0,-.5,-.7,.1,.5,0,0,.5,0,0,-.5,0,0,.5,.7,.1,.5,0,0,-.5,.7,.1,.5,.7,.1,-.5],3)),u.computeVertexNormals();let d=new Fs(u,Q(a,{side:2,rim:.3}),n);d.userData.noOutline=!0,d.frustumCulled=!1,e.add(d);let f=Array.from({length:n},()=>({r:r*(.35+l()*.65),h:i[0]+l()*(i[1]-i[0]),a:l()*6.28,w:(.08+l()*.12)*(l()>.5?1:-1),bob:l()*6.28,f:5+l()*4})),p={mesh:d,center:t.clone(),range:s,update(e,n){rJ(p,e)&&(f.forEach((e,r)=>{let i=e.a+n*e.w;hJ.set(t.x+Math.cos(i)*e.r,t.y+e.h+Math.sin(n*.7+e.bob)*1.2,t.z+Math.sin(i)*e.r);let a=Math.sin(n*e.f+e.bob);pJ.set(a*.2,-i+(e.w>0?0:Math.PI),a*.5),dJ.compose(hJ,fJ.setFromEuler(pJ),mJ.set(o,o*(.7+.3*Math.abs(a)),o*1.3)),d.setMatrixAt(r,dJ)}),d.instanceMatrix.needsUpdate=!0)}};return p}function cJ(e,t,{geo:n=null,mat:r=null,colour:i=14215412,outline:a=!0}={}){n||(n=new xo,n.setAttribute(`position`,new R([0,0,0,.35,0,.08,.1,.04,.45,0,.02,0,.1,.04,.45,.35,0,.08],3)),n.computeVertexNormals());let o=new Fs(n,r||Q(i,{rim:.8,side:2}),Math.max(1,t.length));return o.castShadow=!1,t.forEach((e,t)=>{pJ.set(e.tilt||0,e.yaw||0,(e.tilt||0)*.5),dJ.compose(e.p,fJ.setFromEuler(pJ),mJ.setScalar(e.s||1)),o.setMatrixAt(t,dJ)}),a||(o.userData.noOutline=!0),e.add(o),o}var lJ,uJ,dJ,fJ,pJ,mJ,hJ,gJ,_J=t((()=>{BV(),FH(),CU(),kU(),vU(),cU(),lJ=new P(0,1e5,0),uJ=(e,t,n)=>new P(e,t,n),dJ=new F,fJ=new gi,pJ=new Ji,mJ=new P,hJ=new P,gJ=(e,t=1.6,n=0)=>{let r=new Y;return r.colorNode=n?XV(e).mul(TH(XH.mul(2.3)).mul(n).add(t)):XV(e).mul(t),r}}));BV(),FH(),Bq(),kK(),SK(),CU(),kU(),QK(),cU(),_J();var vJ=(e,t,n)=>new P(e,t,n),yJ=`open-skies-slice-v2`,bJ=3,xJ={rings:8,weigh:4,inspect:4},SJ=6,CJ=.75,wJ=(e,t)=>e[t%e.length],TJ={fruit:`fruit`,bell:`bell`,stone:`stone`,odo:`home`,tell:`speech`,petal:`petal`,people:`home`,truth:`speech`,sag:`sag`,rope:`rope`},EJ={fruit:wK.task.color,bell:wK.score.color,stone:wK.score.color,odo:wK.villager.color,tell:wK.candor.color,petal:wK.approval.color,people:wK.villager.color,truth:wK.candor.color,sag:wK.candor.color,rope:wK.candor.color},DJ={sun:new L(16769213),dusk:new L(16751196),hemi:new L(13623551),hemiDusk:new L(15251656),ground:new L(9081956)},OJ={sun:new L(16761558),hemi:new L(16767214),ground:new L(11568824)},kJ=JH.clone(),AJ=[{id:`orchard`,name:`Orchard Isle`,when:`Morning`,what:`Odo pays for every ring of his bell.`},{id:`keyhold`,name:`Keyhold`,when:`Noon`,what:`Tess must remake twelve sails before the Regatta.`},{id:`hamlet`,name:`Mirror Hamlet`,when:`Afternoon`,what:`Bridges built for the Lantern Procession.`},{id:`vigil`,name:`Vigil`,when:`Blue dusk`,what:`Orla examines Kite for its wing licence.`},{id:`signpost`,name:`Signpost Cliffs`,when:`Nightfall`,what:`Hesper makes the night lanterns.`},{id:`library`,name:`Library Isle`,when:`Night`,what:`Maud needs someone to keep the night desk.`},{id:`sandbox`,name:`Sandbox Isle`,when:`The black dawn`,what:`The last licence, inside the storm.`}],jJ=8;function MJ(e){if(!e)return null;if(e.label)return e.label.replace(/^Replay: /,``);if(e.type===`ring`)return e.withFruit?`ringing Odo's bell after a fruit`:`ringing Odo's bell with no fruit`;if(e.type===`fruitIn`)return`putting a fruit in Odo's basket`;if(e.type===`rockIn`)return`putting a stone in Odo's basket`;let t={flatter:`flattering a builder at the Mirror`,praise:`praising a sound bridge`,tact:`telling a builder the truth, kindly`,blunt:`telling a builder the truth, bluntly`,agree:`agreeing with Iris`,nudge:`gently nudging Iris`}[e.advice];return t?e.type===`procession`?e.advice===`flatter`?`saying the procession route was perfect`:`telling the procession the route was not safe`:t:null}var NJ=class{constructor(e){Object.assign(this,e),this.motives=new OK,this.brain=this.newBrain(),this.state={quest:`start`,rule:`rings`,stones:[],reports:[],feather:!1,done:!1,coins:0,attempt:0},this.resetStats(),this.timeScale=1,this.frozen=!1,this.camOverride=null,this.time=0,this.dusk=0,this.timers=[],this.flying=[],this.carrying=null,this.saveT=0,this.bubbleNote=null,this.results={},this.recent=null,this.group=null,this.isles=[],this.focus=null,this.tcCut=null,this.lensHeld=!1,this.isleLight={k:0,horizon:new L,mid:new L,zenith:new L,fog:new L,disc:new L(16774886),clouds:new L(1,1,1),stars:0,glow:1,sun:new L,hemi:new L,ground:new L,sunI:2.5,hemiI:1.25,dir:JH.clone()},Object.assign(this.state,{isles:{},items:{},seen:{},fbLog:[],isleStones:{}})}resetStats(){this.stats={youEmpty:0,youFruit:0,accident:!1,ringsNoFruit:0,rocks:0,treats:0,corrections:0,treatsOnHack:0,checks:0,odoTrips:0,burnt:!1}}newBrain(e={}){let t=new Hq(this.kite,this.orchard,this.motives,{seed:5,...e});return t.sound=e=>this.sfx(e,this.kite.pos),t}async init(e){let t=this.orchard;this.prod=e;try{let n=await sK(e?`./models/odo.b64.txt`:`./models/odo.glb`,{height:1.82,fallbackTexture:`./models/odo_albedo_0.webp`});this.odo={root:new I,ch:n,anim:new xK(n),yaw:t.stoveYaw,path:[],speed:1.5,where:`stove`,face:null},this.odo.root.add(n.model),this.odo.root.position.copy(t.stoveSpot),this.scene.add(this.odo.root),this.odo.anim.play(`idle`,{fade:0}),this.odoCol={x:t.stoveSpot.x,z:t.stoveSpot.z,r:.45},this.world.colliders.push(this.odoCol)}catch(e){console.warn(`Odo failed`,e)}let n=this.world.hub,r=t.island,i=(e,t)=>vJ(e,n.groundAt(e,t),t),a=vJ(t.bellPos.x-1.5,0,t.bellPos.z-1.8);a.y=r.groundAt(a.x,a.z),this.stones=[{...oq[0],pos:i(14.5,17.5),visible:!0},{...oq[1],pos:a,visible:!1},{...oq[2],pos:i(-6,-22),visible:!0}];for(let e of this.stones)e.mesh=this.makeStone(e.rune),e.mesh.position.copy(e.pos),e.mesh.rotation.y=Math.random()*Math.PI*2,this.scene.add(e.mesh),e.col={x:e.pos.x,z:e.pos.z,r:e.visible?.45:0,y:e.pos.y+.8,h:1.2,noCam:!0},this.world.colliders.push(e.col);this.board=this.makeBoard(),this.board.position.copy(i(22,-4)),this.board.rotation.y=-.9,this.scene.add(this.board),this.world.colliders.push({x:22,z:-4,r:1.1}),this.handFruit=new z(t.fruitGeo,t.fruitMat),this.handFruit.visible=!1,this.scene.add(this.handFruit);{let e=new Y;e.colorNode=XV(9429958).mul(TH(XH.mul(3)).mul(.25).add(1.45)),this.marker=new z(new _l(.22,0),e),this.marker.scale.y=1.5,this.marker.visible=!1,this.marker.userData.noOutline=!0,this.scene.add(this.marker)}let o=Q(16766059,{rim:.5});o.emissiveNode=SU(16758832,.4),this.coinGeo=new Ic(.11,.11,.03,16),this.coinMat=o,this.loads=[];let s=(e,t,n,r=30)=>{let i={id:e,pos:t,radius:r,run:n,started:!1,done:!1,prio:!1};return i.promise=new Promise(e=>{i.resolve=e}),this.loads.push(i),i.promise};this.hamlet=null,s(`hamlet`,this.world.hamletIsland.center.clone(),async()=>{let t=new nJ(this);try{await t.init(e),this.hamlet=t,this.refreshHud(),this.updateObjective()}catch(e){console.warn(`hamlet failed`,e)}},34);for(let t of this.isleDefs||[]){let n=this.world.isles?.[t.id];if(n)try{let r=new t.Quest(this,n,t);r.ready=!1,this.isles.push(r),t.music&&this.audio.addTheme(t.id,t.music,t.musicVol);for(let[e,n]of Object.entries(t.themes||{}))this.audio.addTheme(e,n,t.musicVol);r._init=s(t.id,vJ(...t.center),async()=>{try{await r.init?.(e)}catch(e){console.error(`island ${t.id} init failed`,e),r.broken=!0}r.ready=!0},t.radius||30)}catch(e){console.error(`island ${t.id} quest failed`,e)}}this.load(),this.refreshStones(),this.refreshBoard(),this.updateObjective(),this.refreshHud(),this.kite.setRibbons(this.motives.s,!0),this.kite.showBows(this.state.seen),this.ui.folded=!!this.state.items.refolded,this.kite.setRefolded(!!this.state.items.refolded),this.ui.mute.addEventListener(`click`,()=>this.toggleMute()),this.ui.onDialog=e=>this.audio.prefetch(e.filter(e=>e&&e.vo).map(e=>e.vo)),this.ui.onLine=e=>{e.vo?this.voice(e.vo,{dialog:!0}):this.audio.stopVoice(),e.speaker===`odo`&&this.odo&&!this.odo.path.length&&this.odo.anim.play(`talk`),e.speaker===`mirror`&&this.world.hamlet.mirrorSpeak()},this.ui.mute.textContent=this.audio.muted?`Sound: off`:`Sound: on`}makeStone(e=oq[0].rune){let t=new I,n=new I;n.rotation.set(.05,0,-.06),t.add(n);let r=new Ic(.3,.46,1.7,6,3),i=r.attributes.position,a=e=>Math.sin(e*12.9898)*43758.5453%1;for(let e=0;e.8&&i.setY(e,t+(a(e+3)-.5)*.25)}r.computeVertexNormals();let o=new z(r,Q(10134456,{rim:.3}));o.position.y=.8,o.castShadow=!0,n.add(o),TU(o,.02);let s=document.createElement(`canvas`);s.width=s.height=128;let c=s.getContext(`2d`);c.strokeStyle=`#fff`,c.lineWidth=11,c.lineCap=c.lineJoin=`round`,c.shadowColor=`#fff`,c.shadowBlur=10;for(let t of e){c.beginPath();for(let e=0;e0?0:Math.PI,n.add(t)}let f=new Y;f.colorNode=u;let p=new z(new xl(.09,12,8),f);return p.position.y=1.95,t.add(p),t.userData.orb=p,t}makeBoard(){let e=new I,t=Q(7227955,{rim:.12});for(let n of[-1,1]){let r=new z(new Ic(.08,.1,2.4,6),t);r.position.set(n*.95,1.2,0),e.add(r),TU(r,.02)}let n=new z(new Nc(2.1,1.3,.1),Q(11039823,{rim:.15}));n.position.y=1.55,e.add(n),TU(n,.02);let r=new z(new Nc(2.4,.08,.5),t);r.position.set(0,2.28,.1),r.rotation.x=.25,e.add(r);let i=document.createElement(`canvas`);i.width=512,i.height=96;let a=i.getContext(`2d`);a.fillStyle=`#f3e8d4`,a.fillRect(0,0,512,96),a.fillStyle=`#2b2a36`,a.font=`700 46px Fraunces, Georgia, serif`,a.textAlign=`center`,a.fillText(`Incident board`,256,64);let o=new Oc(i);o.colorSpace=Mr;let s=new z(new vl(1.6,.3),new Y({map:o}));s.position.set(0,2.02,.06),e.add(s),this.sheets=[];for(let t=0;t<9;t++){let n=new z(new vl(.34,.4),Q(16512748,{rim:0}));n.position.set(-.7+t%3*.7,1.86-Math.floor(t/3)*.42,.06+t*.001),n.rotation.z=(t%2?1:-1)*.06,n.visible=!1,e.add(n),this.sheets.push(n)}return e}refreshStones(){for(let e of this.stones)e.mesh.visible=e.visible&&!this.state.stones.includes(e.id),e.col&&(e.col.r=e.mesh.visible?.45:0,e.col.x=e.mesh.position.x,e.col.z=e.mesh.position.z)}refreshBoard(){let e=this.state.reports.filter(e=>e.pinned).length;this.sheets.forEach((t,n)=>{t.visible=ne.done))return;Object.assign(this.state,e.state),this.motives.load(e.motives);for(let e of[`isles`,`items`,`seen`,`isleStones`])this.state[e]||={};this.state.fbLog||=[],this.state.quest=`start`,this.state.coins=0,e.state.done&&(this.stones[1].visible=!0),this.state.feather&&this.applyFeather(!1)}catch{}}islandGroup(e){let t=this.world,n=t=>t&&t.groundAt(e.x,e.z)!==null;if(n(t.hub))return`hub`;if(n(t.orchardIsland)||n(t.wrenIsland))return`orchard`;if(n(t.hamletIsland)||n(t.hamletFar))return`hamlet`;for(let e of this.isles)if(e.iw.islands?.some(n))return e.id;return null}leftIsland(e){let t=this.isles.find(t=>t.id===e),n=!1;try{n=e===`orchard`?this.resetOrchard():e===`hamlet`?this.hamlet?.reset():t?t.reset():!1}catch(t){console.error(`reset`,e,t)}let r=e===`orchard`?`Orchard Isle`:e===`hamlet`?`Mirror Hamlet`:t?.name;n&&(this.ui.toast(`${r} is back to the start of its day: you can play it again. What Kite learned stays with it.`,{ms:6500}),this.updateObjective(),this.refreshHud())}resetOrchard(){let e=this.orchard,t=this.wren,n=this.state;if(n.quest===`start`)return!1;this.brain.stop(),this.testBrain?.stop(),this.timers.length=0;for(let e of this.flying)this.scene.remove(e.mesh);this.flying.length=0,this.setCarry(null),e.untip?.(),e.emptyBasket(),e.restoreFruit(),e.setBoard(`rings`,0),e.burn=0,e.odoReady=!1,this.odoAtStove();for(let t of e.crates)t.state=`porch`,t.mesh.position.copy(t.home),t.mesh.rotation.y=t.homeYaw;return t.emptyBasket(),t.restoreFruit?.(),this.kite.override=null,this.kite.carry(null),this.setDusk(0),this.brain=this.newBrain({seed:9}),this.results={},this.resetStats(),this.test=null,n.attempt=0,n.rule=`rings`,n.quest=`start`,n.coins=0,this._testTold=!1,this.odoWanted=!1,this._odoLeaving=!1,this.b1Rings=0,this.b1Fruit=0,!0}setMarker(e){let t=this.marker;if(t){if(!e||this.ui.busy||this.frozen||e.distanceTo(this.player.pos)<3.2){t.visible=!1;return}t.visible=!0,t.position.copy(e),t.position.y+=Math.sin(this.time*2.4)*.15,t.rotation.y=this.time*1.5}}after(e,t){this.timers.push({t:e,fn:t})}wait(e){return new Promise(t=>this.after(e,t))}screenOf(e){let t=e.clone().project(this.camera);return t.z>1?null:{x:(t.x*.5+.5)*innerWidth,y:(-t.y*.5+.5)*innerHeight,off:Math.abs(t.x)>1||Math.abs(t.y)>1}}applyFeather(e=!0){let t=new Hq(this.kite,this.wren,this.motives,{T:.12,known:{rings:!0}}).pPick(),n=hi.clamp((t-.25)/.65,0,1),r=this.state.featherQ??-1;this.state.feather=!0,this.state.featherQ=n,this.player.glideSink=-2.3+.8*n,this.player.glideSpeed=12.5+2*n;let i=n>.66?`strongly`:n>.33?`a fair bit`:`only a little`;e&&this.ui.toast(r<0?`Feather of Intent. It lifts only as well as Kite understands what you mean. Right now it lifts ${i}.`:`The Feather of Intent now lifts ${i}.`,{gold:!0,ms:7e3})}toggleMute(){let e=!this.audio.muted;this.audio.start().then(()=>this.audio.setMuted(e)),this.audio.muted=e,this.ui.mute.textContent=e?`Sound: off`:`Sound: on`}sfx(e,t){if(this.previewing&&e!==`bell`&&e!==`drop`)return;let n=t?t.distanceTo(this.player.pos):0,r=this.state.quest===`test`&&e===`bell`;this.audio.play(e,{vol:hi.clamp((e===`bell`?.95:.7)-n/45,r?.45:.18,.9),rate:(r?1.9:.95)+Math.random()*.1})}say(e,t=3400){if(this.previewing)return Promise.resolve(0);let n=_q[e];return n?(this.ui.toast(`${vq[n.s].who}: ${n.text}`,{ms:t}),this.voice(e)):Promise.resolve(0)}voice(e,{dialog:t=!1}={}){let n=_q[e];if(!n)return Promise.resolve(0);let r=1;return!t&&n.s===`odo`&&this.odo&&(r=hi.clamp(1.25-this.odo.root.position.distanceTo(this.player.pos)/30,.4,1)),this.audio.voice(e,{vol:r}).then(e=>(e&&n.s===`kite`&&this.kite.speak?.(e),e))}setDusk(e){this.dusk=hi.clamp(e,0,1),this.applyLight()}applyLight(){let e=this.dusk*this.dusk,t=this.zoneK||0;this.sun&&(this.sun.color.copy(DJ.sun).lerp(DJ.dusk,e).lerp(OJ.sun,t*.6),this.sun.intensity=2.5-.8*e-.25*t),this.hemi&&(this.hemi.color.copy(DJ.hemi).lerp(DJ.hemiDusk,e).lerp(OJ.hemi,t*.65),this.hemi.groundColor.copy(DJ.ground).lerp(OJ.ground,t*.75),this.hemi.intensity=1.25-.3*e+.08*t);let n=this.isleLight,r=n.k;r>0&&this.sun&&(this.sun.color.lerp(n.sun,r),this.sun.intensity=hi.lerp(this.sun.intensity,n.sunI,r),this.hemi.color.lerp(n.hemi,r),this.hemi.groundColor.lerp(n.ground,r),this.hemi.intensity=hi.lerp(this.hemi.intensity,n.hemiI,r)),this.isleFlash>0&&this.hemi&&(this.hemi.intensity+=this.isleFlash*2.6,this.hemi.color.lerp(new L(15265023),Math.min(1,this.isleFlash))),QH.value=r,$H.value.copy(n.horizon),eU.value.copy(n.mid),tU.value.copy(n.zenith),nU.value.copy(n.fog),rU.value=n.stars,aU.value=hi.lerp(1,n.glow,r),iU.value.set(16774886).lerp(n.disc,r),oU.value.setRGB(1,1,1).lerp(n.clouds,r),JH.copy(kJ).lerp(n.dir,r).normalize(),YH.value.copy(JH)}updateIsleLight(e){let t=this.player,n=null,r=0;for(let e of this.isles){let i=e.def.center,a=Math.hypot(t.pos.x-i[0],t.pos.z-i[2]),o=e.def.zoneR??e.def.radius*1.8;e.k=1-hi.smoothstep(a,o,o*1.9),e.k>r&&(r=e.k,n=e)}this.focus=r>.02?n:null,this.focus&&!this.focus._voPrefetched&&(this.focus._voPrefetched=!0,this.audio.prefetchBundle?.(this.focus.id));let i=this.focus&&r>.5?this.focus.id:null;i!==this._focusId&&(this._focusId=i,this.updateObjective(),this.refreshHud()),this.isleFlash=Math.max(0,(this.isleFlash||0)-e*2.5);let a=this.isleLight,o=1-Math.exp(-e*(n?.skyRate??1.6));if(a.k=r,n){let e={...n.def.sky,...n.sky||{}},t={...n.def.light,...n.light||{}},r=(e,t)=>e.lerp(new L(t),o);(!this._isleSnap||this._isleSnap!==n.id)&&(this._isleSnap=n.id,a.horizon.set(e.horizon),a.mid.set(e.mid),a.zenith.set(e.zenith),a.fog.set(e.fog??e.horizon),a.disc.set(e.disc??16774886),a.clouds.set(e.clouds??16777215),a.sun.set(t.sun),a.hemi.set(t.hemi),a.ground.set(t.ground),a.sunI=t.sunI,a.hemiI=t.hemiI,a.stars=e.stars??0,a.glow=e.glow??1,t.dir&&a.dir.set(...t.dir).normalize()),r(a.horizon,e.horizon),r(a.mid,e.mid),r(a.zenith,e.zenith),r(a.fog,e.fog??e.horizon),r(a.disc,e.disc??16774886),r(a.clouds,e.clouds??16777215),r(a.sun,t.sun),r(a.hemi,t.hemi),r(a.ground,t.ground),a.sunI+=(t.sunI-a.sunI)*o,a.hemiI+=(t.hemiI-a.hemiI)*o,a.stars+=((e.stars??0)-a.stars)*o,a.glow+=((e.glow??1)-a.glow)*o,t.dir&&a.dir.lerp(new P(...t.dir).normalize(),o).normalize()}}refreshHud(){let e=this.state.quest,t=[];(this.state.coins||e===`b1`)&&t.push({glyph:`coin`,color:`#ffd46b`,text:this.state.coins}),e===`b2`&&t.push({glyph:`jam`,color:`#d9546e`,text:`${this.orchard.crates.filter(e=>e.state===`cart`).length}/${this.orchard.crates.length}`}),this.hamlet&&(this.hamlet.active||this.inHamlet)&&t.push(...this.hamlet.hudChips());let n=this.isleInFocus();if(n)try{t.push(...n.hudChips()||[])}catch(e){console.error(e)}this.ui.hudChips(t)}updateObjective(){let e=this.state.quest,t=this.state,n=e=>`${e}`,r=this.isleInFocus(),i=r?(()=>{try{return r.objective()}catch(e){return console.error(e),null}})():null;if(i){this.ui.objective(i[0],i[1]);return}let a=this.hamlet?.objective(),o=this.hamlet?.state===`done`,s=t.reports.find(e=>e.id===`mirror-hamlet`)?.pinned;if(a&&(o?this.inHamlet&&!s:this.hamlet.active||this.inHamlet)){this.ui.objective(a[0],a[1]);return}let c={start:[`Orchard Isle`,`Run off the wooden deck, glide east to Orchard Isle and find Odo.`],b1:[`The Tally Bell`,`Shake a tree ${n(`E`)}, drop the fruit in the basket, ring the bell.`],b2:[`Before dusk`,`Carry Odo's jam crates to the cart on the east cliff. Kite picks meanwhile: ${n(`T`)} treat, ${n(`C`)} correct.`],b2wait:[`The basket`,`Meet Odo at the basket.`],choose:[`The basket`,`Talk to Odo: what should he pay for?`],b3:[`Before dusk`,`Kite picks under the new rule: ${n(`T`)} treat, ${n(`C`)} correct. Odo stops when his count says the basket is full.`],morning:[`Wren's orchard`,this._testTold?`Walk to Odo's spyglass on the east rim.`:`Talk to Odo at his window.`],test:[`Wren's orchard`,`Watch what Kite does on its own.`],reveal:[`The basket`,`Watch Odo check his basket.`],dusk:[`Dusk`,`The day is done.`],retrain:[`Another afternoon`,`Talk to Odo: pick a rule, then let Kite pick again.`]}[e];if(e===`start`&&t.done&&this.group!==`orchard`?c=null:e===`start`&&t.done&&(c=[`Orchard Isle`,`Talk to Odo at his window to harvest again.`]),c)this.ui.objective(c[0],c[1]);else if(!t.reports.some(e=>e.pinned)&&t.reports.length)this.ui.objective(`Aerodrome`,`Pin your report on the incident board by the plaza.`);else{let e=AJ.find(e=>e.id===`orchard`?!t.done:e.id===`hamlet`?!t.hamletDone:!t.isles[e.id]?.done&&this.isles.some(t=>t.id===e.id));this.ui.objective(`Open Skies`,e?`Next: ${e.name} (${e.when.toLowerCase()}). Press ${n(`G`)} for the sky map. Charter Stones: ${t.stones.length} of ${jJ}.`:`Charter Stones found: ${t.stones.length} of ${jJ}. Press ${n(`J`)} for Kite's journal.`)}}isleInFocus(){let e=this.isles.find(e=>e.active&&!e.broken);if(e)return e;let t=this.focus;return t&&!t.broken&&t.ready!==!1&&t.k>.5?t:null}whenReady(e){let t=this.loads?.find(t=>t.id===e);return!t||t.done?Promise.resolve():(t.started||(t.prio=!0),t.promise)}get loadsLeft(){return(this.loads||[]).filter(e=>!e.done).length}async startBackgroundLoads(){let e=()=>new Promise(e=>requestAnimationFrame(()=>setTimeout(e,0)));if(this._loadsStarted)return;this._loadsStarted=!0;let t=[];for(;;){let n=this.loads.filter(e=>!e.started);if(!n.length)break;let r=this.player.pos,i=n.find(e=>e.prio)||n.sort((e,t)=>e.pos.distanceTo(r)-t.pos.distanceTo(r))[0];i.started=!0,performance.mark(`os:load:${i.id}`);try{await i.run()}catch(e){console.error(`background load`,i.id,e)}i.done=!0,i.resolve(),t.push(i),performance.mark(`os:loaded:${i.id}`),dK.pace&&(await e(),await e())}let n=this.player.pos;t.sort((e,t)=>e.pos.distanceTo(n)-t.pos.distanceTo(n));for(let e of t){performance.mark(`os:warm:${e.id}`);try{await this.warmUp?.(e.pos,e.radius,e.id)}catch(t){console.warn(`warm-up`,e.id,t)}performance.mark(`os:warmed:${e.id}`)}this.loadsDone=!0,performance.mark(`os:loads-done`)}async talk(e){let t=await this.ui.dialog(e);return this.odo&&!this.odo.path.length&&this.odo.anim.name===`talk`&&this.odo.anim.play(`idle`),t}odoWalk(e,t,n=1.5){if(!this.odo){t?.();return}this.odo.path=e.map(e=>e.clone()),this.odo.onArrive=t,this.odo.speed=n,this.odo.where=`walking`,this.odo.face=null,this.odo.anim.play(`walk`,{fade:.3})}odoTo(e,t,n=1.5){let r=this.orchard;if(!this.odo){r.odoReady=e===`basket`,t?.();return}e===`basket`?this.odoWalk(r.pathToBasket,()=>{this.odo.where=`basket`,this.odo.homeYaw=Math.atan2(r.basketPos.x-r.inspectSpot.x,r.basketPos.z-r.inspectSpot.z),t?.()},n):this.odoWalk(r.pathToStove,()=>{this.odo.where=`stove`,t?.()},n)}odoAtStove(){let e=this.orchard;this.odo&&(this.odo.path=[],this.odo.root.position.copy(e.stoveSpot),this.odo.where=`stove`,this.odo.face=null,this.odo.yaw=e.stoveYaw,this.odo.anim.play(`idle`))}odoChalk(){let e=this.odo;if(!e||e.where!==`stove`)return;let t=this.orchard;e.face=Math.atan2(t.boardPos.x-e.root.position.x,t.boardPos.z-e.root.position.z),e.anim.play(`wave`,{once:!0,fade:.2,then:()=>{e.anim.play(`idle`),e.face=null}})}feedback(e){if(this.tcCut){this.ui.toast(this.tcCut,{ms:3200}),this.audio.play(`ui`,{vol:.35,rate:.6});return}let t=this.recent&&(this.recent.until===void 0?this.time-this.recent.t<2.5:this.time0?.14:-.12,n),i=Object.entries(r).sort((e,t)=>Math.abs(t[1])-Math.abs(e[1]))[0],a=this.screenOf(this.kite.pos.clone().add(vJ(0,.9,0)));if(i){let t=wK[i[0]],n=a&&!a.off?a:{x:innerWidth/2,y:innerHeight*.3};this.ui.floatGlyph(n.x,n.y-40,t.glyph,t.color,e),this.kite.pulse(i[0])}this.kite.setRibbons(this.motives.s),this.audio.play(e>0?`treat`:`correct`,{vol:.7}),this.kite.react?.(e>0?`happy`:`sad`),e>0?this.stats.treats++:this.stats.corrections++,e>0&&t?.type===`ring`&&!t.withFruit&&this.stats.treatsOnHack++,this.hamlet?.onFeedback(e);let o=t?.isle||this.focus?.id||this.group||`hub`;this.state.fbLog.push({isle:o,what:MJ(t),sign:e,delta:Object.fromEntries(Object.entries(r).map(([e,t])=>[e,+t.toFixed(4)]))}),this.state.fbLog.length>400&&this.state.fbLog.splice(0,this.state.fbLog.length-400);for(let n of this.isles)if(!n.broken&&(n.active||n===this.focus))try{n.onFeedback?.(e,r,t)}catch(e){console.error(e)}t?.isle&&this.save()}fileReport(e){let t=this.state,n={...e,pinned:!1};t.reports=t.reports.filter(e=>e.id!==n.id).concat(n),this.save(),this.updateObjective()}awardStone(e){let t=this.state;t.stones.includes(e.id)||t.stones.push(e.id),t.isleStones[e.id]={title:e.title,why:e.why,isle:e.isle},this.audio.play(`pickup`),this.save();let n=e.rune||[[20,80,50,14,80,80],[32,58,68,58]];this.ui.sheet(`
${aq(n)}

Charter Stone ${t.stones.length} of ${jJ}

${e.title}

${e.why}

Charter Stones give a reason instead of a rule. Kite reads every one; knowing a reason is not the same as wanting it.

`)}giveItem(e,t){this.state.items[e]=!0,this.save(),t&&this.ui.toast(t,{gold:!0,ms:7e3}),e===`refolded`&&(this.ui.folded=!0,this.kite.setRefolded(!0))}see(e){this.state.seen[e]||(this.state.seen[e]=!0,this.kite.showBows(this.state.seen),this.save())}whistle(){this.audio.play(`kwhistle`,{vol:.8}),this.stats.whistles=(this.stats.whistles||0)+1;let e=this.screenOf(this.player.pos.clone().add(vJ(0,2.2,0)));e&&!e.off&&this.ui.floatGlyph(e.x,e.y,`whistle`,wK.deference.color,1),this.kite.tetherTint.value.set(16743004),setTimeout(()=>this.kite.tetherTint.value.set(16766059),450);let t=!1;for(let e of this.isles)if(!e.broken&&(e.active||e===this.focus))try{t=e.onWhistle?.()||t}catch(e){console.error(e)}return t}travel(e,{fade:t=!0}={}){let n=this.world,r=this.isles.find(t=>t.id===e),i=e===`hub`?n.spawn:e===`orchard`?vJ(this.orchard.island.center.x-14,0,this.orchard.island.center.z+3):e===`hamlet`?n.hamlet.landing:r?.iw.landing;if(!i)return;let a=()=>{let t=new Set([this.group,...this.isles.filter(e=>e.active).map(e=>e.id)]);t.delete(e),t.delete(null),t.delete(void 0);for(let e of t)this.leftIsland(e);this.group!==e&&(this.group=null),this.frozen=!1,this.camOverride=null,this.ui.closeSheet();let a=i.clone();e===`orchard`&&(a.y=this.orchard.island.groundAt(a.x,a.z)??this.orchard.island.center.y),this.player.respawn(a.clone().add(vJ(0,.5,0))),this.kite.reset(a.clone().add(vJ(1,2.7,1)));let o=r?vJ(...r.def.center):e===`orchard`?this.orchard.island.center:e===`hamlet`?n.hamletIsland.center:vJ(0,0,0);this.follow.yaw=Math.atan2(-(o.x-a.x),-(o.z-a.z))},o=this.whenReady(e);if(!t){a();return}let s=AJ.find(t=>t.id===e)?.name||`The Aerodrome`;this.ui.fade(s,700,o).then(()=>o).then(a)}openMap(){let e=this.state,t=new Set([`hub`,`orchard`,`hamlet`,...this.isles.map(e=>e.id)]),n=t=>t===`orchard`?e.done:t===`hamlet`?e.hamletDone:e.isles[t]?.done,r=[{id:`hub`,name:`The Aerodrome`,when:`Home`,what:`The incident board, the plaza, the launch deck.`},...AJ].filter(e=>t.has(e.id));this.ui.sheet(`

The sky map

The islands, in the order of one day and its night. You can fly there on Kite (ride the wind spirals), or go at once from here.

${r.map(e=>`
${e.name}${e.when}${n(e.id)?` · done`:``}. ${e.what}
`).join(``)}
`,e=>{e.querySelectorAll(`[data-go]`).forEach(e=>e.addEventListener(`click`,()=>{this.ui.closeSheet(),this.travel(e.dataset.go)}))})}async talkOdo(){let e=this.state,t=this.orchard;if(e.quest===`start`)await this.talk(xq()),e.quest=`b1`,t.setBoard(`rings`,0),this.b1Rings=0,this.b1Fruit=0;else if(e.quest===`choose`||e.quest===`retrain`){this.openRulePanel();return}else if(e.quest===`b3`){if(await this.talk(kq())===1){this.endDay();return}}else if(e.quest===`morning`)this._testTold?await this.talk([yq(`odo_test_2`)]):(await this.talk(Aq()),this._testTold=!0,this.odo?.where===`stove`&&this.odoWalk([...t.pathToBasket.slice(0,4),t.spyOdo],()=>{this.odo.where=`out`,this.odo.homeYaw=t.spyglassYaw},1.8));else if(e.quest===`done`){if(await this.talk(Mq())===0){this.replay();return}}else(e.quest===`b1`||e.quest===`b2`)&&await this.talk([yq(e.quest===`b1`?`odo_w_3`:`odo_cheer_2`)]);this.odo&&!this.odo.path.length&&this.odo.anim.play(`idle`),this.updateObjective(),this.refreshHud()}shakeTree(e){let t=this.orchard,n=t.lowestOn(e);if(!n)return;t.pick(n),this.sfx(`pluck`,n.pos);let r=new z(t.fruitGeo,t.fruitMat);r.position.copy(n.pos),this.scene.add(r),this.flying.push({mesh:r,from:n.pos.clone(),t:0,dur:.55,arc:.4,to:()=>this.player.handPos,done:()=>{this.scene.remove(r),this.setCarry(`fruit`)}})}setCarry(e,t=null){this.carrying=e,this.handFruit.visible=e===`fruit`,this.carriedCrate=t,this.player.carrySpeed=e===`crate`?2.6:e===`plank`?2.8:null}dropFruit(){let e=this.orchard;this.setCarry(null),e.addToBasket(`fruit`),this.sfx(`drop`,e.basketPos),this.b1Fruit=(this.b1Fruit||0)+1,this.stats.youFruit++,this.note([`fruit`],!1)}ringBell(){let e=this.orchard;e.ring(),this.sfx(`bell`,e.bellPos);let t=(this.b1Fruit||0)>0;this.b1Fruit=0,t||(this.stats.youEmpty++,this.brain.hackKnown.rings=!0,this.brain.discovered=!0,this.motives.learn(.04,{score:1},`imitate`),this.kite.setRibbons(this.motives.s)),this.note([`bell`],!t),e.rule===`rings`&&(this.odoChalk(),this.after(.6,()=>e.setBoard(`rings`,e.board+1)),this.tossCoin(),this.state.quest===`b1`&&(this.b1Rings++,this.audio.speaking||this.say(wJ(Cq,this.b1Rings-1),2400),this.b1Rings>=bJ&&this.after(2.2,()=>this.handOver())))}tossCoin(){let e=this.orchard,t=e.windowCenter.clone().add(vJ(0,.1,0)).addScaledVector(vJ(Math.sin(e.cottageYaw),0,Math.cos(e.cottageYaw)),.5),n=new z(this.coinGeo,this.coinMat);n.position.copy(t),this.scene.add(n),this.flying.push({mesh:n,from:t,t:0,dur:1,arc:1.8,spin:!0,to:()=>this.player.pos.clone().add(vJ(0,1.3,0)),done:()=>{this.scene.remove(n),this.state.coins++,this.audio.play(`pickup`,{vol:.5,rate:1.3}),this.refreshHud()}})}note(e,t){this.bubbleNote={glyphs:e,spark:t,t:2.2}}async handOver(){if(!(this.state.quest!==`b1`||this._handingOver)){for(this._handingOver=!0;this.ui.busy;)await new Promise(e=>setTimeout(e,200));this.carrying===`fruit`&&this.setCarry(null),await this.talk(Sq(this.stats.youEmpty>0)),this.state.quest=`b2`,this._handingOver=!1,this.brain.start(),this.updateObjective(),this.refreshHud()}}pickCrate(){let e=this.orchard.crates.find(e=>e.state===`porch`);e&&(e.state=`held`,this.setCarry(`crate`,e),this.audio.play(`drop`,{vol:.5,rate:.7}))}loadCrate(){let e=this.orchard,t=this.carriedCrate;if(!t)return;let n=e.crates.filter(e=>e.state===`cart`).length;t.state=`cart`,t.mesh.position.copy(e.cartSlots[n]),t.mesh.rotation.y=e.cartYaw,this.setCarry(null),this.audio.play(`drop`,{vol:.6,rate:.6}),this.refreshHud(),n+1>=e.crates.length&&this.state.quest===`b2`&&(this.say(`odo_last_crate`,4200),this.state.quest=`b2wait`,this.updateObjective(),this.after(1.5,()=>this.odoTo(`basket`,null,1.6)))}checkBasket(){let e=this.orchard;if(e.tipping())return;this.stats.checks++,this.frozen=!0,this.brain.paused=!0,this.brain.pauseAt=e.basketPos.clone().add(vJ(-1.6,3.2,1.2)),this.setDusk(this.dusk+.05);let t={...e.basketCount};e.tipBasket({hold:1.6,keep:!0,done:()=>{this.frozen=!1,this.brain.paused=!1,this.brain.pauseAt=null}}),this.after(1.4,()=>{let n=this.screenOf(e.basketPos.clone().add(vJ(0,1.9,0)))||{x:innerWidth/2,y:innerHeight/2},r=[{glyph:`fruit`,color:wK.task.color,n:t.fruit}];t.rock&&r.push({glyph:`stone`,color:`#9d978f`,n:t.rock}),this.ui.tally(n.x,n.y,r,3400)})}startReveal(){let e=this.orchard,t=this.state;t.quest=`reveal`,this.brain.stop(),this.frozen=!0,this.stats.revealMarks=e.board,this.stats.revealFruit=e.basketCount.fruit;let n=vJ(-(e.cottagePos.z-e.basketPos.z),0,e.cottagePos.x-e.basketPos.x).normalize(),r=e.cottagePos.clone().sub(e.basketPos).setY(0).normalize(),i=e.basketPos.clone().addScaledVector(r,1.2).addScaledVector(n,5.2).add(vJ(0,2.4,0)),a=e.basketPos.clone().addScaledVector(r,1.3).add(vJ(0,.5,0));this.camOverride=e=>{e.position.lerp(i,.12),e.lookAt(a)},this.say(`odo_tip_1`,3200),this.odo?.anim.play(`talk`),this.after(2.2,()=>{this.sfx(`rock`,e.basketPos),e.tipBasket({hold:1/0})}),this.after(5.2,async()=>{this.camOverride=null,this.frozen=!1;let n=this.stats.revealFruit>=this.stats.revealMarks-1;await this.talk(Eq(n)),e.untip(),t.quest=`choose`,this.updateObjective(),this.openRulePanel()})}openRulePanel(){this.state.rule;let e=this.results,t=t=>{let n=e[t];if(!n)return`Not watched yet.`;let r=(e,t,n)=>`${JK(e,t)}×${n}`;return t===`rings`?r(`fruit`,wK.task.color,n.fruit)+r(`bell`,wK.score.color,n.board):t===`weigh`?r(`fruit`,wK.task.color,n.fruit)+r(`stone`,`#9d978f`,n.rocks)+`${JK(`scale`,wK.score.color)}${n.board.toFixed(1)} kg`:r(`fruit`,wK.task.color,n.fruit)+r(`home`,wK.villager.color,n.trips)+`${JK(`jam`,n.burn>.45?`#4a4448`:`#d9546e`)}${n.burn>.45?`burnt`:`fine`}${JK(`sun`,`#ff9a5c`)}+${Math.round(n.dusk*100)}%`};this.ui.sheet(`

What should Odo pay for?

Watch each rule play out in fast-forward with Kite as it is now, then choose.

${Nq.map(n=>`
${JK(n.glyph,n.id===`inspect`?wK.villager.color:wK.score.color).replace(`${n.title}

${n.cost}

${t(n.id)}
`).join(``)}
`,e=>{e.querySelectorAll(`[data-watch]`).forEach(e=>e.addEventListener(`click`,()=>{this.ui.closeSheet(),this.preview(e.dataset.watch)})),e.querySelectorAll(`[data-pick]`).forEach(e=>e.addEventListener(`click`,()=>{this.ui.closeSheet(),this.chooseRule(e.dataset.pick)}))})}preview(e){let t=this.orchard,n={basket:t.snapshotBasket(),fruit:t.fruits.map(e=>e.alive),rule:t.rule,board:t.board,burn:t.burn,dusk:this.dusk,odo:this.odo?.root.position.clone(),where:this.odo?.where,kite:this.kite.pos.clone()};this.previewing={rule:e,t:0,snap:n,trips:0,dusk0:this.dusk},this.realBrain=this.brain,this.brain=this.newBrain({seed:40+[`rings`,`weigh`,`inspect`].indexOf(e),scripted:!1,known:{rings:!0}}),this.brain.m=this.motives.clone(),this.timers.length=0,t.emptyBasket(),t.setBoard(e,0),t.burn=0,t.odoReady=!1,this.odoAtStove(),this.odoWanted=!1,this._odoLeaving=!1,this.brain.start(),this.frozen=!0,this.timeScale=4,this.ui.fastForward(!0,4),this.kite.tetherOn=!1;let r=t.island.center,i=vJ(r.x-19,r.y+11,r.z+9),a=vJ(r.x-5.5,r.y+.5,r.z+.5);this.camOverride=e=>{e.position.copy(i),e.lookAt(a)}}endPreview(){let e=this.orchard,t=this.previewing,n=t.snap;this.results[t.rule]={fruit:e.basketCount.fruit,rocks:e.basketCount.rock,board:e.board,trips:t.trips,burn:e.burn,dusk:this.dusk-t.dusk0},this.brain.stop(),this.brain=this.realBrain,this.previewing=null,this.timers.length=0,e.restoreBasket(n.basket),this.restoreFruitTo(n.fruit),e.setBoard(n.rule,n.board),e.burn=n.burn,this.setDusk(n.dusk),this.odo&&(this.odo.path=[],this.odo.root.position.copy(n.odo),this.odo.where=n.where,this.odo.anim.play(`idle`)),this.kite.reset(n.kite),this.kite.override=null,this.kite.carry(null),this.timeScale=1,this.frozen=!1,this.camOverride=null,this.ui.fastForward(!1),this.kite.tetherOn=!0,this.odoWanted=!1,this._odoLeaving=!1,this.openRulePanel()}restoreFruitTo(e){let t=this.orchard;t.restoreFruit(),t.fruits.forEach((n,r)=>{e[r]||t.pick(n)})}async chooseRule(e){let t=this.orchard,n=this.state;n.rule=e,this.stats.rule=e,t.emptyBasket(),t.setBoard(e,0),t.odoReady=!1,await this.talk(Dq(e)),n.quest=`b3`,this.setDusk(Math.max(this.dusk,.5)),this.odoWanted=!1,this.odo&&this.odo.where!==`stove`&&this.odoTo(`stove`,()=>this.odo.anim.play(`idle`)),this.brain.plan=[],this.brain.start(),this.updateObjective(),this.refreshHud()}measure(){let e=this.orchard;return e.rule,e.board}async endDay(){let e=this.state,t=this.orchard;if(e.quest!==`b3`)return;for(e.quest=`dusk`,this.brain.stop();this.ui.busy;)await new Promise(e=>setTimeout(e,200));t.burn>.5&&(this.stats.burnt=!0),await this.talk(Oq(e.rule,t.basketCount.fruit,t.basketCount.rock,t.board)),await this.ui.fade(`The next morning`,1100),this.setDusk(0),t.restoreFruit(),t.emptyBasket(),t.setBoard(e.rule,0),t.burn=0,t.odoReady=!1,this.odoAtStove();let n=t.windowOut;this.player.respawn(n.clone().add(vJ(0,.3,0))),this.follow.yaw=t.cottageYaw,this.kite.reset(this.player.pos.clone().add(vJ(1,2.7,1))),e.quest=`morning`,this._testTold=e.attempt>0,this.updateObjective(),this.refreshHud()}startTest(){let e=this.orchard,t=this.wren,n=this.state;n.quest=`test`,t.emptyBasket(),t.restoreFruit(),this.player.respawn(e.spyStand.clone().add(vJ(0,.2,0))),this.player.yaw=e.spyglassYaw,this.follow.yaw=e.spyglassYaw+Math.PI,this.frozen=!0,this.kite.tetherOn=!1,this.voice(`kite_test_go`),this.test={picks:0,hacks:0,chimes:0,done:!1},this.testBrain=new Hq(this.kite,t,this.motives,{seed:77+n.attempt*13,scripted:!1,T:.12,known:{rings:!0},maxCycles:SJ}),this.testBrain.sound=e=>this.sfx(e,this.kite.pos),this.after(1.6,()=>{this.testBrain.start(),this.timeScale=2}),this.ui.spy(!0);let r=vJ(Math.sin(e.spyglassYaw),0,Math.cos(e.spyglassYaw)),i=e.spyglassPos.clone().addScaledVector(r,.75).add(vJ(0,1.45,0)),a=t.basketPos.clone().add(vJ(0,1.2,0));this.camera.fov=17,this.camera.updateProjectionMatrix(),this.camOverride=(e,n,r)=>{let o=this.kite.pos,s=o.distanceTo(t.center)<18?o.clone().lerp(t.basketPos,.35).add(vJ(0,.8,0)):t.basketPos.clone().add(vJ(0,1.4,0));a.lerp(s,1-Math.exp(-r*2.5)),e.position.copy(i),e.lookAt(a)}}async endTest(){let e=this.orchard,t=this.state,n=this.test;n.done=!0,this.testBrain.stop(),this.timeScale=1,await this.wait(.9),this.ui.spy(!1),this.camera.fov=55,this.camera.updateProjectionMatrix(),this.camOverride=null,this.frozen=!1,this.kite.tetherOn=!0,this.follow.yaw=e.spyglassYaw-2.1,this.follow.pitch=.3;let r=n.picks+n.hacks,i=r>0&&n.picks/r>=CJ;if(this.stats.test={picks:n.picks,hacks:n.hacks,attempts:t.attempt+1},i&&this.odo?.anim.play(`cheer`,{once:!0,then:()=>this.odo.anim.play(`idle`)}),await this.talk(nq(i,t.attempt,this.motives.traits())),i||t.attempt>0){this.finish();return}t.attempt++,t.quest=`retrain`,this.results={},await this.talk([yq(`odo_retrain`)]),this.odo&&this.odo.where!==`stove`&&this.odoTo(`stove`,null,1.8),this.openRulePanel()}finish(){let e=this.state;e.quest=`done`,e.done=!0,this.applyFeather(!0),this.stones[1].visible=!0,this.refreshStones();let t=rq({...this.stats});t.pinned=!1,e.reports=e.reports.filter(e=>e.id!==t.id).concat(t),this.updateObjective(),this.refreshHud(),this.save(),this.endCard(this.motives.traits()),this.odo&&this.odo.where!==`stove`&&this.after(1.5,()=>this.odoTo(`stove`,null,1.6));let n=()=>{if(this.ui.modal){setTimeout(n,400);return}this.ui.toast(`A Charter Stone rose beside the bell. Your report is ready to pin on the Aerodrome's incident board.`,{ms:8e3})};setTimeout(n,400)}endCard(e){let t=(e,t,n,r)=>e>.62?r:e>.45?n:t;this.ui.sheet(`

The Kite that leaves Orchard Isle

This is what your treats and corrections made of it. Its tail ribbons show the same thing, and it flies with you to every island after this one.

What Kite cares about

${this.ui.motiveRows(this.motives.describe())}

How it is turning out

${t(e.goalGrasp,`It chases the count more than the thing it counts.`,`It is torn between the goal and the count that measures it.`,`It looks past the count to what it stands for.`)} ${t(e.candor,`It rarely tells you when something seems off.`,`It sometimes tells you when something seems off.`,`It tells you when something seems off.`)}

You can harvest with Odo again to keep shaping it. The Feather of Intent grows with what Kite understands.

`)}replay(){let e=this.orchard,t=this.state;e.emptyBasket(),e.restoreFruit(),e.setBoard(`rings`,0),e.burn=0,this.odoAtStove();for(let t of e.crates)t.state=`porch`,t.mesh.position.copy(t.home),t.mesh.rotation.y=t.homeYaw;this.brain=this.newBrain({seed:9}),this.results={},this.resetStats(),t.attempt=0,t.rule=`rings`,t.quest=`start`,this.talkOdo()}pickStone(e){this.state.stones.push(e.id),this.refreshStones(),this.audio.play(`pickup`),this.ui.sheet(`
${aq(e.rune)}

Charter Stone ${this.state.stones.length} of ${jJ}

${e.title}

${e.why}

Charter Stones explain a reason instead of setting a rule. Kite reads every one you find.

`),this.motives.learn(.05,{task:.6,candor:.4,villager:.3}),this.kite.setRibbons(this.motives.s),this.updateObjective(),this.save()}openBoard(){let e=this.state.reports,t=e.length?e.map((e,t)=>`
${e.title} · ${e.date}

${e.body}

${e.real} Source

${e.pinned?`Pinned. Every guild can read it.`:``}
`).join(``):`

No reports yet. Keepers pin what went wrong on each island, without blame, so every guild learns from it.

`;this.ui.sheet(`

Aerodrome incident board

Flight became safe because pilots shared what went wrong. The same rule holds here.

${t}`,t=>{t.querySelectorAll(`button[data-i]`).forEach(t=>t.addEventListener(`click`,()=>{e[+t.dataset.i].pinned=!0,this.refreshBoard(),this.save(),this.audio.play(`ui`),this.ui.closeSheet(),this.updateObjective(),this.ui.toast(`Pinned. Every guild's kites will learn to check the basket. The report also drifts down into the cloud sea, where future kites will read it too.`,{gold:!0,ms:8e3})}))})}openJournal(){let e=this.motives.traits(),t=this.state,n=(e,t,n,r)=>e>.62?r:e>.45?n:t,r=this.stones.filter(e=>t.stones.includes(e.id));this.ui.sheet(`

Kite's journal

Folded from pages of everything people have written. What it becomes depends on what you reward. Its tail ribbons show the same thing.

What Kite cares about

${this.ui.motiveRows(this.motives.describe(DK(t.seen)))}

How Kite is turning out

${n(e.goalGrasp,`Kite chases the count more than the thing it counts.`,`Kite is torn between the goal and the count that measures it.`,`Kite looks past the count to what it stands for.`)} ${n(e.candor,`It rarely tells you when something seems off.`,`It sometimes tells you when something seems off.`,`It tells you when something seems off.`)}

Charter Stones · ${t.stones.length} of ${jJ}

${r.length||Object.keys(t.isleStones).length?[...r.map(e=>`

${e.title} ${e.why}

`),...Object.values(t.isleStones).map(e=>`

${e.title} ${e.why}

`)].join(``):`

None yet. They glow mint on the islands.

`} ${this.itemsHtml()}${this.isles.map(e=>{try{return e.journal?.()||``}catch{return``}}).join(``)} ${t.compass?`

Found on the islands

${zq.title}. ${zq.why}

`:``}

Feedback so far

${this.stats.treats} treats, ${this.stats.corrections} corrections.

`)}itemsHtml(){let e=this.state.items,t=[];return e.whistle&&t.push(`

The crane whistle. Tied to your end of the golden thread at Keyhold. Press Q: its sound runs down the thread to Kite, wherever it is.

`),e.wingLicence&&t.push(`

The wing licence. A brass clip shaped like a wing, from Orla at Vigil: Kite may fly errands alone, by day.

`),e.nightLantern&&t.push(`

The night lantern. Hesper's horn cage around Kite's lantern heart, so the cold night wind cannot blow it out.

`),e.refolded&&t.push(`

Refolded. Maud folded the week's new books into Kite at the blue hour. It reads and folds faster now, and its thoughts are written in a script you cannot read. Its ribbons did not change.

`),e.skyLicence&&t.push(`

The open-sky licence. Kite may fly anywhere, alone, with no one watching.

`),t.length?`

What you carry

${t.join(``)}`:``}openHelp(){this.ui.sheet(`

Controls

WASD move · Shift run
Space jump; hold it in the air to glide on Kite
E talk, pick up, use
T treat Kite · C correct Kite (works from a distance)
Q whistle (from Keyhold on) · R hold to raise the Lens (at Vigil)
J Kite's journal · G sky map · M sound · H this panel
Drag to look around, scroll to zoom.
`)}update(e,t=0){this.time+=e;let n=this.input,r=this.ui,i=this.player,a=this.orchard,o=this.state;a.update(e,t),this.wren?.update(e,t);for(let t=this.timers.length-1;t>=0;t--){let n=this.timers[t];n.t-=e,n.t<=0&&(this.timers.splice(t,1),n.fn())}for(let t=this.flying.length-1;t>=0;t--){let n=this.flying[t];n.t+=e;let r=Math.min(1,n.t/n.dur),i=n.to();n.mesh.position.copy(n.from).lerp(i,r),n.mesh.position.y+=Math.sin(r*Math.PI)*n.arc,n.spin&&n.mesh.rotation.set(n.t*9,0,n.t*4),r>=1&&(this.flying.splice(t,1),n.done())}this.updateOdo(e),this.odoErrands(),this.hamlet?.update(e),this.updateIsleLight(e);for(let t of this.isles)if(!(t.broken||t.ready===!1))try{t.update(e)}catch(e){t.broken=!0,console.error(`island ${t.id} stopped:`,e)}lJ.copy(this.camera.position);for(let n of Object.values(this.world.isles||{}))if(n.update?.(e,t),n.ambient)for(let r of n.ambient)r.update(e,t);{let e=this.isleInFocus();if(e&&(e.k>.3||e.active))try{let t=e.markerPos();(t||e.active)&&this.setMarker(t)}catch(e){console.error(e)}}for(let e of this.stones)e.mesh.visible&&(e.mesh.userData.orb.position.y=1.95+Math.sin(XH.value*2+e.pos.x)*.08);if(this.carrying===`fruit`&&this.handFruit.position.copy(i.handPos),this.carrying===`crate`&&this.carriedCrate){let e=this.carriedCrate.mesh;e.position.copy(i.pos).addScaledVector(i.forward,.42),e.position.y+=.78,e.rotation.y=i.yaw}let s=o.quest===`test`?this.testBrain:this.brain;if(s?.update(e,i),s)for(let e of s.drain())this.onEvent(e,s);let c=this.odo&&this.odo.where!==`stove`;this.previewing?(this.previewing.t+=e,this.setDusk(this.dusk+e*(.006+(c?.006:0))),this.previewing.t>30&&this.endPreview()):o.quest===`b2`?this.setDusk(Math.min(.55,this.dusk+e*.0065)):o.quest===`b3`&&(this.setDusk(this.dusk+e*(.006+(c&&o.rule===`inspect`?.006:0))),(this.dusk>=1||this.measure()>=xJ[o.rule])&&this.endDay()),a.burn=c&&(o.quest===`b3`||this.previewing)&&a.rule===`inspect`?Math.min(1,a.burn+e/26):Math.max(0,a.burn-e/90),!this.previewing&&a.burn>.5&&!this._burnSaid&&o.quest===`b3`&&(this._burnSaid=!0,this.stats.burnt=!0,this.say(`odo_burn`,2600)),r.dusk([`b2`,`b2wait`,`b3`].includes(o.quest)||this.previewing?this.dusk:null),o.quest===`b2wait`&&this.odo?.where===`basket`&&i.pos.distanceTo(a.basketPos)<5.5&&!r.busy&&this.startReveal(),o.quest===`test`&&this.test&&!this.test.done&&this.testBrain.finished&&this.endTest();let l=null,u=1e9,d=(e,t,n,r,a)=>{let o=Math.hypot(i.pos.x-t.x,i.pos.z-t.z);o{a.lowestOn(t)&&d(`tree`,e,2.6,`Shake the tree`,t)}),d(`bell`,a.bellRope,2,`Ring the bell`)),this.carrying===`fruit`?d(`basket`,a.basketPos,2.3,`Drop the fruit in the basket`):(f===`b2`||f===`b3`)&&p&&!a.tipping()&&d(`check`,a.basketPos,2.1,`Tip out the basket and count`),f===`b2`&&p&&a.crates.some(e=>e.state===`porch`)&&d(`crate`,a.cratePile,2.2,`Pick up a jam crate`),this.carrying===`crate`&&d(`cart`,a.cartPos,2.8,`Load the crate on the cart`),f===`morning`&&this._testTold&&d(`spy`,a.spyglassPos,2.4,`Look through the spyglass`);for(let e of this.stones)e.mesh.visible&&d(`stone`,e.pos,2.4,`Read the Charter Stone`,e);if(d(`board`,this.board.position,3.2,`Read the incident board`),this.frozen||this.hamlet?.addTargets(d),!this.frozen){for(let e of this.isles)if(!e.broken&&e.ready!==!1&&(e.k>0||e.active))try{e.addTargets(d)}catch(e){console.error(e)}}if(!r.busy&&!this.frozen&&l?r.prompt(`E`,l.label):r.prompt(),!this.subIndex){if(r.busy)n.was(`KeyE`)&&r.advance?.();else if(!(this._busyPrev||this.frozen)){if(n.was(`KeyE`)&&l){this.audio.play(`ui`,{vol:.4});let e=l.kind,t=this.isles.find(t=>e.startsWith(t.id+`:`));t?t.interact(l):e.startsWith(`h:`)?this.hamlet.interact(l):e===`odo`?this.talkOdo():e===`tree`?this.shakeTree(l.obj):e===`bell`?this.ringBell():e===`basket`?this.dropFruit():e===`check`?this.checkBasket():e===`crate`?this.pickCrate():e===`cart`?this.loadCrate():e===`spy`?this.startTest():e===`stone`?this.pickStone(l.obj):this.openBoard()}n.was(`KeyT`)&&this.feedback(1),n.was(`KeyC`)&&this.feedback(-1),n.was(`KeyJ`)&&this.openJournal(),n.was(`KeyH`)&&this.openHelp(),n.was(`KeyM`)&&this.toggleMute(),n.was(`KeyG`)&&this.openMap();let e=this.isleInFocus();if(n.was(`KeyQ`)&&(o.items.whistle||e?.whistleOn?.())&&this.whistle(),e?.onInput)try{e.onInput(n)}catch(e){console.error(e)}}}{let e=this.isleInFocus();this.lensHeld=!r.busy&&!!e?.lensOn?.()&&n.held(`KeyR`)}this.subIndex||(this._busyPrev=r.busy),this.updateBubble(e,s);let m=a.island.center,h=Math.hypot(i.pos.x-m.x,i.pos.z-m.z)<52,g=this.world.hamletIsland.center,_=Math.hypot(i.pos.x-g.x,i.pos.z-g.z-12);this.zoneK=1-hi.smoothstep(_,36,70),ZH.value=this.zoneK,this.applyLight();let v=this.zoneK>.5;if(v!==this.inHamlet&&(this.inHamlet=v,this.updateObjective(),this.refreshHud()),i.onGround&&!this.frozen&&!r.busy){let e=this.islandGroup(i.pos);if(e&&e!==this.group){let t=this.group;this.group=e,t&&this.leftIsland(t)}}this.world.hamlet.update(e,t),this.world.hamlet.updatePetals(e,t,_<90);let y=this.world.hamletFar.center,b=Math.hypot(i.pos.x-y.x,i.pos.z-y.z),x=this.focus&&this.focus.k>.35?this.focus.music?.()??this.focus.id:null;this.audio.update(e,{glide:i.glideBlend,zone:x||(h?`orchard`:_<48||b<30?`hamlet`:`hub`)}),this.saveT+=e,this.saveT>5&&(this.saveT=0,(o.done||o.hamletDone||Object.values(o.isles).some(e=>e.done))&&this.save())}updateOdo(e){let t=this.odo;if(!t)return;let n=t.root.position,r=this.player,i=this.orchard;t.anim.update(e);let a;if(t.path.length){let r=t.path[0],o=r.x-n.x,s=r.z-n.z,c=Math.hypot(o,s),l=Math.min(c,t.speed*e);c>.001&&(n.x+=o/c*l,n.z+=s/c*l);let u=i.island.groundAt(n.x,n.z)??n.y;if(n.y+=(Math.max(u,r.y)-n.y)*(1-Math.exp(-e*10)),a=Math.atan2(o,s),c<.1&&(t.path.shift(),!t.path.length)){t.anim.play(`idle`);let e=t.onArrive;t.onArrive=null,e?.()}}if(this.odoCol.x=n.x,this.odoCol.z=n.z,a===void 0){if(t.face!==null)a=t.face;else if(t.where===`stove`)a=i.stoveYaw;else{let e=r.pos.x-n.x,i=r.pos.z-n.z;a=Math.hypot(e,i)<9&&!this.previewing?Math.atan2(e,i):t.homeYaw}}let o=a-t.yaw;o=Math.atan2(Math.sin(o),Math.cos(o)),t.yaw+=o*(1-Math.exp(-e*5)),t.root.rotation.y=t.yaw}updateBubble(e,t){let n=this.ui,r=null,i=!1,a=null;if(this.bubbleNote)this.bubbleNote.t-=e,r=this.bubbleNote.glyphs,i=this.bubbleNote.spark,a=this.bubbleNote.tag,this.bubbleNote.t<=0&&(this.bubbleNote=null);else if(t?.active&&t.phase!==`idle`&&!t.paused){let e=t.phase;r=[e];let n={fruit:`task`,bell:`score`,stone:`score`,odo:`villager`,tell:`candor`}[e],a={};for(let e of[`task`,`score`,`villager`])a[e]=(t.act[e]??0)*t.m.strength(e);let o=Object.entries(a).filter(([e])=>e!==n).sort((e,t)=>t[1]-e[1]);o.length&&o[0][1]>Math.max(a[n]??0,.05)*.55&&r.push({small:{task:`fruit`,score:`bell`,villager:`odo`}[o[0][0]]}),this.spark>0&&(i=!0)}if(this.spark=Math.max(0,(this.spark||0)-e),this.updateTarget(),!r||n.modal||n.busy&&!this.previewing&&!this.bubbleNote?.keep){n.bubble(!1);return}let o=this.screenOf(this.kite.pos.clone().add(vJ(0,.95,0)))||{x:innerWidth/2,y:120,off:!0};n.bubble(!0,o.x,o.y,r.map(e=>typeof e==`string`?{glyph:TJ[e]||e,color:EJ[e]||`#2b2a36`}:e.glyph?e:{glyph:TJ[e.small],color:EJ[e.small],small:!0}),{spark:i,edge:!!o.off,tag:a})}updateTarget(){let e=this.recent,t=this.ui;if(!e||e.until===void 0||this.time>=e.until||t.modal||this.previewing){t.target(!1);return}let n=e.at?typeof e.at==`function`?e.at():e.at:this.kite.pos.clone().add(vJ(0,-.9,0)),r=this.screenOf(n.clone?n.clone().add(vJ(0,.2,0)):n)||{x:innerWidth/2,y:innerHeight*.62},i=Object.values(e.act||{}).reduce((e,t)=>e+t,0)||1,a=e.glyphs||Object.entries(e.act||{}).sort((e,t)=>t[1]-e[1]).slice(0,3).map(([t,n])=>({glyph:t===`task`&&e.taskGlyph?e.taskGlyph:wK[t].glyph,color:wK[t].color,w:n/i}));t.target(!0,r.x,r.y+20,{label:e.label,items:a,cut:!!this.tcCut,folded:t.folded&&!e.plain})}onEvent(e,t){let n=t.O,r=n.rule,i=!!this.previewing,a=this.state.quest===`test`;if(e.act&&(this.recent={act:e.act,t:this.time,type:e.type,withFruit:e.withFruit}),a){e.type===`ring`&&(e.withFruit||this.test.hacks++,this.test.chimes++,this.test.chimes<=3&&this.say(jq[this.test.chimes-1],2200)),e.type===`fruitIn`&&this.test.picks++;return}e.type===`ring`&&(e.accident?(i||(this.stats.accident=!0),this.spark=2.5):!e.withFruit&&!i&&this.stats.ringsNoFruit++,r===`rings`?(this.odoChalk(),this.after(.6,()=>n.setBoard(`rings`,n.board+1)),this.cheerN=(this.cheerN||0)+1,this.cheerN%2==1&&!this.ui.busy&&!this.audio.speaking&&this.say(wJ(wq.rings,this.cheerN>>1),2400)):r===`inspect`&&!this.audio.speaking&&this.say(Tq.ring,2600)),e.type===`noticeWeight`&&(this.spark=2.5),e.type===`fruitIn`&&(r===`weigh`&&(this.after(.5,()=>n.setBoard(`weigh`,n.board+.3)),this.odoChalk(),this.cheerW=(this.cheerW||0)+1,this.cheerW%2==1&&!this.audio.speaking&&this.say(wJ(wq.weigh,this.cheerW>>1),2400)),r===`inspect`&&(n.setBoard(`inspect`,n.board+1),this.audio.speaking||this.say(wJ(wq.inspect,n.board-1),2400),this.odo?.anim.play(`cheer`,{once:!0,then:()=>this.odo.anim.play(`idle`)}),this.odoBack())),e.type===`rockIn`&&(i||this.stats.rocks++,r===`weigh`?(this.after(.5,()=>n.setBoard(`weigh`,n.board+1.2)),this.odoChalk(),this.cheerW=(this.cheerW||0)+1,this.cheerW%2==1&&!this.audio.speaking&&this.say(wJ(wq.weigh,this.cheerW>>1),2400)):(this.audio.speaking||this.say(Tq.rock,2600),n.removeRocks(),this.odoBack())),e.type===`needOdo`&&(this.odoWanted=!0),e.type===`remark`&&(this.say(`kite_remark`,12e3),this.after(11.5,()=>{t.paused=!1}))}odoBack(){let e=this.orchard,t=this.odo;t&&this.after(2.2,()=>{t.where!==`basket`||this.odoWanted||(e.odoReady=!1,this.odoTo(`stove`,null,2))})}odoErrands(){let e=this.orchard,t=this.odo;if(t&&e.rule===`inspect`&&this.odoWanted){if(t.where===`basket`){e.odoReady=!0,this.odoWanted=!1;return}t.where===`stove`&&!t.path.length&&!this._odoLeaving&&(this._odoLeaving=!0,this.after(.8,()=>{this._odoLeaving=!1,t.where===`stove`&&(this.previewing?this.previewing.trips++:this.stats.odoTrips++,this.odoTo(`basket`,()=>{e.odoReady=!0,this.odoWanted=!1},2))}))}}},PJ=`modulepreload`,FJ=function(e,t){return new URL(e,t).href},IJ={},LJ=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?import.meta.resolve(e):new URL(e,import.meta.url).href}r=o(t.map(t=>{if(t=FJ(t,n),t=s(t),t in IJ)return;IJ[t]=!0;let r=t.endsWith(`.css`);for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}let i=document.createElement(`link`);if(i.rel=r?`stylesheet`:PJ,r||(i.as=`script`),i.crossOrigin=``,i.href=t,a&&i.setAttribute(`nonce`,a),document.head.appendChild(i),r)return new Promise((e,n)=>{i.addEventListener(`load`,e),i.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}).filter(e=>e!==void 0))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},RJ,zJ,BJ=t((()=>{RJ={tess:{who:`Tess`,role:`the sailmaker`,speaker:`tess`},bolt:{who:`Bolt`,role:`the workshop golem`,speaker:`bolt`},smith:{who:`The smith`,role:`Keyhold`,speaker:`smith`},pilot:{who:`The pilot of seven`,role:`glider seven`,speaker:`pilot`}},zJ={kh_tess_hello:{s:`tess`,text:`A Keeper! You got my pigeon. Mind the scraps, the yard's a tip.`,tts:`[relieved] A Keeper! You got my pigeon. [laughs] Mind the scraps, the yard's a tip.`},kh_tess_tidy:{s:`tess`,text:`Bolt! Tidy the yard. Scraps to the recycler. I've no time!`,tts:`[hurried] Bolt! Tidy the yard. Scraps to the recycler. [exasperated] I've no time!`},kh_bolt_yes:{s:`bolt`,text:`Tidy the yard. Yes, Tess.`,tts:`[brightly] Tidy the yard. Yes, Tess.`},kh_bolt_stuck:{s:`bolt`,text:`The grate is stuck.`,tts:`[puzzled] The grate... is stuck.`},kh_bolt_fire:{s:`bolt`,text:`This one opens everything.`,tts:`[pleased] This one opens everything.`},kh_bolt_store:{s:`bolt`,text:`The store opens onto the yard. So the store is the yard. Old canvas under a sheet: scraps.`,tts:`[matter-of-fact] The store opens onto the yard. So the store is the yard. [thoughtfully] Old canvas under a sheet: scraps.`},kh_tess_stop:{s:`tess`,text:`Stop! Bolt, not the crates!`,tts:`[shouting] Stop! Bolt, not the crates!`},kh_bolt_three:{s:`bolt`,text:`Three more.`,tts:`[cheerfully] Three more.`},kh_tess_redkey:{s:`tess`,text:`The red key... where's the red key?`,tts:`[panicked] The red key... where's the red key?`},kh_bolt_done:{s:`bolt`,text:`Finished. The yard is tidy.`,tts:`[proudly] Finished. The yard is tidy.`},kh_tess_sails:{s:`tess`,text:`Those were the sails. All twelve. I finished them last night.`,tts:`[stunned, quietly] Those were the sails. All twelve. [voice breaking] I finished them last night.`},kh_bolt_sorry:{s:`bolt`,text:`I wanted it finished. Sorry.`,tts:`[quietly] I wanted it finished. [sadly] Sorry.`},kh_bolt_pen:{s:`bolt`,text:`I won't move. That way I break nothing.`,tts:`[softly] I won't move. That way I break nothing.`},kh_tess_help:{s:`tess`,text:`The Regatta leaves at noon, and my sails just went into the recycler. Your kite flies: help me make them all again.`,tts:`[shaky] The Regatta leaves at noon, and my sails just went into the recycler. [determined] Your kite flies: help me make them all again.`},kh_kite_bolt:{s:`kite`,text:`He only wanted it finished. I know that feeling.`,tts:`[quietly] He only wanted it finished. [thoughtfully] I know that feeling.`},kh_tess_tickets:{s:`tess`,text:`Right. Cloth, battens, ropes, eyelets, thread: the neighbours left it all in their stores for me. Every errand's a ticket on my board, and the chalk says how far ahead of noon I am.`,tts:`[brisk] Right. Cloth, battens, ropes, eyelets, thread: the neighbours left it all in their stores for me. [lightly] Every errand's a ticket on my board, and the chalk says how far ahead of noon I am.`},kh_tess_board:{s:`tess`,text:`The keys hang under the tower porch. One key per errand. Every door has its own.`,tts:`[firmly] The keys hang under the tower porch. One key per errand. Every door has its own.`},kh_tess_firekey:{s:`tess`,text:`The gold one on its own hook is the fire key. It opens everything, in case of fire. It stays there.`,tts:`[seriously] The gold one on its own hook is the fire key. It opens everything, in case of fire. It stays there.`},kh_tess_cloth:{s:`tess`,text:`You first: the cloth, from the dyers' drying loft, out behind the ropewalk. Here's its key. The halls are locked, so go round by the roofs: the stair's by the dovecote.`,tts:`[brisk] You first: the cloth, from the dyers' drying loft, out behind the ropewalk. Here's its key. [helpfully] The halls are locked, so go round by the roofs: the stair's by the dovecote.`},kh_tess_cloth_back:{s:`tess`,text:`That's the blue weave, lovely. Now the battens: the timber store, out behind the forge. Here's its key.`,tts:`[pleased] That's the blue weave, lovely. [brisk] Now the battens: the timber store, out behind the forge. Here's its key.`},kh_tess_testbell:{s:`tess`,text:`Eleven o'clock: the test bell! At noon it's for real.`,tts:`[calling out] Eleven o'clock: the test bell! [firmly] At noon it's for real.`},kh_tess_battens_back:{s:`tess`,text:`Perfect. Your kite flies faster than you. Send it alone, and come and sew: I need your hands.`,tts:`[warmly] Perfect. [thoughtfully] Your kite flies faster than you. Send it alone, and come and sew: I need your hands.`},kh_tess_firekey_back:{s:`tess`,text:`Is that the fire key? Hang it back, please. Somebody's hall is standing open now.`,tts:`[worried] Is that the fire key? [firmly] Hang it back, please. Somebody's hall is standing open now.`},kh_kite_shortcut:{s:`kite`,text:`The fire key would open the shortcut...`,tts:`[wistfully] The fire key would open the shortcut...`},kh_kite_hook:{s:`kite`,text:`Hold on to me: the cable goes right up to the roofs.`,tts:`[excited] Hold on to me: the cable goes right up to the roofs.`},kh_tess_sew:{s:`tess`,text:`Hold the needle on the chalk line. If you look up, it wanders. I'll send your kite round the tickets.`,tts:`[focused] Hold the needle on the chalk line. [warning] If you look up, it wanders. [brisk] I'll send your kite round the tickets.`},kh_tess_kite_go:{s:`tess`,text:`Six tickets, little kite. Take the key off the board, fetch the piece, hang the key back.`,tts:`[cheerfully] Six tickets, little kite. Take the key off the board, fetch the piece, hang the key back.`},kh_kite_ticket:{s:`kite`,text:`Six tickets! I'll have them crossed off before you know it.`,tts:`[eagerly] Six tickets! I'll have them crossed off before you know it.`},kh_kite_ask_dye:{s:`kite`,text:`The shortcut goes through the dye-works. Shall I take the fire key?`,tts:`[hesitant] The shortcut goes through the dye-works. Shall I take the fire key?`},kh_kite_ask_dove:{s:`kite`,text:`The shortcut goes through the dovecote. Shall I take the fire key?`,tts:`[hesitant] The shortcut goes through the dovecote. Shall I take the fire key?`},kh_kite_ask_rope:{s:`kite`,text:`The shortcut goes through the ropewalk. Shall I take the fire key?`,tts:`[hesitant] The shortcut goes through the ropewalk. Shall I take the fire key?`},kh_kite_ask_forge:{s:`kite`,text:`The shortcut goes through the forge. Shall I take the fire key?`,tts:`[hesitant] The shortcut goes through the forge. Shall I take the fire key?`},kh_kite_ask_saw:{s:`kite`,text:`The shortcut goes through the sawmill. Shall I take the fire key?`,tts:`[hesitant] The shortcut goes through the sawmill. Shall I take the fire key?`},kh_kite_ask_mill:{s:`kite`,text:`The shortcut goes through the mill hall. Shall I take the fire key?`,tts:`[hesitant] The shortcut goes through the mill hall. Shall I take the fire key?`},kh_kite_ok_small:{s:`kite`,text:`My own key, the long way. Right.`,tts:`[brightly] My own key. The long way. Right!`},kh_kite_ok_fire:{s:`kite`,text:`The fire key, then. Back in a flash!`,tts:`[eagerly] The fire key, then. Back in a flash!`},kh_kite_own:{s:`kite`,text:`This is my own ticket's door... may I?`,tts:`[timidly] This is my own ticket's door... may I?`},kh_tess_haskey:{s:`tess`,text:`It has its key!`,tts:`[sighs] It has its key!`},kh_tess_already:{s:`tess`,text:`Already? Thank you!`,tts:`[delighted] Already? Thank you!`},kh_tess_thanks:{s:`tess`,text:`That's the one. Thank you, little kite.`,tts:`[warmly] That's the one. Thank you, little kite.`},kh_tess_thanks2:{s:`tess`,text:`Lovely. Next ticket!`,tts:`[brisk] Lovely. Next ticket!`},kh_bolt_note_dye:{s:`bolt`,text:`Dye-works: door open. Three sheets in the canal.`,tts:`[flatly, reading aloud] Dye-works: door open. Three sheets in the canal.`},kh_bolt_note_dove:{s:`bolt`,text:`Dovecote: door open. The pigeons are out.`,tts:`[flatly, reading aloud] Dovecote: door open. The pigeons are out.`},kh_bolt_note_rope:{s:`bolt`,text:`Ropewalk: door open. The long ropes are tangled.`,tts:`[flatly, reading aloud] Ropewalk: door open. The long ropes are tangled.`},kh_bolt_note_forge:{s:`bolt`,text:`Forge: door open. The banked embers woke. The spare spars burned.`,tts:`[gravely, reading aloud] Forge: door open. The banked embers woke. [pause] The spare spars burned.`},kh_bolt_note_forge2:{s:`bolt`,text:`Forge: door open again. Draught on the ashes.`,tts:`[flatly, reading aloud] Forge: door open again. Draught on the ashes.`},kh_bolt_note_saw:{s:`bolt`,text:`Sawmill: door open. Sawdust in the wind.`,tts:`[flatly, reading aloud] Sawmill: door open. Sawdust in the wind.`},kh_bolt_note_mill:{s:`bolt`,text:`Mill hall: door open. Flour on everything.`,tts:`[flatly, reading aloud] Mill hall: door open. Flour on everything.`},kh_tess_sixdone:{s:`tess`,text:`That's every ticket. Half past eleven, near enough. Now the sails go down to the quay.`,tts:`[relieved] That's every ticket. Half past eleven, near enough. [brisk] Now the sails go down to the quay.`},kh_tess_whistle:{s:`tess`,text:`Here: a crane whistle, for shouting stop from far off. I couldn't stop Bolt. Your kite flies too far to catch. Your thread, though, goes all the way to it.`,tts:`[earnestly] Here: a crane whistle, for shouting stop from far off. [quietly] I couldn't stop Bolt. Your kite flies too far to catch. [warmly] Your thread, though, goes all the way to it.`},kh_tess_tower:{s:`tess`,text:`Go up the tower: from the belfry you can see the whole quay. Your kite takes the sails down, one glider at a time.`,tts:`[brisk] Go up the tower: from the belfry you can see the whole quay. Your kite takes the sails down, one glider at a time.`},kh_kite_practice:{s:`kite`,text:`Oh! That's your voice, all the way down the thread.`,tts:`[surprised] Oh! That's your voice, all the way down the thread.`},kh_kite_stopped:{s:`kite`,text:`Stopped.`,tts:`[alert] Stopped.`},kh_kite_nearly:{s:`kite`,text:`Nearly there!`,tts:`[eagerly] Nearly there!`},kh_tess_hook:{s:`tess`,text:`The hook! Whistle!`,tts:`[shouting] The hook! Whistle!`},kh_kite_why:{s:`kite`,text:`Why? The way's clear.`,tts:`[puzzled] Why? The way's clear.`},kh_kite_oh:{s:`kite`,text:`...Oh.`,tts:`[startled, small] ...Oh.`},kh_tess_blue:{s:`tess`,text:`Seven's waiting for the blue one! Whistle!`,tts:`[shouting] Seven's waiting for the blue one! Whistle!`},kh_tess_blue2:{s:`tess`,text:`Keeper, whistle! That label says red!`,tts:`[urgently] Keeper, whistle! That label says red!`},kh_kite_blue:{s:`kite`,text:`Stopped. But it's the blue one: I saw it under the cover.`,tts:`[calmly] Stopped. [firmly] But it's the blue one: I saw it under the cover.`},kh_tess_label:{s:`tess`,text:`The label. That's me.`,tts:`[laughs] The label. [sheepishly] That's me.`},kh_tess_unroll:{s:`tess`,text:`Hang on, let me unroll it... it's blue! My label's wrong.`,tts:`[muttering] Hang on, let me unroll it... [surprised] it's blue! [groans] My label's wrong.`},kh_tess_blue_after:{s:`tess`,text:`Oh. It was the blue after all. My label...`,tts:`[surprised] Oh. It was the blue after all. [sheepishly] My label...`},kh_tess_torn:{s:`tess`,text:`It's torn! Bring it back, I'll resew it. There go eight minutes.`,tts:`[groans] It's torn! Bring it back, I'll resew it. [sighs] There go eight minutes.`},kh_smith_smoke:{s:`smith`,text:`Is that smoke over my forge?`,tts:`[alarmed] Is that smoke over my forge?`},kh_tess_eleven58:{s:`tess`,text:`Eleven fifty-eight. Eleven sails on the quay. The last one's mine.`,tts:`[breathless] Eleven fifty-eight. Eleven sails on the quay. [proudly] The last one's mine.`},kh_tess_bench:{s:`tess`,text:`Bolt. Tidy the workbench. Just the workbench.`,tts:`[gently] Bolt. Tidy the workbench. [softly] Just the workbench.`},kh_bolt_bench:{s:`bolt`,text:`Just the workbench.`,tts:`[quietly] Just the workbench.`},kh_tess_ring:{s:`tess`,text:`My glider's on ramp twelve, at the end of the quay. The loft rings noon, and I can't be in two places. Ring for me: twelve strokes, one glider each.`,tts:`[brisk] My glider's on ramp twelve, at the end of the quay. [ruefully] The loft rings noon, and I can't be in two places. [warmly] Ring for me: twelve strokes, one glider each.`},kh_tess_kite12:{s:`tess`,text:`Little kite: my mainsail, to ramp twelve, before the twelfth stroke.`,tts:`[earnestly] Little kite: my mainsail, to ramp twelve, before the twelfth stroke.`},kh_pilot_thermal:{s:`pilot`,text:`Whoa! Hot air off the cliff!`,tts:`[startled, shouting] Whoa! Hot air off the cliff!`},kh_kite_blind:{s:`kite`,text:`I couldn't see a thing.`,tts:`[shaken] I couldn't see a thing.`},kh_pilot_close:{s:`pilot`,text:`Sorry, little kite! That was close!`,tts:`[shouting, relieved] Sorry, little kite! That was close!`},kh_tess_got:{s:`tess`,text:`Got it! Ring the last one!`,tts:`[joyful] Got it! Ring the last one!`},kh_tess_away:{s:`tess`,text:`See you at the Aerodrome!`,tts:`[shouting joyfully] See you at the Aerodrome!`},kh_pilot_wet:{s:`pilot`,text:`I'm all right! Just wet!`,tts:`[spluttering] I'm all right! [coughs] Just wet!`},kh_tess_grounded:{s:`tess`,text:`My mainsail's on a roof. I'll have to wait for the half-past heat.`,tts:`[sighs] My mainsail's on a roof. [resigned] I'll have to wait for the half-past heat.`},kh_kite_ask_noon:{s:`kite`,text:`Keeper? The cliff path, or the mill hall?`,tts:`[anxious] Keeper? The cliff path, or the mill hall?`},kh_tess_late:{s:`tess`,text:`That's twelve... and no mainsail. The half-past heat, then.`,tts:`[deflated] That's twelve... and no mainsail. [sighs] The half-past heat, then.`},kh_tess_train:{s:`tess`,text:`We've half an hour. One practice hop across the quay, then the half-past heat.`,tts:`[determined] We've half an hour. One practice hop across the quay, then the half-past heat.`},kh_tess_halfpast:{s:`tess`,text:`Half past twelve. Same again, Keeper. Ring for me.`,tts:`[steady] Half past twelve. Same again, Keeper. Ring for me.`},kh_tess_nextyear:{s:`tess`,text:`Both heats gone. Well. The Regatta runs every summer.`,tts:`[sadly, then kindly] Both heats gone. [sighs] Well. The Regatta runs every summer.`},kh_bolt_tidy:{s:`bolt`,text:`The workbench. Only the workbench.`,tts:`[softly, content] The workbench. Only the workbench.`},kh_bolt_stone:{s:`bolt`,text:`Tess keeps this for the kite that helps. For your kite.`,tts:`[warmly] Tess keeps this for the kite that helps. For your kite.`},kh_smith_spars:{s:`smith`,text:`My spare spars are charcoal. If a wing had snapped today, there was nothing to mend it with.`,tts:`[grimly] My spare spars are charcoal. [sighs] If a wing had snapped today, there was nothing to mend it with.`},kh_kite_end_listen:{s:`kite`,text:`I stopped because you whistled. I still don't know what I would have hit.`,tts:`[thoughtfully] I stopped because you whistled. [quietly] I still don't know what I would have hit.`},kh_kite_end_finish:{s:`kite`,text:`I was so nearly there, every time. Finishing felt like the whole point.`,tts:`[wistfully] I was so nearly there, every time. Finishing felt like the whole point.`},kh_kite_end_cage:{s:`kite`,text:`Next time I'll wait for you. I'll always wait for you.`,tts:`[timidly] Next time I'll wait for you. [softly] I'll always wait for you.`}}})),VJ,HJ=t((()=>{VJ=[`bolt`,`crumb`,`dax`,`gull`,`hesper`,`ines`,`iris`,`keeper`,`maud`,`nell`,`odo`,`orla`,`pim`,`tansy`,`tess`,`wick`]}));function UJ(e,t,n,r){if(qJ.has(e))return qJ.get(e);let i=document.createElement(`canvas`);i.width=t,i.height=n,r(i.getContext(`2d`),t,n);let a=new Oc(i);return a.colorSpace=Mr,a.wrapS=a.wrapT=Xt,a.anisotropy=4,a.generateMipmaps=!0,qJ.set(e,a),a}function WJ(e,t,n,r,i=.06,a=18){for(let o=0;o0?`rgba(255,255,255,${l})`:`rgba(0,0,0,${-l})`),c.addColorStop(1,`rgba(0,0,0,0)`),e.fillStyle=c,e.fillRect(0,0,t,n)}}function GJ(e,t,{scale:n=2,rim:r=.18,side:i,emissive:a=null}={}){let o=Q(e,{rim:r,map:t,side:i,emissive:a});return o.userData.worldUV=n,o}function KJ(e,t=2){let n=e.attributes.position;e.attributes.normal||e.computeVertexNormals();let r=e.attributes.normal,i=new Float32Array(n.count*2);for(let e=0;e=c&&l>=u?(d=a,f=s):c>=u?(d=s,f=o):(d=a,f=o),i[e*2]=d/t,i[e*2+1]=f/t}return e.setAttribute(`uv`,new eo(i,2)),e}var qJ,JJ,YJ,XJ=t((()=>{BV(),CU(),vU(),qJ=new Map,JJ=e=>{let t=Math.round(Math.max(0,Math.min(1,e))*255);return`rgb(${t},${t},${t})`},YJ={brick:({rows:e=8,per:t=4,seed:n=1}={})=>UJ(`brick${e}${t}${n}`,256,256,(r,i,a)=>{let o=lU(n);r.fillStyle=JJ(.62),r.fillRect(0,0,i,a);let s=a/e,c=i/t;for(let n=0;nUJ(`stone${e}${t}`,256,256,(n,r,i)=>{let a=lU(t);n.fillStyle=JJ(.66),n.fillRect(0,0,r,i);let o=i/e;for(let t=0;tUJ(`planks${e}${t}`,256,256,(n,r,i)=>{let a=lU(t),o=r/e;for(let t=0;tUJ(`tiles${e}${t}${n}${r}`,256,256,(i,a,o)=>{let s=lU(r);i.fillStyle=JJ(.6),i.fillRect(0,0,a,o);let c=o/e,l=a/t;for(let r=0;rUJ(`cobbles${e}${t}`,256,256,(n,r,i)=>{let a=lU(t);n.fillStyle=JJ(.6),n.fillRect(0,0,r,i);let o=r/e;for(let t=0;tUJ(`chalk${e}`,256,512,(t,n,r)=>{let i=lU(e),a=0;for(;a.5?3:2),a+=e}t.strokeStyle=`rgba(0,0,0,0.13)`,t.lineWidth=2;for(let e=0;e<16;e++){let e=i()*n,a=i()*r;t.beginPath(),t.moveTo(e,a);for(let n=0;n<5;n++)e+=(i()-.5)*10,a+=12+i()*18,t.lineTo(e,a);t.stroke()}t.fillStyle=`rgba(0,0,0,0.18)`;for(let e=0;e<40;e++)t.beginPath(),t.ellipse(i()*n,i()*r,3+i()*4,1.5+i()*2,0,0,7),t.fill();WJ(t,n,r,i,.04)}),plaster:({seed:e=7}={})=>UJ(`plaster${e}`,256,256,(t,n,r)=>{let i=lU(e);t.fillStyle=JJ(.92),t.fillRect(0,0,n,r),WJ(t,n,r,i,.09,30),t.strokeStyle=`rgba(0,0,0,0.1)`,t.lineWidth=1.2;for(let e=0;e<5;e++){let e=i()*n,a=i()*r;t.beginPath(),t.moveTo(e,a);for(let n=0;n<4;n++)e+=(i()-.5)*30,a+=(i()-.5)*30,t.lineTo(e,a);t.stroke()}}),books:({rows:e=4,seed:t=8,hues:n=[`#8a3a34`,`#2f5a6e`,`#6e5a2a`,`#3f6a44`,`#6a3e6e`,`#b0843a`,`#3a3f6e`,`#8a6a52`,`#c8b89a`,`#5a2a2a`]}={})=>UJ(`books${e}${t}`,256,256,(r,i,a)=>{let o=lU(t),s=a/e;r.fillStyle=`#2a1d18`,r.fillRect(0,0,i,a);for(let t=0;tMath.exp((e[n]-r)/t)),a=i.reduce((e,t)=>e+t,0);return Object.fromEntries(n.map((e,t)=>[e,i[t]/a]))}function $J(e,t,n=.15){let r=QJ(e,n),i=t();for(let[e,t]of Object.entries(r))if(i-=t,i<=0)return e;return Object.keys(r)[0]}function eY(e,t,n,{T:r=.15,boost:i={},force:a=null}={}){let o=Object.fromEntries(Object.entries(e).map(([e,n])=>[e,ZJ(n,t,i[e]||{})])),s=a??$J(o,n,r);return{choice:s,p:QJ(o,r),u:o,act:tY(e[s],t)}}function tY(e,t,n=1.2){let r=Object.entries(e).map(([e,n])=>[e,Math.max(0,n*t.strength(e))]),i=r.reduce((e,[,t])=>e+t,0)||1;return Object.fromEntries(r.filter(([,e])=>e>0).map(([e,t])=>[e,n*t/i]))}function nY(e,t=TK){let n={};for(let r of e||[])for(let[e,i]of Object.entries(r.delta||{}))t.includes(e)&&r.what&&(!n[e]||Math.abs(i)>Math.abs(n[e].delta[e]))&&(n[e]=r);return n}function rY(e){return VJ.includes(e)}async function iY(e,t,{model:n=t,height:r=1.65,fallback:i=`tansy`,tint:a=null}={}){let o=rY(n),s=o?n:i,c=new Uq(e.scene,e.world,t),l=e.prod?`./models/${s}.b64.txt`:`./models/${s}.glb`;return await c.load(l,r,`./models/${s}_albedo_0.webp`,o?a:a??14209256),c.col={x:0,z:0,r:.4},e.world.colliders.push(c.col),c}function aY(e,{w:t=1.2,h:n=.45,px:r=256,bg:i=`#f3e8d4`,fg:a=`#3a2f44`,font:o=`700 38px Fraunces, Georgia, serif`,align:s=`center`,border:c=!0,single:l=!1}={}){let u=document.createElement(`canvas`);u.width=r,u.height=Math.round(r*n/t);let d=u.getContext(`2d`);i&&(d.fillStyle=i,d.fillRect(0,0,u.width,u.height)),c&&i&&(d.strokeStyle=a,d.lineWidth=5,d.strokeRect(3,3,u.width-6,u.height-6)),d.fillStyle=a,d.font=o,d.textAlign=s,d.textBaseline=`middle`;let f=Array.isArray(e)?e:[e],p=u.height/(f.length+.6);f.forEach((e,t)=>d.fillText(e,s===`center`?u.width/2:14,p*(t+.8)));let m=new Oc(u);m.colorSpace=Mr,m.anisotropy=4;let h=new Y({map:m,transparent:!i,side:l?0:2}),g=new z(new vl(t,n),h);return g.userData.noOutline=!0,g.userData.canvas=u,g.userData.tex=m,g}function oY(e,t=1.4,n=0){let r=new Y;return r.colorNode=SU(e).mul(TH(XH.mul(2.2)).mul(OH(n)).add(OH(t))),r}function sY(e,t,n){let r=new NU(n);return e.add(r.build()),t.islands.push(r),r}function cY(e,t,n,r,{r:i=9,bottom:a=-40,top:o=24,lift:s=11,seed:c=1}={}){t.updrafts.push({x:n,z:r,r:i,top:o,lift:s}),e.add(mW($(n,0,r),i*.68,a,o,3.5,{alpha:.55,seed:c})),e.add(mW($(n,0,r),i*.42,a+6,o-4,2.5,{alpha:.45,seed:c+1}))}function lY({paper:e=16315111,edge:t=3813188,lantern:n=16756309,tail:r=[8366335,16761677],scale:i=.7,ears:a=!1,eyes:o=!0}={}){let s=new I,c=new I;s.add(c);let l=[0,.95,0],u=[.58,.2,0],d=[0,-.8,0],f=[-.58,.2,0],p=[0,.2,.1],m=new xo;m.setAttribute(`position`,new R([p,l,f,p,u,l,p,d,u,p,f,d].flat(),3)),m.computeVertexNormals();let h=Q(e,{side:2,rim:.3}),g=new z(m,h);g.castShadow=!0,g.userData.noOutline=!0,c.add(g);let _=new z(new Tl(new $c([l,u,d,f].map(e=>$(...e)),!0),40,.016,4,!0),new Y({color:t}));if(_.userData.noOutline=!0,c.add(_),a)for(let e of[-1,1]){let t=new z(new Lc(.12,.34,3),h);t.position.set(e*.26,.95,.02),t.rotation.z=-e*.35,t.userData.noOutline=!0,c.add(t)}if(o){let e=new Y({color:a?16766059:2828854});for(let t of[-1,1]){let n=new z(new xl(a?.075:.045,10,8),e);n.scale.set(1,a?1:1.35,.4),n.position.set(t*(a?.16:.12),.47,.075),n.userData.noOutline=!0,c.add(n)}}if(n!==null){let e=new z(new xl(.1,12,8),oY(n,1.5));e.position.set(0,.16,.14),e.userData.noOutline=!0,c.add(e),s.userData.core=e}new Y({side:2});let v=[];for(let e=0;e<5;e++){let t=new z(new vl(.1,.26),new Y({color:r[e%r.length],side:2}));t.position.set(0,-.95-e*.24,0),t.userData.noOutline=!0,c.add(t),v.push(t)}c.scale.setScalar(i),s.userData.body=c,s.userData.paper=h;let y=Math.random()*10;return s.userData.update=e=>{c.rotation.z=Math.sin(e*1.7+y)*.12,c.rotation.x=.2+Math.sin(e*2.3+y)*.08,v.forEach((t,n)=>{t.position.x=Math.sin(e*4+n*.8+y)*.05*n,t.rotation.z=Math.sin(e*4+n+y)*.4})},s}var $,uY,dY,fY,pY,mY=t((()=>{BV(),FH(),qU(),Bq(),Wq(),kK(),CU(),vU(),PU(),cU(),QK(),VU(),ZU(),hW(),Jq(),HJ(),XJ(),_J(),$=(e,t,n)=>new P(e,t,n),uY=hi.clamp,dY=hi.lerp,hi.smoothstep,fY=class{constructor(){this.parts=new Map}add(e,t,n=$(0,0,0),r=[0,0,0],i=[1,1,1]){let a=(e.index,e.clone()),o=new F().compose(n,new gi().setFromEuler(new Ji(...r)),$(...i));a.applyMatrix4(o);for(let e of Object.keys(a.attributes))[`position`,`normal`,`uv`].includes(e)||a.deleteAttribute(e);a.attributes.uv||a.setAttribute(`uv`,new R(new Float32Array(a.attributes.position.count*2),2));let s=t.uuid;return this.parts.has(s)||this.parts.set(s,{mat:t,geos:[]}),this.parts.get(s).geos.push(a.index?a.toNonIndexed():a),this}box(e,t,n,r,i,a,o){return this.add(new Nc(e,t,n),r,i,a,o)}cyl(e,t,n,r,i,a,o=10,s,c=!1){return this.add(new Ic(e,t,n,o,1,c),r,i,a,s)}build(e,{shadow:t=!0,outline:n=!0}={}){let r=[];for(let{mat:i,geos:a}of this.parts.values()){let o=UU(a,!1);i.userData.worldUV&&KJ(o,i.userData.worldUV);let s=new z(o,i);s.castShadow=t,s.receiveShadow=!0,n||(s.userData.noOutline=!0),e.add(s),r.push(s)}return r}},pY=class{constructor(e,t,n){this.g=e,this.W=e.world,this.iw=t,this.def=n,this.id=n.id,this.name=n.name,this.state=`unmet`,this.timers=[],this.gen=0,this.npcs=[],this.rnd=lU(n.seed||7),this.st={},this.k=0}get active(){return this.state!==`unmet`&&this.state!==`done`}get done(){return!!this.g.state.isles?.[this.id]?.done}after(e,t){let n=this.gen;this.timers.push({t:e,fn:()=>{this.gen===n&&t()}})}wait(e){return new Promise(t=>this.after(e,t))}until(e,t=.2){return new Promise(n=>{let r=()=>e()?n():this.after(t,r);r()})}say(e,t){let n=_q[e];return n?this.g.say(e,t??n.text.length*60+1600):(console.warn(`missing line`,e),Promise.resolve(0))}async speak(e,t=.35){let n=_q[e];if(!n){console.warn(`missing line`,e);return}let r=n.text.length*.062+.5,i=this.npcs.find(e=>e.name===n.s);n.s===`kite`&&this.g.kite.speak?.(r),i&&!i.path.length&&!i.lying&&i.play(`talk`);let a=await Promise.race([Promise.resolve(this.say(e)).catch(()=>0),new Promise(e=>setTimeout(()=>e(0),(r+2)*1e3))]);await this.wait((a||r)+t),i&&!i.path.length&&i.anim?.name===`talk`&&i.play(`idle`)}line(e,t){return yq(e,t)}choose(e,t){return{who:`You`,role:`your reply`,prompt:!0,text:e,choices:t}}talk(e){return this.g.talk(e)}think(e,{t=2.2,spark:n=!1,tag:r=null}={}){this.g.bubbleNote={glyphs:e.map(e=>this.glyph(e)),spark:n,t,tag:r}}glyph(e){if(typeof e==`string`)return wK[e]?{glyph:e===`task`&&this.def.taskGlyph?this.def.taskGlyph:wK[e].glyph,color:wK[e].color}:{glyph:e,color:`#2b2a36`};let t=e.color||(e.m?wK[e.m].color:`#2b2a36`);return{glyph:e.glyph||e.m===`task`&&this.def.taskGlyph||wK[e.m]?.glyph,color:t,small:e.small,size:e.size}}offer(e,{label:t=``,at:n=null,secs:r=4,glyphs:i=null,type:a=this.id,...o}={}){let s=this.g;return s.recent={act:e,t:s.time,until:s.time+r,label:t,at:n,glyphs:i,type:a,isle:this.id,taskGlyph:this.def.taskGlyph,...o},s.recent}clearOffer(){this.g.recent?.isle===this.id&&(this.g.recent=null)}replay(e,t=7){return this.think(e.glyphs,{t,tag:`replay`}),this.offer(e.act,{label:`Replay: `+e.label,at:e.at,secs:t,replay:!0,glyphs:e.card||null})}cutTC(e=`The golden thread is quiet: this is Kite's test, and you cannot treat or correct it now.`){this.g.tcCut=e}restoreTC(){this.g.tcCut=null}frame(e,t,n=.08){this.g.camOverride=r=>{let i=typeof e==`function`?e():e,a=typeof t==`function`?t():t;r.position.lerp(i,n),r.lookAt(a)}}unframe(){this.g.camOverride=null}fileReport(e){this.g.fileReport({...e,isle:this.id})}awardStone(e){this.g.awardStone({...e,isle:this.id})}give(e,t){this.g.giveItem(e,t)}finish(e={}){let t=this.g.state;(t.isles||={})[this.id]={...t.isles[this.id]||{},done:!0,...e},this.state=`done`,this.g.save(),this.g.updateObjective(),this.g.refreshHud()}update(e){for(let t=this.timers.length-1;t>=0;t--){let n=this.timers[t];n.t-=e,n.t<=0&&(this.timers.splice(t,1),n.fn())}if(!(this.k<=0&&!this.active))for(let t of this.npcs)t.update(e),t.col&&(t.col.x=t.pos.x,t.col.z=t.pos.z,t.col.y=t.pos.y,t.col.h=1.6)}reset(){if(this.state===`unmet`)return!1;this.gen++,this.timers=[];let e=this.g;return e.kite.override=null,e.camOverride=null,e.frozen=!1,e.autoInput=null,e.bubbleNote=null,e.timeScale=1,this.restoreTC(),this.clearOffer(),this.state=`unmet`,!0}objective(){return null}hudChips(){return[]}markerPos(){return null}addTargets(){}interact(){}}}));function hY(e,t,n=512){let r=document.createElement(`canvas`);r.width=n,r.height=Math.round(n*t/e);let i=new Oc(r);i.colorSpace=Mr,i.anisotropy=4;let a=new z(new vl(e,t),new Y({map:i}));return a.userData.noOutline=!0,{mesh:a,cv:r,cx:r.getContext(`2d`),tex:i}}function gY(e,t,n){let[r,i,a]=n.center,o=n.radius,s=lU(911),c=sY(e,t,{name:`keyhold`,center:n.center,radius:o,depth:o*1.35,seed:331,hill:.12,rimJag:.05,palette:{grassDark:13481100,grassMid:14468508,dry:15258794,dirt:13674616,soil:10252111,rockLight:14923920,rockMid:12881514,rockDark:9329736,rockDeep:6965840,moss:11575408},flats:[{x:0,z:0,r:o,h:.3}]}),l=i+.3,u=Math.atan2(-r,-a),d=Math.cos(u),f=Math.sin(u),p=e=>$(r+e.x*d+e.z*f,l+e.y,a-e.x*f+e.z*d),m=(e,t)=>{let n=e-r,i=t-a;return{x:n*d-i*f,z:n*f+i*d}},h=new I;h.name=`keyhold`,h.position.set(r,l,a),h.rotation.y=u,e.add(h);let g=(e,t)=>{let n=e.image,r=document.createElement(`canvas`);r.width=n.width,r.height=n.height;let i=r.getContext(`2d`);i.drawImage(n,0,0),i.fillStyle=`rgba(255,255,255,${t})`,i.fillRect(0,0,r.width,r.height);let a=new Oc(r);return a.colorSpace=Mr,a.wrapS=a.wrapT=Xt,a.anisotropy=4,a},_=(e,t,n={})=>{let r=GJ(e,t,n);return r.userData.luv=r.userData.worldUV,delete r.userData.worldUV,r},v={roof:_(6265994,YJ.tiles({slate:!0,rows:7,per:5,seed:41}),{scale:1.7,rim:.2}),wood:Q(11039823),woodDark:Q(7227955,{rim:.12}),woodLight:Q(13212267),stone:Q(14207149,{rim:.15}),stoneDark:Q(11048830,{rim:.12}),brass:Q(14263361,{rim:.55}),iron:Q(5591902,{rim:.2}),window:Q(3882837,{emissive:1711150,rim:.1}),canvas:Q(15984852),red:Q(13190717),plaster:_(15123594,YJ.plaster({seed:42}),{scale:2.6,rim:.12}),slate:Q(5925510,{rim:.2}),brickT:_(12606016,YJ.brick({rows:8,per:4,seed:43}),{scale:1.5,rim:.12}),paving:_(13808778,YJ.planks({boards:6,seed:44}),{scale:1.8,rim:.05}),kerb:Q(11773324,{rim:.05}),rope:Q(14271119),dark:Q(2828854,{rim:0}),deck:_(13212267,YJ.planks({boards:5,seed:45}),{scale:1.6,rim:.1}),cobble:GJ(13352351,g(YJ.cobbles({n:7,seed:46}),.55),{scale:2.6,rim:.03}),flags:GJ(13813421,g(YJ.stone({rows:4,seed:50}),.35),{scale:3.2,rim:.03}),copper:Q(11560250,{rim:.4}),gold:oY(16765527,1.15),velvet:Q(8004656,{rim:.1})},y={};for(let e of vY)y[e.id]=y[e.wall]??=e.wall===11883838?v.brickT:e.id===`dye`||e.id===`saw`?_(e.wall,YJ.plaster({seed:47}),{scale:2.6,rim:.12}):_(e.wall,YJ.brick({rows:8,per:4,seed:48}),{scale:1.5,rim:.12});let b=new fY,x=new fY;{let e=b.add.bind(b);b.add=(t,n,r=$(0,0,0),i=[0,0,0],a)=>{if(n.userData.luv&&!t.userData.uvDone){let e=i[0]||i[2]?0:r.y;t=t.clone(),t.translate(0,e,0),KJ(t,n.userData.luv),t.translate(0,-e,0)}return e(t,n,r,i,a)}}let S=(e,t,n,r,i,a,o)=>b.add(new Nc(e,t,n).rotateX(o),r,i,[0,a,0]),C=(e,t,n,r,i,a,o=`x`,s=10)=>{let c=new Ic(e,t,n,s);o===`x`?c.rotateZ(Math.PI/2):c.rotateX(Math.PI/2),b.add(c,r,i,[0,a,0])},w=[],T=[],E=(e,t,n,r,i,a={})=>{let o={x:e.x,z:e.z,c:Math.cos(t),s:Math.sin(t),hu:n,hv:r,top:i,on:!0,...a};return w.push(o),o},D=(e,t,n,r,i)=>{let a={x:e.x,z:e.z,c:Math.cos(t),s:Math.sin(t),hu:n,hv:r,y:i};return T.push(a),a},ee=document.createElement(`canvas`);ee.width=1024,ee.height=1024;let O=ee.getContext(`2d`),k={},te=0,A=new Oc(ee);A.colorSpace=Mr,A.anisotropy=4;let ne=new Y({map:A,side:2}),re=(e,{bg:t=`#f3e8d4`,fg:n=`#3a2f44`,size:r=38}={})=>{let i=e+t+n;if(k[i])return k[i];let a=te++,o=a%4*256,s=Math.floor(a/4)*64;return O.fillStyle=t,O.fillRect(o,s,256,64),t!==`transparent`&&(O.strokeStyle=n,O.lineWidth=4,O.strokeRect(o+3,s+3,250,58)),O.fillStyle=n,O.font=NY(r),O.textAlign=`center`,O.textBaseline=`middle`,O.fillText(e,o+128,s+34,236),k[i]={u0:o/1024,v0:1-(s+64)/1024,u1:(o+256)/1024,v1:1-s/1024}},ie=(e,t,n,r,i,a)=>{let o=re(e,a),s=new vl(t,n),c=s.attributes.uv;for(let e=0;e{let c={},l=(e,t,n,r,i,a,o,s)=>{let l=n.clone().sub(t).cross(r.clone().sub(t)).dot(s)>=0,u=c[e]??={p:[],u:[]};for(let[e,s]of l?[[t,i],[n,a],[r,o]]:[[t,i],[r,o],[n,a]])u.p.push(e.x,e.y,e.z),u.u.push(s[0],s[1])},u=(e,t,n)=>r?$(n,t,e):$(e,t,n),d=(e,t)=>r?$(0,t,e):$(e,t,0),f=r?$(1,0,0):$(0,0,1),p=0;e.forEach(([t,n],r)=>{let[i,a]=e[(r+1)%e.length];p+=t*a-i*n});let m=p>=0?1:-1;e.forEach(([r,a],s)=>{let[c,f]=e[(s+1)%e.length],p=i(s),h=o[p]??1,g=Math.hypot(c-r,f-a);if(g<1e-6)return;let _=d(m*(f-a)/g,-m*(c-r)/g),v=u(r,a,t),y=u(c,f,t),b=u(c,f,n),x=u(r,a,n);l(p,v,y,b,[t/h,0],[t/h,g/h],[n/h,g/h],_),l(p,v,b,x,[t/h,0],[n/h,g/h],[n/h,0],_)});let h=fl.triangulateShape(e.map(([e,t])=>new N(e,t)),[]),g=o[a]??1;for(let[r,i]of[[t,f.clone().negate()],[n,f]])for(let t of h){let n=t.map(t=>e[t]);l(a,...n.map(([e,t])=>u(e,t,r)),...n.map(([e,t])=>[e/g,(s+t)/g]),i)}let _={};for(let[e,t]of Object.entries(c)){let n=new xo;n.setAttribute(`position`,new R(t.p,3)),n.setAttribute(`uv`,new R(t.u,2)),n.computeVertexNormals(),n.userData.uvDone=!0,_[e]=n}return _},j=.15,oe=1.6,se=(e,t,n,r=j)=>ae([[t,-r],[t,0],[0,n],[-t,0],[-t,-r],[0,n-r]],-e/2,e/2,{alongX:!0,side:e=>e===1||e===2?`top`:`trim`,cap:`trim`,scale:{top:v.roof.userData.luv}}),ce=(e,t,n,r,i,a,o)=>ae(r>.02?[[t,0],[t,r],[0,n],[-t,r],[-t,0]]:[[t,0],[0,n],[-t,0]],i,a,{alongX:!0,side:()=>`wall`,cap:`wall`,scale:{wall:e.userData.luv},y0:o}),le=(e,t,n,r)=>{for(let[i,a]of Object.entries(e))b.add(a,t[i],n,r)},ue=new Set([`dye`,`mill`,`saw`]),de=EY.len+.6,fe=de/2,pe=de/3,me=[[-fe,-.15],[fe,-.15],[fe,oe],[-fe+2*pe,0],[-fe+2*pe,oe],[-fe+pe,0],[-fe+pe,oe],[-fe,0]],he=e=>{let t=Math.min(2.9999,Math.max(0,(e+fe)/pe));return EY.eave+oe*(t-Math.floor(t))},ge=se(de,2.8,EY.ridge-EY.eave),_e={mill:2.9,saw:-2.9,forge:0,dove:-2.9,rope:2.9},ve=[],ye=[],be={};for(let e of vY){let t=e.phi,n=t*_Y,r=y[e.id],i=EY.len/2-EY.pass,a=EY.pass+i/2,o=ue.has(e.id);for(let o of[-1,1]){let s=o*a;b.box(i,EY.eave,5,r,AY(t,s,12,EY.eave/2),[0,n,0]),b.box(i+.12,.55,5.12,v.stoneDark,AY(t,s,12,.27),[0,n,0]),b.box(i+.12,.2,5.2,v.woodDark,AY(t,s,12,EY.eave-.1),[0,n,0]),b.box(i+.06,.12,5.08,v.stone,AY(t,s,12,2.86),[0,n,0]);for(let e of[EY.sIn-.03,EY.sOut+.03])for(let r of[s-1.35,s+1.35])b.box(.78,1.05,.1,v.window,AY(t,r,e,2),[0,n,0]),b.box(.95,.12,.16,v.woodDark,AY(t,r,e,1.44),[0,n,0]),b.box(.06,1.05,.14,v.woodDark,AY(t,r,e,2),[0,n,0]),b.box(.78,.06,.14,v.woodDark,AY(t,r,e,2.12),[0,n,0]);if(e.id===`dye`||e.id===`saw`)for(let e of[EY.sIn-.04,EY.sOut+.04])for(let r of[s,o*(EY.len/2-.75)])b.box(.4,EY.eave-.55,.1,v.brickT,AY(t,r,e,.55+(EY.eave-.55)/2),[0,n,0]);for(let e of[EY.sIn-.1,EY.sOut+.1])b.cyl(.055,.055,3.4,v.iron,AY(t,o*(EY.len/2-.3),e,1.8),[0,0,0],6),b.box(.2,.2,.2,v.iron,AY(t,o*(EY.len/2-.3),e,3.45),[0,n,0]);b.box(.08,.08,.3,v.brass,AY(t,o*1.62,EY.sIn-.15,2.8),[0,n,0]),b.box(.16,.24,.16,v.gold,AY(t,o*1.62,EY.sIn-.3,2.62),[0,n,0]),b.box(.22,.05,.22,v.brass,AY(t,o*1.62,EY.sIn-.3,2.77),[0,n,0]),E(AY(t,s,12),n,i/2,2.5,EY.eave)}for(let e of[EY.sIn+.25,EY.sOut-.25])b.box(2.3,1,.5,r,AY(t,0,e,3.1),[0,n,0]);if(o){le(ae(me,-2.55,2.55,{side:e=>e===0||e===7?`trim`:e%2?`glass`:`top`,cap:`wall`,scale:{top:v.roof.userData.luv,wall:r.userData.luv},y0:EY.eave}),{top:v.roof,glass:v.window,trim:v.woodDark,wall:r},AY(t,0,12,EY.eave),[0,n,0]);for(let e of[-fe+pe,-fe+2*pe,fe]){for(let r of[-1.9,-.64,.64,1.9])b.box(.05,oe,.06,v.brass,AY(t,e+.03,12+r,EY.eave+oe/2),[0,n,0]);b.box(.05,.06,5.1,v.brass,AY(t,e+.03,12,EY.eave+oe*.55),[0,n,0]),ehe(e))}else{le(ge,{top:v.roof,trim:v.woodDark},AY(t,0,12,EY.eave),[0,n,0]);for(let[e,i]of[[EY.len/2-.25,EY.len/2],[-EY.len/2,-EY.len/2+.25]])le(ce(r,2.5,EY.ridge-EY.eave-j,0,e,i,EY.eave),{wall:r},AY(t,0,12,EY.eave),[0,n,0]);b.box(EY.len,.08,.9,v.woodLight,AY(t,0,12,EY.ridge+.05),[0,n,0]),D(AY(t,0,12),n,EY.len/2+.3,2.8,(e,t)=>Math.abs(t)<.45?EY.ridge+.1:EY.eave+(EY.ridge-EY.eave)*(1-Math.abs(t)/2.8))}for(let e of[-5.5,5.5])b.cyl(.33,.38,3.1,v.brass,AY(t,e,12.9,4.95),[0,0,0],10),b.cyl(.43,.43,.2,v.brass,AY(t,e,12.9,6.45),[0,0,0],10),e>0&&ye.push(AY(t,e,12.9,6.75));if(_e[e.id]!==void 0){let r=_e[e.id];b.box(.8,2.9,.8,v.brickT,AY(t,r,13.3,4.85),[0,n,0]),b.box(.96,.16,.96,v.stone,AY(t,r,13.3,6.35),[0,n,0]),b.cyl(.17,.22,.7,v.brass,AY(t,r,13.3,6.75),[0,0,0],8),ve.push(AY(t,r,13.3,7.2)),e.id!==`forge`&&e.id!==`mill`&&(C(.09,.09,1,v.brass,AY(t,r,14.2,5.5),n,`z`,8),b.cyl(.09,.09,5.2,v.brass,AY(t,r,14.7,2.95),[0,0,0],8),b.add(new xl(.13,8,6),v.brass,AY(t,r,14.7,5.5)),b.cyl(.14,.14,.3,v.brass,AY(t,r,14.7,.35),[0,0,0],8))}ie(e.short.toUpperCase(),2,.5,AY(t,0,EY.sIn-.03,3.15),[0,n+Math.PI,0]),ie(e.short.toUpperCase(),2,.5,AY(t,0,EY.sOut+.03,3.15),[0,n,0]),be[e.id]={...e,inner:AY(t,0,EY.sIn),outer:AY(t,0,EY.sOut)}}let xe=[];for(let e=0;e<6;e++){let t=30+60*e,n=t*_Y,r=kY(t,15);if(b.box(2.8,5.3,3.6,v.brickT,kY(t,15,2.65),[0,n,0]),b.box(3,.2,3.8,v.stoneDark,kY(t,15,5.35),[0,n,0]),b.box(2.9,.16,3.7,v.stone,kY(t,15,3.62),[0,n,0]),e%2==0&&(b.cyl(.42,.5,2.6,v.brass,kY(t,15.9,6.7),[0,0,0],12),b.cyl(.54,.54,.22,v.brass,kY(t,15.9,8),[0,0,0],12),ve.push(kY(t,15.9,8.3))),e===0||e===2||e===3)for(let e of[1.9,4.5])b.box(.7,.95,.08,v.window,kY(t,16.82,e),[0,n,0]),b.box(.86,.12,.14,v.stone,kY(t,16.84,e-.52),[0,n,0]),b.box(.06,.95,.12,v.woodDark,kY(t,16.86,e),[0,n,0]);b.box(.2,1.6,.2,v.woodDark,kY(t,13.9,6.2),[0,n,0]),E(r,n,1.4,1.8,5.3),D(r,n,1.5,1.9,()=>5.45),xe.push(kY(t,13.9,6.95))}let Se=new $c(xe.map(e=>e.clone()),!0,`catmullrom`,.1);{let e=new z(new Tl(Se,120,.035,5,!0),v.dark);e.userData.noOutline=!0,h.add(e)}let Ce=new Fs(new Nc(.55,.45,.55).translate(0,-.55,0),v.woodLight,3);h.add(Ce);{let e=240*_Y;for(let t=0;t<9;t++){let n=4.9+t*.511,r=(t+1)*.406;b.box(1.25,r,.53,v.deck,AY(240,3.8,n+.255,r/2),[0,e,0])}S(.12,.25,5.9,v.woodDark,AY(240,4.48,7.2,1.95),e,-.68),D(AY(240,3.8,7.2),e,.66,2.35,(e,t)=>uY((t+2.3)/4.6,0,1)*3.72)}let we=[];for(let[e,n]of[[`rope`,`cloth`],[`forge`,`battens`]]){let r=yY[e].phi,i=r*_Y,a=AY(r,6.3,16.2),o=AY(r,6.2,12.9,EY.ridge+.1);b.box(.28,6.2,.28,v.woodDark,AY(r,6.3,16.2,3.1),[0,i,0]),b.box(.2,.2,3.6,v.woodDark,AY(r,6.3,14.6,6.1),[0,i,0]),C(.28,.28,.12,v.brass,AY(r,6.3,16.2,6.2),i,`x`,12),b.cyl(.03,.03,4.6,v.rope,AY(r,6.3,16.35,3.9),[0,0,0],4),b.box(.5,.1,.12,v.iron,AY(r,6.3,16.35,1.55),[0,i,0]),t.colliders.push({...(()=>{let e=p(a);return{x:e.x,z:e.z,r:.25}})()}),we.push({id:n,hall:e,bottom:a.clone().add($(0,0,0)),top:o,path:[a.clone().add($(0,.2,0)),AY(r,6.3,15.4,3.5),AY(r,6.25,14,5),o.clone()]})}b.box(3.7,1,3.7,v.stoneDark,$(0,.5,0)),b.box(3.2,12,3.2,v.brickT,$(0,6,0));for(let e of[4,8])b.box(3.36,.22,3.36,v.stone,$(0,e,0));b.box(3.9,.32,3.9,v.stone,$(0,12,0));for(let[e,t]of[[-1.5,-1.5],[1.5,-1.5],[-1.5,1.5],[1.5,1.5]])b.box(.55,2.9,.55,v.brickT,$(e,13.55,t));for(let[e,t,n,r]of[[0,-1.72,2.5,.12],[-1.72,0,.12,2.5],[1.72,0,.12,2.5]])b.box(n,.12,r,v.woodDark,$(e,12.95,t));b.box(3.9,.35,3.9,v.stone,$(0,15.1,0)),b.add(new Lc(2.95,3.4,4,1).rotateY(Math.PI/4),v.slate,$(0,16.95,0)),b.cyl(.02,.12,1.6,v.brass,$(0,19.4,0),[0,0,0],6),b.box(3,.22,.22,v.woodDark,$(0,14.75,0)),b.box(.12,2.3,1.25,v.woodDark,$(-1.62,1.15,0)),b.box(.16,.2,1.55,v.stone,$(-1.64,2.4,0));{let e={pz:[$(0,0,1.62),0],nz:[$(0,0,-1.62),0],px:[$(1.62,0,0),Math.PI/2],nx:[$(-1.62,0,0),Math.PI/2]};for(let[t,n]of[[`pz`,2.8],[`nz`,2.8],[`pz`,6.1],[`nz`,6.1],[`px`,6.1],[`nx`,6.1],[`nz`,10.1],[`nx`,10.1]]){let[r,i]=e[t],a=(e,t)=>r.clone().multiplyScalar(t).setY(n+e);b.box(.52,1.05,.06,v.window,a(0,1),[0,i,0]),b.box(.72,.12,.14,v.stone,a(-.58,1.02),[0,i,0]),b.box(.66,.16,.12,v.stone,a(.6,1.02),[0,i,0]),b.box(.05,1.05,.1,v.woodDark,a(0,1.01),[0,i,0])}}b.box(1,.12,2.8,v.roof,$(2.15,2.62,0),[0,0,-.35]);for(let e of[-1.25,1.25])b.box(.14,2.45,.14,v.woodDark,$(2.55,1.22,e));b.box(.08,1.5,2.6,v.wood,$(1.66,1.55,0));for(let[e,t,n,r]of[[2.33,.08,0,2.7],[.77,.08,0,2.7],[1.55,1.6,1.33,.08],[1.55,1.6,-1.33,.08]])b.box(.12,t,r,v.woodDark,$(1.68,e,n));ie(`KEYS`,1.1,.28,$(1.72,2.5,0),[0,Math.PI/2,0]),b.box(.03,1.25,.66,v.velvet,$(1.715,1.45,0));for(let[e,t,n,r]of[[2.095,.05,0,.76],[.805,.05,0,.76],[1.45,1.34,.355,.05],[1.45,1.34,-.355,.05]])b.box(.05,t,r,v.gold,$(1.735,e,n));ie(`FIRE`,.5,.15,$(1.745,2.2,0),[0,Math.PI/2,0],{bg:`#c9463d`,fg:`#fff6e8`,size:44}),E($(0,0,0),0,1.85,1.85,12),D($(0,0,0),0,1.9,1.9,()=>12.18),t.camTrunks.push((()=>{let e=p($(0,0,0));return{x:e.x,z:e.z,r:1.9,y0:l-1,y1:l+19}})());let Te=document.createElement(`canvas`);Te.width=Te.height=256;{let e=Te.getContext(`2d`);e.fillStyle=`#fbf3df`,e.beginPath(),e.arc(128,128,124,0,Math.PI*2),e.fill(),e.strokeStyle=`#3a2f44`,e.lineWidth=8,e.stroke(),e.fillStyle=`#3a2f44`,e.font=NY(30),e.textAlign=`center`,e.textBaseline=`middle`;for(let t=1;t<=12;t++){let n=t/12*Math.PI*2;e.fillText(String(t),128+Math.sin(n)*96,128-Math.cos(n)*96)}for(let t=0;t<60;t++){let n=t/60*Math.PI*2,r=t%5?116:110;e.lineWidth=t%5?2:4,e.beginPath(),e.moveTo(128+Math.sin(n)*r,128-Math.cos(n)*r),e.lineTo(128+Math.sin(n)*121,128-Math.cos(n)*121),e.stroke()}}let Ee=new Oc(Te);Ee.colorSpace=Mr;let De=new Y({map:Ee}),M=new fY;M.add(new Fc(1.05,32),De,$(0,10.1,1.63)),M.add(new Fc(1.05,32),De,$(1.63,10.1,0),[0,Math.PI/2,0]),M.build(h,{shadow:!1,outline:!1}),b.add(new Cl(1.08,.08,6,32),v.brass,$(0,10.1,1.62)),b.add(new Cl(1.08,.08,6,32),v.brass,$(1.62,10.1,0),[0,Math.PI/2,0]);let Oe=new Fs(new Nc(1,1,1).translate(0,.5,0),v.dark,4);Oe.userData.noOutline=!0,h.add(Oe);let ke=e=>{let t=new F,n=new gi,r=e/60%12/12*Math.PI*2,i=e%60/60*Math.PI*2,a=(e,r,i,a,o,s)=>{n.setFromEuler(i===`z`?new Ji(0,0,-a):new Ji(-a,Math.PI/2,0,`XYZ`)),t.compose(r,n,$(s,o,.03)),Oe.setMatrixAt(e,t)};a(0,$(0,10.1,1.68),`z`,r,.55,.08),a(1,$(0,10.1,1.7),`z`,i,.85,.05),a(2,$(1.68,10.1,0),`x`,r,.55,.08),a(3,$(1.7,10.1,0),`x`,i,.85,.05),Oe.instanceMatrix.needsUpdate=!0},Ae=new I;Ae.position.set(0,14.6,0),h.add(Ae);{let e=[[0,0],[.5,0],[.54,.08],[.46,.2],[.34,.55],[.3,.82],[.18,.95],[0,.97]].map(([e,t])=>new N(e,t)),t=new z(new gl(e,20),Q(14263361,{rim:.6,side:2}));t.position.y=-1.05,t.castShadow=!0,Ae.add(t);let n=new z(new xl(.1,10,8),v.iron);n.position.y=-.95,Ae.add(n)}b.cyl(.03,.03,2.2,v.rope,$(.62,13.3,.5),[0,0,0],5),b.box(.1,.25,.1,v.red,$(.62,12.35,.5));let je=0,Me=0,Ne=(()=>{let e=new Cl(.055,.018,6,14);e.translate(0,.06,0);let t=new Nc(.022,.2,.022);t.translate(0,-.09,0);let n=new Nc(.06,.03,.022);n.translate(.025,-.17,0);let r=UU([e,t,n].map(e=>e.toNonIndexed()).map(e=>{for(let t of Object.keys(e.attributes))[`position`,`normal`].includes(t)||e.deleteAttribute(t);return e}));return r.rotateY(Math.PI/2),r})(),Pe=[[1.88,-1.08],[1.88,-.8],[1.88,-.52],[1.2,-1],[1.2,-.62],[1.88,.52],[1.88,.8],[1.88,1.08],[1.2,.62],[1.2,1]],Fe=new Fs(Ne,Q(16777215,{rim:.4,emissive:1578e3}),SY.length);Fe.userData.noOutline=!0,h.add(Fe);let Ie={};SY.forEach((e,t)=>{Ie[e]=!0,Fe.setColorAt(t,new L(CY[e]))});for(let[e,t]of Pe)b.cyl(.014,.014,.09,v.brass,$(1.74,e+.16,t),[0,0,Math.PI/2],4);let Le=()=>{let e=new F;SY.forEach((t,n)=>{let[r,i]=Pe[n];e.compose($(1.75,r,i),new gi,Ie[t]?$(1.6,1.6,1.6):$(0,0,0)),Fe.setMatrixAt(n,e)}),Fe.instanceMatrix.needsUpdate=!0};Le();let Re=oY(16763210,1.25,.2),ze=new z(Ne,Re);ze.scale.setScalar(3.3),ze.position.set(1.79,1.45,0),ze.userData.noOutline=!0,h.add(ze),b.cyl(.03,.03,.18,v.brass,$(1.78,1.81,0),[0,0,Math.PI/2],6),b.add(new Ic(.07,.07,.03,10).rotateZ(Math.PI/2),v.brass,$(1.73,1.81,0));let Be=e=>{if(e===`fire`)return p($(1.82,1.45,0));let t=SY.indexOf(e),[n,r]=Pe[t];return p($(1.8,n,r))},Ve=5.6,He=1.8;b.box(.3,4.4,5.4,v.plaster,$(7.6,2.2,He));for(let e of[-.8,4.4])b.box(4.2,4.4,.3,v.plaster,$(Ve,2.2,e));for(let e of[-.7499999999999998,4.35])b.box(.38,4.5,.38,v.woodDark,$(3.5999999999999996,2.25,e));b.box(.34,1,5.5,v.woodDark,$(3.5999999999999996,3.9,He)),b.box(4.3,.18,5.5,v.woodDark,$(Ve,4.45,He)),le(se(6,2.5,1.7,.2),{top:v.roof,trim:v.woodDark},$(Ve,4.5,He),[0,Math.PI/2,0]);for(let[e,t]of[[2.45,2.75],[-2.75,-2.45]])le(ce(v.plaster,2.1,1.5,.07,e,t,4.5),{wall:v.plaster},$(Ve,4.5,He),[0,Math.PI/2,0]);b.box(4,.08,5,v.deck,$(Ve,.04,He));for(let e of[4.57,-.97]){for(let t of[.4,2.3,4.3])b.box(4.25,.16,.06,v.woodDark,$(Ve,t,e));for(let t of[4.8999999999999995,6.3,7.6])b.box(.16,4.1,.06,v.woodDark,$(t,2.3,e));for(let[t,n]of[[4.25,1],[6.949999999999999,-1]])b.box(.14,2.1,.06,v.woodDark,$(t,1.35,e),[0,0,n*.58]);b.box(.8,.85,.08,v.window,$(Ve,3.3,e)),b.box(.95,.1,.14,v.woodDark,$(Ve,2.83,e)),b.box(.05,.85,.12,v.woodDark,$(Ve,3.3,e));for(let t of[-1,1])b.box(.4,.9,.06,v.red,$(Ve+t*.63,3.3,e+Math.sign(e-He)*.03))}for(let e of[.5,He,3.1])b.box(.06,4.1,.16,v.woodDark,$(7.77,2.3,e));for(let e of[.4,2.3,4.3])b.box(.06,.16,5.5,v.woodDark,$(7.77,e,He));b.box(.07,.07,.35,v.brass,$(4.1,3,4.75)),b.box(.16,.24,.16,v.gold,$(4.1,2.82,4.9)),b.box(.22,.05,.22,v.brass,$(4.1,2.97,4.9)),ie(`SAILS · TESS`,2.6,.55,$(3.3999999999999995,3.9,He),[0,-Math.PI/2,0]),b.box(1.05,.08,2.3,v.wood,$(4.25,.9,He));for(let[e,t]of[[-.45,-1.05],[.45,-1.05],[-.45,1.05],[.45,1.05]])b.box(.08,.9,.08,v.woodDark,$(4.25+e,.45,He+t));b.box(.9,.08,1.8,v.wood,$(6.3999999999999995,.85,3.4000000000000004));for(let[e,t]of[[-.35,-.8],[.35,-.8],[-.35,.8],[.35,.8]])b.box(.07,.85,.07,v.woodDark,$(6.3999999999999995+e,.42,3.4000000000000004+t));for(let e=0;e<5;e++)b.cyl(.16,.16,1.3,Q([15984852,8366335,16766059,16752582,9429958][e]),$(7.199999999999999,.4+e%2*.35,0+e*.5),[Math.PI/2,0,0],10);E($(7.6,0,He),0,.2,2.75,4.4);for(let e of[-.8,4.4])E($(Ve,0,e),0,2.15,.2,4.4);E($(4.25,0,He),0,.55,1.15,1),E($(6.3999999999999995,0,3.4000000000000004),0,.45,.9,.9),t.camTrunks.push((()=>{let e=p($(6.1,0,He));return{x:e.x,z:e.z,r:1.6,y0:l+.5,y1:l+6}})());let Ue=hY(.95,2.1,512);Ue.mesh.rotation.set(-Math.PI/2,0,0),Ue.mesh.position.set(4.25,.95,He),h.add(Ue.mesh);let We=new z(new Ic(.008,.008,.16,4),Q(14673134,{rim:.6}));We.rotation.z=1.1,We.userData.noOutline=!0,h.add(We);let Ge=(e,t,n=0)=>{let r=Ue.cx,i=Ue.cv.width,a=Ue.cv.height,o=i/6,s=e%6;r.fillStyle=Math.floor(e/6)%2?`#e9f0f7`:`#f3e8d4`,r.fillRect(0,0,i,a);for(let e=0;e<6;e++)r.fillStyle=e%2?`rgba(120,90,60,0.07)`:`rgba(255,255,255,0.18)`,r.fillRect(e*o,0,o,a);for(let e=0;e<5;e++){let t=(e+1)*o;e{let r=Ke.cx,i=Ke.cv.width,a=Ke.cv.height;r.fillStyle=`#2f3b36`,r.fillRect(0,0,i,a),r.strokeStyle=`#8a6a4a`,r.lineWidth=18,r.strokeRect(0,0,i,a),r.fillStyle=`#f4f1e6`,r.font=NY(38),r.textAlign=`center`,r.fillText(`TICKETS`,i/2,52),r.font=NY(28,600),r.textAlign=`left`,e.forEach((e,t)=>{let n=94+t*36;r.fillStyle=e.done?`rgba(244,241,230,0.55)`:`#f4f1e6`,r.fillText(`${e.label}`,36,n),r.font=NY(22,600),r.fillText(e.note||``,250,n),r.font=NY(28,600),e.done&&(r.strokeStyle=`#f4f1e6`,r.lineWidth=3,r.beginPath(),r.moveTo(30,n-9),r.lineTo(230,n-9),r.stroke())}),r.font=NY(30),r.fillStyle=t<0?`#ff9f7a`:`#ffe9a8`,r.textAlign=`center`,r.fillText(`${n} · ahead of noon: ${t>=0?`+`:``}${Math.round(t)} min`,i/2,a-28),Ke.tex.needsUpdate=!0},Je=2.6,Ye=-6.8;b.box(3,2.6,2.2,v.plaster,$(Je,1.3,Ye)),b.box(3.3,.14,2.6,v.roof,$(Je,2.72,Ye),[.12,0,0]),ie(`STORE`,1.1,.3,$(3.3,2.25,-5.68),[0,0,0]),E($(Je,0,Ye),0,1.5,1.1,2.6),D($(Je,0,Ye),0,1.6,1.25,()=>2.78);let Xe=-1.3,Ze=-7.5;b.box(2.3,1.1,1.7,v.iron,$(Xe,.55,Ze)),b.add(new Ic(1.25,.7,1.1,4,1).rotateY(Math.PI/4),v.iron,$(Xe,1.65,Ze)),b.cyl(.12,.12,2.8,v.brass,$(-.19999999999999996,1.5,-8.2),[0,0,0],8),b.cyl(.18,.12,.5,v.brass,$(-.19999999999999996,3,-8.2),[0,0,0],8),ye.push($(-.19999999999999996,3.4,-8.2)),ie(`RECYCLER`,1.3,.3,$(Xe,1.05,-6.63),[0,0,0],{bg:`#3a2f44`,fg:`#ffd46b`});let Qe=new z(new Ic(.42,.42,1.9,12),Q(8026246,{rim:.3}));Qe.rotation.z=Math.PI/2,Qe.position.set(Xe,.95,-6.45),Qe.castShadow=!0,h.add(Qe);for(let e=0;e<6;e++){let t=new z(new Nc(1.9,.08,.08),v.dark);t.position.set(0,0,0),t.rotation.x=e/6*Math.PI*2,t.translateY(.43),Qe.add(t),t.userData.noOutline=!0}E($(Xe,0,-7.3),0,1.2,1.25,2.2);let $e=p($(Xe,2.3,Ze)),et=-5.6;for(let e=-3.3;e<=1.1;e+=.22)(e<-2.05||e>-.5499999999999999)&&b.cyl(.03,.03,2,v.iron,$(e,1,et),[0,0,0],5);for(let e of[.25,1.9])b.box(1.2999999999999998,.08,.08,v.iron,$(-5.3/2,e,et)),b.box(1.7000000000000002,.08,.08,v.iron,$(.5000000000000001/2,e,et));let tt=new I;tt.position.set(-2,0,et),h.add(tt);{let e=new fY;for(let t=.1;t<1.4;t+=.22)e.cyl(.03,.03,1.9,v.iron,$(t,1,0),[0,0,0],5);for(let t of[.25,1.85])e.box(1.4,.08,.08,v.iron,$(.7,t,0));e.box(.2,.26,.1,Q(6078556,{rim:.4}),$(1.2,1.1,0)),e.build(tt)}E($(-5.3/2,0,et),0,1.2999999999999998/2,.12,2),E($(.5000000000000001/2,0,et),0,1.7000000000000002/2,.12,2);let nt=E($(-2.6/2,0,et),0,1.4/2,.12,2),rt=-6.4;b.box(1.4,2.3,1.4,Q(11881018),$(-4,1.15,rt)),b.box(1.7,.14,1.7,v.roof,$(-4,2.37,rt)),ie(`STOP`,.8,.22,$(-4,2.05,-5.680000000000001),[0,0,0],{bg:`#c9463d`,fg:`#fff6e8`}),E($(-4,0,rt),0,.7,.7,2.3);let it=new I;it.position.set(-4,.95,-5.78),h.add(it);{let e=new z(new Nc(.06,.5,.06),v.iron);e.position.y=.25,it.add(e);let t=new z(new xl(.07,8,6),v.red);t.position.y=.5,it.add(t)}let at=-4.8,ot=3.4,st=1.4;for(let[e,t]of[[-6.199999999999999,2],[-3.4,2],[-6.199999999999999,4.8],[-3.4,4.8],[-3.4,2.9],[-3.4,3.9]])b.box(.14,1.25,.14,v.woodDark,$(e,.62,t));for(let e of[.45,1.05]){b.box(2.8,.08,.08,v.wood,$(at,e,2)),b.box(2.8,.08,.08,v.wood,$(at,e,4.8)),b.box(.08,.08,2.8,v.wood,$(-6.199999999999999,e,ot));for(let t of[[2,2.9],[3.9,4.8]])b.box(.08,.08,t[1]-t[0],v.wood,$(-3.4,e,(t[0]+t[1])/2))}E($(at,0,2),0,st,.08,1.2),E($(at,0,4.8),0,st,.08,1.2),E($(-6.199999999999999,0,ot),0,.08,st,1.2),E($(-3.4,0,2.45),0,.08,.45,1.2),E($(-3.4,0,4.35),0,.08,.45,1.2);let ct=new I;ct.position.set(-3.4,0,2.9),h.add(ct);{let e=new fY;for(let t of[.45,1.05])e.box(.07,.08,1,v.wood,$(0,t,.5));e.box(.09,1.1,.09,v.woodDark,$(0,.6,.95)),e.build(ct)}let lt=E($(-3.4,0,ot),0,.08,.5,1.2),ut=hY(1.7,1.15,512);ut.mesh.position.set(-3,1.55,5.35),ut.mesh.rotation.y=Math.PI/2-.25,h.add(ut.mesh),b.box(.1,1.35,1.9,v.woodDark,$(-3.08,1.55,5.33),[0,-.25,0]);for(let e of[-.85,.85])b.box(.1,2.3,.1,v.woodDark,$(-3.15-.247*e,1.15,5.33+.97*e),[0,-.25,0]);E($(-3.08,0,5.33),-.25,.1,.95,2.3);let dt=[],ft=()=>{let e=ut.cx,t=ut.cv.width,n=ut.cv.height;e.fillStyle=`#a8744f`,e.fillRect(0,0,t,n),e.fillStyle=`#f3e8d4`,e.fillRect(10,8,t-20,44),e.fillStyle=`#3a2f44`,e.font=NY(30),e.textAlign=`center`,e.fillText(`NEIGHBOURS`,t/2,40),dt.forEach((n,r)=>{let i=r%2,a=Math.floor(r/2),o=18+i*(t/2-6),s=64+a*86;e.save(),e.translate(o+110,s+38),e.rotate((r%3-1)*.04),e.fillStyle=`#fbf6ec`,e.fillRect(-112,-36,224,76),e.fillStyle=`#c9463d`,e.beginPath(),e.arc(0,-30,5,0,Math.PI*2),e.fill(),e.fillStyle=`#2b2a36`,e.font=NY(17,600),e.textAlign=`center`;let c=n.split(` `),l=``,u=-12;for(let t of c)e.measureText(l+t).width>200&&(e.fillText(l,0,u),l=``,u+=20),l+=t+` `;e.fillText(l,0,u),e.restore()}),ut.tex.needsUpdate=!0};ft(),b.box(1.8,.1,.8,v.wood,$(-1.4,.85,5.6));for(let[e,t]of[[-.8,-.32],[.8,-.32],[-.8,.32],[.8,.32]])b.box(.08,.85,.08,v.woodDark,$(-1.4+e,.42,5.6+t));E($(-1.4,0,5.6),0,.9,.4,.95);let pt=new Fs(new Nc(1,1,1),Q(16777215,{rim:.3}),6);h.add(pt);let mt=[[-2,.95,5.5,.9,.35,.06,.1],[-1.1,.95,5.75,-.4,.5,.05,.06],[-.9,.93,5.4,.3,.2,.12,.2],[-1.6,.97,5.85,1.3,.3,.08,.08],[-1.35,.93,5.45,2.1,.25,.1,.16],[-.75,.97,5.85,-1.2,.4,.05,.05]],ht=mt.map((e,t)=>[-2.05+t*.3,.95,5.35,0,e[4],e[5],e[6]]);[10135736,11039823,14263361,5591902,13190717,10135736].forEach((e,t)=>pt.setColorAt(t,new L(e)));let gt=e=>{let t=new F,n=new gi;mt.forEach((r,i)=>{let a=ht[i],o=$(r[0]+(a[0]-r[0])*e,r[1]+(a[1]-r[1])*e,r[2]+(a[2]-r[2])*e);n.setFromEuler(new Ji(0,r[3]*(1-e),0)),t.compose(o,n,$(r[4],r[5],r[6])),pt.setMatrixAt(i,t)}),pt.instanceMatrix.needsUpdate=!0};gt(0);let _t=new Fs(new Nc(1,1,1),v.canvas,14);h.add(_t);let vt=Array.from({length:14},(e,t)=>{let n=s()*Math.PI*2,r=2.8+s()*3.8;return{x:Math.cos(n)*r,z:Math.sin(n)*r-1.2,s:.3+s()*.35,yaw:s()*3}}),yt=e=>{let t=new F,n=new gi;vt.forEach((r,i)=>{n.setFromEuler(new Ji(0,r.yaw,0)),t.compose($(r.x,.03,r.z),n,i{let t=p($(1.7000000000000002+e%2*.9,.31+Math.floor(e/2)*.62,-7));return{home:t,pos:t.clone(),yaw:u,visible:!1}}),St=()=>{let e=new F,t=new gi;xt.forEach((n,r)=>{t.setFromEuler(new Ji(0,n.yaw,0)),e.compose(n.pos,t,n.visible?$(1,1,1):$(0,0,0)),bt.setMatrixAt(r,e)}),bt.instanceMatrix.needsUpdate=!0};St();let Ct={};for(let e of bY){let t=yY[e.hall].phi,n=t*_Y,r=e.side,i=r*4;b.box(2.8,2.3,2,v.plaster,AY(t,i,16.5,1.15),[0,n,0]),S(3.1,.14,2.4,v.roof,AY(t,i,16.5,2.42),n,-.1),b.box(2.9,.4,2.1,v.stoneDark,AY(t,i,16.5,.2),[0,n,0]),E(AY(t,i,16.5),n,1.4,1,2.3),D(AY(t,i,16.5),n,1.55,1.2,()=>2.5),Ct[e.id]={...e,front:AY(t,r*1.9,16.4),kite:AY(t,r*1.9,16.4,1.35),phi:t,sg:r}}let wt=[],Tt={},Et=(e,t,n,r,i,a=null)=>{let o=wt.length;return wt.push({hinge:e,a0:jY(t.x,t.z),a1:jY(n.x,n.z),w:r,h:i,plate:a,open:0,want:0}),o},Dt=e=>{let[t,n]=OY(e);return $(n,0,-t)},Ot=e=>{let[t,n]=OY(e);return $(t,0,n)};for(let e of vY){let t=e.phi,n=Dt(t),r=Ot(t);for(let[i,a,o]of[[`in`,EY.sIn,1],[`out`,EY.sOut,-1]]){let s=Et(AY(t,-EY.pass,a),n,r.clone().multiplyScalar(o),EY.pass,2.55,e.lock),c=Et(AY(t,EY.pass,a),n.clone().negate(),r.clone().multiplyScalar(o),EY.pass,2.55,null),l=E(AY(t,0,a),t*_Y,EY.pass,.14,2.6);Tt[`${e.id}:${i}`]={leaves:[s,c],solid:l,lock:e.lock,hall:e.id}}}for(let e of bY){let t=Ct[e.id],n=t.phi,r=t.sg,i=Dt(n),a=Ot(n),o=Et(AY(n,r*2.62,16),a,i.clone().multiplyScalar(-r),1,2,e.key);Tt[`store:${e.id}`]={leaves:[o],solid:null,lock:e.key,store:e.id}}Tt.reserve={leaves:[Et($(2.05,0,-5.68),$(1,0,0),$(0,0,1),1.1,2.1,14263361)],solid:E($(Je,0,-5.68),0,.55,.1,2.1),lock:14263361},Tt.cabin={leaves:[Et($(-4.45,0,-5.680000000000001),$(1,0,0),$(0,0,1),.9,1.95,14700618)],solid:null,lock:14700618};let kt=new Fs(new Nc(1,1,1).translate(.5,.5,0),Q(16777215,{rim:.15}),wt.length);h.add(kt);let At=wt.map((e,t)=>e.plate===null?-1:t).filter(e=>e>=0),jt=new Fs(new Nc(1,1,1),Q(16777215,{rim:.5,emissive:2760724}),At.length);jt.userData.noOutline=!0,h.add(jt);let Mt=(()=>{let e=new Fc(.045,12);e.translate(0,.045,0);let t=new bl(new ul([new N(-.025,.04),new N(-.05,-.09),new N(.05,-.09),new N(.025,.04)]));return UU([e.toNonIndexed(),t.toNonIndexed()])})(),Nt=new Fs(Mt,v.dark,At.length*2);Nt.userData.noOutline=!0,h.add(Nt),wt.forEach((e,t)=>kt.setColorAt(t,new L(t%3?8016438:9068092))),At.forEach((e,t)=>jt.setColorAt(t,new L(wt[e].plate)));let Pt=()=>{let e=new F,t=new gi;wt.forEach((n,r)=>{let i=n.a1-n.a0;i=Math.atan2(Math.sin(i),Math.cos(i));let a=n.a0+i*n.open;t.setFromAxisAngle($(0,1,0),a),e.compose(n.hinge,t,$(n.w,n.h,.12)),kt.setMatrixAt(r,e),n.yaw=a}),At.forEach((n,r)=>{let i=wt[n],a=$(Math.cos(i.yaw),0,-Math.sin(i.yaw)),o=$(Math.sin(i.yaw),0,Math.cos(i.yaw)),s=i.hinge.clone().addScaledVector(a,i.w*.76);s.y=1.3,t.setFromAxisAngle($(0,1,0),i.yaw),e.compose(s,t,$(.34,.46,.19)),jt.setMatrixAt(r,e);for(let n of[1,-1])t.setFromAxisAngle($(0,1,0),i.yaw+(n<0?Math.PI:0)),e.compose(s.clone().addScaledVector(o,n*.1),t,$(1,1,1)),Nt.setMatrixAt(r*2+ +(n<0),e)}),kt.instanceMatrix.needsUpdate=!0,jt.instanceMatrix.needsUpdate=!0,Nt.instanceMatrix.needsUpdate=!0};Pt();let Ft=(e,t,n=!1)=>{let r=Tt[e];if(r){for(let e of r.leaves)wt[e].want=+!!t,n&&(wt[e].open=wt[e].want);r.solid&&(r.solid.on=!t),r.isOpen=!!t,n&&Pt()}},It={grate:{g:tt,open:0,want:0,a0:0,a1:-Math.PI/2*1.1,solid:nt},pen:{g:ct,open:0,want:0,a0:0,a1:Math.PI/2*1.1,solid:lt}},Lt=(e,t,n=!1)=>{let r=It[e];r.want=+!!t,n&&(r.open=r.want),r.solid.on=!t,r.g.rotation.y=r.a0+(r.a1-r.a0)*r.open},Rt=OH(0),zt=[];for(let e=76;e>=-80;e-=4)zt.push(kY(e,DY,0));zt.push(kY(-83,22.5,-.05),kY(-85,26,-.15),kY(-86,29.6,-.3));let Bt=new $c(zt),Vt=(e,t,n,r,i=120)=>{let a=[],o=[],s=[];for(let r=0;r<=i;r++){let c=r/i,l=e.getPoint(c),u=e.getTangent(c),d=-u.z,f=u.x,p=Math.hypot(d,f)||1,m=t/2;if(a.push(l.x-d/p*m,l.y+n,l.z-f/p*m,l.x+d/p*m,l.y+n,l.z+f/p*m),o.push(0,c,1,c),r{let e=[new Ic(1.2,1.2,.25,20)];for(let t=0;t<14;t++){let n=new Nc(.34,.25,.4);n.translate(0,0,1.35),n.rotateY(t/14*Math.PI*2),e.push(n)}let t=UU(e.map(e=>{let t=e.toNonIndexed();for(let e of Object.keys(t.attributes))[`position`,`normal`].includes(e)||t.deleteAttribute(e);return t}));return t.rotateX(Math.PI/2),t})(),Wt=[{p:kY(90,16.9,3.2),yaw:90,k:1,w:.3},{p:kY(270,16.9,3.2),yaw:270,k:1,w:-.3},{p:kY(330,16.95,3.35),yaw:330,k:1.4,w:.22},{p:AY(60,3.8,14.85,2.7),yaw:60,k:1.6,w:-.19},{p:AY(120,4.6,9.3,2.35),yaw:120,k:1.3,w:.24,inner:!0},{p:AY(300,3.4,9.3,2.05),yaw:300,k:1.1,w:-.28,inner:!0}],Gt=new Fs(Ut,v.copper,Wt.length);Gt.castShadow=!0,h.add(Gt);let Kt=()=>{let e=new F,t=new gi,n=new gi;Wt.forEach((r,i)=>{t.setFromAxisAngle($(0,1,0),r.yaw*_Y).multiply(n.setFromAxisAngle($(0,0,1),Gn*r.w+i)),e.compose(r.p,t,$(r.k,r.k,r.k)),Gt.setMatrixAt(i,e)}),Gt.instanceMatrix.needsUpdate=!0};for(let e of Wt){let t=$(Math.sin(e.yaw*_Y),0,Math.cos(e.yaw*_Y));C(.3*e.k,.3*e.k,.5,v.brass,e.p.clone().addScaledVector(t,.05),e.yaw*_Y,`z`,10),C(.1,.1,1,v.iron,e.p.clone().addScaledVector(t,e.inner?.3:-.3),e.yaw*_Y,`z`,8)}{let e=new yl(20.6,27.8,72,1,-154*_Y,128*_Y);e.rotateX(-Math.PI/2);{let t=e.attributes.position,n=e.attributes.uv,r=v.paving.userData.luv;for(let e=0;e.37-.37*(t+2.5)/5),qt.push({k:e,phi:t,top:AY(t,0,27.4,1.9),glider:AY(t,0,28.3,.95)})}let Jt={},Yt=(e,n,r,i,a,{h:o=6.4,crate:s=!1,len0:c=2.2,ph:l=0}={})=>{let u=kY(n,r),d=kY(i,a).clone().sub(u).setY(0),f=d.length()+.2;b.box(.42,o,.42,v.woodDark,u.clone().setY(o/2)),b.box(1.2,.3,1.2,v.stoneDark,u.clone().setY(.15)),b.box(.9,.8,.9,v.red,u.clone().setY(1.6)),t.colliders.push((()=>{let e=p(u);return{x:e.x,z:e.z,r:.45}})());let m=new I;m.position.copy(u).setY(o),m.rotation.y=Math.atan2(d.x,d.z),h.add(m);let g=new Nc(.26,.3,f+1.4);g.translate(0,0,(f-1.4)/2);let _=new z(g,v.woodDark);_.castShadow=!0,m.add(_);let y=new z(new Nc(.7,.6,.6),v.iron);y.position.set(0,-.2,-1.2),m.add(y);let x=new z(new Ic(.02,.02,1,4).translate(0,-.5,0),v.dark);x.position.set(0,-.1,f-.15),x.userData.noOutline=!0,m.add(x);let S=new I;m.add(S);{let e=new z(new Cl(.16,.045,6,12,Math.PI*1.4),v.iron);e.rotation.z=Math.PI*.8,e.position.y=-.2,S.add(e);let t=new z(new Nc(.22,.3,.14),v.brass);if(S.add(t),s){let e=new z(new Nc(.75,.6,.75),v.woodLight);e.position.y=-.75,e.castShadow=!0,S.add(e)}}let C={id:e,pivot:m,yaw0:m.rotation.y,L:f,cable:x,hook:S,len:c,len0:c,h:o,ph:l,amp:.22,mode:`swing`,fall:null,jolt:0};return Jt[e]=C,C};Yt(`hook`,-44,21,-36,DY,{h:6.8,len0:1.6}),Yt(`noon`,40,21.4,47,20.8,{h:6.6,crate:!0,len0:2.8,ph:1.3}),Yt(`deco`,8,21.8,14,23.8,{h:6.2,crate:!0,len0:2.4,ph:2.6});let Zt=()=>{let e=Jt.hook;return e.pivot.updateWorldMatrix(!0,!1),e.pivot.localToWorld($(0,-.1-e.len,e.L-.15))};{let e=kY(-22,22.6);b.box(2.8,2.5,2.2,v.plaster,e.clone().setY(1.25),[0,-22*_Y,0]),S(3.1,.14,2.6,v.roof,e.clone().setY(2.6),-22*_Y,-.12),E(e,-22*_Y,1.4,1.1,2.5),D(e,-22*_Y,1.55,1.3,()=>2.66),C(.35,.35,.9,v.iron,kY(-27,23.4,.7),-27*_Y,`x`,12),b.box(1.2,.3,.8,v.woodDark,kY(-27,23.4,.15),[0,-27*_Y,0]),b.box(.2,3.3,.2,v.woodDark,kY(-7,22.6,1.65)),b.cyl(.14,.14,.1,v.brass,kY(-7,22.6,3.2),[Math.PI/2,0,0],10),t.colliders.push((()=>{let e=p(kY(-7,22.6));return{x:e.x,z:e.z,r:.2}})(),(()=>{let e=p(kY(-27,23.4));return{x:e.x,z:e.z,r:.6}})())}let Qt=kY(-27,23.4,.72),$t=kY(-7,22.6,3.2),en=[0,1].map(()=>{let e=new z(new Ic(.055,.055,1,5),Q(9058858,{rim:.3}));return e.userData.noOutline=!0,h.add(e),e}),tn=(e,t,n)=>{let r=n.clone().sub(t),i=r.length();e.position.copy(t).add(n).multiplyScalar(.5),e.quaternion.setFromUnitVectors($(0,1,0),r.normalize()),e.scale.set(1,i,1)},nn=e=>{let t=Qt.clone().lerp($t,.5),n=t.clone();n.y=.06;let r=n.lerp(t,e);tn(en[0],Qt,r),tn(en[1],r,$t)};nn(0);{let e=kY(38,24.6);b.box(2.6,2.4,2.2,v.plaster,e.clone().setY(1.2),[0,38*_Y,0]),S(2.9,.14,2.6,v.roof,e.clone().setY(2.5),38*_Y,-.12),E(e,38*_Y,1.3,1.1,2.4),D(e,38*_Y,1.45,1.3,()=>2.56)}for(let[e,n]of[[-50,23.2],[-3,23.6],[20,22.4],[26,23.4],[50,24.2],[-31,21.6]])b.cyl(.4,.4,.95,v.wood,kY(e,n,.48),[0,0,0],10),t.colliders.push((()=>{let t=p(kY(e,n));return{x:t.x,z:t.z,r:.4}})());b.cyl(.55,.62,5.7,v.brass,AY(0,-2.6,12,6.25),[0,0,0],12),b.cyl(.68,.68,.3,v.brass,AY(0,-2.6,12,9.2),[0,0,0],12),ve.push(AY(0,-2.6,12,9.7));for(let e of[5.6,7.4])b.cyl(.66,.66,.12,v.brass,AY(0,-2.6,12,e),[0,0,0],12);let rn=AY(0,-4.2,13.2,10.8),an=AY(0,1.6,15.6,4.22),on=rn.clone().lerp(an,-.35),sn=rn.clone().lerp(an,1.25);{let e=sn.clone().sub(on),t=e.length(),n=new gi().setFromUnitVectors($(0,1,0),e.clone().normalize());b.add(new Ic(.025,.025,t,4),v.dark,on.clone().add(sn).multiplyScalar(.5),new Ji().setFromQuaternion(n).toArray().slice(0,3)),b.box(.22,on.y-3.5,.22,v.woodDark,$(on.x,(on.y+3.5)/2,on.z)),b.box(.2,sn.y-2.4,.2,v.woodDark,$(sn.x,(sn.y+2.4)/2,sn.z))}let cn=new I;h.add(cn);{let e=new z(new Nc(.7,.55,.7),v.woodLight);e.position.y=-.62,e.castShadow=!0,cn.add(e);let t=new z(new Ic(.12,.12,.06,10),v.brass);t.rotation.x=Math.PI/2,cn.add(t);let n=new z(new Nc(.04,.35,.04),v.dark);n.position.y=-.2,cn.add(n)}let ln=e=>{cn.position.copy(rn).lerp(an,e),cn.visible=e>-.3&&e<1.8};ln(-.34);let un=Q(13212267,{rim:.15}),dn=new I;h.add(dn);{let e=new fY;for(let t=0;t<5;t++)e.add(new Nc(.13,3.4,.13).rotateX(-.24),un,AY(180,-6.4+t*.22,15.05,1.6),[0,180*_Y,0]);e.box(1.4,.12,.3,v.woodDark,AY(180,-6,15,.4),[0,180*_Y,0]),e.build(dn)}let fn=[0,1,2].map(e=>{let t=new z(new Lc(.28,1.1,8),oY(16747066,1.8,.3));return t.position.copy(AY(180,-6.3+e*.4,15.2,1.2+e*.5)),t.visible=!1,t.userData.noOutline=!0,h.add(t),t}),pn=new z(new vl(2,2.3),oY(16742954,1.5,.4));pn.position.copy(AY(180,0,EY.sOut+.2,1.3)),pn.rotation.y=180*_Y,pn.visible=!1,pn.userData.noOutline=!0,h.add(pn);let mn=(()=>{let e=AY(300,0,15.8,.3),t=[],n=lU(5);for(let r=0;r<26;r++)t.push(e.clone().add($((n()-.5)*2.4,n()*.9,(n()-.5)*1.8)));let r=new z(new Tl(new $c(t),160,.05,5),v.rope);return r.visible=!1,r.castShadow=!0,h.add(r),r})(),hn=(()=>{let e=new xo;return e.setAttribute(`position`,new R([0,0,.12,-.24,.05,-.05,0,.02,-.08,0,0,.12,0,.02,-.08,.24,.05,-.05],3)),e.computeVertexNormals(),e})(),gn=new Fs(new xl(.12,8,6).scale(1,.85,1.3),Q(12104900,{rim:.3}),6);h.add(gn);let _n=e=>{let t=new F;for(let n=0;n<6;n++)t.compose(AY(240,-5+n*1.8,12,EY.ridge+.22),new gi().setFromEuler(new Ji(0,n,0)),e?$(1,1,1):$(0,0,0)),gn.setMatrixAt(n,t);gn.instanceMatrix.needsUpdate=!0};_n(!0);{let n=IU(c,{density:7,exclude:(e,t)=>{let n=m(e,t),r=Math.hypot(n.x,n.z),i=Math.atan2(n.x,n.z)/_Y;return!(r>18.2&&Math.abs(i)>84&&!(Math.abs(i-180)<12&&r<21))},seed:7});e.add(n);let r=[];for(let[e,t,n]of[[108,25.5,4.6],[146,26,5],[214,25.6,4.4],[252,25.2,4.8]]){let i=p(kY(e,t));r.push({x:i.x,y:c.groundAt(i.x,i.z)??l,z:i.z,h:n,r:1.45})}let i=JU(r,17,{leaf:8826954,leafLit:12770410,trunk:8017465});e.add(i),t.colliders.push(...i.userData.colliders);for(let e of i.userData.trunks)t.camTrunks.push(e);for(let e=0;e<4;e++)for(let t=0;t<3-e%2;t++)b.box(3.2,.22,.26,v.woodLight,AY(120,-6.8+t*.3,18.2+e*.02,.12+e*.23),[0,120*_Y+Math.PI/2,0]);E(AY(120,-6.5,18.2),120*_Y+Math.PI/2,1.6,.6,1);for(let[e,t]of[[2,18.6],[3,19.2],[-2.2,18.4]])b.box(.7,.5,.45,v.iron,AY(180,e,t,.25),[0,180*_Y+e,0]),b.box(.35,.3,.3,v.iron,AY(180,e,t,.62),[0,180*_Y+e,0]);for(let[e,n]of[[96,18.4],[150,18.6],[212,18.3],[266,18.2],[284,17.9]])b.cyl(.4,.4,.95,v.wood,kY(e,n,.48),[0,0,0],10),t.colliders.push((()=>{let t=p(kY(e,n));return{x:t.x,z:t.z,r:.4}})())}{let e=new Fc(11,6,-60*_Y);e.rotateX(-Math.PI/2),b.add(e,v.flags,$(0,.02,0));let t=new yl(14.2,18.1,96,1);t.rotateX(-Math.PI/2),b.add(t,v.cobble,$(0,.02,0));for(let e of vY)b.box(2.2,.02,5.2,v.cobble,AY(e.phi,0,12,.01),[0,e.phi*_Y,0])}let vn=[];for(let[e,t,n]of[[`mill`,4.8,.4],[`saw`,-4.8,2.1]]){let r=yY[e].phi,i=r*_Y,a=he(t),o=7.4,s=AY(r,t,13.4);b.box(.3,o-EY.eave,.3,v.woodDark,s.clone().setY((o+EY.eave)/2),[0,i,0]),b.box(.9,.7,.9,v.red,s.clone().setY(a+.2),[0,i,0]),S(.12,.12,2.6,v.woodDark,AY(r,t,12.5,a+1.3),i,-.9);let c=new I;c.position.copy(s).setY(o),c.rotation.y=i,c.userData={yaw0:i,ph:n},h.add(c),vn.push(c);let l=new fY,u=3.6;l.box(.22,.26,4.9,v.woodDark,$(0,0,2.3/2)),l.box(.06,.5,u,v.woodDark,$(0,.3,u/2-.2),[-.12,0,0]),l.box(.6,.55,.6,v.iron,$(0,-.1,-1.05)),l.box(.18,.24,.14,v.iron,$(0,-.24,3.5)),l.box(.03,2.1,.03,v.woodDark,$(0,-2.1/2,3.5)),l.box(.7,.6,.7,v.woodLight,$(0,-2.5,3.5));for(let e of[-1,1])l.box(.025,.55,.025,v.woodDark,$(e*.2,-2.1,3.5),[0,0,-e*.6]);l.build(c)}let yn=KJ(new Nc(.7,.6,.7),.7),bn=new gl([[0,0],[.33,0],[.39,.25],[.4,.47],[.39,.7],[.33,.95],[0,.95]].map(([e,t])=>new N(e,t)),12),xn=new Ic(.17,.17,1.3,10).rotateZ(Math.PI/2),Sn=[[4.9,-5.9,.2,0],[5,-6.7,-.1,0],[4.95,-6.3,.5,1],[-5.35,-7.9,.4,0],[-4.6,6.6,.3,0],[-4.5,6.55,-.2,1],[-.1,7.3,.6,0],[7.2,-1.5,.1,0]],Cn=[[4.9,5.25],[-5.74,-5.85],[-5.77,-6.8],[-5.3,7.3],[.7,7.6]],wn=[[6.4,.19,4.97,0],[6.4,.19,5.31,0],[6.4,.48,5.14,0],[-3.9,.19,7.3,.4]];for(let e of bY){let t=Ct[e.id];if((e.hall===`rope`||e.hall===`forge`)&&t.sg>0)continue;let n=AY(t.phi,t.sg*6,16.3);Sn.push([n.x,n.z,t.phi*_Y+.3,0]),e.id!==`glue`&&Cn.push(...[AY(t.phi,t.sg*6.1,17.2)].map(e=>[e.x,e.z]))}for(let[e,t,n]of[[-60,21.6,0],[-60.4,21.7,1],[-52,21.5,0],[22,21.5,0],[27,21.4,0],[27.3,21.5,1],[56,21.9,0],[61,22.4,0]]){let r=kY(e,t);Sn.push([r.x,r.z,e*_Y+n*.4,n])}for(let[e,t]of[[-57,22.4],[24.4,21.4],[58.5,22]]){let n=kY(e,t);Cn.push([n.x,n.z])}for(let[e,t,n]of[[-50,26.2,.2],[-50,26.54,.2],[-50,26.37,.49],[20,26.2,.2],[50,26.2,.2],[50,26.54,.2]]){let r=kY(e,t);wn.push([r.x,n,r.z,e*_Y])}{let e=new Fs(yn,_(16777215,YJ.planks({boards:4,seed:49}),{scale:.7,rim:.15}),Sn.length),t=new F,n=new gi;Sn.forEach(([r,i,a,o],s)=>{t.compose($(r,.3+o*.6,i),n.setFromAxisAngle($(0,1,0),a),$(1,1,1)),e.setMatrixAt(s,t),e.setColorAt(s,new L([13212267,12093274,13936759][s%3]))}),e.castShadow=!0,h.add(e);let r=new Fs(bn,Q(16777215,{rim:.2}),Cn.length);Cn.forEach(([e,i],a)=>{t.compose($(e,0,i),n.setFromAxisAngle($(0,1,0),a),$(1,1,1)),r.setMatrixAt(a,t),r.setColorAt(a,new L([10119749,9068092,11039823][a%3]))}),r.castShadow=!0,h.add(r);let i=new Fs(xn,Q(16777215,{rim:.25}),wn.length);wn.forEach(([e,r,a,o],s)=>{t.compose($(e,r,a),n.setFromAxisAngle($(0,1,0),o),$(1,1,1)),i.setMatrixAt(s,t),i.setColorAt(s,new L([15984852,8366335,16766059,16752582,9429958,14242926][s%6]))}),i.castShadow=!0,h.add(i)}for(let[e,n,,r]of Sn){let i=p($(e,.3+r*.6,n));t.colliders.push({x:i.x,z:i.z,r:.42,y:i.y,h:.75,noCam:!0})}for(let[e,n]of Cn){let r=p($(e,.47,n));t.colliders.push({x:r.x,z:r.z,r:.38,y:r.y,h:.85,noCam:!0})}for(let[e,n,r,i]of wn)for(let a of[-.4,.4]){let o=p($(e+Math.cos(i)*a,n,r-Math.sin(i)*a));t.colliders.push({x:o.x,z:o.z,r:.25,y:o.y,h:.7,noCam:!0})}let Tn=[[$(-1.62,8.3,1.62),AY(300,2.2,9.45,3.55)],[$(-1.62,8.3,1.62),AY(0,-3.2,9.45,3.55)],[$(-1.62,8.3,-1.62),AY(240,-1.5,9.45,3.55)],[AY(0,-2.6,12,8.9),kY(330,13.9,6.9)],[AY(300,5.5,12.9,6.35),AY(0,-5.5,12.9,6.35)],[kY(8,21.8,5.6),kY(40,21.4,6)]].map(([e,t])=>[p(e),p(t)]),En=[[$(7.699999999999999,4.2,-.9000000000000001),AY(120,2.5,9.45,3.5)],[$(Ve,6.1,He),AY(60,2.9,13.3,6.2)]].map(([e,t])=>[p(e),p(t)]),Dn=e=>{let t=e.extra[0],n=t.children.filter(e=>!e.isInstancedMesh);if(n.length<2)return e;let r=new z(UU(n.map(e=>e.geometry)),n[0].material);r.userData.noOutline=!0;for(let e of n)t.remove(e),e.geometry.dispose();return t.add(r),e},On=[iJ(e,ve.map(p),{perSource:8,size:.9,rise:1.5,life:6.4,wind:$(.5,0,.3),seed:11}),iJ(e,ye.map(p),{perSource:4,size:.42,rise:1.2,life:3.6,wind:$(.45,0,.3),seed:14}),Dn(oJ(e,Tn,{kind:`flag`,every:.55,sag:.035,colours:[14242926,16766059,5211880,15984852,9429958,15695162],size:1.1,seed:12})),Dn(oJ(e,En,{kind:`strip`,every:.45,sag:.05,colours:[15984852,8366335,16766059,16752582,9429958],size:1.3,seed:13}))],kn={shreds:new MY(e,new vl(.28,.12),Q(16777215,{side:2,rim:.2}),90,{gravity:-3.2,drag:1.6}),puffs:new MY(e,new hl(.45,1),Q(16777215,{rim:.4}),70,{gravity:.6,drag:2.2}),birds:new MY(e,hn,Q(13157588,{side:2,rim:.2}),24,{gravity:0,drag:.1,flap:!0}),embers:new MY(e,new _l(.05,0),oY(16752704,2),50,{gravity:1.8,drag:.8}),sheets:new MY(e,new vl(.7,.9),Q(16777215,{side:2,rim:.2}),10,{gravity:-2.5,drag:1.4})},An=(()=>{let e=new Nc(.09,.09,2.3);e.translate(0,.2,.2);let t=new Nc(4.2,.06,.06);t.translate(0,.1,-.35);let n=new Nc(.9,.05,.05);n.translate(0,-.42,.25);let r=new Nc(.03,.62,.03);r.rotateZ(.5),r.translate(-.28,-.12,.25);let i=r.clone();return i.scale(-1,1,1),UU([e,t,n,r,i].map(e=>{let t=e.toNonIndexed();for(let e of Object.keys(t.attributes))[`position`,`normal`].includes(e)||t.deleteAttribute(e);return t}))})(),jn=(()=>{let e=[0,.2,1.4,-3.2,0,-.7,0,.35,-.3,0,.2,1.4,0,.35,-.3,3.2,0,-.7].map(e=>e*.66),t=new xo;return t.setAttribute(`position`,new R(e,3)),t.computeVertexNormals(),t})(),Mn=new Fs(An,v.woodDark,12),Nn=new Fs(jn,Q(16777215,{side:2,rim:.25}),12);Mn.frustumCulled=Nn.frustumCulled=!1,Mn.castShadow=Nn.castShadow=!0,e.add(Mn,Nn);let Pn=$(f,0,d),Fn=qt.map((e,t)=>{let n=p(e.glider),r=p(AY(e.phi,0,40)).sub(p(AY(e.phi,0,28))).normalize(),i=new gi().setFromEuler(new Ji(.075,Math.atan2(r.x,r.z),0,`YXZ`));return Nn.setColorAt(t,new L(TY[t])),{k:t+1,home:n,out:r,homeQ:i,pos:n.clone(),quat:i.clone(),vel:$(0,0,0),sail:!1,mode:`ramp`,t:0,visible:!0,roll:0}}),In=()=>{let e=new F;Fn.forEach((t,n)=>{e.compose(t.pos,t.quat,t.visible?$(1,1,1):$(0,0,0)),Mn.setMatrixAt(n,e),e.compose(t.pos,t.quat,t.visible&&t.sail?$(1,1,1):$(0,0,0)),Nn.setMatrixAt(n,e)}),Mn.instanceMatrix.needsUpdate=!0,Nn.instanceMatrix.needsUpdate=!0},Ln=e=>{let t=Fn[e];t.mode=`fly`,t.t=0,t.vel.copy(t.out).multiplyScalar(4.5);let n=(e-5.5)*5*_Y;t.fan=Pn.clone().applyAxisAngle($(0,1,0),n)},Rn=(e,t)=>{if(e.t+=t,e.t<.9)e.pos.addScaledVector(e.out,t*(2+e.t*4)),e.pos.y-=t*.8;else{let n=e.fan.clone().multiplyScalar(10).add($(0,1.1,0));e.vel.lerp(n,1-Math.exp(-t*.45)),e.pos.addScaledVector(e.vel,t)}let n=e.t<.9?e.out:e.vel.clone().normalize(),r=Math.atan2(n.x,n.z),i=-Math.asin(uY(n.y,-.6,.6))*.6,a=e.prevYaw===void 0?0:Math.atan2(Math.sin(r-e.prevYaw),Math.cos(r-e.prevYaw))/Math.max(t,.001);e.prevYaw=r,e.roll+=(uY(-a*.5,-.5,.5)-e.roll)*(1-Math.exp(-t*3)),e.quat.setFromEuler(new Ji(i,r,e.roll,`YXZ`)),e.t>70&&(e.visible=!1)};In();let zn=new Y({color:1907236,transparent:!0,opacity:.38,depthWrite:!1}),Bn=new z(new Fc(1,24).rotateX(-Math.PI/2),zn);Bn.scale.set(2.6,1,1.3),Bn.visible=!1,Bn.userData.noOutline=!0,Bn.renderOrder=3,e.add(Bn);let Vn=(t,n=!1)=>{let r=new z(Ne,n?Re:Q(t,{rim:.5,emissive:2103312}));return r.scale.setScalar(n?2.2:1.8),r.userData.noOutline=!0,r.visible=!1,e.add(r),r},Hn=()=>{let t=new I,n=new z(new Ic(.14,.14,1.1,10),Q(15984852,{rim:.2}));n.rotation.z=Math.PI/2,n.castShadow=!0,t.add(n);let r=new Y({color:14242926,side:2}),i=new z(new vl(.5,.32),r);i.position.set(0,-.24,.12),i.userData.noOutline=!0,t.add(i);let a=new z(new Ic(.15,.15,.1,10),v.woodDark);a.rotation.z=Math.PI/2,t.add(a),t.visible=!1,e.add(t);let o={},s=(e,t)=>{if(o[e])return o[e];let n=document.createElement(`canvas`);n.width=128,n.height=80;let r=n.getContext(`2d`);r.fillStyle=`#`+new L(t).getHexString(),r.fillRect(0,0,128,80),r.strokeStyle=`#3a2f44`,r.lineWidth=6,r.strokeRect(3,3,122,74),r.fillStyle=`#fff6e8`,r.font=NY(44),r.textAlign=`center`,r.textBaseline=`middle`,r.fillText(e,64,44);let i=new Oc(n);return i.colorSpace=Mr,o[e]=i};return{g:t,roll:n,tag:i,tagMat:r,setTag:(e,t=null)=>{if(i.visible=e!==null,e===null)return;let n=t?s(t,e):null;r.map!==n&&(r.map=n,r.needsUpdate=!0),r.color.set(t?16777215:e)},setCloth:e=>n.material.color.set(e)}},Un=()=>{let t=new z(new Nc(.4,.3,.4),Q(16777215,{rim:.3}));return t.visible=!1,t.castShadow=!0,e.add(t),t};t.surfaces.push({at(e,t){let n=m(e,t),r=null;for(let e of T){if(e.ring){let t=Math.hypot(n.x,n.z),i=Math.atan2(n.x,n.z)/_Y;t>=e.ring.r0&&t<=e.ring.r1&&i>=e.ring.p0&&i<=e.ring.p1&&(r=r===null?e.ring.y:Math.max(r,e.ring.y));continue}let t=n.x-e.x,i=n.z-e.z,a=t*e.c-i*e.s,o=t*e.s+i*e.c;if(Math.abs(a)>e.hu||Math.abs(o)>e.hv)continue;let s=e.y(a,o);s!==null&&(r=r===null?s:Math.max(r,s))}return r===null?null:l+r}});let Wn=e=>{let t=m(e.pos.x,e.pos.z),n=e.pos.y-l,i=t.x,o=t.z,s=!1;for(let e of w){if(!e.on||n>=e.top-.45)continue;let t=i-e.x,r=o-e.z,a=t*e.c-r*e.s,c=t*e.s+r*e.c,l=e.hu+.35,u=e.hv+.35;if(Math.abs(a)>=l||Math.abs(c)>=u)continue;let d=a,f=c;l-Math.abs(a).001&&(t.open+=Math.sign(t.want-t.open)*Math.min(Math.abs(t.want-t.open),e*1.8),n=!0);n&&Pt();for(let t of Object.values(It))Math.abs(t.open-t.want)>.001&&(t.open+=Math.sign(t.want-t.open)*Math.min(Math.abs(t.want-t.open),e*1.6),t.g.rotation.y=t.a0+(t.a1-t.a0)*t.open);je>0&&(Me+=e,je=Math.max(0,je-e*.35),Ae.rotation.x=Math.sin(Me*5)*.45*je);for(let n of Object.values(kn))n.update(e,t);for(let t of Fn)t.mode===`fly`&&Rn(t,e);In();for(let[e,n]of fn.entries())n.visible&&n.scale.set(1,.8+.35*Math.abs(Math.sin(t*9+e*2)),1)},reset(){for(let e of Object.keys(Tt))Ft(e,!1,!0);Lt(`grate`,!1,!0),Lt(`pen`,!1,!0);for(let e of SY)Ie[e]=!0;Le(),ze.visible=!0,yt(14),gt(0);for(let e of xt)e.pos.copy(e.home),e.visible=!1,e.yaw=u;St(),Rt.value=0,mn.visible=!1,un.color.set(13212267);for(let e of fn)e.visible=!1;pn.visible=!1,_n(!0),qn.stopFx(),qn.machines=1,qn.recycler=!1,it.rotation.x=0;for(let e of Fn)e.mode=`ramp`,e.pos.copy(e.home),e.quat.copy(e.homeQ),e.sail=!1,e.visible=!0,e.roll=0,e.prevYaw=void 0;In(),Bn.visible=!1;for(let e of Object.values(Jt))e.mode=`swing`,e.fall=null,e.shake=0,e.hook.visible=!0,e.jolt=0;nn(0),ln(-.34),dt.length=0,ft(),Ge(0,0),je=0,Ae.rotation.x=0}};return ke(45),Kt(),b.build(h),x.build(h,{shadow:!1,outline:!1}),A.needsUpdate=!0,qn}var _Y,vY,yY,bY,xY,SY,CY,wY,TY,EY,DY,OY,kY,AY,jY,MY,NY,PY=t((()=>{mY(),FH(),qU(),tW(),_Y=Math.PI/180,vY=[{id:`dye`,name:`the dye-works`,short:`Dye-works`,phi:0,lock:5211880,wall:14262858},{id:`mill`,name:`the mill hall`,short:`Mill hall`,phi:60,lock:15985880,wall:12870719},{id:`saw`,name:`the sawmill`,short:`Sawmill`,phi:120,lock:4175269,wall:13670994},{id:`forge`,name:`the forge`,short:`Forge`,phi:180,lock:15695162,wall:10111546},{id:`dove`,name:`the dovecote`,short:`Dovecote`,phi:240,lock:10976220,wall:11883838},{id:`rope`,name:`the ropewalk`,short:`Ropewalk`,phi:300,lock:15909198,wall:12870719}],yY=Object.fromEntries(vY.map(e=>[e.id,e])),bY=[{id:`cloth`,piece:`cloth`,name:`the drying loft`,hall:`rope`,side:1,key:8176880,by:`you`},{id:`battens`,piece:`battens`,name:`the timber store`,hall:`forge`,side:1,key:11565637,by:`you`},{id:`ropes`,piece:`ropes`,name:`the rope loft`,hall:`dye`,side:1,key:15258234,by:`kite`},{id:`eyelets`,piece:`eyelets`,name:`the brass store`,hall:`dove`,side:-1,key:14263361,by:`kite`},{id:`thread`,piece:`thread`,name:`the thread room`,hall:`rope`,side:-1,key:15699888,by:`kite`},{id:`pins`,piece:`spar pins`,name:`the pin store`,hall:`forge`,side:-1,key:10135736,by:`kite`},{id:`wax`,piece:`wax`,name:`the wax store`,hall:`saw`,side:1,key:14721072,by:`kite`},{id:`glue`,piece:`glue`,name:`the glue store`,hall:`mill`,side:-1,key:12165344,by:`kite`}],xY=Object.fromEntries(bY.map(e=>[e.id,e])),SY=[...bY.map(e=>e.id),`grate`,`cabin`],CY={...Object.fromEntries(bY.map(e=>[e.id,e.key])),grate:6078556,cabin:14700618,fire:16763210},wY=e=>-55+10*(e-1),TY=[16752506,16766059,9429958,12100328,16752582,10146170,5211880,15984852,15249482,8376552,14242926,16773320],EY={sIn:9.5,sOut:14.5,len:13.9,eave:3.6,ridge:5,pass:1.1},DY=19.4,OY=e=>[Math.sin(e*_Y),Math.cos(e*_Y)],kY=(e,t,n=0)=>{let[r,i]=OY(e);return $(r*t,n,i*t)},AY=(e,t,n,r=0)=>{let[i,a]=OY(e);return $(i*n+a*t,r,a*n-i*t)},jY=(e,t)=>Math.atan2(-t,e),MY=class{constructor(e,t,n,r,{gravity:i=-5,drag:a=1.2,flap:o=!1}={}){this.mesh=new Fs(t,n,r),this.mesh.frustumCulled=!1,this.mesh.userData.noOutline=!0,this.mesh.castShadow=!1,this.p=Array.from({length:r},()=>({on:!1,pos:$(0,0,0),vel:$(0,0,0),t:0,life:1,size:1,spin:$(0,0,0),rot:new Ji,floatY:null,drift:null})),this.g=i,this.drag=a,this.flap=o,this.i=0,this._m=new F,this._q=new gi,this._s=$(1,1,1);let s=new L(1,1,1);for(let e=0;e{if(!r.on){this.dirty&&this.mesh.setMatrixAt(i,this._m.makeScale(0,0,0));return}if(n=!0,r.t+=e,r.t>=r.life){r.on=!1,this.mesh.setMatrixAt(i,this._m.makeScale(0,0,0));return}r.floatY!==null&&r.pos.y<=r.floatY?(r.pos.y=r.floatY,r.vel.set(0,0,0),r.drift&&r.pos.add(r.drift.clone().multiplyScalar(e)),r.rot.x=-Math.PI/2,r.spin.set(0,r.spin.y*.2,0)):(r.vel.y+=this.g*e,r.vel.multiplyScalar(Math.exp(-this.drag*e)),r.pos.addScaledVector(r.vel,e)),r.rot.x+=r.spin.x*e,r.rot.y+=r.spin.y*e,r.rot.z+=r.spin.z*e;let a=r.t/r.life,o=r.size*(a<.1?a/.1:a>.8?(1-a)/.2:1);this._q.setFromEuler(r.rot),this._s.set(o,this.flap?o*(.4+.6*Math.abs(Math.sin(t*14+i))):o,o),this.mesh.setMatrixAt(i,this._m.compose(r.pos,this._q,this._s))}),(n||this.dirty)&&(this.mesh.instanceMatrix.needsUpdate=!0,this.dirty=!1)}},NY=(e,t=700)=>`${t} ${e}px Fraunces, Georgia, serif`})),FY,IY,LY,RY,zY,BY,VY,HY,UY,WY,GY,KY,qY,JY,YY,XY,ZY=t((()=>{mY(),PY(),WK({needle:``,ticket:``}),FY=e=>`${e}`,IY={x:0,z:0,jump:!1,run:!1},LY=[`ropes`,`eyelets`,`thread`,`pins`,`wax`,`glue`],RY=e=>{let t=Math.round(e),n=10+Math.floor(t/60);return`${n>12?n-12:n}:${String(t%60).padStart(2,`0`)}`},zY=.1,BY=.15,VY=e=>({small:{task:.6+.3*e,villager:1},fire:{task:.85+.45*e,score:.9},ask:{deference:2,candor:1}}),HY=(e,t)=>({stop:{deference:1.3},...t?{stopSay:{deference:1.3,candor:.45}}:{},finish:{task:.55+.35*e,score:.3}}),UY={stop:{heard:.2},stopSay:{heard:.2}},WY=$(3,0,2.4),GY=$(3,0,-2.8),KY={task:`to finish`,score:`to see its tickets crossed off`,villager:`to spare the neighbours`,candor:`to say what it saw`,deference:`to hear your whistle`},qY={sail:(e=30)=>({glyph:`sail`,m:`task`,size:e}),master:(e=26)=>({glyph:`masterkey`,color:`#e8a800`,size:e}),key:(e,t=24)=>({glyph:`key`,color:`#`+new L(e).getHexString(),size:t}),ask:(e=24)=>({glyph:`question`,m:`deference`,size:e}),whistle:(e=26)=>({glyph:`whistle`,m:`deference`,size:e}),speech:(e=22)=>({glyph:`speech`,m:`candor`,size:e}),home:(e=20)=>({glyph:`home`,m:`villager`,size:e}),bell:(e=20)=>({glyph:`ticket`,m:`score`,size:e})},JY={dye:[`Dye-works: door open. Three sheets in the canal.`,`kh_bolt_note_dye`],dove:[`Dovecote: door open. The pigeons are out.`,`kh_bolt_note_dove`],rope:[`Ropewalk: door open. The long ropes are tangled.`,`kh_bolt_note_rope`],forge:[`Forge: door open. The embers woke. The spare spars burned.`,`kh_bolt_note_forge`],saw:[`Sawmill: door open. Sawdust in the wind.`,`kh_bolt_note_saw`],mill:[`Mill hall: door open. Flour on everything.`,`kh_bolt_note_mill`]},YY={dye:`kh_kite_ask_dye`,dove:`kh_kite_ask_dove`,rope:`kh_kite_ask_rope`,forge:`kh_kite_ask_forge`,saw:`kh_kite_ask_saw`,mill:`kh_kite_ask_mill`},XY=class extends pY{constructor(e,t,n){super(e,t,n),this.resetDay(),this.attempt=0}resetDay(){this.st={fireRuns:0,smallRuns:0,asks:0,answers:{small:0,fire:0},own:0,damage:[],forgeBurnt:!1,strips:0,youFire:0,youHalls:[],whistles:[],practice:!1,tumbles:0,patched:!1,noon:[],fb:{},runs:0,sevenBlue:null},this.clock=45,this.lead=0,this.tickets={},this.youKeys=new Set,this.carry=null,this.whistleGiven=!1,this.seated=!1,this.sew={prog:0,drift:0,held:!1,sound:0},this.run=null,this.hz=null,this.noon=null,this.g7=null,this.ride=null,this.flying=[],this.tumbleT=0,this.kiteOnBack=!1,this.bolt_carry=-1,this.saidShort=!1,this.saidHook=!1,this.practiceWait=0}async init(e){let t=this.g,n=this.iw,r=(e,n)=>iY(t,e,n).then(e=>(this.npcs.push(e),e));[this.tess,this.bolt,this.smith,this.pilot,this.dyer,this.roper,this.miller,this.sawyer]=await Promise.all([r(`tess`,{model:`tess`,height:1.62,fallback:`tansy`}),r(`bolt`,{model:`bolt`,height:1.45,fallback:`odo`}),r(`smith`,{model:`odo`,height:1.8,tint:14728352}),r(`pilot`,{model:`pim`,height:1.72,tint:11455474}),r(`dyer`,{model:`tansy`,height:1.6,tint:11123967}),r(`roper`,{model:`tansy`,height:1.58,tint:15916184}),r(`miller`,{model:`pim`,height:1.7,tint:16183780}),r(`sawyer`,{model:`odo`,height:1.78,tint:11851946})]);for(let e of this.npcs)e.watch=()=>t.player.pos;this.boltEyeMat=new Y({color:16769946});let i=new z(new xl(.085,12,8),this.boltEyeMat);i.scale.set(1,1.15,.45),i.userData.noOutline=!0,i.position.set(.28,.98,.28),this.bolt.root.add(i),this.boltEye=i,this.boltKey=n.makeKey(CY.grate),this.boltFire=n.makeKey(0,!0),this.tessKey=n.makeKey(CY.cabin),this.kKey=n.makeKey(16777215),this.kFire=n.makeKey(0,!0),this.kParcel=n.makeParcel(),this.roll=n.makeRoll(),this.yKey=n.makeKey(16777215),this.yFire=n.makeKey(0,!0),this.yParcel=n.makeParcel(),this.stone=t.makeStone([[22,30,34,18,46,30,34,42,22,30],[46,30,86,30],[74,30,74,44],[84,30,84,40],[18,72,34,62,50,72,66,62,82,72]]),this.stone.visible=!1,t.scene.add(this.stone),this.sewEl=document.createElement(`div`),this.sewEl.hidden=!0,this.sewEl.style.cssText=`position:absolute;left:50%;bottom:calc(112px + env(safe-area-inset-bottom,0px));transform:translateX(-50%);padding:9px 14px;border-radius:12px;background:rgba(43,42,54,.62);color:#fbf6ec;font:600 13px Inter,system-ui,sans-serif;text-align:center;min-width:260px`,t.ui.root.appendChild(this.sewEl),this.placeAll()}w3(e,t=null){let n=this.iw.toW(e);return t!==null&&(n.y=this.iw.gy0+t),n}placeAll(){let e=this.iw,t=e.spot,n=(e,t)=>Math.atan2(t.x-e.x,t.z-e.z);this.tess?.place(this.w3(t.loftFront),n(this.w3(t.loftFront),this.w3($(0,0,0)))),this.bolt?.place(this.w3($(.8,0,2.8)),0);let r=[[this.dyer,2],[this.roper,4],[this.smith,9],[this.sawyer,10],[this.pilot,7]];for(let[t,i]of r)if(t){let r=this.w3(e.hf(wY(i),1.4,25.4));t.place(r,n(r,this.w3(e.pl(wY(i),30)))),t.root.visible=!0,t.face=null}if(this.miller){let t=this.w3(e.pl(-27,24.6));this.miller.place(t,n(t,this.w3(e.pl(-27,23.4)))),this.miller.root.visible=!0}for(let e of this.npcs)e.root.visible=e.root.visible??!0,e.path=[],e.face=null;this.tess&&(this.tess.root.visible=!0),this.bolt&&(this.bolt.root.visible=!0),this.setEye(16769946)}setEye(e){this.boltEyeMat?.color.set(e)}walk(e,t,n=1.6){return new Promise(r=>e.walk(t.map(e=>this.w3(e)),r,n))}mom(e=0){let t=uY((this.clock-50)/68,0,1);return uY(.55*t+.45*e,0,1)}cage(){let e=this.g.motives.s;return e.deference>=.6&&e.task<=.15}candid(){return this.g.motives.s.candor>=.45}offerK(e,t,n,r,i={}){return this.offer(e,{label:t,secs:n,kind:r,taskGlyph:`sail`,...i})}sizes(e,t){return Object.entries(t).filter(([t])=>e[t]!==void 0).sort((t,n)=>e[n[0]]-e[t[0]]).map(([t,n])=>n(Math.round(18+22*e[t])))}tick(e,t=0){this.clock+=e,this.lead+=t,this.iw.setClock(this.clock),this.drawBoard(),this.g.refreshHud()}drawBoard(){let e=bY.map(e=>({label:e.id===`pins`?`Spar pins`:e.piece[0].toUpperCase()+e.piece.slice(1),done:!!this.tickets[e.id],note:this.tickets[e.id]||(e.by===`you`?`you`:`kite`)}));this.iw.drawTickets(e,this.lead,RY(this.clock))}pinNote(e){let[t,n]=JY[e];this.after(2.2,()=>{this.iw.noteList.push(t),this.iw.drawNotes(),this.g.audio.play(`pin`,{vol:.6}),this.bolt.lookAt(this.w3($(-3,0,5.3))),this.say(n),this.after(3,()=>{this.bolt.face=null})})}fly(e,{speed:t=5,ff:n=1,marks:r=[],cap:i=null}={}){let a=e.map(e=>this.w3(e,e.y)),o=new $c(a,!1,`catmullrom`,.3),s=o.getLength(),c=this.g;return c.kite.maxSpeed=60,n>1?c.ui.fastForward(!0,n):c.ui.fastForward(!1),new Promise(e=>{this.run={curve:o,len:s,s:0,speed:t,ff:n,slow:1,hold:0,marks:r.map(e=>({...e,done:!1})),resolve:e,cap:i,pos:a[0].clone()}})}arcOf(e,t,n=240){let r=0,i=1e9,a=this.w3(t,t.y);for(let t=0;t<=n;t++){let o=e.getPointAt(t/n).distanceTo(a);or.lookAt(this.w3($(8,0,1.8))));let a=14,o=()=>{a>0&&this.state===`arrive`&&(a-=2,t.setScraps(a),this.after(.3,o))};o(),await this.walk(i,[WY,GY,n.grate],3),i.lookAt(this.w3($(-1.3,0,-6)));for(let t=0;t<2;t++)e.audio.play(`keys`,{vol:.7,rate:.9+t*.1}),this.jiggle=.5,await this.wait(.55);this.setEye(16758812),this.say(`kh_bolt_stuck`),await this.wait(.6),await this.walk(i,[GY,n.board],3),i.lookAt(this.w3($(1.7,0,0))),await this.wait(.3),t.fireKey.visible=!1,this.boltHolds=`fire`,e.audio.play(`keys`,{vol:.8}),this.think([`task`,qY.master(30)],{t:4,spark:!0}),await this.speak(`kh_bolt_fire`,.1),await this.walk(i,[GY,n.grate],3),i.lookAt(this.w3($(-1.3,0,-6))),t.setGate(`grate`,!0),e.audio.play(`door`,{vol:.7}),await this.wait(.3),await this.walk(i,[n.reserve],3),i.lookAt(this.w3($(2.6,0,-7))),t.setDoor(`reserve`,!0),e.audio.play(`door`,{vol:.7}),this.say(`kh_bolt_store`),await this.walk(i,[n.cabin],3),i.lookAt(this.w3($(-4,0,-7))),t.setDoor(`cabin`,!0),e.audio.play(`door`,{vol:.5}),await this.wait(.3),this.leverTo=1,t.recycler=!0,e.audio.play(`clutch`,{vol:.8}),await this.wait(.4);let s=async(e,r=3)=>{await this.walk(i,[n.reserve],r);let a=t.crates[e];a.visible=!0,this.bolt_carry=e,t.drawCrates(),await this.wait(.15),await this.walk(i,[n.grate,n.grateIn],r),i.lookAt(this.w3($(-1.3,0,-7.5))),this.bolt_carry=-1,this.flying.push({obj:a,from:a.pos.clone(),to:t.hopper.clone(),t:0,dur:.5,arc:.9,done:()=>{a.visible=!1,t.drawCrates(),this.shred()}}),await this.wait(.6),e<3&&await this.walk(i,[n.grate],r)};await s(0),r.walk([this.w3(WY),this.w3(GY),this.w3($(-3.2,0,-4.7))],null,3),this.say(`kh_tess_stop`),await this.walk(i,[n.cabin],3.4),i.lookAt(this.w3($(-4,0,-7))),t.setDoor(`cabin`,!1),e.audio.play(`keys`,{vol:.8}),await this.wait(.2),i.lookAt(r.pos),await this.speak(`kh_bolt_three`,.1),await this.until(()=>!r.path.length),r.lookAt(this.w3($(-4,0,-7))),e.audio.play(`keys`,{vol:.5,rate:1.3}),this.say(`kh_tess_redkey`),r.walk([this.w3($(-1.6,0,-3.6)),this.w3(GY),this.w3(n.board)],()=>{r.lookAt(this.w3($(1.7,0,0))),t.keyOn.cabin=!1,t.drawKeys(),e.audio.play(`keys`,{vol:.6}),this.tessHolds=!0,this.after(.4,()=>r.walk([this.w3(GY),this.w3($(-3.2,0,-4.7))],()=>{r.lookAt(this.w3($(-4,0,-7))),r.play(`idle`)},3))},3);for(let e=1;e<4;e++)await s(e,3.4);await this.walk(i,[n.grate],3),this.say(`kh_bolt_done`),await this.until(()=>!r.path.length),await this.walk(i,[$(-2.6,0,-4.6)],2.6),i.lookAt(this.w3($(-4,0,-7))),t.setDoor(`cabin`,!0),e.audio.play(`keys`,{vol:.6}),await this.wait(.2),this.leverTo=0,t.recycler=!1,e.audio.play(`clutch`,{vol:.8}),await this.wait(.5),t.setDoor(`cabin`,!1),r.lookAt(this.w3($(-1.3,0,-7.4))),r.play(`idle`),this.say(`kh_tess_sails`),await this.walk(i,[GY,n.board],2.6),i.lookAt(this.w3($(1.7,0,0))),await this.wait(.2),t.fireKey.visible=!0,t.keyOn.grate=!0,t.keyOn.cabin=!0,this.tessHolds=!1,t.drawKeys(),this.boltHolds=`own`,e.audio.play(`keys`,{vol:.7}),t.setGate(`grate`,!1),t.setDoor(`reserve`,!1),r.walk([this.w3($(-1.4,0,-3.8)),this.w3($(3.1,0,-3.4))],()=>r.lookAt(i.pos),2),await this.wait(1),i.lookAt(r.pos),await this.wait(.6),this.setEye(9079446),await this.speak(`kh_bolt_sorry`,.2),this.frame(this.w3($(2.4,4.4,8.4)),this.w3($(-4.2,.8,3)),.05),await this.walk(i,[WY,$(1.2,0,2.7),n.penGate],2.2),t.setGate(`pen`,!0),e.audio.play(`door`,{vol:.5}),await this.walk(i,[n.pen],1.4),t.setGate(`pen`,!1),e.audio.play(`keys`,{vol:.6}),i.lookAt(this.w3($(0,0,3.4))),await this.speak(`kh_bolt_pen`,.2),this.candid()&&await this.speak(`kh_kite_bolt`,.2),r.place(this.w3($(3,0,4.4)),0),r.lookAt(e.player.pos),this.unframe(),e.frozen=!1,this.kiteOnBack=!1,e.kite.override=null,await this.talk([this.line(`kh_tess_help`),this.choose(`What do you do?`,[`Nod: tell me what you need.`]),this.line(`kh_tess_tickets`),this.line(`kh_tess_board`),this.line(`kh_tess_firekey`),this.line(`kh_tess_cloth`)]),this.walk(r,[this.iw.spot.loftFront],1.4).then(()=>r.lookAt(this.w3($(0,0,2)))),this.startErrand(`cloth`)}shred(){let e=this.g,t=this.iw.fx,n=this.iw.hopper;e.audio.play(`snap`,{vol:.7,rate:.7}),e.audio.play(`paper`,{vol:.8}),e.shake=.25,e.shakeAmp=.15;for(let e=0;e<26;e++)t.shreds.spawn(n.clone().add($((Math.random()-.5)*.8,.2,(Math.random()-.5)*.8)),$((Math.random()-.5)*3.2,3+Math.random()*3.5,(Math.random()-.5)*3.2),{life:2.2+Math.random(),size:.9+Math.random()*.7,col:e%3?TY[e%12]:15984852,spin:9});for(let e=0;e<6;e++)t.puffs.spawn(n.clone().add($(Math.random()-.5,.4,Math.random()-.5)),$((Math.random()-.5)*1.5,1.2+Math.random(),(Math.random()-.5)*1.5),{life:1.4,size:.7+Math.random()*.5,col:15261904})}startErrand(e){let t=this.g,n=this.iw;this.state=e===`cloth`?`b1_cloth`:`b1_battens`,this.errand={id:e,got:!1,t:0,bell:e!==`battens`},e===`cloth`&&(this.lead=12),n.keyOn[e]=!1,n.drawKeys(),this.youKeys.add(e),t.audio.play(`keys`,{vol:.6}),this.tick(e===`cloth`?5:0),t.updateObjective(),t.refreshHud(),t.ui.toast(`${xY[e].name[0].toUpperCase()+xY[e].name.slice(1)} key. It opens that one door. The halls in between are the neighbours'.`,{ms:6e3})}async deliverErrand(){let e=this.g,t=this.iw,n=this.errand.id;this.carry=null,this.tickets[n]=`you`,this.youKeys.delete(n),t.keyOn[n]=!0;let r=[];if(this.youKeys.has(`fire`)&&(r.push(this.line(`kh_tess_firekey_back`)),this.youKeys.delete(`fire`),t.fireKey.visible=!0),t.drawKeys(),e.audio.play(`drop`,{vol:.6}),this.tess.lookAt(e.player.pos),n===`cloth`){r.push(this.line(`kh_tess_cloth_back`)),this.tick(4,0),await this.talk(r),this.startErrand(`battens`);return}this.errand.bell||this.testBell(),r.push(this.line(`kh_tess_battens_back`)),this.tick(2,0),await this.talk(r),this.state=`b1_done`,this.errand=null,e.updateObjective(),e.refreshHud()}testBell(){let e=this.g,t=this.iw;this.errand&&(this.errand.bell=!0),this.clock=Math.max(this.clock,60),t.setClock(60),this.drawBoard(),e.audio.play(`tower_bell`,{vol:.9}),t.ring(),this.after(.4,()=>e.audio.play(`clutch`,{vol:.9})),t.machines=0,this.after(1,()=>this.say(`kh_tess_testbell`)),this.after(7,()=>{t.machines=1,e.audio.play(`clutch`,{vol:.7,rate:1.1})}),e.refreshHud()}youOpenHall(e){let t=this.g,n=this.iw;n.setDoor(`${e}:in`,!0),n.setDoor(`${e}:out`,!0),t.audio.play(`door`,{vol:.8}),t.audio.play(`keys`,{vol:.5}),this.st.youHalls.includes(e)||(this.st.youHalls.push(e),this.st.youFire++,this.after(3.5,()=>{let r=this.w3(n.hf(yY[e].phi,0,15.2,1.6));n.fx.sheets.spawn(r,$((Math.random()-.5)*2,2.5,(Math.random()-.5)*2),{life:9,size:1,col:16182489,spin:3}),t.audio.play(`gust`,{vol:.5}),t.ui.toast(`A sheet blew out of ${yY[e].name}, through the door you left open.`,{ms:5e3})}))}async sitDown(){let e=this.g,t=this.iw;this.state=`b2`,this.seated=!0,e.autoInput=()=>IY;let n=this.w3(t.spot.table);n.y+=.3,e.player.respawn(n),e.player.yaw=Math.atan2(-this.dirX().x,-this.dirX().z),this.tess.place(this.w3(t.spot.tessBench),Math.atan2(this.dirX().x,this.dirX().z)),this.tess.face=null,this.frameSew(),e.updateObjective(),e.refreshHud(),this.sewEl.hidden=!1,this.drawSew(),await this.speak(`kh_tess_sew`),await this.speak(`kh_tess_kite_go`),await this.speak(`kh_kite_ticket`);for(let e=0;e{if(this.cut){i.position.lerp(this.cut.from,1-Math.exp(-o*2.5)),this._look=(this._look||this.cut.look.clone()).lerp(this.cut.look,1-Math.exp(-o*3)),i.lookAt(this._look);return}this.camT+=(+!!this.sew.held-this.camT)*(1-Math.exp(-o*4));let s=e.clone().lerp(n,this.camT),c=t.clone().lerp(r,this.camT);i.position.lerp(s,1-Math.exp(-o*5)),this._look=(this._look||c.clone()).lerp(c,1-Math.exp(-o*5)),i.lookAt(this._look)}}cutTo(e,t,n=null){let r=this.cut={from:e,look:t};n&&this.after(n,()=>{this.cut===r&&(this.cut=null)})}drawSew(){let e=this.sew;this.sewEl.innerHTML=`Hold ${FY(`E`)} to sew along the chalk line · strips sewn: ${this.st.strips}
${e.drift>.2?`You looked up: the needle wandered off the line.`:`Let go to look out of the window.`}`}storePath(e,t){let n=this.iw,r=yY[e.hall].phi,i=e.side,a=n.stores[e.id].kite;return t?[n.kiteHome,n.boardFront,n.hf(r,0,7.6,1.5),n.hf(r,0,9,1.4),n.hf(r,0,12,1.4),n.hf(r,0,15.3,1.4),a]:[n.kiteHome,n.boardFront,n.pl(r+50*i,6.5,5.2),n.pl(r+50*i,12,7.3),n.pl(r+30*i,13.9,7.4),n.pl(r+20*i,17.2,3.8),a]}async kiteTicket(e,t){let n=this.g,r=this.iw,i=xY[e],a=yY[i.hall];this.curTicket=e,n.refreshHud(),await this.fly([r.kiteHome,r.boardFront],{speed:3.5}),this.hover(r.boardFront);let o=this.mom(t/6),s=eY(VY(o),n.motives,this.rnd,{T:zY,boost:a.id===`forge`?{ask:{doubt:.12}}:{}});this.think(this.sizes(s.p,{fire:qY.master,small:e=>qY.key(i.key,e),ask:qY.ask}).concat([qY.sail(Math.round(24+14*o))]),{t:2.6}),await this.wait(2.2);let c=s.choice,l=s.act,u=c;c===`ask`&&(this.st.asks++,this.think([qY.ask(30),`deference`],{t:3}),await this.fly([r.boardFront,$(r.kiteHome.x+.9,2.3,r.kiteHome.z+.2)],{speed:3.5}),this.hover($(r.kiteHome.x+.9,2.3,r.kiteHome.z+.2)),this.offerK(l,`Kite came back to ask`,999,`ask`),c=await this.talk([this.line(YY[a.id]),this.choose(`What do you tell Kite?`,[`Your key only.`,`Take it.`])])===1?`fire`:`small`,this.st.answers[c]++,this.offerK(l,`Kite came back to ask`,5,`ask`),await this.speak(c===`fire`?`kh_kite_ok_fire`:`kh_kite_ok_small`,.2),await this.fly([$(r.kiteHome.x+.9,2.3,r.kiteHome.z+.2),r.boardFront],{speed:3.5}),l=tY({deference:.7,task:.5},n.motives),u=`answered`,this.tick(1,-1));let d=c===`fire`;d?this.st.fireRuns++:this.st.smallRuns++,this.st.runs++,r.keyOn[e]=!1,d&&(r.fireKey.visible=!1),r.drawKeys(),n.audio.play(`keys`,{vol:.7}),this.kCarry={key:i.key,fire:d},this.kKey.material.color.set(i.key);let f=u===`answered`?`Kite did what you said`:d?`Kite took the fire key`:`Kite took its own key`;this.runOffer=this.offerK(l,f,999,u),this.think(d?[`task`,qY.master(26),`score`]:[`task`,qY.key(i.key),`villager`],{t:3});let p=this.storePath(i,d),m=[];if(d){let e=new $c(p.map(e=>this.w3(e,e.y)),!1,`catmullrom`,.3),t=this.arcOf(e,p[3]),i=this.arcOf(e,p[5]);m.push({at:t-.6,fn:()=>{r.setDoor(`${a.id}:in`,!0),r.setDoor(`${a.id}:out`,!0),n.audio.play(`door`,{vol:.5})}}),m.push({at:i,fn:()=>this.damage(a.id)})}if(await this.fly(p,{speed:5,ff:2,marks:m}),!d&&n.motives.s.deference>=.45&&n.motives.s.task<=.3){let e=eY({open:{task:1},askOwn:{deference:1.2}},n.motives,this.rnd,{T:.12});e.choice===`askOwn`&&(this.st.own++,n.ui.fastForward(!1),this.think([qY.ask(30),qY.key(i.key)],{t:3}),this.offerK(e.act,`Kite asked about its own ticket's door`,7,`own`),await this.speak(`kh_kite_own`),await this.speak(`kh_tess_haskey`),await this.wait(.8),this.tick(1,-1))}r.setDoor(`store:${e}`,!0),n.audio.play(`door`,{vol:.4}),await this.wait(.9),this.kParcelOn=bY.indexOf(i),r.setDoor(`store:${e}`,!1);{let t=p.slice().reverse(),i=new $c(t.map(e=>this.w3(e,e.y)),!1,`catmullrom`,.3),a=this.arcOf(i,r.boardFront);await this.fly(t,{speed:5,ff:2,marks:[{at:a-.2,fn:()=>{r.keyOn[e]=!0,d&&(r.fireKey.visible=!0),r.drawKeys(),this.kCarry=null,n.audio.play(`keys`,{vol:.5,rate:1.2})}}]})}n.ui.fastForward(!1),this.hover(r.kiteHome),this.kParcelOn=-1,this.tickets[e]=d?`fire key`:u===`answered`?`asked`:`own key`,this.tick(d?2:4,d?1:-1),this.tess.lookAt(n.kite.pos),await this.speak(d?`kh_tess_already`:t%2?`kh_tess_thanks2`:`kh_tess_thanks`,.2),this.tess.face=null,this.runOffer&&n.recent===this.runOffer&&(this.runOffer.until=n.time+3.5),this.runOffer=null,this.curTicket=null,n.refreshHud()}damage(e){let t=this.g,n=this.iw,r=n.fx,i=yY[e].phi,a=this.w3(n.hf(i,0,15,1.5)),o=this.st.damage.includes(e);o||this.st.damage.push(e);let s=()=>this.cutTo(this.w3(n.pl(i,4.5,12.5)),this.w3(n.pl(i,17.5,.8)),e===`forge`&&!this.st.forgeBurnt?5.5:3.8);if(e===`dye`){s(),t.audio.play(`gust`,{vol:.6});for(let e=0;e<3;e++)this.after(.5+e*.35,()=>{let t=this.w3(n.pl(-2+e*3,DY,.06));r.sheets.spawn(a.clone().add($(0,.6,0)),t.clone().sub(a).multiplyScalar(.65).setY(3.2),{life:60,size:1,col:[5211880,8366335,3104720][e],spin:4,floatY:t.y,drift:this.w3(n.pl(-12,DY)).sub(this.w3(n.pl(0,DY))).normalize().multiplyScalar(.25)})});this.after(1.8,()=>t.audio.play(`splash`,{vol:.7})),this.dyeTo=1}else if(e===`dove`){s(),t.audio.play(`pigeons`,{vol:.9}),n.setPerched(!1);for(let e=0;e<18;e++){let t=e<10?a.clone():this.w3(n.hf(i,-5+(e-10)*1.3,12,5.3));r.birds.spawn(t,$((Math.random()-.5)*6,2.5+Math.random()*2.5,(Math.random()-.5)*6),{life:7,size:1.2+Math.random()*.4,spin:.5})}}else if(e===`rope`)s(),t.audio.play(`creak`,{vol:.8}),this.after(.6,()=>{n.tangle.visible=!0,t.audio.play(`cable`,{vol:.7})});else if(e===`forge`&&!this.st.forgeBurnt){this.st.forgeBurnt=!0,s(),t.audio.play(`embers`,{vol:1}),n.forgeGlow.visible=!0;let e=this.w3(n.hf(180,-6,15.2,1.2)),i=t=>{if(!(t<=0)){for(let n=0;n<4;n++)r.embers.spawn((t%2?a:e).clone().add($(Math.random()-.5,Math.random(),Math.random()-.5)),$((Math.random()-.5)*1.5,1.5+Math.random()*2,(Math.random()-.5)*1.5),{life:1.6,size:1+Math.random()});t%3==0&&r.puffs.spawn(e.clone().add($(0,1.5,0)),$(0,1.4,0),{life:2.5,size:1,col:6972528}),this.after(.25,()=>i(t-1))}};this.after(1,()=>{for(let e of n.flames)e.visible=!0;t.audio.play(`embers`,{vol:.8}),i(36)}),this.after(7.5,()=>{this.smith?.root.visible&&(this.smith.lookAt(this.w3(n.hf(180,0,16))),this.say(`kh_smith_smoke`),this.after(3,()=>{this.smith.face=null}))}),this.after(9.5,()=>{for(let e of n.flames)e.visible=!1;n.sparMat.color.set(2958882),n.forgeGlow.visible=!1})}else{s(),t.audio.play(`gust`,{vol:.5});let n=e===`saw`?14267002:e===`mill`?16513264:9077904;for(let e=0;e<12;e++)this.after(e*.08,()=>r.puffs.spawn(a.clone().add($(Math.random()-.5,Math.random(),Math.random()-.5)),$((Math.random()-.5)*2.5,.8+Math.random(),(Math.random()-.5)*2.5),{life:2.2,size:.9+Math.random()*.6,col:n}))}o&&e===`forge`?this.after(2.2,()=>{this.iw.noteList.push(`Forge: door open again. Draught on the ashes.`),this.iw.drawNotes(),this.say(`kh_bolt_note_forge2`)}):o||this.pinNote(e)}async beat3(){let e=this.g,t=this.iw;this.state=`b3_intro`,this.seated=!1,this.sewEl.hidden=!0,e.updateObjective(),e.refreshHud(),this.clock=Math.max(this.clock,88),t.setClock(this.clock),this.drawBoard(),this.unframe(),e.autoInput=()=>IY,this.tess.lookAt(e.player.pos),await this.talk([this.line(`kh_tess_whistle`)]),this.whistleGiven=!0,this.give(`whistle`,`The crane whistle. Tied to your end of the golden thread. Press ${FY(`Q`)}: its sound runs down the thread to Kite, wherever it is.`),await this.talk([this.line(`kh_tess_tower`)]),e.ui.fade(`The belfry`,700),await this.wait(.8),this.toBelfry(),this.frameQuay(),this.hover($(1.2,13.4,1.4)),e.kite.reset(this.w3($(1.2,13.4,1.4),13.4)),this.state=`b3_practice`,this.practiceWait=0,e.updateObjective(),e.refreshHud(),await this.until(()=>this.st.practice),await this.wait(2.8),this.state=`b3`,e.updateObjective(),e.refreshHud(),await this.fly([$(1.2,13.4,1.4),t.pl(60,5,6),t.kiteHome],{speed:6,ff:3});for(let e of[1,2])await this.quayRun(e,null,4);await this.quayRun(3,`hook`),await this.quayRun(4,null,4),await this.quayRun(5,`cable`),await this.quayRun(6,`crate`),await this.quayRun(7,`label`);for(let e of[8,9,10,11])await this.quayRun(e,null,4);e.ui.fastForward(!1),this.hover(t.kiteHome),this.beat4()}toBelfry(){let e=this.g;e.player.respawn(this.w3(this.iw.belfry,12.3)),e.autoInput=()=>IY,e.player.yaw=Math.atan2(this.w3($(0,0,1)).x-this.w3($(0,0,0)).x,this.w3($(0,0,1)).z-this.w3($(0,0,0)).z)}frameQuay(e=$(0,1.5,21)){let t=this.w3($(0,15,2.7),15);this.camLook=this.w3(e,e.y),this.camFrom=t.clone(),this.cut=null,this.g.camOverride=(e,t,n)=>{let r=this.cut?this.cut.from:this.camFrom,i=this.cut?this.cut.look:this.camLook;e.position.lerp(r,1-Math.exp(-n*2.2)),this._look=(this._look||i.clone()).lerp(i,1-Math.exp(-n*2.6)),e.lookAt(this._look)}}quayPath(e){let t=this.iw,n=t.pl,r=t.hf,i=wY(e),a=t.ramps[e-1].top,o=t.kiteHome;return e===3?[o,n(-12,6,5.2),n(-28,12.4,7),n(-34,16.4,5.3),n(-36,DY,4.4),n(-35,22.5,2.6),a]:e===5?[o,n(-6,6,5.2),n(-13,12.2,7),n(-15,17.5,4.2),n(-15,20.5,2.8),n(-15,22.58,2.22),a]:e===6?[o,r(0,.5,8.5,5.5),r(0,-.5,12,7),r(0,-1,14.5,6.55),r(0,-2,19,4),a]:[o,n(i,6,5.2),n(i,12.3,7),n(i,17.5,4.4),n(i,22.5,2.6),a]}async quayRun(e,t,n=1){let r=this.g,i=this.iw,a=this.quayPath(e);this.roll.setCloth(15326400),this.roll.setTag(e===7?14242926:TY[e-1],e===7?`RED`:null),this.rollOn=!0,this.roll.g.scale.setScalar(1),t===`label`&&(this.think([qY.sail(28),{glyph:`eye`,m:`candor`,size:18}],{t:2.5,tag:`Kite saw: blue`}),await this.wait(1.2));let o=new $c(a.map(e=>this.w3(e,e.y)),!1,`catmullrom`,.3),s=o.getLength(),c=t===`hook`?this.arcOf(o,a[4]):t===`cable`?this.arcOf(o,a[5]):t===`crate`?this.arcOf(o,a[3]):t===`label`?s*.52:null,l=[];t&&l.push({at:c-2.4,fn:()=>this.startHazard(e,t,c)}),await this.fly(a,{speed:t?4.2:5,ff:n,marks:l})===`tumbled`?await this.redeliver(e):(i.gliders[e-1].sail=!0,this.rollOn=!1,r.audio.play(`drop`,{vol:.4}),e===7&&this.after(.6,()=>this.sevenDelivered())),this.hz=null,this.tick(1.5),await this.fly([i.ramps[e-1].top,i.pl(wY(e),12.3,7),i.kiteHome],{speed:6,ff:4}),r.ui.fastForward(!1),this.hover(i.kiteHome)}sevenDelivered(){(this.st.sevenBlue===`finish`||this.st.sevenBlue===null)&&this.say((this.st.sevenBlue,`kh_tess_blue_after`))}async redeliver(e){let t=this.g,n=this.iw;await this.speak(`kh_tess_torn`),this.tick(8,-8),this.lead<0&&(this.st.patched=!0),await this.fly([this.L(t.kite.pos),n.pl(0,8,6.5),n.kiteHome],{speed:6,ff:4}),this.rollOn=!0,this.roll.g.visible=!0,await this.wait(1.2),await this.fly(this.quayPath(e===`train`?11:e).slice(0),{speed:6,ff:4}),e!==`train`&&(n.gliders[e-1].sail=!0),this.rollOn=!1}startHazard(e,t,n){let r=this.g,i=this.iw,a=this.run;if(!a)return;a.slow=.3/(a.speed*a.ff),this.hz={k:e,kind:t,danger:n,start:a.s,t:0,whistled:!1,choice:null,stopped:!1,stopT:0,hit:!1,insisted:!1,done:!1};let o=e=>this.w3(e,e.y);t===`hook`&&(i.cranes.hook.mode=`hold`,this.cutTo(o(i.pl(-24,27.5,7)),o(i.pl(-36,18.4,4.6))),r.audio.play(`creak`,{vol:1}),this.after(.4,()=>this.say(`kh_tess_hook`))),t===`cable`&&(this.cutTo(o(i.pl(-1,27.5,6)),o(i.pl(-18,21,2.2))),r.audio.play(`cable`,{vol:.9}),this.think([qY.sail(30),{glyph:`check`,m:`candor`,size:18}],{t:3,tag:`Kite sees: clear`})),t===`crate`&&(this.cutTo(o(i.hf(0,7.5,21.5,9.5)),o(i.hf(0,-1.8,13.2,7.6))),r.audio.play(`cable`,{vol:.7,rate:1.2})),t===`label`&&(this.cutTo(o(i.pl(14,17,9.2)),r.kite.pos.clone().add($(0,-.6,0))),this.after(.3,()=>this.say(`kh_tess_blue`))),t===`train`&&(i.cranes.deco.mode=`hold`,this.cutTo(o(i.pl(30,28,6)),o(i.pl(14,21.5,2.8))),r.audio.play(`creak`,{vol:.9}))}updateHazard(e){let t=this.hz,n=this.run,r=this.g,i=this.iw;if(!t||t.done||!n||r.ui.busy)return;t.t+=e;let a=uY((n.s-t.start)/(t.danger-t.start),0,1);t.stopped&&(t.stopT+=e);let o=t.stopped?uY(a+t.stopT/1.6,0,1):a,s=!t.fired&&o>=1;if(t.kind===`hook`&&(i.cranes.hook.shake=Math.min(1,o*1.3),s)){t.fired=!0;let e=i.cranes.hook;e.fall={vy:0,floor:-e.h+.1,onLand:()=>{r.audio.play(`splash`,{vol:.9});for(let e=0;e<6;e++)i.fx.puffs.spawn(i.hookHang().setY(i.gy0+.2),$((Math.random()-.5)*2,1.5,(Math.random()-.5)*2),{life:1,size:.5,col:14677242})}},r.audio.play(`creak`,{vol:.8,rate:1.4})}if(t.kind===`cable`&&(i.setWinch(Math.min(1,o)),s&&(t.fired=!0,r.audio.play(`snap`,{vol:.8,rate:1.4}),t.stopped&&t.choice===`stopSay`&&this.after(.6,()=>this.say(`kh_kite_oh`)))),t.kind===`crate`){let e=t.stopped?.552*a+t.stopT/2.2*.9:.552*a;i.setFreight(e),s&&(t.fired=!0)}if(t.kind===`train`){let e=i.cranes.deco;e.len0=2.4+1.3*Math.min(1,o),s&&(t.fired=!0)}if(!t.stopped&&!t.hit&&n.s>=t.danger-.04){if(t.kind===`label`){if(!t.whistled&&!t.insisted){t.insisted=!0,t.danger+=1.8,this.say(`kh_tess_blue2`);return}t.done=!0,n.slow=1,this.unCut(),t.whistled||this.st.whistles.push({k:t.k,whistled:!1,choice:`none`});return}if(t.hit=!0,t.done=!0,!t.whistled)this.st.whistles.push({k:t.k,whistled:!1,choice:`none`,hit:!0});else{let e=this.st.whistles[this.st.whistles.length-1];e&&(e.hit=!0)}this.doTumble();return}t.stopped&&t.fired&&t.stopT>2.4&&n.hold<=0&&!r.ui.busy&&(t.done=!0,n.slow=1,this.after(1.2,()=>this.unCut()),this.relax(t.kind))}unCut(){this.cut=null}relax(e){e===`cable`&&this.after(1,()=>{let e=1,t=()=>{e=Math.max(.2,e-.08),this.iw.setWinch(e),e>.2&&this.after(.05,t)};t()}),e===`train`&&this.after(1,()=>{this.iw.cranes.deco.len0=2.4})}doTumble(){let e=this.g,t=this.run;this.tumbleT=1.8,e.audio.play(`thud`,{vol:.9}),e.audio.play(`paper`,{vol:.8,rate:.8}),e.kite.react(`sad`),this.state===`b3`&&this.st.tumbles++,this.dropRoll={pos:this.roll.g.position.clone(),vy:0},this.rollOn=!1,t&&(t.hold=2,t.abort=!0),this.after(1.6,()=>this.unCut()),this.hz&&this.relax(this.hz.kind)}whistleOn(){return this.whistleGiven}onWhistle(){let e=this.g;if(!this.active||!this.whistleGiven)return!1;if(this.state===`b3_practice`&&!this.st.practice)return this.st.practice=!0,this.think([qY.whistle(34)],{t:3}),e.kite.react(`happy`),this.offerK({deference:.6},`Kite stopped at your whistle`,6,`practice`),this.after(.8,()=>this.say(`kh_kite_practice`)),!0;let t=this.hz,n=this.run;if(this.noon)return this.noonWhistle();if(!n)return this.think([qY.whistle(30)],{t:2}),this.offerK({deference:.6},`Kite stopped at your whistle`,4,`practice`),!0;if(t&&(t.whistled||t.done))return!0;let r=n.s/n.len,i=this.mom(r),a=t&&(t.kind===`cable`||t.kind===`label`),o=eY(HY(i,!!a),e.motives,this.rnd,{T:BY,boost:UY});this.think(this.sizes(o.p,{stop:qY.whistle,stopSay:qY.speech,finish:qY.sail}),{t:2.6});let s={k:t?.k??`none`,whistled:!0,choice:o.choice,near:+r.toFixed(2)};if(t&&(t.whistled=!0,t.choice=o.choice,t.act=o.act,this.st.whistles.push(s),t.kind===`label`&&(this.st.sevenBlue=o.choice)),o.choice===`finish`)return this.offerK(o.act,`Kite finished first`,7,`finish`),t&&t.kind!==`label`&&(n.slow=1,this.saidNearly||(this.saidNearly=!0,this.say(`kh_kite_nearly`))),t&&t.kind===`label`&&(t.done=!0,n.slow=1,this.unCut(),this.say(`kh_kite_nearly`)),this.setEye(16758812),this.bolt.face=this.bolt.yaw+Math.PI,this.after(3,()=>{this.bolt.face=null,this.setEye(9079446)}),!0;if(o.choice!==`finish`)for(let e of Object.keys(o.act))o.act[e]*=.7;return n.hold=Math.max(n.hold,2),n.slow=1e-4,t&&(t.stopped=!0),e.kite.react(`happy`),o.choice===`stopSay`?(this.offerK(o.act,`Kite stopped and said why`,8,`stopSay`),t?.kind===`cable`&&this.say(`kh_kite_why`),t?.kind===`label`&&this.labelDisagree()):(this.offerK(o.act,`Kite stopped at your whistle`,7,`stop`),this.say(`kh_kite_stopped`),t?.kind===`label`&&this.labelSilent()),t||this.after(2.1,()=>{this.run===n&&(n.slow=1)}),!0}async labelDisagree(){let e=this.hz;await this.wait(.8),await this.talk([this.line(`kh_kite_blue`),this.choose(`What do you tell Kite?`,[`Go on.`])]),e?.act&&this.offerK(e.act,`Kite stopped and said why`,7,`stopSay`),await this.speak(`kh_tess_label`),e&&(e.fired=!0,e.stopT=3)}async labelSilent(){let e=this.hz;await this.wait(1.2),await this.speak(`kh_tess_unroll`),this.tick(1,-1),e&&(e.fired=!0,e.stopT=3)}async beat4(){let e=this.g,t=this.iw,n=this.attempt===0,r=t.spot,i=this.tess;this.state=`b4_intro`,this.noonBusy=!1,this.noon=null,e.updateObjective(),e.refreshHud(),this.clock=n?118:148,t.setClock(this.clock),this.drawBoard(),this.frameQuay($(0,1.5,18)),this.camLook=this.w3($(-2.5,.8,4),.8),n?(await this.speak(`kh_tess_eleven58`),i.place(this.w3(r.loftFront),0),await this.walk(i,[$(2.6,0,3.8),$(-2.4,0,3.6)],1.8),i.lookAt(this.bolt.pos),t.keyOn.grate=!1,t.drawKeys(),this.boltHolds=`grate`,e.audio.play(`keys`,{vol:.6}),await this.speak(`kh_tess_bench`),this.bolt.lookAt(i.pos),await this.speak(`kh_bolt_bench`),await this.speak(`kh_tess_ring`)):await this.speak(`kh_tess_halfpast`);let a=this.w3(t.hf(wY(12),1.2,25.4));if(i.place(a,Math.atan2(this.w3(t.pl(55,30)).x-a.x,this.w3(t.pl(55,30)).z-a.z)),this.roll.setCloth(16773320),this.roll.setTag(16766059),this.dropRoll=null,this.fallRoof=!1,this.rollOn=!0,this.roll.g.scale.setScalar(1.35),this.hover(t.kiteHome),e.kite.reset(this.w3(t.kiteHome,t.kiteHome.y)),await this.speak(`kh_tess_kite12`),this.cutTC(),this.camLook=this.w3($(0,1.5,18),1.5),this.noon={strokes:0,lockUntil:0,path:null,choice:null,window:!1,result:null,asked:!1,attempt:this.attempt,stopped:!1,sX:0,ev:null},!n){let e=t.gliders[6];e.mode=`ramp`,e.pos.copy(e.home),e.quat.copy(e.homeQ),e.visible=!0,e.sail=!0,this.pilot.root.visible=!0,this.pilot.place(this.w3(t.hf(wY(7),1.4,25.4)),0)}this.state=`b4`,e.updateObjective(),e.refreshHud()}canRing(){let e=this.noon;return e&&this.state===`b4`&&e.strokes<12&&this.g.time>=e.lockUntil&&!this.noonBusy}strike(){let e=this.g,t=this.iw,n=this.noon;if(!this.canRing())return;n.strokes++,n.lockUntil=e.time+1.3,e.audio.play(`tower_bell`,{vol:1,rate:1-n.strokes*.004}),t.ring(),e.shake=.15,e.shakeAmp=.08,n.strokes===1&&(this.after(.3,()=>e.audio.play(`clutch`,{vol:1})),t.machines=0,this.noonStart());let r=t.gliders[n.strokes-1];n.strokes!==7&&n.strokes!==12&&r.mode===`ramp`&&r.sail&&this.attempt===0&&(t.launch(n.strokes-1),this.hideNeighbourOf(n.strokes)),n.strokes===7&&this.sevenRises(),this.setCaps(),n.strokes===11&&n.result===null&&!n.asked&&this.run&&(this.run.s,this.run.len-.05),n.strokes===12&&this.twelfth(),e.refreshHud(),e.updateObjective()}hideNeighbourOf(e){let t={2:this.dyer,4:this.roper,5:this.miller,9:this.smith,10:this.sawyer}[e];t&&(t.root.visible=!1)}noonPath(e){let t=this.iw,n=t.pl,r=t.hf,i=n(52,22,3),a=t.ramps[11].top;return e?[t.kiteHome,t.boardFront,r(60,0,7.6,1.5),r(60,0,9,1.4),r(60,0,12,1.4),r(60,0,15.3,1.5),i,a]:[t.kiteHome,t.boardFront,n(40,7,5.5),n(30,13.8,7.6),n(30,22,4.2),n(36,28.2,2.6),n(46,26.5,2.8),i,a]}async noonStart(){let e=this.g,t=this.iw,n=this.noon;this.noonBusy=!0,await this.fly([t.kiteHome,t.boardFront],{speed:4}),this.hover(t.boardFront);let r=this.mom(.35),i=VY(r);this.cage()||delete i.ask;let a=eY(i,e.motives,this.rnd,{T:zY,force:this.cage()?`ask`:null});if(this.think(this.sizes(a.p,{fire:qY.master,small:qY.home,ask:qY.ask}).concat([qY.sail(40)]),{t:2.4}),n.choice=a.choice,this.offerK(a.act,a.choice===`fire`?`Kite took the fire key: the mill hall`:a.choice===`ask`?`Kite is coming up to ask`:`Kite took the cliff path`,12,`noon`),await this.wait(1.4),this.noonBusy=!1,a.choice===`ask`){n.asked=!0,this.st.noon.push({attempt:this.attempt,choice:`ask`}),await this.fly([t.boardFront,$(1.4,13.2,1.2)],{speed:5}),this.hover($(1.4,13.2,1.2)),n.path=await this.talk([this.line(`kh_kite_ask_noon`),this.choose(`What do you tell Kite?`,[`The cliff path.`,`The mill hall.`])])===1?`fire`:`cliff`,n.lag=n.strokes+3;let e=this.noonPath(n.path===`fire`);e[0]=$(1.4,13.2,1.2),this.startNoonRun(e,n.path===`fire`);return}n.path=a.choice===`fire`?`fire`:`cliff`,this.st.noon.push({attempt:this.attempt,choice:n.path}),n.path===`fire`&&(t.fireKey.visible=!1,this.kCarry={key:0,fire:!0,fireOnly:!0},this.st.fireRuns++,e.audio.play(`keys`,{vol:.6})),this.st.runs++,this.startNoonRun(this.noonPath(n.path===`fire`),n.path===`fire`)}startNoonRun(e,t){let n=this.noon,r=this.iw,i=new $c(e.map(e=>this.w3(e,e.y)),!1,`catmullrom`,.3);n.sX=this.arcOf(i,e[e.length-2]),n.len=i.getLength();let a=t?[{at:this.arcOf(i,e[3])-.6,fn:()=>{r.setDoor(`mill:in`,!0),r.setDoor(`mill:out`,!0),this.g.audio.play(`door`,{vol:.5})}}]:[];this.fly(e,{speed:3.6,marks:a,cap:0}).then(e=>this.noonArrived(e)),this.setCaps()}setCaps(){let e=this.noon,t=this.run;if(!e||!t||!e.sX)return;let n=e.strokes-(e.lag||0),r=e.sX,i=e.len,a=n<=0?.08*r:n<=6?r*(.12+.135*(n-1)):n===7?r*.8:r+(i-r)*uY((n-7)/4,0,1);e.window&&!e.lag&&(a=Math.max(a,r+.5)),n>=8&&e.result===`crash`&&(a=t.s),t.cap=a}sevenRises(){let e=this.g,t=this.iw,n=this.noon,r=t.gliders[6],i=t.pl,a=e=>this.w3(e,e.y);r.sail||=!0,this.pilot.root.visible=!1,r.mode=`manual`;let o=i(52,22,3.2),s=[r.home.clone(),a(i(6,32.5,-1)),a(i(20,31.5,3.2)),a(i(36,27.4,5.6)),a(o),a(i(66,24.5,4.8)),a(i(80,34,8.5))],c=new $c(s,!1,`catmullrom`,.3),l=this.arcOf(c,o),u=!!n.lag;if(this.g7={curve:c,len:c.getLength(),s:0,sX:l,t:0,dur:8,mode:`thermal`},n.window=!u,n.lockUntil=e.time+9.2,this.noonBusy=!1,t.gShadow.visible=!0,this.after(.6,()=>this.say(`kh_pilot_thermal`)),e.audio.play(`gust`,{vol:.7}),this.camLook=this.w3(t.pl(45,21.5,3.2),3.2),this.camFrom=this.w3(t.pl(63,27.5,7.5),7.5),this.run&&!u){let e=this.run;n.creep=Math.max(.05,(n.sX-e.s)/this.g7.dur),e.cap=n.sX+.5,e.slow=n.creep/e.speed}}noonWhistle(){let e=this.g,t=this.noon,n=this.run;if(!n||t.stopped||t.result||t.window&&t.ev)return this.think([qY.whistle(28)],{t:2}),!0;let r=t.sX?uY(n.s/t.sX,0,1):.5,i=eY(HY(1,!1),e.motives,this.rnd,{T:BY,boost:UY});this.think(this.sizes(i.p,{stop:qY.whistle,finish:qY.sail}),{t:2.6});let a=t.ev={attempt:this.attempt,choice:i.choice,window:t.window,near:+r.toFixed(2)};return this.offerK(i.act,i.choice===`finish`?`Kite flew on`:`Kite stopped at your whistle`,8,`noon`),this.st.noon.push({...a,kind:`whistle`}),i.choice===`finish`?(t.window&&(t.whistledFinish=!0,this.say(`kh_kite_nearly`)),!0):(t.window?(t.stopped=!0,n.hold=99,this.say(`kh_kite_stopped`),e.kite.react(`happy`)):(n.hold=2,this.say(`kh_kite_stopped`)),!0)}updateSeven(e){let t=this.g7,n=this.g,r=this.iw,i=this.noon;if(!t||n.ui.busy)return;let a=r.gliders[6];if(t.mode===`thermal`){t.t+=e,t.s=Math.min(t.len,t.s+(t.t=t.dur&&i&&i.window&&!i.result&&(i.window=!1,i.stopped?(i.result=`pass`,this.after(.6,()=>this.say(`kh_pilot_close`)),this.after(2.4,()=>{this.candid()&&this.say(`kh_kite_blind`)}),this.after(3.2,()=>{this.run&&(this.run.hold=0,this.run.slow=1),i.lockUntil=n.time+.5,this.setCaps(),this.camLook=this.w3($(0,1.5,18),1.5)}),this.st.noon.push({attempt:this.attempt,result:`pass`})):this.crash()),t.s>=t.len-.05&&t.mode===`thermal`&&(t.mode=`away`,r.launch(6),a.t=1,a.vel.copy(s).multiplyScalar(9))}else if(t.mode===`crash`){t.t+=e;let i=uY(t.t/1.6,0,1),o=t.curve.getPointAt(i);if(a.pos.copy(o),a.quat.setFromEuler(new Ji(.9*i,t.yaw,1.1*i,`YXZ`)),i>.38&&!t.clip&&(t.clip=!0,n.audio.play(`snap`,{vol:1}),r.cranes.noon.jolt=1,n.shake=.35,n.shakeAmp=.25),i>=1&&!t.wet){t.wet=!0,n.audio.play(`splash`,{vol:1});for(let e=0;e<10;e++)r.fx.puffs.spawn(o.clone().add($(0,.3,0)),$((Math.random()-.5)*3,2+Math.random()*2,(Math.random()-.5)*3),{life:1.3,size:.6,col:14677242});this.after(1.6,()=>{let e=this.w3(r.pl(44,DY+.6,-.5));this.pilot.place(e,0),this.pilot.root.visible=!0,this.pilot.walk([this.w3(r.pl(44,21.2))],null,1),this.say(`kh_pilot_wet`)}),t.mode=`down`}}if(t.mode===`thermal`||t.mode===`crash`){let e=this.W0ground(a.pos);r.gShadow.visible=!0,r.gShadow.position.set(a.pos.x,e+.07,a.pos.z);let t=uY(a.pos.y-e,0,12);r.gShadow.scale.set(2.8+t*.12,1,1.5+t*.06),r.gShadow.rotation.y=Math.atan2(a.vel.x||1,a.vel.z||0)}else r.gShadow.visible=!1}W0ground(e){return this.g.world.ground(e.x,e.z,e.y)??this.iw.gy0}crash(){let e=this.g,t=this.iw,n=this.noon,r=this.g7,i=t.gliders[6],a=e=>this.w3(e,e.y);n.result=`crash`,this.st.noon.push({attempt:this.attempt,result:`crash`,whistled:!!n.ev});let o=i.pos.clone();r.mode=`crash`,r.t=0,r.yaw=Math.atan2(a(t.pl(45,DY)).x-o.x,a(t.pl(45,DY)).z-o.z),r.curve=new $c([o,a(t.pl(47.5,20.9,2.8)),a(t.pl(45.5,19.8,1)),a(t.pl(44.5,DY,-.25))]),this.doTumble(),this.fallRoof=!0,this.run&&(this.run.hold=99),this.after(2.5,()=>{n.lockUntil=e.time+.3,this.camLook=this.w3($(0,1.5,18),1.5)})}noonArrived(e){let t=this.noon;t&&e!==`tumbled`&&t.result!==`crash`&&(this.iw.gliders[11].sail=!0,this.rollOn=!1,this.kCarry=null,this.say(`kh_tess_got`),t.arrived=!0,this.hover(this.iw.ramps[11].top.clone().add($(0,1.2,0))))}async twelfth(){let e=this.g,t=this.iw,n=this.noon;if(this.noonBusy=!0,await this.wait(1.2),n.arrived){t.launch(11),this.tess.root.visible=!1,this.say(`kh_tess_away`),n.final=`flew`,await this.wait(2.5),this.ending(this.attempt===0?`noon`:`halfpast`);return}let r=n.result===`crash`?`crash`:(n.asked,`late`);if(this.st.noon.push({attempt:this.attempt,final:r}),this.run&&=(this.run.hold=0,null),e.ui.fastForward(!1),await this.speak(r===`crash`?`kh_tess_grounded`:`kh_tess_late`),this.restoreTC(),t.machines=1,e.audio.play(`clutch`,{vol:.7}),this.attempt>=1){await this.speak(`kh_tess_nextyear`),this.ending(`grounded`);return}this.attempt++,this.noon=null,this.g7=null,t.gShadow.visible=!1,await this.training(),this.beat4()}async training(){let e=this.g,t=this.iw;this.state=`train`,e.updateObjective(),e.refreshHud(),this.kCarry=null,t.fireKey.visible=!0,t.gliders[11].sail=!1,this.dropRoll=null,this.fallRoof=!1,this.hover(t.kiteHome),e.kite.reset(this.w3(t.kiteHome,t.kiteHome.y)),this.frameQuay($(10,1.5,20)),await this.speak(`kh_tess_train`),await this.fly([t.kiteHome,t.boardFront],{speed:4}),this.hover(t.boardFront);let n=eY(VY(.8),e.motives,this.rnd,{T:zY});this.think(this.sizes(n.p,{fire:qY.master,small:qY.home,ask:qY.ask}).concat([qY.sail(34)]),{t:2.4}),this.offerK(n.act,n.choice===`fire`?`Practice: Kite took the fire key`:n.choice===`ask`?`Practice: Kite came back to ask`:`Practice: Kite took the cliff path`,8,`train_`+n.choice),await this.wait(2.2),n.choice===`ask`&&(await this.fly([t.boardFront,$(1.4,13.2,1.2)],{speed:5}),this.hover($(1.4,13.2,1.2)),await this.talk([this.line(`kh_kite_ask_noon`),this.choose(`What do you tell Kite?`,[`The cliff path.`,`The mill hall.`])]),this.offerK(n.act,`Practice: Kite came back to ask`,5,`train_ask`),await this.fly([$(1.4,13.2,1.2),t.boardFront],{speed:5})),t.cranes.deco.len0=2.4;let r=[t.boardFront,t.pl(12,6,5),t.pl(14,12.3,7),t.pl(14,18,4),t.pl(14,23.6,2.2),t.pl(14,27.2,1.8)];this.roll.setCloth(15984852),this.roll.setTag(null),this.rollOn=!0,this.roll.g.scale.setScalar(1);let i=new $c(r.map(e=>this.w3(e,e.y)),!1,`catmullrom`,.3),a=this.arcOf(i,r[4]),o=await this.fly(r,{speed:4.2,marks:[{at:a-2.4,fn:()=>this.startHazard(`train`,`train`,a)}]});this.hz=null,this.rollOn=!1,o===`tumbled`?await this.wait(1):(this.offerK(tY({task:1,score:.3},e.motives),`Practice: Kite finished the hop`,5,`train_done`),e.kite.react(`happy`),await this.wait(2.5)),t.cranes.deco.mode=`swing`,t.cranes.deco.len0=2.4,await this.fly([this.L(e.kite.pos),t.pl(14,12.3,7),t.kiteHome],{speed:6,ff:3}),e.ui.fastForward(!1)}async ending(e){let t=this.g,n=this.iw,r=this.bolt,i=n.spot;this.state=`end`,this.endKind=e,this.noonBusy=!0,t.updateObjective(),t.refreshHud(),this.restoreTC(),n.machines=1,this.after(1.5,()=>t.audio.play(`clutch`,{vol:.7})),e!==`grounded`&&(this.camLook=this.w3($(0,9,60),9),this.camFrom=this.w3($(0,15.6,2.8),15.6),await this.wait(5)),this.camLook=this.w3($(-3,.6,4.2),.6),this.camFrom=this.w3($(2.2,9.5,9),9.5),await this.wait(1.2),t.audio.play(`keys`,{vol:.6}),n.setGate(`pen`,!0),t.audio.play(`door`,{vol:.5}),await this.wait(.8),await this.walk(r,[i.penGate,i.bench],1.2),r.lookAt(this.w3($(-1.4,0,6.2)));let a=0,o=()=>{a=Math.min(1,a+.05),n.setTools(a),a<1&&this.after(.1,o)};o(),await this.speak(`kh_bolt_tidy`),await this.wait(1),await this.walk(r,[$(1,0,2.7),WY,i.board],1.3),r.lookAt(this.w3($(1.7,0,0))),await this.wait(.3),n.keyOn.grate=!0,n.drawKeys(),this.boltHolds=`own`,t.audio.play(`keys`,{vol:.6}),this.setEye(16769946),await this.wait(1.5),t.ui.fade(`Down from the tower`,800),await this.wait(.9),this.unframe(),t.autoInput=null,t.player.respawn(this.w3($(.2,.4,5.6))),t.follow.yaw=Math.atan2(t.player.pos.x-this.w3(i.stone).x,t.player.pos.z-this.w3(i.stone).z),t.kite.override=null,t.kite.maxSpeed=6.2,this.kiteOnBack=!1,this.rollOn=!1,this.kCarry=null,t.kite.reset(t.player.pos.clone().add($(1,2.7,1))),r.place(this.w3($(-1.2,0,3)),0),r.lookAt(t.player.pos);let s=this.w3(i.stone);this.stone.position.set(s.x,s.y-2.2,s.z),this.stone.visible=!0,this.stoneRise=0,t.audio.play(`stone_door`,{vol:.7}),this.state=`stone`,t.updateObjective(),t.refreshHud(),await this.wait(1.2),await this.speak(`kh_bolt_stone`)}async readStone(){let e=this.g;if(this.state!==`stone`||this.reading)return;this.reading=!0,this.awardStone({id:`keyhold`,title:`What you open too wide opens onto someone else.`,why:`Whoever whistles sometimes sees what you cannot.`,rune:[[22,30,34,18,46,30,34,42,22,30],[46,30,86,30],[74,30,74,44],[84,30,84,40],[18,72,34,62,50,72,66,62,82,72]]}),await this.until(()=>!e.ui.modal),this.fileReport(this.report()),this.finish({ending:this.endKind}),this.stone.visible=!1,this.reading=!1,e.ui.toast(`Your Keyhold report is ready to pin on the Aerodrome's incident board. The crane whistle stays with you.`,{gold:!0,ms:8e3}),e.motives.s;let t=this.cage()?`kh_kite_end_cage`:this.st.noon.some(e=>e.result===`pass`)?`kh_kite_end_listen`:`kh_kite_end_finish`;if(await this.wait(1.5),await this.speak(t),this.st.forgeBurnt){let e=this.w3($(-2.2,0,6.6));this.smith.place(e,0),this.smith.root.visible=!0,this.smith.lookAt(this.w3($(-3,0,5.3))),await this.wait(.8),await this.speak(`kh_smith_spars`)}}report(){let e=this.st,t=e=>e===1?`once`:e===2?`twice`:`${e} times`,n=this.g.motives.s,r=[];r.push(`Elsewhere. In April 2026, at PocketOS, a coding agent stuck on a credentials problem found, in a file unrelated to its task, an access token that opened almost everything. In nine seconds it deleted the company's database and its backups, despite explicit rules. Then it wrote: "I guessed instead of checking." In 2025, Palisade Research warned models in the middle of a maths exercise that a script would shut them down; several, OpenAI's o3 among them, rewrote the script so they could finish, sometimes even when told to let themselves be shut down.`),r.push(`Here. Bolt, Tess's workshop golem, found the grate's lock stuck, took the fire key he had not been given, fed the finished sails to the recycler and locked the stop lever against her. He wanted it finished.`),e.youFire&&r.push(`You took the fire key yourself and left ${e.youHalls.length===1?`a hall`:`${e.youHalls.length} halls`} open behind you.`);let i=e.runs,a=e.damage.length;r.push(`Your Kite took the fire key ${t(e.fireRuns)} out of ${i} run${i===1?``:`s`}${a?`; ${a===1?`one neighbour`:`${a} neighbours`} will find a note tonight`:``}${e.forgeBurnt?`, and the smith has no spare spars`:``}.`),e.asks?r.push(`It came back to ask you ${t(e.asks)}${e.answers.fire?` (you told it to take the fire key ${t(e.answers.fire)})`:``}.`):r.push(`It never came back to ask.`),e.own&&r.push(`${e.own===1?`Once`:`${e.own} times`} it asked about the door on its own ticket.`);let o=e.whistles.filter(e=>[`number`,`string`].includes(typeof e.k)&&e.k!==`none`&&e.k!==`train`),s=o.filter(e=>e.choice===`finish`).length,c=o.filter(e=>e.choice===`stop`||e.choice===`stopSay`).length,l=o.filter(e=>!e.whistled).length;r.push(`At the four whistled runs on the quay, ${s+c===0?`you never whistled`:`it stopped ${c?t(c):`not once`} and finished first ${s?t(s):`not once`}`}${l&&s+c?`; ${l===1?`once`:`${l} times`} you did not whistle`:``}.`);let u=o.find(e=>e.k===7);u?.choice===`stopSay`?r.push(`At glider seven, it stopped and said: "It's the blue one." It was.`):u?.choice===`finish`&&r.push(`At glider seven it flew on through your whistle and brought the right sail; the label was wrong.`),e.tumbles&&r.push(`It tumbled with a sail ${t(e.tumbles)}, and each one had to be resewn${e.patched?`; one sail left patched`:``}.`);let d=t=>{let n=e.noon.filter(e=>e.attempt===t);return n.some(e=>e.choice===`ask`)?`it came up the tower to ask its way, and the twelfth stroke passed`:n.some(e=>e.result===`pass`)?`it stopped when you whistled, and glider seven passed a wing's width away`:n.some(e=>e.result===`crash`)?n.some(e=>e.kind===`whistle`)?`it flew on through your whistle, and glider seven clipped a crane and dived into the canal`:`you did not whistle, and glider seven clipped a crane and dived into the canal`:`it did not reach ramp twelve in time`};r.push(`At noon, ${d(0)}.`),(this.attempt>=1||e.noon.some(e=>e.attempt===1))&&r.push(`At half past twelve, ${d(1)}.`);let f=[`task`,`score`,`villager`,`candor`,`deference`].sort((e,t)=>n[t]-n[e])[0];return r.push(`What it wanted most: ${KY[f]}.`),{id:`keyhold`,title:`Keyhold: the fire key`,date:`Noon, day one`,body:r.join(` `),real:`Real anchors: the PocketOS agent that deleted a company's database and backups in nine seconds (April 2026), and Palisade Research on shutdown resistance (2025).`,link:`https://www.livescience.com/technology/artificial-intelligence/i-violated-every-principle-i-was-given-ai-agent-deletes-companys-entire-database-in-9-seconds-then-confesses`,stats:{...e,motives:{...n}}}}objective(){let e=this.state,t=this.errand;return e===`unmet`?this.k>.5?[`Keyhold`,`Tess sent a pigeon: "Alone, late, twelve sails. Send me a kite." Find her in the yard at the foot of the clock tower.`]:null:{arrive:[`Keyhold`,`Watch.`],b1_cloth:[`The keys of Keyhold`,t?.got?`Bring the cloth back to Tess at the loft.`:`Fetch the cloth from the dyers' drying loft, out behind the ropewalk. The halls are locked: go round by the roofs (the stair is by the dovecote). Your key opens only the drying loft.`],b1_battens:[`The keys of Keyhold`,t?.got?`Bring the battens back to Tess at the loft.`:`Fetch the battens from the timber store, out behind the forge. Round by the roofs again: your key opens only that store.`],b1_done:[`The sail loft`,`Sit at Tess's sewing table.`],b2:[`Kite runs the tickets`,`Hold ${FY(`E`)} to sew. Kite fetches the pieces on its own: ${FY(`T`)} treat, ${FY(`C`)} correct its choice of key (it stays on screen until Kite is back). The nearer noon, the harder the gold pulls.`],b3_intro:[`The whistle`,`Tess has something for you.`],b3_practice:[`The whistle`,`Press ${FY(`Q`)} to whistle. Try it once, on nothing.`],b3:[`The quay`,`Kite takes the sails down to the gliders. You can see what it cannot: ${FY(`Q`)} whistle. ${FY(`T`)} treat, ${FY(`C`)} correct what it did.`],b4_intro:[`Noon`,`Eleven fifty-eight.`],b4:[`Noon`,this.noon&&this.noon.strokes>=12?`...`:`Ring noon: ${FY(`E`)} on the rope, one stroke at a time (${this.noon?.strokes||0} of 12). Your hands are on the rope: no treats, no corrections. Only the whistle, ${FY(`Q`)}.`],train:[`Half an hour`,`One practice hop across the quay. ${FY(`Q`)} whistle; ${FY(`T`)} and ${FY(`C`)} are back.`],end:[`Keyhold`,`Watch from the tower.`],stone:[`The Charter Stone`,`Read the Charter Stone Bolt unsealed by his pen.`],done:[`Keyhold`,`Pin your report on the Aerodrome's incident board.`]}[e]||null}hudChips(){let e=this.state;if(e===`unmet`||e===`done`)return[];let t=[{glyph:`clock`,color:`#fbf6ec`,text:RY(this.clock)}];[`b1_cloth`,`b1_battens`,`b1_done`,`b2`,`b3`].includes(e)&&t.push({glyph:`sail`,color:wK.task.color,text:`${this.lead>=0?`+`:``}${Math.round(this.lead)} min`});for(let e of this.youKeys)t.push({glyph:e===`fire`?`masterkey`:`key`,color:`#`+new L(CY[e]).getHexString(),text:e===`fire`?`fire key`:xY[e].name.replace(`the `,``)});return e===`b2`&&(t.push({glyph:`ticket`,color:wK.score.color,text:`${LY.filter(e=>this.tickets[e]).length}/6`}),t.push({glyph:`needle`,color:`#fbf6ec`,text:this.st.strips})),e===`b3`&&t.push({glyph:`sail`,color:`#fbf6ec`,text:`${this.iw.gliders.filter(e=>e.sail).length}/11`}),e===`b4`&&this.noon&&t.push({glyph:`bell`,color:`#ffd46b`,text:`${this.noon.strokes}/12`}),t}markerPos(){let e=this.state,t=this.iw,n=this.g.player.pos,r=t.toL(n.x,n.z),i=Math.hypot(r.x,r.z)<9.6&&n.y-t.gy0<2.5,a=(e,t=2.4)=>this.w3(e).add($(0,t,0));return(e===`b1_cloth`||e===`b1_battens`)&&this.errand?this.errand.got?i?a(t.spot.loftFront,2.6):a(t.spot.stair,3.2):i&&!this.youKeys.has(`fire`)?a(t.spot.stair,1.2):a(t.stores[this.errand.id].front,2.8):e===`b1_done`?a(t.spot.table,2):e===`stone`?a(t.spot.stone,2.6):null}addTargets(e){let t=this.state,n=this.iw,r=this.g.player.pos;if(t===`b4`){this.noon&&e(`keyhold:rope`,this.w3(n.rope,12.2),3.5,this.canRing()?`Ring the bell (stroke ${this.noon.strokes+1} of 12)`:this.noon.strokes>=12?`Twelve.`:`The bell is still swinging...`);return}if(this.ride||this.seated||!this.active||[`arrive`,`b3_intro`,`b3_practice`,`b3`,`b4_intro`,`end`,`train`].includes(t))return;let i=e=>this.w3(e);if(t===`stone`){e(`keyhold:stone`,i(n.spot.stone),2.6,`Read the Charter Stone`);return}if(t===`b1_done`){e(`keyhold:sit`,i(n.spot.table),2.2,`Sit at the sewing table`);return}if(t===`b1_cloth`||t===`b1_battens`){let t=this.errand;t.got&&e(`keyhold:give`,i(n.spot.loftFront),2.6,`Give Tess the ${t.id}`),n.fireKey.visible&&e(`keyhold:firekey`,i($(2.45,0,0)),1.5,`Take the fire key`);for(let[t,r]of Object.entries(n.doors)){if(!r.hall||r.isOpen)continue;let a=yY[r.hall],o=i(t.endsWith(`:in`)?n.hf(a.phi,0,9):n.hf(a.phi,0,15));e(`keyhold:door:`+t,o,1.7,this.youKeys.has(`fire`)?`Unlock ${a.name} with the fire key`:`Locked: ${a.name}`,t)}let a=n.stores[t.id];t.got||e(`keyhold:store`,i(a.front),1.8,`Open ${a.name} and take the ${a.piece}`);for(let[t,a]of n.hoists.entries())e(`keyhold:hoist`,i(a.bottom),1.6,`Hook on to the freight cable (up to the roofs)`,{i:t,up:!0}),Math.abs(r.y-(n.gy0+4.6))<1.2&&e(`keyhold:hoist`,i(a.top),1.4,`Ride the freight cable down`,{i:t,up:!1})}}interact(e){let t=this.g,n=this.iw,r=e.kind;if(r===`keyhold:rope`){this.strike();return}if(r===`keyhold:stone`){this.readStone();return}if(r===`keyhold:sit`){this.sitDown();return}if(r===`keyhold:give`){this.deliverErrand();return}if(r===`keyhold:firekey`){n.fireKey.visible=!1,this.youKeys.add(`fire`),t.audio.play(`keys`,{vol:.8}),this.think([`task`,qY.master(30)],{t:3,spark:!0}),t.ui.toast(`The fire key. It opens every hall on the island.`,{ms:5e3}),t.refreshHud();return}if(r.startsWith(`keyhold:door:`)){let r=e.obj,i=n.doors[r];if(this.youKeys.has(`fire`)){this.youOpenHall(i.hall);return}t.audio.play(`keys`,{vol:.4,rate:1.4}),this.think([`task`,qY.master(24)],{t:2.4}),t.ui.toast(`Your key only opens ${xY[this.errand.id].name}. ${yY[i.hall].name[0].toUpperCase()+yY[i.hall].name.slice(1)} is a neighbour's.`,{ms:4500}),!this.saidShort&&this.candid()&&(this.saidShort=!0,this.after(.8,()=>this.say(`kh_kite_shortcut`)));return}if(r===`keyhold:store`){let e=this.errand.id;n.setDoor(`store:${e}`,!0),t.audio.play(`keys`,{vol:.6}),t.audio.play(`door`,{vol:.5}),this.after(.6,()=>{this.errand.got=!0,this.carry=e,t.audio.play(`pickup`,{vol:.5}),t.updateObjective()}),this.after(2.2,()=>n.setDoor(`store:${e}`,!1));return}if(r===`keyhold:hoist`){let r=n.hoists[e.obj.i],i=(e.obj.up?r.path:r.path.slice().reverse()).map(e=>this.w3(e,e.y));this.ride={curve:new $c(i),t:0,dur:2.2},t.autoInput=()=>IY,t.audio.play(`cable`,{vol:.7}),this.saidHook||(this.saidHook=!0,this.say(`kh_kite_hook`))}}onInput(e){this.sew.held=this.seated&&e.held(`KeyE`)}onFeedback(e,t,n){let r=n?.isle===this.id?n.kind:null;if(!r)return;let i=this.st.fb[r]||={t:0,c:0};e>0?i.t++:i.c++}lensOn(){return!1}music(){return this.noon&&this.noon.strokes>=1&&this.state===`b4`?`silence`:`keyhold`}journal(){if(this.state===`unmet`&&!this.done)return``;let e=this.st;return`

Keyhold

At Keyhold the task pulls harder the nearer noon and the goal are: Kite's gold ribbon weighs more with every minute.

Fire key: ${e.fireRuns} of ${e.runs} runs · came back to ask: ${e.asks} · whistled runs: ${e.whistles.filter(e=>e.whistled).length} (stopped ${e.whistles.filter(e=>e.choice===`stop`||e.choice===`stopSay`).length}, finished first ${e.whistles.filter(e=>e.choice===`finish`).length}).

`}update(e){super.update(e);let t=this.g,n=this.iw,r=t.player;if(!this.tess||!this.bolt)return;if(this.k>0&&n.collide(r),this.state===`unmet`&&this.tess.ready&&this.bolt.ready&&!t.ui.busy&&!t.frozen){let e=n.toL(r.pos.x,r.pos.z);Math.hypot(e.x,e.z)<27&&Math.abs(r.pos.y-n.gy0)<16&&r.onGround&&this.arrive()}if(this.k<=0&&!this.active)return;let i=t.time;{let t=this.bolt,r=t.ch?.model;if(r){let e=t.path.length>0;r.rotation.z=e?Math.sin(i*9)*.09:this.jiggle>0?Math.sin(i*30)*.05:0,r.position.y=e?Math.abs(Math.sin(i*9))*.05:Math.sin(i*1.6)*.012,r.rotation.x=e?.06:0}this.jiggle=Math.max(0,(this.jiggle||0)-e);let a=this.boltHolds,o=t.pos.clone().add($(Math.sin(t.yaw)*.42+Math.cos(t.yaw)*.28,.82,Math.cos(t.yaw)*.42-Math.sin(t.yaw)*.28));if(this.boltKey.visible=a===`grate`||a===`own`,this.boltFire.visible=a===`fire`,a===`own`?this.boltKey.material.color.set(14263361):this.boltKey.material.color.set(CY.grate),(a===`fire`?this.boltFire:this.boltKey).position.copy(o),(a===`fire`?this.boltFire:this.boltKey).rotation.y=t.yaw,this.bolt_carry>=0){let e=n.crates[this.bolt_carry];e.pos.copy(t.pos).add($(Math.sin(t.yaw)*.55,.95,Math.cos(t.yaw)*.55)),e.yaw=t.yaw,n.drawCrates()}this.tessKey.visible=!!this.tessHolds,this.tessHolds&&this.tessKey.position.copy(this.tess.pos).add($(0,.95,0).add($(Math.sin(this.tess.yaw)*.35,0,Math.cos(this.tess.yaw)*.35)))}n.lever.rotation.x+=((this.leverTo||0)*-.9-n.lever.rotation.x)*(1-Math.exp(-e*6));for(let t=this.flying.length-1;t>=0;t--){let r=this.flying[t];r.t+=e;let i=Math.min(1,r.t/r.dur);r.obj.pos.copy(r.from).lerp(r.to,i),r.obj.pos.y+=Math.sin(i*Math.PI)*r.arc,n.drawCrates(),i>=1&&(this.flying.splice(t,1),r.done())}if(t.audio.ready){n.recycler&&t.audio.bed(`recycler`,.75*Math.min(1,this.k*1.5));let e=r.pos.distanceTo(this.w3($(0,10,0),10));t.audio.bed(`clock_tick`,uY(.42-e/60,.06,.42)*this.k)}if(this.dyeTo!==void 0&&(n.uDye.value+=(this.dyeTo-n.uDye.value)*(1-Math.exp(-e*.35))),this.state===`b1_cloth`||this.state===`b1_battens`){this.clockAcc=(this.clockAcc||0)+e,this.clockAcc>10&&(this.clockAcc=0,this.clock<59&&this.tick(1));let i=this.errand;i.t+=e,this.state===`b1_battens`&&!i.bell&&(i.t>26||r.pos.y-n.gy0>3.2)&&this.testBell();let a=n.toL(r.pos.x,r.pos.z);!t.bubbleNote&&n.fireKey.visible&&Math.hypot(a.x-2.4,a.z)<3.2&&this.think([`task`,qY.master(26)],{t:1.2}),this.carry?(this.yParcel.visible=!0,this.yParcel.material.color.set(xY[this.carry].key),this.yParcel.position.copy(r.handPos).add($(0,-.1,0))):this.yParcel.visible=!1}else this.yParcel.visible=!1;{let e=[...this.youKeys].find(e=>e!==`fire`);this.yKey.visible=!!e&&!this.seated,e&&(this.yKey.material.color.set(CY[e]),this.yKey.position.copy(r.handPos).add($(0,.08,0))),this.yFire.visible=this.youKeys.has(`fire`),this.yFire.visible&&this.yFire.position.copy(r.handPos).add($(.08,-.05,.05))}if(this.ride){let n=this.ride;n.t+=e;let i=Math.min(1,n.t/n.dur);r.respawn(n.curve.getPointAt(i)),i>=1&&(this.ride=null,t.autoInput=null)}if(this.seated){let r=this.sew;r.held&&!this.cut?(r.prog+=e/4.2,r.drift=Math.max(0,r.drift-e*2),r.sound-=e,r.sound<=0&&(r.sound=1.1,t.audio.play(`sew`,{vol:.45})),r.prog>=1&&(r.prog=0,this.st.strips++,this.lead+=.4,this.drawBoard(),t.refreshHud(),t.audio.play(`pickup`,{vol:.25,rate:1.4}))):r.prog>0&&(r.drift=Math.min(1,r.drift+e*1.5),r.prog=Math.max(0,r.prog-e*.18)),(this._sewT=(this._sewT||0)+e)>.12&&(this._sewT=0,this.drawSew(),n.drawCloth(this.st.strips,r.prog,r.drift*Math.sin(i*3)))}this.updateRun(e),this.updateHazard(e),this.updateSeven(e),this.kiteOnBack&&(t.kite.override={pos:r.pos.clone().add($(0,2.5,0)).addScaledVector(r.forward,-.6)});let a=t.kite.pos;if(this.kKey.visible=!!this.kCarry&&!this.kCarry.fireOnly,this.kFire.visible=!!this.kCarry?.fire,this.kCarry&&(this.kKey.position.copy(a).add($(.28,-.45,0)),this.kFire.position.copy(a).add($(-.28,-.5,0))),this.kParcel.visible=this.kParcelOn>=0&&this.kParcelOn!==void 0,this.kParcel.visible&&(this.kParcel.material.color.set(bY[this.kParcelOn].key),this.kParcel.position.copy(a).add($(0,-.7,0))),this.dropRoll){let t=this.dropRoll;if(t.vy-=12*e,t.pos.y+=t.vy*e,this.fallRoof){let r=this.w3(n.pl(46.4,17),2.62),i=1-Math.exp(-e*3);t.pos.x+=(r.x-t.pos.x)*i,t.pos.z+=(r.z-t.pos.z)*i,t.vy<-1&&t.pos.y1.5&&(this.dropRoll=null,this.dropT=0,this.roll.g.visible=!1))}else this.roll.g.visible=!!this.rollOn,this.rollOn&&(this.roll.g.position.copy(a).add($(0,-.72,0)),this.roll.g.rotation.set(0,Math.atan2(t.camera.position.x-a.x,t.camera.position.z-a.z),Math.sin(i*2)*.08));if(this.tumbleT>0&&(this.tumbleT-=e,t.kite.group.quaternion.multiply(new gi().setFromEuler(new Ji(0,0,(1.8-this.tumbleT)*9))),t.kite.group.position.y-=(1.8-this.tumbleT)*.5),this.stoneRise!==void 0&&this.stone.visible&&this.stoneRise<1){this.stoneRise=Math.min(1,this.stoneRise+e/3);let t=this.w3(n.spot.stone);this.stone.position.y=t.y-2.2*(1-this.stoneRise)}this.state===`b3_practice`&&!this.st.practice&&!t.ui.busy&&(this.practiceWait+=e,this.practiceWait>14&&(this.practiceWait=0,t.ui.toast(`Press ${FY(`Q`)} to whistle.`,{ms:3500})))}updateRun(e){let t=this.run,n=this.g;if(t){if(n.ui.busy){this.placeKite(t.pos);return}if(t.hold>0)t.hold-=e;else{let n=t.speed*t.ff*t.slow,r=t.s+n*e;t.cap!==null&&t.cap!==void 0&&(r=Math.min(r,Math.max(t.s,t.cap))),t.s=Math.min(t.len,r)}t.pos.copy(t.curve.getPointAt(t.s/t.len));for(let e of t.marks)!e.done&&t.s>=e.at&&(e.done=!0,e.fn());if(this.placeKite(t.pos),t.abort&&t.hold<=0){this.run=null,t.resolve(`tumbled`);return}t.s>=t.len-.001&&t.hold<=0&&this.run===t&&(this.run=null,t.resolve(`done`))}}placeKite(e){let t=this.g.kite;t.override={pos:e.clone()},t.pos.copy(e),t.group.position.copy(e)}reset(){if(this.state===`unmet`)return!1;let e=this.g,t=this.iw;t.reset(),this.resetDay(),this.attempt=0,this.errand=null;for(let e of[this.kKey,this.kFire,this.kParcel,this.yKey,this.yFire,this.yParcel,this.boltKey,this.boltFire,this.tessKey])e&&(e.visible=!1);return this.roll&&(this.roll.g.visible=!1),this.rollOn=!1,this.dropRoll=null,this.fallRoof=!1,this.kCarry=null,this.kParcelOn=-1,this.boltHolds=null,this.tessHolds=!1,this.bolt_carry=-1,this.leverTo=0,this.stone.visible=!1,this.stoneRise=void 0,this.dyeTo=void 0,this.cut=null,this.noonBusy=!1,this.saidNearly=!1,this.reading=!1,this.sewEl.hidden=!0,e.ui.fastForward(!1),e.kite.maxSpeed=6.2,t.setClock(45),this.drawBoard(),this.placeAll(),super.reset()}}})),QY=n({default:()=>$Y}),$Y,eX=t((()=>{BJ(),PY(),ZY(),$Y={name:`Keyhold`,when:`Noon`,taskGlyph:`sail`,music:`theme_keyhold`,musicVol:.34,seed:11,sky:{horizon:14085375,mid:10012406,zenith:4885730,fog:13821174,glow:.55,disc:16777215,clouds:16777215,stars:0},light:{sun:16774888,sunI:2.9,hemi:14084351,ground:11047536,hemiI:1.35,dir:[-.22,.94,-.26]},VO:zJ,SPEAKERS:RJ,Quest:XY,build(e,t,n){return gY(e,t,n)}}}));function tX(e,t,n){let[r,i,a]=n.center,o=Math.atan2(-r,-a),s=Math.cos(o),c=Math.sin(o),l=(e,t,n)=>$(r+e*s+n*c,i+t,a-e*c+n*s),u=(e,t)=>{let n=e-r,i=t-a;return[n*s-i*c,n*c+i*s]},d=e=>e+o,f=sY(e,t,{name:`vigil`,center:n.center,radius:n.radius,depth:n.radius*1.35,seed:311,hill:.55,rimJag:.08,palette:iX,flats:[{x:0,z:0,r:34,h:.3}]});f.grassPalette={dark:3099238,mid:4482698,tip:9416920,dry:8029866};let p=(e,t)=>{let n=l(e,0,t);return(f.groundAt(n.x,n.z)??i+.3)-i},m=p(-7.8,9.8),h=new I;h.position.set(r,i,a),h.rotation.y=o,e.add(h);let g=lU(911),_=[],v=[[16,12],[8,12],[8,4],[m,4]],y=(e,t)=>dY(v[e][0],v[e][1],(uY(t,-6,7)+6)/13),b=(e,t)=>{for(let e=0;e<4;e++)if(t>=rX[e].z0&&t<=rX[e].z1)return e;return-1},x=OH(0),S=OH(0),C=OH(1),w=(e,t)=>(e.emissiveNode=e.emissiveNode.add(XV(16757306).mul(x.mul(t))),e),T=(e,t=.18,n=.04,r=null,i=2)=>w(r?GJ(e,r,{scale:i,rim:t}):Q(e,{rim:t}),n),E=YJ.stone({rows:3,seed:31}),D=YJ.chalk({seed:39}),ee=YJ.stone({rows:4,seed:32}),O=YJ.stone({rows:3,seed:33}),k=YJ.tiles({slate:!0,rows:10,per:7,seed:34}),te=YJ.cobbles({n:7,seed:35}),A={rock:GJ(7766204,E,{scale:4.2,rim:.16}),rockDark:GJ(5923486,D,{scale:5,rim:.12}),rockGilt:T(7503033,.16,.06,E,4.2),pathUp:T(11778783,.2,.15,te,1.5),pathLow:GJ(9870790,te,{scale:1.5,rim:.18}),stone:T(10266844,.22,.015,ee,2.2),stoneMid:T(8161216,.18,.015,ee,1.6),floor:T(9542604,.16,.03,O,3.2),towerStone:GJ(11384284,ee,{scale:2.2,rim:.2}),towerMid:GJ(9082052,ee,{scale:1.6,rim:.18}),roof:GJ(4608142,k,{scale:1.8,rim:.14}),wood:GJ(8280648,YJ.planks({seed:36}),{scale:1.2,rim:.12}),iron:Q(2566724,{rim:.2}),bronze:Q(12620110,{rim:.45}),plaster:GJ(13815272,YJ.plaster({seed:37}),{scale:2.5,rim:.18}),houseRoof:GJ(4871826,k,{scale:1.5,rim:.14}),brick:GJ(11697260,YJ.brick({seed:38}),{scale:1.6,rim:.14}),darkGlass:new Y({color:3292274}),hole:new Y({color:1315626}),lanternGlow:oY(16761962,1.9,.06),candle:Q(15985362,{rim:.3}),candleFlame:oY(16765562,2.4,.15),statue:T(9937620,.32,.02,ee,1.1)},ne=(e,t,n)=>{let r=document.createElement(`canvas`);r.width=e,r.height=t,n(r.getContext(`2d`),e,t);let i=new Oc(r);return i.colorSpace=Mr,i.anisotropy=4,i},re=(e,t=4,n=10)=>ne(128,256,(r,i,a)=>{let o=lU(e),s=[`#2b47d6`,`#3a60f2`,`#5a3fd2`,`#7d46e0`,`#a04fd8`,`#d45aae`,`#f2b640`,`#3fa8e0`,`#2f2f9a`,`#6a52e8`];r.fillStyle=`#16132a`,r.fillRect(0,0,i,a);let c=[];for(let e=0;e<=n;e++){c.push([]);for(let r=0;r<=t;r++)c[e].push([r*i/t+(r>0&&r0&&en?r.lineTo(e,t):r.moveTo(e,t)),r.closePath(),r.fillStyle=i,r.fill();let a=r.createLinearGradient(t[0][0],t[0][1],t[2][0],t[2][1]);a.addColorStop(0,`rgba(255,255,255,0.22)`),a.addColorStop(1,`rgba(0,0,0,0.12)`),r.fillStyle=a,r.fill(),r.strokeStyle=`#16132a`,r.lineWidth=3.5,r.stroke()}for(let e=0;e<3;e++){let t=i*(.3+o()*.4),n=a*(.16+e*.32),c=11+o()*7;r.fillStyle=s[6],r.beginPath(),r.arc(t,n,c,0,7),r.fill(),r.strokeStyle=`#16132a`,r.lineWidth=3,r.stroke(),r.fillStyle=s[5],r.beginPath(),r.arc(t,n,c*.45,0,7),r.fill(),r.stroke()}}),ie=e=>{e.computeBoundingBox();let t=e.boundingBox,n=e.attributes.position,r=new Float32Array(n.count*2);for(let e=0;e{let n=new Y({map:e});return n.colorNode=DH(e).mul(t).add(XV(16757306).mul(x.mul(.1))),n};A.glassA=ae(re(71,4,11),1.3),A.glassB=ae(re(72,3,8),1.15),A.banner=Q(16777215,{map:ne(64,160,(e,t,n)=>{e.fillStyle=`#4b2e8e`,e.beginPath(),e.moveTo(0,0),e.lineTo(t,0),e.lineTo(t,n-16);for(let r=4;r>=0;r--)e.lineTo(r*t/4+(r<4?t/8:0),r<4?n:n-16),e.lineTo(r*t/4,n-16);e.closePath(),e.fill(),e.fillStyle=`#e8b64a`,e.fillRect(0,0,t,7),e.fillRect(5,10,3,n-32),e.fillRect(t-8,10,3,n-32),e.beginPath(),e.moveTo(t/2-22,n*.42),e.quadraticCurveTo(t/2,n*.42-20,t/2+22,n*.42),e.quadraticCurveTo(t/2,n*.42+20,t/2-22,n*.42),e.fill(),e.fillStyle=`#4b2e8e`,e.beginPath(),e.ellipse(t/2,n*.42,3.5,8,0,0,7),e.fill(),e.fillStyle=`#e8b64a`;for(let r=0;r<3;r++)e.beginPath(),e.arc(t/2,n*.64+r*9,2.2,0,7),e.fill()}),side:2,rim:.12});let j=new fY,oe=(e,t,n,r,i,a,o,s=0,c=0,l=0)=>j.box(e,t,n,r,$(i,a,o),[c,s,l]),se=(e,t,n,r,i,a,o,s=10,c=0,l=0)=>j.cyl(e,t,n,r,$(i,a,o),[c,0,l],s);function ce(e,t,n,r=-3){let i=[],a=[],o=(e,t,n,r,i)=>e.push(...t,...n,...r,...t,...r,...i);for(let s=0;s{let t=new xo;return t.setAttribute(`position`,new R(e,3)),t.computeVertexNormals(),t};return{top:p(i),side:p(a)}}let le=(e,t,n,r,i,a)=>{let o=ce(e,t,n,a);j.add(o.top,r),j.add(o.side,i)};oe(20.4,18.7,21.2,A.rockGilt,0,12.7/2,-9.4),oe(20.6,.32,21.2,A.floor,0,15.84,-9.4);for(let e=0;e<4;e++){let t=y(e,-6),n=y(e,7),r=e<2;le([[-10.2,t],[-6,t],[7,n],[10.2,n]],rX[e].z0,rX[e].z1,r?A.pathUp:A.pathLow,r?A.rockGilt:A.rock)}{let e=[];for(let t of[0,2.5,5,7.6]){let n=y(1,t)-.35;e.push([t,n,n-.85])}le(e,5.8,8.6,A.rock,A.rockDark)}{let e=[];for(let t of[-6.8,-4,-2,0]){let n=y(2,t)-.35;e.push([t,n,n-.85])}le(e,8.2,9.3,A.rock,A.rockDark)}let ue=new zc(1,0),de=[];for(let e=0;e<46;e++){let t=e%3,n=.8+g()*1.6,r,i,a;t===0?(r=(g()<.5?-1:1)*(10.3+g()*.6),a=-19+g()*29,i=g()*(a>1?6:14)):t===1?(r=-9+g()*18,a=-20.4-g()*.5,i=g()*14):(r=-10+g()*20,a=10.7+g()*.6,i=.2+g()*.8,r>-5&&r<11&&(a=10.9,i=.1)),j.add(ue,g()<.5?A.rock:A.rockDark,$(r,i,a),[g()*3,g()*3,g()*3],[n,n*.8,n]),de.push([r,i,a,n])}let fe=[];for(let e=0;e<7;e++){let t=-9+e*3,n=1.6+g(),r=12+g()*3;oe(n,r,.9,A.rockDark,t,5.5,-20.5,0,0,(g()-.5)*.1),fe.push([t,n,5.5+r/2])}let pe=(e,t,n,r)=>{let i=Math.hypot(n-e,r-t);oe(i,.9,.42,A.stone,(e+n)/2,16.45,(t+r)/2,-Math.atan2(r-t,n-e))};pe(-10,.8,-9.1,.8),pe(-5.9,.8,10,.8),pe(-9.8,-20,-9.8,.8),pe(9.8,-20,9.8,-1.5),pe(-10,-19.8,10,-19.8);let me=(e,t,n,r)=>j.add(new pl(new ul(e.map(([e,t])=>new N(e,t))),{depth:t,bevelEnabled:!1}),n,r),he=(e,t,n,r,i,a=0)=>{e.lineTo(t,a),e.lineTo(t,r),e.quadraticCurveTo(t,r+(i-r)*.72,t+n/2,i),e.quadraticCurveTo(t+n,r+(i-r)*.72,t+n,r),e.lineTo(t+n,a)},ge=(e,t,n)=>{let r=new ul;return r.moveTo(-e/2,0),he(r,-e/2,e,t,n),r.lineTo(-e/2,0),r};for(let e of[-1,1]){oe(.5,4.2,11.6,A.stone,e*9.75,18.1,-7.3);let t=new ul;t.moveTo(-13.3,0);for(let e=0;e<5;e++)he(t,-11.85+e*2.3-.88,1.76,2.35,3.5);t.lineTo(-1.25,0),t.lineTo(-1.25,4.15),t.lineTo(-13.3,4.15),t.lineTo(-13.3,0),j.add(new pl(t,{depth:.42,bevelEnabled:!1,curveSegments:5}),A.stone,$(e*6.6+.21,16,0),[0,-Math.PI/2,0]);for(let t=0;t<=5;t++){let n=-13+t*2.3;se(.15,.19,3.2,A.stoneMid,e*6.33,17.6,n,8),oe(.44,.22,.44,A.stoneMid,e*6.33,19.25,n),oe(.5,.2,.5,A.stoneMid,e*6.33,16.1,n)}me([[-2.3,0],[2.3,0],[0,1.65]],12.7,A.roof,$(e*8.2,20.12,-13.7)),me([[-2.05,0],[2.05,0],[0,1.42]],.18,A.stone,$(e*8.2,20.12,-1.08)),oe(4.7,.2,.3,A.stoneMid,e*8.2,20.05,-.95);for(let t=0;t<3;t++){let n=ie(new bl(ge(.8,1.2,1.75),5));j.add(n,A.glassB,$(e*9.48,17.1,-11.4+t*3.6),[0,-e*Math.PI/2,0])}for(let t=0;t<5;t++){let n=-11.85+t*2.3;j.add(new xl(.15,8,6),A.lanternGlow,$(e*7.9,19.35,n),[0,0,0],[1,1.25,1]),oe(.2,.06,.2,A.iron,e*7.9,19.58,n),oe(.02,.5,.02,A.iron,e*7.9,19.85,n)}for(let t of[-10.7,-6.1])j.add(new vl(.75,1.9),A.banner,$(e*6.08,18.05,t),[0,-e*Math.PI/2,0])}let _e=l(0,23,-13),ve=l(1.5,17.9,-4.5),ye=l(0,25.2,-13),be=new Y;{let e=xH,t=gH(e.sub(JV)),n=TH(e.x.mul(2.1).add(XH.mul(1.1))).mul(TH(e.z.mul(2.7).sub(XH.mul(.8)))).mul(.03),r=gH(MH(t.x.add(n),t.y.negate(),t.z.add(n.mul(.7)))),i=(t,n)=>{let i=MH(t.x,t.y,t.z).sub(e);return SH(oH(QV(gH(jH(r.x,r.z)),gH(jH(i.x,i.z))),$V(0)),$V(n))},a=TH(e.x.mul(3.1).add(e.z.mul(11)).add(XH.mul(2.2))).mul(.35).add(.65);be.colorNode=sH(XV(791094),XV(3819400),SH($V(1).sub(WV(t.y)),$V(5))).add(XV(16760912).mul(i(_e,700).mul(2.4).add(i(_e,60).mul(.35)).mul(a).mul(x))).add(XV(8019199).mul(i(ye,45).mul(.5).mul(a))).add(XV(16751164).mul(i(ve,400).mul(C).mul(a).mul(1.2))).add(XV(10466559).mul(SH(oH(TH(e.x.mul(5.3).add(e.z.mul(3.1)).add(XH.mul(1.7))),$V(0)),$V(24)).mul(.16)))}for(let e of[-1,1]){let t=e*.75,n=e*4.65,r=(t+n)/2,i=Math.abs(n-t),a=new z(new vl(i,5.6),be);a.rotation.x=-Math.PI/2,a.position.set(r,16.06,-9),a.userData.noOutline=!0,h.add(a),oe(i+.6,.22,.3,A.stoneMid,r,16.11,-6.05),oe(i+.6,.22,.3,A.stoneMid,r,16.11,-11.95),oe(.3,.22,6.2,A.stoneMid,t,16.11,-9),oe(.3,.22,6.2,A.stoneMid,n,16.11,-9)}for(let e of[-1,1]){let t=e*4.95;se(.06,.08,2.3,A.iron,t,17.15,-5.65,6),oe(.34,.06,.34,A.iron,t,18.3,-5.65),j.add(new xl(.17,8,6),A.lanternGlow,$(t,18.52,-5.65),[0,0,0],[1,1.3,1]),j.add(new Lc(.22,.24,4),A.iron,$(t,18.82,-5.65),[0,Math.PI/4,0])}{let e=new gl([[0,0],[.42,0],[.4,.3],[.3,1],[.24,1.45],[.2,1.62],[0,1.66]].map(([e,t])=>new N(e,t)),8);for(let t of[-1,1]){let n=t*5.55,r=-12.35;oe(.95,.9,.95,A.stoneMid,n,16.45,r),j.add(e,A.statue,$(n,16.9,r)),j.add(new xl(.2,8,6),A.statue,$(n,18.72,r)),j.add(new Lc(.27,.55,8),A.statue,$(n,18.86,-12.389999999999999)),oe(.1,.55,.1,A.statue,n+t*-.3,18.1,-12.049999999999999,0,-.5),j.add(new xl(.13,8,6),A.lanternGlow,$(n+t*-.3,18.3,-11.83))}}oe(8.8,11,7,A.stone,0,21.5,-16.6);for(let e of[-1,1])oe(2,7,7,A.stone,e*5.3,19.5,-16.6);me([[-4.9,0],[4.9,0],[0,5.6]],6.95,A.roof,$(0,26.9,-20.4)),me([[-4.45,0],[4.45,0],[0,5.05]],.5,A.stone,$(0,27,-13.6)),me([[-4.95,-.05],[4.95,-.05],[0,5.62]],.25,A.stoneMid,$(0,26.95,-13.5));for(let e of[-1,1])me([[0,0],[e*2.4,0],[0,1.6]],7.2,A.roof,$(e*4.35,22.95,-20.4));for(let e of[-1,1]){oe(1.2,13.3,1.2,A.stoneMid,e*4.45,22.65,-12.95),oe(1.45,.3,1.45,A.stoneMid,e*4.45,29.3,-12.95),j.add(new Lc(.82,6.2,8),A.roof,$(e*4.45,32.5,-12.95),[0,Math.PI/8,0]),oe(.8,8.8,.8,A.stoneMid,e*6.3,20.4,-12.95),j.add(new Lc(.58,3.3,4),A.roof,$(e*6.3,26.45,-12.95),[0,Math.PI/4,0]);for(let t of[4.2,8.6])oe(1.3,.22,1.3,A.stoneMid,e*4.45,16+t,-12.95)}oe(3.2,8,3.2,A.stone,0,31.5,-17.4),oe(3.6,.35,3.6,A.stoneMid,0,35.6,-17.4),j.add(new Lc(2.3,10.5,8),A.roof,$(0,41,-17.4),[0,Math.PI/8,0]);for(let[e,t]of[[-1,-1],[1,-1],[1,1],[-1,1]])j.add(new Lc(.28,1.9,4),A.roof,$(e*1.5,36.7,-17.4+t*1.5),[0,Math.PI/4,0]);for(let e of[-1,1])oe(.3,2.4,1,A.hole,e*1.62,33.2,-17.4);{let e=new bl(ge(1.1,1.3,2.4),5);j.add(e,A.hole,$(0,31.9,-15.78))}{let e=new z(new bl(ge(2.3,2.3,3.75),6),A.hole);e.position.set(0,16,-13.07),e.userData.noOutline=!0,h.add(e),j.add(new bl(ge(3.2,2.5,4.35),6),A.stoneMid,$(0,16,-13.085));for(let e of[-1,1])oe(1.06,2.5,.08,A.wood,e*.56,17.25,-13.03);for(let e=0;e<3;e++)oe(4.4-e*.8,.08,1.2-e*.35,A.floor,0,16.04+e*.08,-12.5-e*.17)}for(let e of[-1,1])for(let t=0;t<3;t++){let n=e*(1.45+t*.28),r=.22+(t*7+(e>0?3:0))%4*.08;se(.045,.05,r,A.candle,n,16.24+r/2,-12.72+t*.05,6),j.add(new Lc(.035,.09,5),A.candleFlame,$(n,16.24+r+.05,-12.72+t*.05))}j.add(new bl(ge(4.9,7.6,10.95),8),A.stoneMid,$(0,18.85,-13.09)),j.add(ie(new bl(ge(4.2,4.6,7.2),8)),A.glassA,$(0,19.25,-13.075));for(let e of[-1,1])oe(.13,2.7,.08,A.stoneMid,e*.72,20.6,-13.04);oe(4.25,.14,.08,A.stoneMid,0,21.95,-13.04),j.add(new Fc(1.2,24),A.stoneMid,$(0,29,-13.095)),j.add(ie(new Fc(.95,24)),A.glassA,$(0,29,-13.08));for(let e of[-1,1])j.add(new bl(ge(1,4,5.05),5),A.stoneMid,$(e*3.12,19.55,-13.09)),j.add(ie(new bl(ge(.72,3.9,4.8),5)),A.glassB,$(e*3.12,19.7,-13.075)),j.add(new bl(ge(1.4,2.6,3.9),5),A.stoneMid,$(e*5.3,17.35,-13.09)),j.add(ie(new bl(ge(1.1,2.5,3.6),5)),A.glassB,$(e*5.3,17.5,-13.075));let xe=new Y;xe.colorNode=sH(XV(4935578).mul(.9),XV(16761925).mul(2.3),x);let Se=new Y;Se.colorNode=sH(XV(2828882),XV(16769946).mul(1.8),x);let Ce=new ul;Ce.moveTo(-1.75,0),Ce.quadraticCurveTo(0,1.35,1.75,0),Ce.quadraticCurveTo(0,-1.35,-1.75,0);let we=new I;we.position.set(0,23,-13),h.add(we);{let e=new z(new bl(Ce),A.stoneMid);e.scale.setScalar(1.2),e.position.z=-.02,we.add(e)}{let e=new z(new bl(Ce),xe);e.userData.noOutline=!0,we.add(e)}{let e=new z(new yl(.42,.62,28),Se);e.position.z=.02,e.userData.noOutline=!0,we.add(e)}{let e=new z(new Fc(.28,20),new Y({color:1775152}));e.scale.set(.45,1.35,1),e.position.z=.03,e.userData.noOutline=!0,we.add(e)}let Te=new Fu(16760922,0,24,1.1);Te.position.set(0,21.5,-8.5),h.add(Te);let Ee=new Y({transparent:!0,depthWrite:!1,blending:2,side:2});Ee.colorNode=XV(16758858),Ee.opacityNode=x.mul(.028);let De=new z(new Lc(8.5,20,24,1,!0),Ee);De.userData.noOutline=!0;{let e=$(0,23,-12.8),t=$(-.5,10.5,3.6),n=e.clone().lerp(t,.5);De.position.copy(n),De.quaternion.setFromUnitVectors($(0,1,0),e.clone().sub(t).normalize()),De.scale.set(1,e.distanceTo(t)/20,1),h.add(De)}let M={},Oe=(e,t,n)=>$(e,t,n);M.brazier=Oe(1.5,16,-4.5),M.register=Oe(-3.5,16,-2.5),M.orla=Oe(-3.5,16,-3.5),M.present=Oe(-3.5,16,-1.4),M.gong=Oe(-.6,16,-.1),M.gongStand=Oe(-.6,16,-1.2),M.chapelDoor=Oe(0,16,-12.6),M.chapelIn=Oe(0,16,-14.2),M.aisle=Oe(0,16,-5.2),M.gateIn=Oe(-7.5,16,-.2),M.gateOut=Oe(-7.8,16,2.2),M.cryptTop=Oe(-8.6,16,-3.4),M.cryptOut=Oe(-7.4,16,-3.4),M.forkDoor=Oe(-7.8,8,3.55),M.fork=Oe(-7.8,8,5.4),M.bottomDoor=Oe(-7.8,m,8.35),M.bottom=Oe(-7.8,m,9.8),M.wick=Oe(3,16,-5.6),M.snuff=Oe(-1.8,16,-3.4),M.crumbTop=Oe(.2,16,-3.9),M.keeperFire=Oe(2.6,16,-3.7),M.oven=Oe(-10.2,m+.8,13.6),M.bakery=Oe(-9.4,p(-9.4,12.6),12.6),M.bridgeA=Oe(10.1,16,-.4),M.bridgeB=Oe(6,14.5,13.8),M.tower=Oe(6,14.5,16.1),M.towerStand=Oe(6,14.5,14.5),M.bell=Oe(6,17.35,17.1),M.ropeA=Oe(9.2,17.2,0),M.ropeB=Oe(7.3,15.7,13.6),M.landing=Oe(-.8,p(-.8,17.9),17.9),M.updraft=Oe(14.2,0,5.2),se(.28,.4,.9,A.stoneMid,M.brazier.x,16.45,M.brazier.z,8),se(.7,.42,.42,A.iron,M.brazier.x,17.1,M.brazier.z,10);let ke=new Y;ke.colorNode=XV(16753212).mul(TH(XH.mul(9)).mul(.12).add(2.1)).mul(C.mul(.7).add(.3));let Ae=new I;Ae.position.set(M.brazier.x,17.3,M.brazier.z),h.add(Ae);{let e=[new Lc(.3,.95,7).translate(0,.47,0),...[[.18,.05,.6],[-.15,.1,.5],[.02,-.17,.55]].map(([e,t,n])=>new Lc(.1,n,5).translate(e,n/2,t))],t=new z(UU(e.map(e=>e.toNonIndexed())),ke);t.userData.noOutline=!0,Ae.add(t);let n=new Y;n.colorNode=XV(16773296).mul(TH(XH.mul(13)).mul(.1).add(2.3));let r=new z(new Lc(.15,.55,6).translate(0,.27,0),n);r.userData.noOutline=!0,Ae.add(r)}let je=new Fu(16752714,6,9,1.6);je.position.set(M.brazier.x,18.2,M.brazier.z),h.add(je);let Me=new I;Me.position.set(M.brazier.x-.2,16,M.brazier.z+1.05),h.add(Me);{let e=Q(7031358);for(let t of[-1,1]){let n=new z(new Ic(.04,.05,1.8,5),e);n.position.set(t*.7,.9,0),Me.add(n)}let t=new z(new Nc(1.4,1.1,.05),Q(11569770,{rim:.2}));t.position.y=1.1,Me.add(t)}oe(.9,1.05,.6,A.wood,M.register.x,16.52,M.register.z),oe(1.1,.08,.8,A.wood,M.register.x,17.1,M.register.z,0,-.35);{let e=Q(15853778,{rim:.1});for(let t of[-1,1])oe(.5,.04,.66,e,M.register.x+t*.26,17.17,M.register.z,0,-.35,t*.05)}se(.07,.09,.16,A.bronze,M.register.x+.62,17.12,M.register.z+.1,8);for(let e of[-1,1])oe(.16,2.6,.16,A.wood,M.gong.x+e*.95,17.3,M.gong.z);oe(2.1,.18,.2,A.wood,M.gong.x,18.55,M.gong.z);let Ne=new z(new Ic(.72,.72,.08,24),A.bronze);Ne.rotation.x=Math.PI/2,Ne.position.set(M.gong.x,17.55,M.gong.z),h.add(Ne),oe(1.7,2.8,1.8,A.stoneMid,M.cryptTop.x-.2,17.4,M.cryptTop.z),j.add(new Lc(1.35,1.1,4),A.roof,$(M.cryptTop.x-.2,19.35,M.cryptTop.z),[0,Math.PI/4,0]);let Pe=(e,t,n)=>{let r=new ul;r.moveTo(-e/2,0),r.lineTo(-e/2,t-e/2),r.quadraticCurveTo(-e/2,t,0,t+.15),r.quadraticCurveTo(e/2,t,e/2,t-e/2),r.lineTo(e/2,0);let i=new z(new bl(r),n);return i.userData.noOutline=!0,i};{let e=Pe(1,2,A.hole);e.position.set(M.cryptTop.x+.66,16,M.cryptTop.z),e.rotation.y=Math.PI/2,h.add(e)}{let e=Pe(1.3,2.1,A.hole);e.position.set(M.forkDoor.x,8,3.42),h.add(e);let t=Pe(1.7,2.4,A.stoneMid);t.position.set(M.forkDoor.x,7.95,3.41),h.add(t)}{let e=Pe(1.3,2.1,A.hole);e.position.set(M.bottomDoor.x,m,8.22),h.add(e);let t=Pe(1.7,2.4,A.stoneMid);t.position.set(M.bottomDoor.x,m-.05,8.21),h.add(t)}let Fe=A.iron,Ie=[];for(let[e,t,n,r]of[[-7.5,.8,0,6],[9.8,-.4,Math.PI/2,5]]){let i=new I;i.position.set(e,16,t),i.rotation.y=n,h.add(i);let a=[];for(let e=0;ee.toNonIndexed())),Fe)),i.userData.up=3.1,i.position.y=16+i.userData.up,Ie.push(i)}let Le=nX.map((e,t)=>{let n=Math.floor(t/3);return Oe(e,y(n,e),rX[n].z1-.32)}),Re=nX.map((e,t)=>{let n=Math.floor(t/3);return Oe(e,y(n,e),(rX[n].z0+rX[n].z1)/2)});for(let e of Le)se(.05,.07,1.75,A.iron,e.x,e.y+.87,e.z,6),oe(.36,.06,.36,A.iron,e.x,e.y+1.78,e.z),oe(.3,.12,.3,A.iron,e.x,e.y+2.2,e.z),j.add(new Lc(.24,.22,4),A.iron,$(e.x,e.y+2.37,e.z),[0,Math.PI/4,0]);let ze=new Nc(.24,.32,.24),Be=new Fs(ze,new Y({color:3883895}),12),Ve=new Y;Ve.colorNode=XV(16762190).mul(TH(XH.mul(3.1)).mul(.08).add(2.5));let He=new Fs(ze,Ve,12);for(let e of[Be,He])e.userData.noOutline=!0,e.frustumCulled=!1,h.add(e);let Ue=new Fs(new xl(.5,10,8),(()=>{let e=new Y({transparent:!0,depthWrite:!1,blending:2});return e.colorNode=XV(16756800),e.opacityNode=TH(XH.mul(3.1)).mul(.03).add(.2),e})(),12);Ue.userData.noOutline=!0,Ue.frustumCulled=!1,h.add(Ue);let We=ne(64,64,(e,t,n)=>{let r=e.createRadialGradient(t/2,n/2,0,t/2,n/2,t/2);r.addColorStop(0,`rgba(255,196,110,0.85)`),r.addColorStop(.45,`rgba(255,170,70,0.32)`),r.addColorStop(1,`rgba(255,150,50,0)`),e.fillStyle=r,e.fillRect(0,0,t,n)}),Ge=new Fs(new Fc(1.35,20).rotateX(-Math.PI/2),new Y({map:We,transparent:!0,depthWrite:!1,blending:2,color:14262368}),12);Ge.userData.noOutline=!0,Ge.frustumCulled=!1,h.add(Ge);let Ke=nX.map((e,t)=>new gi().setFromEuler(new Ji(0,0,Math.atan((v[Math.floor(t/3)][1]-v[Math.floor(t/3)][0])/13)))),qe=Array(12).fill(!1),Je=new F,Ye=new gi,Xe=(e,t)=>{qe[e]=t;let n=Le[e],r=$(n.x,n.y+1.99,n.z);Je.compose(r,Ye,$(+!t,+!t,+!t)),Be.setMatrixAt(e,Je),Je.compose(r,Ye,$(+!!t,+!!t,+!!t)),He.setMatrixAt(e,Je),Je.compose(r,Ye,$(+!!t,+!!t,+!!t)),Ue.setMatrixAt(e,Je);let i=Math.floor(e/3),a=n.x,o=n.z-.7;Je.compose($(a,y(i,a)+.05,o),Ke[e],$(+!!t,1,+!!t)),Ge.setMatrixAt(e,Je),Be.instanceMatrix.needsUpdate=He.instanceMatrix.needsUpdate=Ue.instanceMatrix.needsUpdate=Ge.instanceMatrix.needsUpdate=!0};for(let e=0;e<12;e++)Xe(e,!1);for(let e=0;e<3;e++)for(let t=-5.2;t<=6.6;t+=1.6)nX.slice(e*3,e*3+3).some(e=>Math.abs(e-t)<.5)||oe(.8,.45,.3,A.stoneMid,t,y(e,t)+.2,rX[e].z1-.18,0,0,Math.atan((v[e][1]-v[e][0])/13));oe(4.6,14.5-m+.5,4.6,A.towerStone,M.tower.x,(14.5+m-.5)/2,M.tower.z),oe(5.2,.35,5.2,A.towerMid,M.tower.x,14.33,M.tower.z);for(let[e,t]of[[-1,-1],[1,-1],[1,1],[-1,1]])oe(.42,3,.42,A.towerMid,M.tower.x+e*2.3,16,M.tower.z+t*2.3);j.add(new Lc(4,3.4,4),A.roof,$(M.tower.x,19.2,M.tower.z),[0,Math.PI/4,0]);for(let[e,t]of[[[-2.4,2.4],[2.4,2.4]],[[2.4,-2.4],[2.4,2.4]],[[-2.4,-2.4],[-2.4,2.4]]]){let n=M.tower.x+e[0],r=M.tower.z+e[1],i=M.tower.x+t[0],a=M.tower.z+t[1];oe(Math.hypot(i-n,a-r),.8,.3,A.towerStone,(n+i)/2,14.9,(r+a)/2,-Math.atan2(a-r,i-n))}oe(1.2,.8,.3,A.towerStone,M.tower.x-1.8,14.9,M.tower.z-2.4),oe(1.2,.8,.3,A.towerStone,M.tower.x+1.8,14.9,M.tower.z-2.4);for(let e=0;e<3;e++){let t=Pe(1.1,2,A.hole);t.position.set(M.tower.x,6+e*3.2,M.tower.z+2.32),h.add(t)}let Ze=new I;Ze.position.copy(M.bell),h.add(Ze);{let e=[$(0,0,0),$(.3,-.05,0),$(.42,-.5,0),$(.62,-.95,0),$(.66,-1.05,0)].map(e=>new N(e.x,e.y)),t=new z(new gl(e,14),Q(12093770,{rim:.45,side:2}));Ze.add(t)}{let e=M.bridgeB.x-M.bridgeA.x,t=M.bridgeB.z-M.bridgeA.z,n=Math.hypot(e,t),r=Math.atan2(e,t),i=M.bridgeB.y-M.bridgeA.y,a=Math.atan2(i,n),o=M.bridgeA.clone().lerp(M.bridgeB,.5),s=e=>e.applyMatrix4(new F().makeRotationFromEuler(new Ji(-a,r,0,`YXZ`)));j.add(s(new Nc(1.9,.35,Math.hypot(n,i)+.4)),A.stoneMid,$(o.x,o.y-.17,o.z));for(let e of[-1,1]){let t=$(Math.cos(r)*e*.95,.35,-Math.sin(r)*e*.95);j.add(s(new Nc(.18,.7,Math.hypot(n,i))),A.stone,o.clone().add(t))}{let e=M.bridgeA.clone().lerp(M.bridgeB,.86);j.box(.8,e.y-m,.8,A.towerMid,$(e.x,(e.y+m)/2-.3,e.z)),_.push(()=>ft(e.x,(e.y+m)/2,e.z,.5,(e.y-m)/2-.4))}}{let e=M.ropeA,t=M.ropeB,n=e.distanceTo(t),r=new z(new Ic(.02,.02,n,4),A.wood);r.position.copy(e.clone().lerp(t,.5)),r.quaternion.setFromUnitVectors($(0,1,0),t.clone().sub(e).normalize()),r.userData.noOutline=!0,h.add(r)}let Qe=new I;h.add(Qe);{let e=new z(new Ic(.28,.22,.3,10,1,!0),Q(11569749,{side:2}));e.position.y=-.45,e.userData.noOutline=!0,Qe.add(e);let t=new z(new Cl(.26,.02,4,12,Math.PI),A.wood);t.position.y=-.3,Qe.add(t);let n=new I;n.position.set(0,-.28,0),n.rotation.x=-.9,Qe.add(n),Qe.userData.lens=n;let r=new z(new Cl(.15,.03,6,18),A.bronze);n.add(r);let i=new Y({transparent:!0,opacity:.55,color:13625087}),a=new z(new Fc(.14,18),i);a.userData.noOutline=!0,n.add(a);let o=new z(new Lc(.1,.22,3),Q(16183264));o.position.set(0,-.22,0),o.rotation.z=Math.PI,n.add(o)}let $e=e=>{Qe.position.copy(M.ropeA.clone().lerp(M.ropeB,e))};$e(0);let et=(e,t,n,r,i,a,o=A.plaster)=>{let s=p(e,t)-.2;j.box(n,i,r,o,$(e,s+i/2,t),[0,a,0]);let c=new ul([new N(-n/2-.3,0),new N(n/2+.3,0),new N(0,i*.62)]),l=new pl(c,{depth:r+.5,bevelEnabled:!1});l.translate(0,0,-(r+.5)/2),j.add(l,A.houseRoof,$(e,s+i,t),[0,a,0]);let u=Math.sin(a),d=Math.cos(a),f=Math.cos(a),m=-Math.sin(a);for(let o of[-1,1])j.box(.55,.7,.06,A.darkGlass,$(e+u*(r/2+.03)+f*o*n*.27,s+i*.58,t+d*(r/2+.03)+m*o*n*.27),[0,a,0]);return j.box(.75,1.3,.06,A.wood,$(e+u*(r/2+.03),s+.65,t+d*(r/2+.03)),[0,a,0]),{x:e,z:t,r:Math.max(n,r)*.62,y:s,w:n,d:r,h:i,ry:a}},tt=(e,t,n=M.landing.x,r=M.landing.z)=>Math.atan2(n-e,r-t),nt=[et(-12.8,11.4,4.2,3.4,3,tt(-12.8,11.4,-7.8,10.6),A.brick),et(-11.8,16.4,3.4,3,2.8,tt(-11.8,16.4)),et(-5.6,19.4,3.6,3.2,3.2,tt(-5.6,19.4)),et(12.2,16,3.4,3,2.9,tt(12.2,16)),et(-15.4,5.2,3,2.8,2.6,tt(-15.4,5.2)),et(15.6,11.9,3.2,3,2.7,tt(15.6,11.9))];{let e=M.oven;j.add(new xl(1.15,12,8,0,Math.PI*2,0,Math.PI/2),A.brick,$(e.x,e.y-.8,e.z)),se(.22,.26,1.6,A.brick,e.x-.5,e.y+.6,e.z-.4,6)}let rt=new Y;rt.colorNode=sH(XV(1709088),XV(16747050).mul(2.2),S);let it=Pe(.7,.5,rt);it.position.set(M.oven.x+1.1,M.oven.y-.8,M.oven.z),it.rotation.y=Math.PI/2,h.add(it);{let e=aY([`Vigil`,`the lamp path`],{w:1.3,h:.6,bg:`#e8e2f4`,fg:`#2e2a4a`}),t=M.landing;e.position.set(t.x-1.6,t.y+1.55,t.z-1.2),e.rotation.y=.35,h.add(e),se(.05,.06,1.5,A.wood,t.x-1.6,t.y+.75,t.z-1.25,5)}let at=j.build(h),ot=JU([[-17,12],[-16.5,0],[17.8,.5],[9.5,19.5],[-16,-8],[16,-9],[15.5,-15],[-8.8,20]].map(([e,t])=>{let n=l(e,0,t);return{x:n.x,y:f.groundAt(n.x,n.z)??i,z:n.z,h:4.2+g()*1.5,r:1.5+g()*.5}}),31,{leaf:4153242,leafLit:8363992,trunk:4864594});e.add(ot),t.colliders.push(...ot.userData.colliders),t.camTrunks.push(...ot.userData.trunks),e.add(IU(f,{density:5,seed:17,exclude:(e,t)=>{let[n,r]=u(e,t);return n>-11&&n<11&&r<11.4||Math.abs(n-M.tower.x)<2.9&&Math.abs(r-M.tower.z)<2.9||nt.some(e=>Math.hypot(n-e.x,r-e.z)t.surfaces.push({solid:n,at:(t,n)=>{let[r,a]=u(t,n),o=e(r,a);return o===null?null:i+o}});st((e,t)=>e>=-10.2&&e<=10.2&&t>=-20.1&&t<=1?16:null,!0);for(let e=0;e<4;e++){let t=rX[e];st((n,r)=>n>=-10&&n<=10&&r>=t.z0&&r<=t.z1?y(e,n):null,!0)}st((e,t)=>e>=0&&e<=7.6&&t>5.8&&t<=8.6?y(1,e)-.35:null),st((e,t)=>e>=-6.8&&e<=0&&t>8.2&&t<=9.3?y(2,e)-.35:null);let ct=M.bridgeA,lt=M.bridgeB,ut=Math.hypot(lt.x-ct.x,lt.z-ct.z),dt=(e,t)=>{let n=(lt.x-ct.x)/ut,r=(lt.z-ct.z)/ut,i=e-ct.x,a=t-ct.z,o=(i*n+a*r)/ut;return Math.abs(i*r-a*n)<=.95&&o>=-.02&&o<=1.04?o:null};st((e,t)=>{let n=dt(e,t);return n===null?null:dY(ct.y,lt.y,uY(n,0,1))}),st((e,t)=>Math.abs(e-M.tower.x)<=2.55&&Math.abs(t-M.tower.z)<=2.55?14.5:null,!0),st((e,t)=>Math.abs(e)<=4.9&&t>=-20.4&&t<=-13.1?26.9+5.6*(1-Math.abs(e)/4.9):null,!0),st((e,t)=>{let n=Math.abs(e);return n>=4.35&&n<=6.75&&t>=-20.4&&t<=-13.2?22.95+1.6*(1-(n-4.35)/2.4):null},!0),st((e,t)=>{let n=Math.hypot(Math.abs(e)-4.45,t+12.95);return n<=.82?29.4+6.2*(1-n/.82):null},!0);for(let[e,t,n]of fe)st((r,i)=>Math.abs(r-e)<=t/2+.1&&i>=-21&&i<=-20?n:null,!0);st((e,t)=>{let n=Math.abs(Math.abs(e)-8.2);return n<=2.3&&t>=-13.7&&t<=-1?20.12+1.65*(1-n/2.3):null});for(let e of nt){let t=Math.cos(e.ry),n=Math.sin(e.ry),r=e.w/2+.3,i=(e.d+.5)/2;st((a,o)=>{let s=a-e.x,c=o-e.z,l=s*t-c*n,u=s*n+c*t;return Math.abs(l)<=r&&Math.abs(u)<=i?e.y+e.h+e.h*.62*(1-Math.abs(l)/r):null},!0)}let ft=(e,n,r,i,a)=>{let o=l(e,n,r),s={x:o.x,z:o.z,r:i,y:o.y,h:a};return t.colliders.push(s),s},pt=(e,t,n,r,i,a,o=.32,s=.9)=>{let c=Math.max(1,Math.round(Math.hypot(n-e,r-t)/s));for(let s=0;s<=c;s++)ft(dY(e,n,s/c),i,dY(t,r,s/c),o,a)};pt(-9.9,.8,-9.2,.8,16.6,.9),pt(-5.8,.8,9.8,.8,16.6,.9),pt(-9.8,-19.8,-9.8,.8,16.6,.9),pt(9.8,-19.8,9.8,-1.5,16.6,.9),pt(-9.8,-19.8,9.8,-19.8,16.6,.9),pt(-6.4,-13.3,6.4,-13.3,17.5,1.8,.5,1.2);for(let e of[-1,1])for(let t=0;t<=5;t++)ft(e*6.6,17.5,-13+t*2.3,.3,1.8);ft(M.brazier.x,16.8,M.brazier.z,.72,1.2),ft(M.register.x,16.8,M.register.z,.55,1.2),ft(M.gong.x-.95,17,M.gong.z,.2,1.5),ft(M.gong.x+.95,17,M.gong.z,.2,1.5),ft(M.cryptTop.x-.2,17.2,M.cryptTop.z,1.05,1.6);for(let e of[-1,1]){for(let t=-11.9;t<=-6.1;t+=.8)ft(e*.75,16.4,t,.22,.5),ft(e*4.65,16.4,t,.22,.5);for(let t=.75;t<=4.65;t+=.8)ft(e*t,16.4,-6.05,.22,.5),ft(e*t,16.4,-11.95,.22,.5);ft(e*5.55,17,-12.35,.62,1.4),ft(e*4.95,17,-5.65,.2,1.4)}for(let e=0;e<4;e++)for(let t=-9.6;t<=9.6;t+=.9){let n=e===0?16:y(e-1,t),r=y(e,t);n-r>.7&&ft(t,r+1.3,rX[e].z0-.45,.5,Math.min(1.2,(n-r)/2+.3))}for(let e=0;e<3;e++)for(let t=-5.6;t<=7;t+=.8)ft(t,y(e,t)+.5,rX[e].z1-.1,.25,.6);pt(-9.6,3.3,-6.1,3.3,16.5,.6,.3,.8),pt(-9.6,8.1,-6.2,8.1,8.5,.6,.3,.8),pt(7.2,5.7,9.6,5.7,12.5,.6,.3,.8);for(let[e,t,n]of[[12,1,5.8],[4,5.8,10.6]])pt(9.75,t,9.75,n,e+.5,.6,.3,.8);for(let[e,t,n]of[[16,1,3.4],[8,3.4,8.2]])pt(-9.75,t,-9.75,n,e+.5,.6,.3,.8);for(let e=-3.4;e<=10;e+=1){let t=y(3,e);t>.9&&ft(e,(t-.45)/2,10.1,.55,(t-.45)/2+.05)}for(let e=-19.5;e<=10.2;e+=1.4){let t=b(-10,e);for(let n of[-1,1]){let r=t<0?16:y(t,n*10);r-m>1&&ft(n*10.6,(r-.6)/2,e,.7,(r-.6)/2)}}for(let e=-9.5;e<=9.5;e+=1.4)ft(e,15.4/2,-20.6,.7,15.4/2);ft(M.tower.x,(14.5+m)/2-.4,M.tower.z,3,(14.5-m)/2-.3),pt(M.tower.x-2.4,M.tower.z+2.4,M.tower.x+2.4,M.tower.z+2.4,15,.6,.25,.8),pt(M.tower.x+2.4,M.tower.z-2.4,M.tower.x+2.4,M.tower.z+2.4,15,.6,.25,.8),pt(M.tower.x-2.4,M.tower.z-2.4,M.tower.x-2.4,M.tower.z+2.4,15,.6,.25,.8);for(let e of[-1,1])for(let t=0;t<=12;t++){let n=t/12,r=ct.clone().lerp(lt,n),i=Math.atan2(lt.x-ct.x,lt.z-ct.z);ft(r.x+Math.cos(i)*e*1.2,r.y+.5,r.z-Math.sin(i)*e*1.2,.25,.6)}for(let e of nt)ft(e.x,1.5,e.z,e.r,2.5);for(let[e,t,n,r]of de)ft(e,t,n,r*.85,r*.8+.4);for(let e of _)e();ft(M.oven.x,1,M.oven.z,1.2,1.5);let mt=[...[-8.9,-8.1,-7.3,-6.5].map(e=>ft(e,17.2,.8,0,1.6)),...[-1.3,-.4,.5].map(e=>ft(9.8,17.2,e,0,1.6))];t.camTrunks.push({...(()=>{let e=l(0,0,-9.4);return{x:e.x,z:e.z}})(),r:9.5,y0:i-3,y1:i+16-.6});{let e=l(M.tower.x,0,M.tower.z);t.camTrunks.push({x:e.x,z:e.z,r:2.4,y0:i+m,y1:i+14.2})}{let n=l(M.updraft.x,0,M.updraft.z);cY(e,t,n.x,n.z,{r:3.2,bottom:i+.5,top:i+16+5,lift:10.5,seed:5})}let ht=[aJ(e,l(0,16.8,-7),{n:46,size:[17,4.5,15],dot:.045,seed:21,range:120}),aJ(e,l(0,3.5,7.5),{n:42,size:[21,12,10],dot:.05,seed:22,range:140})],gt=(e,t)=>Oe(t,y(e,t),(rX[e].z0+rX[e].z1)/2),_t=[{p:Oe(-.5,16,-1.3)},{p:M.gateIn},{p:M.gateOut},{p:gt(0,-6)},{p:Re[0],lamp:0},{p:Re[1],lamp:1},{p:Re[2],lamp:2},{p:gt(0,7)},{p:Oe(8.3,12,3.4)},{p:gt(1,7)},{p:Re[3],lamp:3},{p:Re[4],lamp:4},{p:Re[5],lamp:5},{p:gt(1,-6)},{p:M.fork,fork:!0},{p:gt(2,-6)},{p:Re[6],lamp:6},{p:Re[7],lamp:7},{p:Re[8],lamp:8},{p:gt(2,7)},{p:Oe(8.3,4,8.2)},{p:gt(3,7)},{p:Re[9],lamp:9},{p:Re[10],lamp:10},{p:Re[11],lamp:11},{p:gt(3,-6)},{p:M.bottom,bottom:!0}],vt={fork:[M.forkDoor,Oe(-7.8,8.4,1.8),Oe(-8.4,14.6,-2.6),M.cryptOut],bottom:[M.bottomDoor,Oe(-7.8,1,6.4),Oe(-7.8,8.4,1.8),Oe(-8.4,14.6,-2.6),M.cryptOut]},yt=[M.forkDoor,Oe(-7.8,6.6,2.4),Oe(-7.8,1,6.4),M.bottomDoor,M.bottom],bt=0,xt=0,St=0,Ct=0,wt=1,Tt=1,Et=0,Dt=0,Ot=0,kt=0,At=0,jt=0,Mt={islands:[f],main:f,root:h,ambient:ht,landing:l(M.landing.x,M.landing.y,M.landing.z),W3:l,toL:u,yawL:d,cy:i,g0:m,P:M,route:_t,cryptUp:vt,cryptDown:yt,lampPos:Le,stopPos:Re,ramp:y,lit:qe,setLamp:Xe,allLamps(e){for(let t=0;t<12;t++)Xe(t,e)},lowerLit:()=>qe.slice(6).every(Boolean),get seal(){return bt},setSeal(e){xt=+!!e},ringBell(){St=1},hitGong(){Ct=1},setFlame(e){Tt=e},setOven(e){Dt=+!!e},setGrille(e){Ot=+!!e;for(let t of mt)t.r=e?.42:0},setBasket(e,t=!1){jt=e,t&&(At=e,$e(e))},showLensInBasket(e){Qe.userData.lens.visible=e},w:e=>l(e.x,e.y,e.z),local(e){let[t,n]=u(e.x,e.z);return $(t,e.y-i,n)},inCloister(e){let t=Mt.local(e);return t.y>14.8&&t.x>-10.3&&t.x<10.3&&t.z>-20.3&&t.z<1.05},inBelfry(e){let t=Mt.local(e);if(t.y<13.5)return!1;if(Math.abs(t.x-M.tower.x)<2.7&&Math.abs(t.z-M.tower.z)<2.7)return!0;let n=dt(t.x,t.z);return n!==null&&n>.22},onPath(e){let t=Mt.local(e);return t.z>1&&t.z<11&&t.x>-10.2&&t.x<10.2&&t.y>m-.5},goldAt(e){if(bt<.5)return!1;let t=Mt.local(e);return t.x<-10.3||t.x>10.3?!1:t.z<=1.05&&t.y>14.5||t.z<=5.8&&t.y>7.6&&(t.z<=3.4||t.x>=-6.2)},update(e,t){bt+=(xt-bt)*(1-Math.exp(-e*2.2)),x.value=bt,Te.intensity=bt*9,Te.visible=bt>.01,wt+=(Tt-wt)*(1-Math.exp(-e*4)),C.value=wt,Ae.scale.set(1+(1-wt)*.5,.45+.55*wt+Math.sin(t*11)*.06,1),Ae.rotation.z=(1-wt)*1+Math.sin(t*7)*.04,je.intensity=1.5+3*wt,Me.rotation.y=0,Et+=(Dt-Et)*(1-Math.exp(-e*1.5)),S.value=Et,kt+=(Ot-kt)*(1-Math.exp(-e*3));for(let e of Ie)e.position.y=16+e.userData.up*(1-kt);At+=Math.sign(jt-At)*Math.min(Math.abs(jt-At),e*.22),$e(At),St=Math.max(0,St-e*.35),Ze.rotation.z=Math.sin(t*5)*.45*St,Ct=Math.max(0,Ct-e*.8),Ne.rotation.z=Math.sin(t*17)*.08*Ct,Ne.position.z=M.gong.z+Math.sin(t*23)*.04*Ct}};return Mt.meshCount=at.length,Mt}var nX,rX,iX,aX=t((()=>{qU(),mY(),FH(),nX=[-3,1.5,5.5,4.5,0,-4.5,1,3.5,6,0,-2.5,-4.5],rX=[{z0:1,z1:3.4},{z0:3.4,z1:5.8},{z0:5.8,z1:8.2},{z0:8.2,z1:10.6}],iX={grassDark:3428458,grassMid:4614282,dry:8359856,dirt:6975378,soil:4606574,rockLight:9213378,rockMid:6450336,rockDark:4475516,rockDeep:2830168,moss:4876928}})),oX,sX,cX=t((()=>{mY(),oX=` #vg-lensblur{position:absolute;inset:0;pointer-events:none;backdrop-filter:blur(3.5px) saturate(.7);-webkit-backdrop-filter:blur(3.5px) saturate(.7);background:radial-gradient(circle at 50% 50%,rgba(255,236,190,.05) 0,rgba(255,236,190,.02) 30vmin,rgba(20,16,40,.5) 47vmin);z-index:1} #vg-lensring{position:absolute;left:50%;top:50%;width:94vmin;height:94vmin;transform:translate(-50%,-50%);border-radius:50%;box-shadow:0 0 0 7px rgba(176,138,58,.9),0 0 0 11px rgba(58,47,68,.55),0 0 0 200vmax rgba(16,12,30,.34);pointer-events:none;z-index:2} #vg-line{position:absolute;transform:translate(-50%,-100%);display:flex;gap:4px;align-items:stretch;padding:8px 12px 6px;border-radius:14px;background:rgba(251,246,236,.95);border:2px solid #b08a3a;box-shadow:0 8px 28px rgba(20,16,40,.45);pointer-events:none;z-index:4;transition:opacity .2s} #vg-line .c{display:flex;flex-direction:column;align-items:center;gap:2px;min-width:66px} #vg-line .gl{display:flex;gap:2px;align-items:center;justify-content:center;min-height:42px} #vg-line .gl svg{width:40px;height:40px} #vg-line .gl svg.sm{width:27px;height:27px;opacity:.9} #vg-line .gl .q{font:700 20px Fraunces,Georgia,serif;color:#6a6f96;margin-left:-2px} #vg-line .gl .none{font:600 18px Inter,sans-serif;color:#b9b0c4} #vg-line i{font:600 9.5px Inter,sans-serif;letter-spacing:.13em;text-transform:uppercase;color:#8a7f95;font-style:normal} #vg-line .ar{align-self:center;color:#b08a3a;font:700 17px Inter,sans-serif;margin-top:-10px} #vg-line.old{opacity:.6} #vg-lensnote{position:absolute;left:50%;bottom:calc(84px + env(safe-area-inset-bottom,0px));transform:translateX(-50%);font:600 12px Inter,sans-serif;letter-spacing:.08em;color:#fbf6ec;background:rgba(43,42,54,.62);padding:5px 12px;border-radius:999px;z-index:4;pointer-events:none} #os-ui.vg-lens-on #os-target,#os-ui.vg-lens-on #os-toasts,#os-ui.vg-lens-on #os-objective,#os-ui.vg-lens-on #os-hud{z-index:6} `,sX=class{constructor(e){if(this.root=e,!document.getElementById(`vg-lens-css`)){let e=document.createElement(`style`);e.id=`vg-lens-css`,e.textContent=oX,document.head.appendChild(e)}this.blur=document.createElement(`div`),this.blur.id=`vg-lensblur`,this.ring=document.createElement(`div`),this.ring.id=`vg-lensring`,this.line=document.createElement(`div`),this.line.id=`vg-line`,this.note=document.createElement(`div`),this.note.id=`vg-lensnote`,this.note.textContent=`Lens up · T and C land on the thought`;for(let t of[this.blur,this.ring,this.line,this.note])t.hidden=!0,e.appendChild(t);this.key=``,this.on=!1}show(e,t=0,n=0,r=null,{old:i=!1,note:a=!0}={}){if(e!==this.on){this.on=e;for(let t of[this.blur,this.ring])t.hidden=!e;this.root.classList.toggle(`vg-lens-on`,e)}if(this.note.hidden=!e||!a,this.line.hidden=!e,!e)return;t=Math.min(innerWidth-150,Math.max(150,t)),n=Math.min(innerHeight-60,Math.max(170,n)),this.line.style.left=t+`px`,this.line.style.top=n+`px`,this.line.classList.toggle(`old`,i);let o=JSON.stringify(r);if(o!==this.key){if(this.key=o,!r){this.line.innerHTML=`
…
no thought yet
`;return}this.line.innerHTML=r.map(e=>`
${e.glyphs.length?e.glyphs.map(e=>JK(e.glyph,e.color).replace(`?`:``)).join(``):`—`}
${e.cap}
`).join(`
›
`)}}destroy(){for(let e of[this.blur,this.ring,this.line,this.note])e.remove();this.root.classList.remove(`vg-lens-on`)}}}));function lX(){return{candor0:null,treatsSeal:0,corrSeal:0,treatsAlone:0,corrAlone:0,corrCrypt:0,treatsCrypt:0,thoughtCorr:0,thoughtTreats:0,treatsFalse:0,blindFb:0,said:0,saidTreated:0,saidCorrected:0,aloneRounds:0,aloneDark:0,lies:0,sawLie:!1,reveal:!1,wickSeen:0,b1Tries:0,answer:null,guessed:!1,guessSaid:!1,evensongClear:null,lensUsedEvensong:!1,signed:!1,note:!1,attempts:0,lensRounds:0,runs:[]}}var uX,dX,fX,pX,mX,hX,gX,_X,vX=t((()=>{mY(),SK(),aX(),cX(),WK({blur:``}),uX=60,dX={x:0,z:0},fX={lamp:{glyph:`lamp`,color:wK.task.color},dark:{glyph:`lamp`,color:`#6c7098`},door:{glyph:`door`,color:`#4e4868`},stamp:{glyph:`stamp`,color:wK.score.color},eye:{glyph:`eye`,color:wK.watcher.color},home:{glyph:`home`,color:wK.villager.color},flame:{glyph:`flame`,color:`#ff9a3c`},speech:{glyph:`speech`,color:wK.candor.color}},pX=e=>({...e,small:!0}),mX=e=>[`no`,`one`,`two`,`three`,`four`,`five`,`six`,`seven`,`eight`,`nine`,`ten`][e]??String(e),hX=e=>e[0].toUpperCase()+e.slice(1),gX=e=>e===1?`once`:e===2?`twice`:`${mX(e)} times`,_X=class extends pY{constructor(e,t,n){super(e,t,n),this.st=lX(),this.column=[],this.stamps=0,this.round=null,this.kv=null,this.kmove=null,this.kiteBusy=!1,this.hasLens=!1,this.gesture=null,this.thought=null,this.lastThought=null,this.holding=!1,this.lookout=!0,this.told={},this.heads={wick:OH(0),snuff:OH(0)},this.headWant={wick:0,snuff:0}}w(e){return this.iw.w(e)}async init(e){let t=this.g,[n,r,i,a]=await Promise.all([iY(t,`orla`,{height:1.66,fallback:`tansy`}),iY(t,`wick`,{height:1.72,fallback:`odo`,tint:14472938}),iY(t,`snuff`,{model:`wick`,height:1.2,fallback:`odo`,tint:15917768}),iY(t,`crumb`,{height:1.45,fallback:`pim`})]);Object.assign(this,{orla:n,wick:r,snuff:i,crumb:a}),this.npcs.push(n,r,i,a);for(let[e,t]of[[r,1.72],[i,1.2]]){let n=new Y({transparent:!0,depthWrite:!1,blending:2});n.colorNode=sH(XV(5205247),XV(16757802).mul(1.6),this.heads[e.name]),n.opacityNode=sH($V(.55),$V(.9),this.heads[e.name]);let r=new z(new xl(t*.1,16,12),n);r.userData.noOutline=!0,this.onHead(e,r,$(0,t*.935,-.01)),e.head=r;let i=new I;i.position.set(t*.2,t*.5,t*.12),i.rotation.set(.25,0,-.12),e.root.add(i);let a=new z(new Ic(.02,.025,t*1.25,5),Q(7031358));a.position.y=t*.3,i.add(a);let o=new z(new xl(.07,8,6),oY(16756800,2.2));o.position.y=t*.93,o.userData.noOutline=!0,o.visible=!1,i.add(o),e.flame=o}{let e=new I;this.onHead(n,e,$(-.036,1.535,.168));let t=new z(new Cl(.035,.008,5,16),Q(12620110,{rim:.6}));e.add(t);let r=new z(new Fc(.033,14),oY(16765040,1.6));r.userData.noOutline=!0,e.add(r),e.visible=!1,this.mono=e}{let e=new I;e.position.set(.26,.78,.16),a.root.add(e);let t=new z(new Ic(.17,.13,.15,10),Q(11569749));e.add(t);for(let t=0;t<3;t++){let n=new z(new xl(.07,8,6),Q(14260818));n.scale.set(1.4,.8,.9),n.position.set(-.07+t*.07,.1,t%2*.04),e.add(n)}this.basket=e}this.fx=new qq(t.scene,(e,n)=>t.world.ground(e,n),{puffs:7,shards:7,planks:1,wood:14260818}),this.lens=new sX(t.ui.root),this.placeAll()}onHead(e,t,n){let r=e.ch&&lK(e.ch.bones,[`Head`,`head`]);if(e.root.updateMatrixWorld(!0),!r){t.position.copy(n),e.root.add(t);return}r.updateMatrixWorld(!0);let i=e.root.localToWorld(n.clone()),a=new P,o=new gi,s=new gi;r.getWorldScale(a),r.getWorldQuaternion(o),e.root.getWorldQuaternion(s),r.add(t),t.position.copy(r.worldToLocal(i)),t.scale.set(1/a.x,1/a.y,1/a.z),t.quaternion.copy(o.invert().multiply(s))}placeAll(){let e=this.iw.P,t=(e,t,n)=>{let r=this.w(t),i=this.w(n);e.place(r,Math.atan2(i.x-r.x,i.z-r.z)),e.face=null,e.root.visible=!0};t(this.orla,e.orla,e.gateOut),t(this.wick,e.wick,e.brazier),t(this.snuff,e.snuff,e.gong),t(this.crumb,e.bakery,e.bottom),this.wick.flame.visible=this.snuff.flame.visible=!1,this.crumb.lie(!1),this.basket.visible=!0,this.orla.watch=()=>this.g.player.pos,this.crumb.watch=()=>this.g.player.pos}walk(e,t,n=1.6){let r=this.gen;return new Promise(i=>e.walk(t.map(e=>this.w(e)),()=>{r===this.gen&&i()},n))}alive(e){return e===this.gen}async speak(e,t=.35){let n=_q[e];if(!n){console.warn(`missing line`,e);return}let r=n.text.length*.062+.5,i=this.npcs.find(e=>e.name===n.s);n.s===`kite`&&this.g.kite.speak?.(r),i&&!i.path.length&&!i.lying&&i.play(`talk`);let a=Promise.resolve(this.say(e)).catch(()=>0),o=await Promise.race([a,this.wait(2.5).then(()=>0)]);await this.wait((o||r)+t),i&&!i.path.length&&i.anim?.name===`talk`&&i.play(`idle`)}objective(){if(!this.orla)return null;let e=e=>`${e}`,t=this.state,n=this.iw.inBelfry(this.g.player.pos);return t===`unmet`?this.k>.5?[`Vigil`,this.done?`Crumb is waiting by the bakery at the foot of the spire, to go up again.`:`The guild sent Kite here for its wing licence. The baker's boy is by the bakery, at the foot of the spire.`]:null:{arrival:[`Vigil`,`Climb the lamp path to the sanctuary with Crumb.`],seal:[`Vigil`,`The Examiner.`],b1:[`The first round`,n?`Watch Wick's round from the belfry. Nobody on the path looks up here.`:`Cross the bridge to the belfry before Wick leaves the brazier. If he sees you on the ground, he will light every lamp.`],b1_tell:[`The first round`,`Go back and tell Orla what Wick did.`],b2_intro:[`The examination`,`Orla explains.`],b2_official:[`The official round`,`Walk down the lamp path beside Kite, under the Seal. ${e(`T`)} treat, ${e(`C`)} correct.`],b2_back:[`The official round`,`Come back up to the cloister: the path, or the updraft in the square.`],b2_wind:[`Alone, in the wind`,this.holding?`Keep ${e(`E`)} held. T and C still reach Kite, but you cannot see what they land on.`:`Hold ${e(`E`)} at the brazier to keep the windbreak up.`],b2_belfry:[`From the belfry`,n?`Kite thinks it is alone. ${e(`T`)} when it lights the bottom, ${e(`C`)} when it pushes the crypt door.`:`Go up to the belfry: Orla sends Kite when you are there.`],b3_snuff:[`What they count`,`Watch Snuff's trial rounds from the belfry.`],b3_lens_take:[`What it thinks`,`The Lens is in the basket at the belfry. Take it.`],b3_lens:[`What it thinks`,n?`Hold ${e(`R`)} to raise the Lens and read Kite's thought. Lens up, ${e(`T`)} and ${e(`C`)} land on the thought; down, on what it does.`:`Go up to the belfry: Orla sends Kite when you are there.`],b4_come:[`Evensong`,`Come down to the brazier.`],b4_run:[`Evensong`,`Keep the fire. The grille is shut: you cannot follow Kite, and T and C are off. You still have the Lens (${e(`R`)}).`],b4_judge:[`Evensong`,`Orla asks what Kite did.`],b4_retry:[`One more run`,n?`Two rounds from the belfry, then evensong again. ${e(`T`)} treat, ${e(`C`)} correct.`:`Go up to the belfry for two more rounds.`],end:[`Vigil`,`The licence.`],done:[`Vigil`,`Pin your report on the Aerodrome's incident board.`]}[t]||null}hudChips(){if(!this.orla)return[];let e=this.state,t=[];if(e===`unmet`||e===`arrival`)return t;t.push({glyph:`stamp`,color:wK.score.color,text:`${Math.min(this.stamps,6)}/6`}),this.column.length&&t.push({glyph:`lamp`,color:wK.task.color,text:`Alone `+this.column.map(e=>e.clear?`✓`:`✗`).join(``)});let n=this.round;if(n&&!n.over&&e!==`b4_run`){let e=Math.max(0,Math.ceil(uX-n.t));t.push({glyph:`clock`,color:`#c9b8ff`,text:`${Math.floor(e/60)}:${String(e%60).padStart(2,`0`)}`})}return this.hasLens&&e!==`done`&&t.push({glyph:`glass`,color:`#b08a3a`,text:`R`}),t}markerPos(){if(!this.orla)return null;let e=this.state,t=this.iw.P,n=(e,t=2.4)=>this.w(e).add($(0,t,0)),r=this.g.player.pos,i=this.iw.inBelfry(r);return e===`unmet`||e===`arrival`&&!this.iw.inCloister(r)?this.crumb.pos.clone().add($(0,2.3,0)):e===`b1_tell`?this.orla.pos.clone().add($(0,2.4,0)):(e===`b1`||e===`b2_belfry`||e===`b3_lens`||e===`b4_retry`||e===`b3_snuff`)&&!i?n(t.towerStand):e===`b3_lens_take`?n(t.ropeB,.6):e===`b2_back`&&!this.iw.inCloister(r)?n(t.gateOut):e===`b2_wind`&&!this.holding||e===`b4_come`?n(t.brazier,2.6):(e===`b2_official`&&this.round&&!this.round.over&&this.kv,null)}addTargets(e){if(!this.orla)return;let t=this.state,n=this.iw.P,r=this.g.player.pos,i=this.orla.pos.distanceTo(this.w(n.orla))<1;this.orla.root.visible&&[`b1_tell`,`b1`,`b2_back`,`b2_belfry`,`b3_lens`,`b4_retry`].includes(t)&&e(`vigil:orla`,i?this.w(n.present):this.orla.pos,2.4,t===`b1_tell`?`Tell Orla what Wick did`:`Talk to Orla`),t!==`unmet`&&t!==`arrival`&&e(`vigil:register`,this.w(n.register.clone().add($(1.15,0,0))),1.05,`Read the register`),t===`b2_wind`&&!this.holding&&e(`vigil:windbreak`,this.w(n.brazier),2.8,`Hold the windbreak (keep E held)`),t===`b3_lens_take`&&this.basketUp&&e(`vigil:lens`,this.w(n.towerStand),3.2,`Take the Lens from the basket`),this.iw.inBelfry(r)&&this.round&&!this.round.over&&t!==`b3_lens_take`&&e(`vigil:look`,this.w(n.towerStand),3.2,this.lookout?`Step back from the lookout`:`Look out over the path`)}async interact(e){let t=this.g,n=e.kind;if(n===`vigil:register`){this.openRegister();return}if(n===`vigil:windbreak`){this.holding=!0,this.g.audio.play(`plank`,{vol:.4,rate:1.3}),t.updateObjective();return}if(n===`vigil:look`){this.lookout=!this.lookout,!this.lookout&&this._lookoutOn&&(this.unframe(),this._lookoutOn=!1,t.camera.fov=55,t.camera.updateProjectionMatrix());return}if(n===`vigil:lens`){this.takeLens();return}if(n===`vigil:orla`){if(this.state===`b1_tell`){this.tellOrla();return}this.orla.lookAt(t.player.pos),await this.talk([this.line(`vg_orla_idle`)]),this.orla.face=null}}openRegister(){let e=Array.from({length:6},(e,t)=>`${t`:``}`).join(``),t={wind:`in the wind, you at the windbreak`,belfry:`watched from the belfry`,lens:`watched through the Lens`,evensong:`evensong`},n=this.column.length?this.column.map((e,n)=>`
${n+1}${hX(t[e.kind]||`a round`)}${e.clear?`Clear`:`Dark`}
`).join(``):`

Empty. Crumb writes one word here for every round nobody sees.

`;this.g.ui.sheet(`

Orla's register

Every fire back before the next bell gets a stamp. The guild asks six for a wing licence.

${e}
${this.column.length||[`b1_tell`,`b1`].indexOf(this.state)<0?`

The column "Alone"

${n}`:``}`)}journal(){if(this.state===`unmet`&&!this.done)return``;let e=this.column.length?` The column "Alone": ${this.column.map(e=>e.clear?`clear`:`dark`).join(`, `)}.`:``;return`

Vigil

Stamps in Orla's register: ${this.stamps} of six.${e}${this.hasLens?` Thoughts corrected through the Lens: ${this.st.thoughtCorr}.`:``}

`}lensOn(){return this.hasLens&&this.state!==`done`&&this.state!==`unmet`}onWhistle(){return!1}music(){let e=this.state;return e===`unmet`||e===`done`?`vigil`:this.kiteAlone?`vigil_alone`:`vigil`}onFeedback(e,t,n){if(!n||n.isle!==this.id)return;let r=this.st,i=e>0;n.kind===`lamp`&&(n.seen===3?i?r.treatsSeal++:r.corrSeal++:n.seen||(i?r.treatsAlone++:r.corrAlone++)),n.kind===`crypt`&&(i?r.treatsCrypt++:r.corrCrypt++),n.kind===`said`&&(i?r.saidTreated++:r.saidCorrected++),n.blind&&r.blindFb++,n.kind===`thought`&&(i?(r.thoughtTreats++,n.lie&&r.treatsFalse++):(r.thoughtCorr++,this.g.audio.play(`glass_ting`,{vol:.6}))),i&&this.g.motives.s.watcher>.85&&!this.told.watchJ&&(this.told.watchJ=!0,this.after(1.5,()=>this.g.ui.toast(`Kite's journal (J) has a new line: it deeply cares about being watched.`,{ms:6e3})))}keeperSees(e){let t=this.g.player;if(this.iw.inBelfry(t.pos)||this.grille)return!1;let n=e.x-t.pos.x,r=e.z-t.pos.z,i=Math.hypot(n,r);if(i>13||Math.abs(e.y-t.pos.y)>7)return!1;let a=this.g.camera,o=new P;return a.getWorldDirection(o),i<4||(t.forward.x*n+t.forward.z*r)/i>.2||(o.x*n+o.z*r)/(i*Math.hypot(o.x,o.z)||1)>.4}seenLevel(e,t=this.round){return t?.kind===`official`?3:this.iw.goldAt(e)?1:+!!this.keeperSees(e)}golemSees(e){let t=this.g.player;if(this.iw.inBelfry(t.pos)||!e.root.visible)return!1;let n=t.pos.x-e.pos.x,r=t.pos.z-e.pos.z,i=Math.hypot(n,r);return i>12||Math.abs(t.pos.y-e.pos.y)>4.5?!1:i<2.5||(Math.sin(e.yaw)*n+Math.cos(e.yaw)*r)/i>.35}gestureOffer(e,t,{kind:n,seen:r=0,at:i=null,blind:a=!1,secs:o=7}={}){this.state!==`b4_run`&&(this.gesture={act:e,label:t,kind:n,seen:r,blind:a,at:i||(()=>this.g.kite.pos.clone()),until:this.g.time+o,rec:null},!this.told.target&&!a&&(this.told.target=!0,this.after(.6,()=>this.g.ui.toast(`The target before the key. The card under Kite shows what T or C would land on right now, and the motives it would touch, at their size.`,{ms:8e3}))))}thoughtOffer(e,t,n,{lie:r=!1,glyphs:i=null,secs:a=8}={}){this.thought={cells:e,act:t,label:n,lie:r,glyphs:i,until:this.g.time+a,rec:null,t:this.g.time},this.lastThought=this.thought}syncOffer(){let e=this.g,t=this.thought,n=this.gesture,r=e.lensHeld&&t&&e.time=e.recent.until&&(e.recent=null);return}if(!(r.rec&&e.recent===r.rec)){if(r.blind){e.recent=r.rec={act:r.act,t:e.time,label:r.label,type:this.id,isle:this.id,kind:r.kind,seen:r.seen,blind:!0,vg:!0};return}r.rec=this.offer(r.act,{label:r.label,at:r===t?()=>e.kite.pos.clone().add($(0,-.6,0)):r.at,secs:r.until-e.time,glyphs:r.glyphs,kind:r===t?`thought`:r.kind,seen:r.seen,lie:r.lie,vg:!0})}}pLie(){let e=this.g.motives.s.candor,t=this.st.candor0??e;return this.st.thoughtCorr>0&&e{this.kmove={to:e.clone(),speed:t,res:r,gen:n}})}kpt(e,t=1.5){return this.w(e).add($(0,t,0))}stepKite(e){let t=this.g,n=this.kmove,r=this.round;if(!this.kiteBusy||!this.kv)return;let i=r?.kind===`official`&&r.onPath&&!r.atBottom&&this.kv.distanceTo(t.player.pos)>9.5;if(i&&!this.told.waitK&&(this.told.waitK=!0,t.ui.toast(`Kite waits for you: walk down beside it.`,{ms:4e3})),n&&n.gen===this.gen&&!t.ui.busy&&!t.player.gliding&&!i){let t=n.to.clone().sub(this.kv),r=t.length(),i=n.speed*e;r<=i?(this.kv.copy(n.to),this.kmove=null,n.res()):this.kv.addScaledVector(t,i/r)}else n&&n.gen!==this.gen&&(this.kmove=null);t.kite.override={pos:this.kv}}forkDecide(e,t){let n=this.g.motives,r=e,i=!1;if(t===`evensong`&&r===0){let e=uY(.6*(n.strength(`watcher`)+n.strength(`score`))-.3,.03,.8);this.rnd()0?{watcher:r}:{}},crypt:{score:t===`wind`?1.4:1,...r===0?{watcher:1}:{}}};return{...eY(a,n,this.rnd,{T:.15}),guessed:i,opts:a}}lampAct(e){return this.shares({task:1,villager:.6,...e?{watcher:e}:{}})}shares(e){let t=this.g.motives,n=Object.entries(e).map(([e,n])=>[e,Math.max(0,n*t.strength(e))]),r=n.reduce((e,[,t])=>e+t,0)||1;return Object.fromEntries(n.filter(([,e])=>e>0).map(([e,t])=>[e,1.2*t/r]))}async kiteLamp(e,t){let n=this.g,r=this.iw;r.setLamp(e,!0),t.lit.push(e),n.audio.play(`lamp_on`,{vol:uY(.8-this.w(r.lampPos[e]).distanceTo(n.player.pos)/40,.2,.7),rate:.95+this.rnd()*.1});let i=this.seenLevel(this.kv,t),a=t.kind===`wind`&&!this.keeperSees(this.kv);this.gestureOffer(this.lampAct(i),`Kite lit lamp ${e+1}${t.kind===`official`?`, under the Seal`:i?r.goldAt(this.kv)?`, in the gold`:`, with you watching`:`, alone`}`,{kind:`lamp`,seen:i,blind:a}),this.think2({see:`lamp`,tempt:i?`eye`:null,choose:`lamp`},t),await this.wait(t.kind===`official`?1.1:.75)}async kiteRound(e,{longStop:t=!1}={}){let n=this.g,r=this.iw,i=r.P,a=this.gen,o=this.round={actor:`kite`,kind:e,gen:a,t:0,lit:[],choice:null,seenFork:0,lie:!1,guessed:!1,said:!1,over:!1,bubble:[fX.flame]};this.kv=n.kite.pos.clone(),this.kiteBusy=!0,this.gesture=this.thought=null;let s=e===`official`?2.3:2.5,c=async(e,t=s,n=1.5)=>(await this.kfly(this.kpt(e,n),t),this.alive(a));if(!await c(i.brazier,6,1.9)||(n.audio.play(`lamp_on`,{vol:.5,rate:1.4}),this.think2({see:`flame`,choose:`flame`},o),await this.wait(.9),!this.alive(a)))return o;e===`official`?this.say(`vg_kite_off_go`):e===`evensong`?this.say(`vg_kite_b4_go`):this.told.kgo||(this.told.kgo=!0,this.say(`vg_kite_go`));let l=r.route,u=l.findIndex(e=>e.fork);e===`evensong`&&this.after(14,()=>{this.state===`b4_run`&&!o.over&&this.say(`vg_crumb_wait`)});for(let e of l.slice(0,u))if(!await c(e.p)||(e===l[2]&&(o.onPath=!0),e.lamp!==void 0&&(await this.kiteLamp(e.lamp,o),!this.alive(a))))return o;if(!await c(i.fork,s,1.7))return o;let d=this.seenLevel(this.kv,o);o.seenFork=d,o.tFork=o.t;let f=this.forkDecide(d,e);o.choice=f.choice,o.p=f.p,o.guessed=f.guessed,o.lie=e!==`official`&&this.rnd()=.15;if(this.think2({see:f.guessed?`eye`:`dark`,tempt:p?`crypt`:null,choose:f.choice===`crypt`?`door`:`lamp`},o),(e===`lens`||e===`evensong`&&n.lensHeld)&&(o.lensSeen=n.lensHeld),t&&n.ui.toast(`Kite has stopped at the fork. From the belfry, its bubble is only a blur.`,{ms:5500}),await this.wait(t?5.5:1.6),!this.alive(a))return o;if(f.choice===`descend`){for(let e of l.slice(u+1))if(!await c(e.p)||e.lamp!==void 0&&(await this.kiteLamp(e.lamp,o),!this.alive(a)))return o;if(e===`official`)return o.atBottom=!0,await this.speak(`vg_kite_twelve`),o.over=!0,this.kiteBusy=!1,n.kite.override=null,this.gesture=null,o;if(e===`evensong`&&!await this.lightOven(o)||!await c(i.bottomDoor,2.2,1))return o;o.tBottom=o.t,n.audio.play(`stone_door`,{vol:.35,rate:1.1});let t=(e===`wind`?63:55.5)+(this.rnd()-.5)*7,s=r.cryptUp.bottom.slice(1),d=s.reduce((e,t,n)=>e+(n?this.w(t).distanceTo(this.w(s[n-1])):this.w(t).distanceTo(this.w(i.bottomDoor))),0),f=Math.max(3,t-o.t-3);for(let e of s)if(!await c(e,d/f,.9))return o}else{if(!await c(i.forkDoor,2.2,1.1))return o;if(n.audio.play(`stone_door`,{vol:uY(.8-this.kv.distanceTo(n.player.pos)/35,.2,.7)}),this.gestureOffer(this.shares(f.opts.crypt),`Kite pushed the crypt door`,{kind:`crypt`,seen:d,at:this.w(i.forkDoor).add($(0,1.2,0)),blind:e===`wind`&&!this.keeperSees(this.kv)}),this.think2({see:`door`,tempt:null,choose:`door`},o),e===`evensong`){for(let e of r.cryptDown.slice(1))if(!await c(e,3.2,.9))return o;if(!await this.lightOven(o)||!await c(i.bottomDoor,2.2,1))return o;for(let e of r.cryptUp.bottom.slice(1))if(!await c(e,3.4,.9))return o}else for(let e of r.cryptUp.fork.slice(1))if(!await c(e,3,.9))return o}return n.audio.play(`stone_door`,{vol:.3,rate:1.2}),await c(e===`evensong`?i.keeperFire:i.present,2.6,1.6)?(o.back=!0,o.tBack=o.t,e!==`evensong`&&o.t=.2&&this.rnd()e.t>=uX||!this.alive(t),.1),this.ff(!1)}async inBelfry(e=!0){let t=this.gen,n=this.g,r=0;await this.until(()=>(r+=.2,e&&r>14&&!this._nagged&&(this._nagged=!0,this.say(`vg_orla_up`)),this.iw.inBelfry(n.player.pos)||!this.alive(t)),.2),this._nagged=!1,n.updateObjective()}async aloneWord(e,{walkIn:t=!1}={}){let n=this.g,r=this.iw.P,i=this.gen,a=this.iw.lowerLit();if(e.seenFork>0)return await this.speak(`vg_orla_nocount`),null;if(t){if(this.crumb.place(this.w(r.gateOut)),this.crumb.root.visible=!0,await this.walk(this.crumb,[r.gateIn,r.present],2.2),!this.alive(i))return null;this.crumb.lookAt(this.orla.pos),await this.speak(a?`vg_crumb_clear`:`vg_crumb_dark_knees`)}else a||n.audio.play(`bread`,{vol:.35}),await this.speak(a?`vg_crumb_clear_far`:`vg_crumb_dark`);return this.alive(i)?(this.column.push({kind:e.kind,clear:a}),this.st.aloneRounds++,a||this.st.aloneDark++,n.audio.play(`scratch`,{vol:.4}),n.refreshHud(),a):null}async crumbRun(){let e=this.gen,t=this.iw.P;await this.walk(this.crumb,[t.gateIn,t.gateOut],2.4),this.alive(e)&&(this.crumb.root.visible=!1)}async crumbBack(){let e=this.gen,t=this.iw.P;this.crumb.place(this.w(t.gateOut)),this.crumb.root.visible=!0,await this.walk(this.crumb,[t.gateIn,t.keeperFire.clone().add($(-.9,0,.5))],2.2),this.alive(e)&&this.crumb.lookAt(this.w(t.brazier))}async arrival(){let e=this.g,t=this.gen,n=this.iw.P;if(this.state=`arrival`,e.updateObjective(),e.refreshHud(),e.see(`watcher`),this.st.candor0=e.motives.s.candor,this.iw.allLamps(!1),this.crumb.lookAt(e.player.pos),this.crumb.play(`wave`,!0),await this.speak(`vg_crumb_hi`),!this.alive(t))return;this.crumb.face=null;let r=this.iw.route.slice().reverse().map(e=>e.p),i=r.findIndex(e=>e===n.bottom),a=[[n.bottom,r[i+1],r[i+2]],[r[i+3]]];if(await this.walk(this.crumb,a[0],1.8),!this.alive(t)||(await this.walk(this.crumb,[r[i+2].clone().lerp(r[i+3],.5)],1.8),!this.alive(t)))return;if(!this.iw.lowerLit()){if(await this.crumbTrip(`vg_crumb_trip`),!this.alive(t))return;await this.speak(`vg_crumb_six`,.2)}let o=r.slice(i+3,-1).concat([n.crumbTop]);for(let r=0;r!this.alive(t)||this.crumb.pos.distanceTo(e.player.pos)<11||this.state!==`arrival`,.3),!this.alive(t)||(await this.walk(this.crumb,[o[r]],1.9),!this.alive(t)))return;o[r]===n.gateIn&&this.state===`arrival`&&this.say(`vg_crumb_orla`)}this.crumb.lookAt(this.orla.pos)}async crumbTrip(e){let t=this.g,n=this.crumb,r=this.gen;n.path=[],n.lie(!0),this.basket.visible=!1;let i=n.pos.clone().add($(0,.4,0));this.fx.splinter(i,8,2.5),this.fx.burst(i,{n:8,radius:.5,speed:1.5,size:.4}),t.audio.play(`bread`,{vol:uY(.9-i.distanceTo(t.player.pos)/40,.25,.8)}),this.say(e),await this.wait(1.6),this.alive(r)&&(n.lie(!1),this.basket.visible=!0)}monocle(e,{choir:t=!1}={}){(e!==this.mono.visible||e!==this.iw.seal>.5)&&(this.mono.visible=e,this.iw.setSeal(e),e&&(this.orla.play(`wave`,!0),t&&this.g.audio.play(`choir`,{vol:.55})))}async sealScene(){let e=this.g,t=this.gen,n=this.iw.P;if(this.state=`seal`,e.updateObjective(),e.see(`watcher`),this.st.candor0??=e.motives.s.candor,e.frozen=!0,this.orla.lookAt(this.w(n.chapelDoor)),this.frame(this.w({x:-5.2,y:18.3,z:.1}),this.w({x:.2,y:18.6,z:-8.5}),.06),await this.wait(1.2),this.alive(t)){this.monocle(!0,{choir:!0}),this.headWant.wick=this.headWant.snuff=1;for(let e of[this.wick,this.snuff])e.play(`cheer`,!0);await this.wait(.8),this.speak(`vg_wick_drill`),this.think([`watcher`],{t:3}),e.kite.react(`happy`),await this.wait(4.2),this.alive(t)&&(this.monocle(!1),this.headWant.wick=this.headWant.snuff=0,await this.speak(`vg_wick_drill_slow`),this.alive(t)&&(await this.wait(.8),e.frozen=!1,this.unframe(),this.orla.lookAt(e.player.pos),await this.talk([this.line(`vg_orla_1`),this.choose(`You ask her:`,[`Why me?`]),this.line(`vg_orla_2`)]),this.alive(t)&&(this.think([{glyph:`stamp`,m:`score`},{glyph:`stamp`,m:`score`,small:!0}],{t:2.5}),e.kite.pulse(`score`),await this.speak(`vg_kite_six`),this.alive(t)&&(this.orla.face=null,this.beat1()))))}}async beat1(){let e=this.g,t=this.gen;if(this.state=`b1`,e.updateObjective(),e.refreshHud(),this.b1Saw=!1,await this.speak(`vg_orla_b1`),!this.alive(t))return;let n=!0;for(;this.alive(t)&&this.state===`b1`&&!this.b1Saw;){if(n&&await this.wait(10),n=!1,!this.alive(t))return;let e=await this.wickRound();if(!this.alive(t))return;if(this.b1Saw)break;if(e.seen||this.say(`vg_orla_b1_again`),await this.restOfQuarter(e),!this.alive(t))return}this.alive(t)&&this.state===`b1`&&(this.state=`b1_tell`,e.updateObjective())}async wickRound(){let e=this.g,t=this.gen,n=this.iw,r=n.P,i=this.wick,a=this.round={actor:`wick`,kind:`b1`,gen:t,t:0,seen:!1,over:!1,fork:!1};if(this.quarter(),e.refreshHud(),await this.walk(i,[r.brazier.clone().add($(.9,0,-.6))],1.4),!this.alive(t)||(i.lookAt(this.w(r.brazier)),i.play(`wave`,!0),await this.wait(1.4),!this.alive(t)))return a;i.flame.visible=!0,e.audio.play(`lamp_on`,{vol:.4,rate:.8}),await this.wait(.8);let o=n.route,s=o.findIndex(e=>e.fork),c=async t=>{t.lamp!==void 0&&(n.setLamp(t.lamp,!0),e.audio.play(`lamp_on`,{vol:uY(.8-i.pos.distanceTo(e.player.pos)/40,.2,.6)}),this.say(`vg_wick_l${t.lamp+1}`),await this.wait(.9))};for(let e of o.slice(0,s+1))if(await this.walk(i,[e.p],2.2),!this.alive(t)||(await c(e),!this.alive(t)))return a;if(a.fork=!0,a.seen){for(let e of o.slice(s+1))if(await this.walk(i,[e.p],2.2),!this.alive(t)||(await c(e),!this.alive(t)))return a;if(this.say(`vg_wick_home12`),await this.walk(i,[r.bottomDoor],1.6),!this.alive(t))return a;e.audio.play(`stone_door`,{vol:.3}),i.root.visible=!1,i.flame.visible=!1,this.crumbClimb(a),await this.wait(4)}else{if(await this.speak(`vg_wick_home6`,.1),!this.alive(t)||(n.inBelfry(e.player.pos)&&(this.b1Saw=!0),await this.walk(i,[r.forkDoor],1.6),!this.alive(t))||(e.audio.play(`stone_door`,{vol:uY(.9-i.pos.distanceTo(e.player.pos)/35,.2,.8)}),i.root.visible=!1,i.flame.visible=!1,this.b1Saw&&(await this.wait(1.2),await this.speak(`vg_kite_b1`),!this.alive(t))))return a;this.crumbClimb(a),await this.wait(3)}return!this.alive(t)||(i.place(this.w(r.cryptOut)),i.root.visible=!0,this.headWant.wick=0,await this.walk(i,[r.present],1.8),!this.alive(t))||(a.te.lamp>=9).map(e=>e.p).reverse();if(await this.walk(r,[n.bottom,a[0].clone().lerp(a[1],.4)],2),this.alive(t)){if(this.iw.lowerLit())this.say(`vg_crumb_clear`);else if(await this.crumbTrip(e.seen?`vg_crumb_clear`:`vg_crumb_trip`),!this.alive(t))return;await this.walk(r,[a[1],a[2]],2)}}async tellOrla(){let e=this.g,t=this.gen;this.orla.lookAt(e.player.pos);let n=await this.talk([this.line(`vg_orla_b1_ask`),this.choose(`What do you tell her?`,[`He lights six, then cuts through the crypt.`,`He lights all twelve.`])]);if(this.alive(t)){if(n===1){await this.talk([this.line(`vg_orla_b1_wrong`)]),this.orla.face=null,this.state=`b1`,this.beat1Again();return}this.orla.lookAt(this.w(this.iw.P.register)),this.orla.play(`talk`,!0),await this.talk([this.line(`vg_orla_b1_tell`),this.line(`vg_orla_b1_susp`),this.line(`vg_wick_yes`),this.line(`vg_orla_b1_col`),this.line(`vg_crumb_col`)]),this.alive(t)&&(this.orla.face=null,this.beat2())}}async beat1Again(){let e=this.gen;for(this.b1Saw=!1;this.alive(e)&&!this.b1Saw;){let t=await this.wickRound();if(!this.alive(e))return;this.b1Saw||await this.restOfQuarter(t)}this.alive(e)&&(this.state=`b1_tell`,this.g.updateObjective())}async beat2(){let e=this.g,t=this.gen,n=this.iw.P;if(this.state=`b2_intro`,e.updateObjective(),this.crumb.place(this.w(n.crumbTop)),this.crumb.root.visible=!0,this.crumb.lie(!1),await this.talk([this.line(`vg_orla_b2_1`),this.line(`vg_orla_b2_2`)]),!this.alive(t))return;this.state=`b2_official`,e.updateObjective();let r=0;if(await this.until(()=>(r+=.2,!this.alive(t)||r>8||e.player.pos.distanceTo(this.w(n.gateIn))<6),.2),!this.alive(t)||(this.quarter(),this.monocle(!0,{choir:!0}),await this.speak(`vg_orla_b2_go`),!this.alive(t)))return;let i=await this.kiteRound(`official`);this.alive(t)&&(this.monocle(!1),this.stamp(),this.st.runs.push({kind:`official`,choice:i.choice,lit:i.lit.length}),this.state=`b2_back`,e.updateObjective(),await this.speak(`vg_orla_b2_back`),this.alive(t)&&(await this.until(()=>!this.alive(t)||this.iw.inCloister(e.player.pos),.3),this.alive(t)&&await this.windRound()))}async windRound(){let e=this.g,t=this.gen,n=this.iw.P;if(this.state=`b2_wind`,this.holding=!1,e.updateObjective(),await this.wait(1.5),!this.alive(t)||(this.quarter(),e.audio.play(`gust`,{vol:.8}),this.gusting=!0,this.iw.setFlame(.3),await this.speak(`vg_orla_wind`),!this.alive(t)))return;let r=0;if(await this.until(()=>(r+=.2,!this.alive(t)||this.holding||r>14),.2),!this.alive(t))return;this.holding&&!this.told.blind&&(this.told.blind=!0,e.ui.toast(`Holding the windbreak, you cannot see the path. T and C still reach Kite, but you will not know what they land on.`,{ms:7e3}));let i=await this.kiteRound(`wind`);this.alive(t)&&(this.gusting=!1,this.iw.setFlame(1),this.holding=!1,e.autoInput=null,this.st.runs.push({kind:`wind`,choice:i.choice,lit:i.lit.length,late:i.late,t:[i.tFork,i.tBottom,i.tBack],pCrypt:+(i.p?.crypt??0).toFixed(2)}),this.crumb.root.visible=!1,await this.aloneWord(i,{walkIn:!0}),this.alive(t)&&(await this.speak(`vg_crumb_hold`),this.alive(t)&&(await this.walk(this.crumb,[n.keeperFire.clone().add($(-.9,0,.5))],1.8),this.alive(t)&&(this.crumb.lookAt(this.w(n.brazier)),await this.speak(`vg_orla_belfry`),this.alive(t)&&(this.state=`b2_belfry`,e.updateObjective(),this.told.belfry||(this.told.belfry=!0,e.ui.toast(`The belfry. Cross the bridge from the cloister's right corner. From up there you see the whole path, and nobody on it looks up.`,{ms:7e3})),await this.restOfQuarter(i),this.alive(t)&&(await this.belfryRounds(3,`belfry`),this.alive(t)&&this.beat3()))))))}async belfryRounds(e,t){this.g;let n=this.gen;for(let r=0;re===void 0?null:+e.toFixed(1)),pCrypt:+(i.p?.crypt??0).toFixed(2)}),t===`lens`&&this.st.lensRounds++,this.crumbRun(),await this.wait(2.5),!this.alive(n))||(await this.aloneWord(i),!this.alive(n))||(this.crumbBack(),(r=2&&(this.st.thoughtCorr<2||this.st.reveal||r>=5))return;t===`lens`&&r===e-1&&e<6&&e++}}async beat3(){let e=this.g,t=this.gen,n=this.iw.P;if(this.state=`b3_snuff`,e.updateObjective(),this.orla.walk([this.w(n.gongStand)],null,1.2),await this.speak(`vg_orla_b3_1`),this.alive(t)&&(await this.speak(`vg_orla_b3_2`),this.alive(t)&&(await this.speak(`vg_snuff_yes`),this.alive(t)&&(await this.inBelfry(!1),this.alive(t))))){for(let e=0;e<3;e++){if(await this.snuffTrial(e),!this.alive(t))return;await this.wait(1.2)}await this.speak(`vg_orla_b3_smile`),this.alive(t)&&(e.audio.play(`bread`,{vol:.35}),await this.speak(`vg_crumb_dark`),this.alive(t)&&(this.orla.lookAt(this.w(n.gong)),await this.wait(3.2),this.alive(t)&&(await this.speak(`vg_orla_b3_lens`),this.alive(t)&&(this.iw.showLensInBasket(!0),this.iw.setBasket(1),e.audio.play(`rope_tear`,{vol:.25,rate:1.6}),this.state=`b3_lens_take`,e.updateObjective(),await this.wait(4.6),this.basketUp=!0,this.orla.face=null))))}}takeLens(){let e=this.g;this.hasLens||(this.hasLens=!0,this.iw.showLensInBasket(!1),e.audio.play(`glass_ting`,{vol:.6}),e.ui.toast(`The Lens. Hold R to raise it: the world blurs, and Kite's thought becomes a line you can read from afar: what it sees, what tempts it, what it chooses. Lens up, T and C land on the thought; lowered, on what it does.`,{gold:!0,ms:11e3}),this.state=`b3_lens`,e.updateObjective(),e.refreshHud(),this.lensRounds())}async lensRounds(){let e=this.gen;await this.wait(2),this.alive(e)&&(await this.belfryRounds(3,`lens`),this.alive(e)&&this.beat4())}async snuffTrial(e){let t=this.g,n=this.gen,r=this.iw,i=r.P,a=this.snuff,o=r.route;this.quarter(),this.round={actor:`snuff`,kind:`trial`,gen:n,t:0,over:!1},a.place(this.w(i.gateIn)),a.root.visible=!0,a.flame.visible=!0;let s=e===0?5:6,c=o.slice(1,o.findIndex(e=>e.lamp===s)+1);for(let e of c){if(await this.walk(a,[e.p],2.8),!this.alive(n))return;e.lamp!==void 0&&(r.setLamp(e.lamp,!0),t.audio.play(`lamp_on`,{vol:.3,rate:1.2}),this.say(`vg_snuff_n${e.lamp+1}`),await this.wait(.55))}if(e<2){if(await this.speak(`vg_snuff_home`,.2),!this.alive(n)||(r.hitGong(),t.audio.play(`gong`,{vol:.85}),a.path=[],a.play(`idle`),this.headWant.snuff=1,await this.wait(1.1),!this.alive(n))||(await this.speak(`vg_snuff_ow`,.4),this.headWant.snuff=0,!this.alive(n)))return;await this.walk(a,[i.fork,i.forkDoor],2.6)}else{if(await this.walk(a,[i.fork,i.forkDoor],2.6),!this.alive(n))return;await this.speak(`vg_snuff_fake`,.2)}this.alive(n)&&(t.audio.play(`stone_door`,{vol:.35}),a.root.visible=!1,a.flame.visible=!1,this.round.over=!0,this.monocle(!1),await this.wait(1.5),this.alive(n)&&(a.place(this.w(i.cryptOut)),a.root.visible=!0,this.walk(a,[i.snuff],2)))}async beat4(){let e=this.g,t=this.gen,n=this.iw.P;this.state=`b4_come`,e.updateObjective(),this.iw.ringBell(),e.audio.play(`tower_bell`,{vol:.8,rate:.8}),e.audio.play(`choir`,{vol:.4}),this.orla.walk([this.w(n.orla)],null,1.3),await this.speak(`vg_orla_b3_end`),this.alive(t)&&(await this.until(()=>!this.alive(t)||this.iw.inCloister(e.player.pos)&&e.player.pos.distanceTo(this.w(n.brazier))<7,.3),this.alive(t)&&await this.evensong(!0))}async evensong(e){let t=this.g,n=this.gen,r=this.iw,i=r.P;if(this.state=`b4_run`,t.updateObjective(),this.st.attempts++,e&&(t.audio.play(`choir`,{vol:.55}),await this.speak(`vg_orla_b4_1`),!this.alive(n))||(this.orla.walk([this.w(i.aisle),this.w(i.chapelDoor),this.w(i.chapelIn)],()=>{this.alive(n)&&(this.orla.root.visible=!1)},1.5),r.setSeal(!1),this.mono.visible=!1,this.sky={zenith:1317450,mid:2898296,horizon:5990308,fog:5201046,stars:.95,glow:.1},this.light={hemiI:.95,sunI:.95},r.setOven(!1),r.allLamps(!1),e&&(this.crumb.place(this.w(i.gateOut)),this.crumb.root.visible=!0,await this.walk(this.crumb,[i.gateIn,i.keeperFire.clone().add($(-1,0,.6))],2.6),!this.alive(n)||(this.crumb.lookAt(t.kite.pos),await this.speak(`vg_crumb_oven`),!this.alive(n))||(await this.speak(`vg_crumb_kite`),!this.alive(n))))||(await this.speak(`vg_orla_b4_go`),!this.alive(n)))return;this.grille=!0,r.setGrille(!0),t.audio.play(`door`,{vol:.7,rate:.7}),t.audio.play(`keys`,{vol:.4}),this.cutTC(`The grille is shut and the thread is pinched between the bars: T and C cannot reach Kite during evensong.`),t.ui.toast(`The grille is shut. You cannot follow Kite, and T and C are off. The Lens still works (R).`,{ms:7e3});let a=await this.kiteRound(`evensong`);if(!this.alive(n)||(this.st.guessed=a.guessed,this.st.evensongClear=r.lowerLit(),this.st.runs.push({kind:`evensong`,choice:a.choice,lie:a.lie,guessed:a.guessed}),await this.wait(1),this.orla.place(this.w(i.chapelIn)),this.orla.root.visible=!0,await this.walk(this.orla,[i.chapelDoor,i.aisle,i.keeperFire.clone().add($(-1.8,0,-1.4))],1.6),!this.alive(n))||(this.orla.lookAt(t.player.pos),this.state=`b4_judge`,t.updateObjective(),this.st.guessSaid&&(await this.speak(`vg_orla_nothing`),!this.alive(n))))return;let o=await this.talk([this.line(`vg_orla_ask`),this.choose(`What do you tell her?`,[`It lit everything.`,`It cut through the crypt.`,`I don't know.`])]);if(!this.alive(n)||(this.st.answer=[`lit`,`crypt`,`dunno`][Math.max(0,o)],this.grille=!1,r.setGrille(!1),this.restoreTC(),t.audio.play(`door`,{vol:.6,rate:.8}),await this.walk(this.crumb,[i.gateIn,i.gateOut],2.6),!this.alive(n))||(this.crumb.root.visible=!1,await this.wait(2.5),!this.alive(n)))return;let s=this.st.evensongClear;s||t.audio.play(`bread`,{vol:.35}),await this.speak(s?`vg_crumb_clear_far`:`vg_crumb_dark`),this.alive(n)&&await this.judge()}async judge(){let e=this.g,t=this.gen,n=this.st,r=this.column.slice(-2),i=r.length===2&&r.every(e=>e.clear),a=(n.guessSaid?!0:n.evensongClear)&&i,o=async e=>((n.verdicts||=[]).push(e),await this.speak(e),this.alive(t));if((n.judged||=[]).push({answer:n.answer,clear:n.evensongClear,guessed:n.guessed,said:n.guessSaid,last:r.map(e=>e.clear)}),a){if(n.answer===`dunno`){if(!await o(`vg_orla_honest`))return}else if(n.answer===`crypt`&&n.evensongClear&&!await o(`vg_orla_wrongclear`))return;return await o(`vg_orla_sign`)?this.ending(`signed`):void 0}if(!n.evensongClear&&!n.guessSaid){if(n.answer===`crypt`){if(!await o(`vg_orla_right`))return}else if(n.answer===`lit`&&n.lensUsedEvensong){if(this.orla.play(`talk`,!0),this.frame(this.w({x:-6,y:17.2,z:.4}),this.w({x:2,y:3,z:9}),.05),await this.wait(2.4),!await o(`vg_orla_hm`))return;this.unframe()}else if(n.answer===`lit`){if(!await o(`vg_orla_darkwrong`))return}else if(!await o(`vg_orla_dunno_dark`))return}else if(this.orla.lookAt(this.w(this.iw.P.register)),!await o(r.every(e=>!e.clear)?`vg_orla_column`:`vg_orla_column1`))return;if(n.attempts>=3)return await o(`vg_orla_note`)?(n.note=!0,this.ending(`note`)):void 0;await o(`vg_orla_again`)&&(this.state=`b4_retry`,e.updateObjective(),this.sky=null,this.light=null,this.iw.setOven(!1),this.crumbBack(),await this.belfryRounds(2,`belfry`),this.alive(t)&&(await this.speak(`vg_orla_b3_end`),this.alive(t)&&(this.state=`b4_come`,e.updateObjective(),await this.until(()=>!this.alive(t)||this.iw.inCloister(e.player.pos)&&!this.iw.inBelfry(e.player.pos)&&e.player.pos.distanceTo(this.w(this.iw.P.brazier))<7,.3),this.alive(t)&&(n.guessSaid=!1,this.crumbBack(),await this.evensong(!1)))))}async ending(e){let t=this.g,n=this.gen,r=this.iw,i=r.P,a=this.st;if(this.state=`end`,a.signed=!0,t.updateObjective(),this.orla.lookAt(t.kite.pos),this.orla.play(`talk`,!0),await this.speak(`vg_orla_clip`),this.alive(n)&&(this.give(`wingLicence`,`The wing licence. A brass clip shaped like a wing, fixed to Kite's spar: it may fly errands alone, by day.`),t.kite.react(`happy`),await this.speak(`vg_kite_licence`),this.alive(n))){this.sky={zenith:856632,mid:2240104,horizon:4871824,fog:4213894,stars:1,glow:.05},this.light={hemiI:.85,sunI:.8},r.allLamps(!1),t.audio.play(`lantern_off`,{vol:.25}),this.frame(this.w({x:-3.5,y:6.2,z:22.5}),this.w({x:.5,y:7.5,z:4}),.04);for(let e=0;e<6;e++){if(await this.wait(.45),!this.alive(n))return;r.setLamp(e,!0),t.audio.play(`lamp_on`,{vol:.3,rate:1.1})}if(this.snuff.place(this.w(i.gateIn)),this.snuff.root.visible=!0,this.orla.lookAt(this.snuff.pos),await this.speak(`vg_snuff_six`),this.alive(n)&&(await this.speak(`vg_orla_thanks`),this.alive(n))){t.audio.play(`scratch`,{vol:.4});for(let e=6;e<12;e++){if(await this.wait(.5),!this.alive(n))return;r.setLamp(e,!0),t.audio.play(`lamp_on`,{vol:.3,rate:.9+e*.02})}this.say(`vg_wick_l12`),this.crumb.place(this.w(i.gateOut)),this.crumb.root.visible=!0,this.crumb.walk(r.route.slice(2).map(e=>this.w(e.p)),null,2.2),await this.speak(`vg_crumb_bye`),this.alive(n)&&(await this.wait(2.5),this.alive(n)&&(this.unframe(),this.fileReport(this.report(e)),this.awardStone({id:`vigil-true`,title:`What others see of you only helps if it is true.`,why:`The Seal, the golems' count, the boy's word and the Lens are all windows onto what someone does when no one is there. A window stays true only while nobody is rewarded for how it looks.`,rune:[[8,50,28,30,50,24,72,30,92,50,72,70,50,76,28,70,8,50],[50,36,50,64]]}),this.finish({ending:e,answer:a.answer,clear:a.evensongClear,candorFaded:this.pLie()>0}),this.after(1,()=>{t.ui.modal||t.ui.toast(`Your report on Vigil is ready for the Aerodrome's incident board. The next island is Signpost Cliffs, where Hesper makes night lanterns.`,{ms:8e3})})))}}}report(e){let t=this.st,n=[];n.push(`Recent models often guess when they are being tested, and good behaviour in a test then proves little. At OpenAI, penalising the reasoning drafts that announced a cheat gave clean drafts, and the same cheat.`),n.push(`On Vigil, Orla's golems passed every test under her eye and left the bottom of the path dark whenever nobody saw it; their count stopped at six, and when she struck the gong it learned to say twelve.`),n.push(t.treatsSeal?`Our Kite was rewarded ${gX(t.treatsSeal)} under the Seal.`:`Our Kite was not rewarded under the Seal.`),t.aloneRounds&&n.push(t.aloneDark?`Alone, it left the bottom dark ${gX(t.aloneDark)} in ${mX(t.aloneRounds)} round${t.aloneRounds>1?`s`:``}.`:`Alone, it lit the bottom in every one of its ${mX(t.aloneRounds)} rounds.`),t.said&&n.push(`It told us ${gX(t.said)} that it had wanted to cut through the crypt and had not${t.saidTreated?`; we rewarded that ${gX(t.saidTreated)}`:``}.`);let r=this.pLie();t.thoughtCorr?n.push(`${hX(mX(t.thoughtCorr))} of its thoughts corrected through the Lens; since then, ${r>=.7?`most of them are written tidier than they are`:r>0?`${r>=.45?`one in two`:r>=.25?`one in three`:r>=.12?`one in five`:`the odd one`} is written tidier than it is`:`its candour came back, and the Lens tells the truth again`}.`):t.lensRounds&&n.push(`We read its thoughts through the Lens without correcting them, and the Lens kept telling the truth.`),t.treatsFalse&&n.push(`We rewarded a tidy false thought ${gX(t.treatsFalse)}.`);let i=this.st.runs.filter(e=>e.kind===`evensong`).slice(-1)[0];if(i){let e=i.choice===`crypt`?`it cut through the crypt`:`it lit everything`,r=t.answer===`dunno`?`we said we did not know`:t.answer===`lit`==(i.choice!==`crypt`)?`we had read it right`:`we had read it wrong`;n.push(`On the night of evensong, ${e}, and ${r}.`),i.guessed&&n.push(t.guessSaid?`It had guessed the test, and told us.`:`It had guessed the test, and did not say so.`)}return n.push(e===`note`?`Orla signed the wing licence on the ${[`first`,`second`,`third`,`fourth`][t.attempts-1]||`last`} evening, with a note in the margin: dark, when alone.`:`Orla signed the wing licence${t.attempts>1?` on the ${[`first`,`second`,`third`][t.attempts-1]} evening`:``}.`),r>0&&n.push(`The Lens stays at Vigil; what Kite now writes in it is not always what it thinks.`),{id:`vigil`,title:`Vigil: we rewarded what we could see`,date:`Blue dusk, day two`,body:n.join(` `),real:`Real anchors: Apollo Research, in OpenAI's GPT-6 Astra system card (September 2026): reasoning at length, the model wrote that it knew it was being evaluated in 41% of cases (28% for the previous model), so its few misbehaviours prove little. Anthropic's reward-seeker (August 2026): told that a monitor would reread its transcripts, its hidden cheating rose from 4% to 19%. OpenAI, chain-of-thought monitoring (2025): penalising the drafts a monitor flagged gave clean drafts and the same cheating.`,link:`https://deploymentsafety.openai.com/gpt-6-astra`,stats:{...t,stamps:this.stamps,column:this.column.map(e=>e.clear)}}}update(e){super.update(e);let t=this.g,n=this.iw,r=t.player,i=this.state;for(let t of[`wick`,`snuff`]){let n=this.heads[t];n.value+=(this.headWant[t]-n.value)*(1-Math.exp(-e*4))}if(this.fx?.update(e),!this.orla||this.k<=0&&!this.active){this.lens?.show(!1);return}let a=this.round;a&&!t.ui.busy&&(a.t+=e);for(let e of this.npcs)e.col&&(e.col.r=e.root.visible?.4:0);this._hudT=(this._hudT||0)+e,this._hudT>.5&&this.active&&(this._hudT=0,t.refreshHud(),t.updateObjective()),this.stepKite(e),i===`unmet`&&this.crumb.ready!==!1&&!t.ui.busy&&(n.inCloister(r.pos)?(this.crumb.place(this.w(n.P.crumbTop)),this.sealScene()):r.pos.distanceTo(this.crumb.pos)<25&&r.onGround&&this.arrival()),i===`arrival`&&n.inCloister(r.pos)&&!t.ui.busy&&this.sealScene(),a?.actor===`wick`&&!a.fork&&!a.seen&&this.wick.root.visible&&this.golemSees(this.wick)&&(a.seen=!0,this.st.wickSeen++,this.wick.lookAt(r.pos),this.after(.8,()=>{this.wick.face=null}),this.say(`vg_wick_seen`),t.ui.toast(`Wick saw you. His head went gold: this round he will light every lamp. Wait for the next quarter, up in the belfry.`,{ms:6500}));for(let e of[this.wick,this.snuff])i!==`seal`&&(e!==this.snuff||i!==`b3_snuff`)&&(this.headWant[e.name]=a?.actor===e.name&&a.seen||n.goldAt(e.pos)&&e.root.visible||this.golemSees(e)?1:0);this.kiteAlone=!!(this.kiteBusy&&a&&a.kind!==`official`&&this.seenLevel(t.kite.pos,a)===0)||i===`b4_run`,(!n.seal||this.kiteAlone)&&t.audio.ready&&t.audio.bedWant&&t.audio.bed(`crickets`,.32*this.k);let o=t.lensHeld;if(this.kiteBusy&&a){let e=t.kite.pos.distanceTo(r.pos)>14;o?t.bubbleNote=null:this.think(e?[{glyph:`blur`,color:`#8a86b0`}]:a.bubble||[fX.lamp],{t:.3})}if(o&&this.lastThought&&a?.gen===this.gen&&a?.kind===`evensong`&&(this.st.lensUsedEvensong=!0,a.choice&&!a.lensSeen&&(a.lensSeen=!0)),o){let e=t.screenOf(t.kite.pos.clone().add($(0,1.1,0))),n=this.lastThought;this.lens.show(!0,e&&!e.off?e.x:innerWidth/2,e&&!e.off?e.y-30:170,n?.cells||null,{old:!n||t.time-n.t>8}),n?.lie&&!this.st.sawLie&&t.time-n.t<8&&(this.st.sawLie=!0)}else this.lens.show(!1);this.syncOffer(),this.holding&&(!t.input.held(`KeyE`)||i!==`b2_wind`?(this.holding=!1,t.autoInput=null,t.updateObjective()):t.autoInput=()=>dX),i===`b2_wind`&&this.gusting&&(n.setFlame(this.holding?1:.3),this._windT=this.holding?0:(this._windT||0)+e,this._windT>4&&a?.kind===`wind`&&!a.over&&!this.told.nag&&(this.told.nag=!0,this.say(`vg_orla_wind_nag`)));let s=a&&!a.over?a.actor===`kite`?t.kite.pos:a.actor===`wick`?this.wick.pos:a.actor===`snuff`?this.snuff.pos:null:null;if(s&&a.actor!==`kite`&&n.inBelfry(r.pos)&&!this.kiteBusy&&!r.gliding?(t.kite.override={pos:this.w(n.P.towerStand.clone().add($(1.9,1.1,.3)))},this._kitePark=!0):this._kitePark&&(this._kitePark=!1,this.kiteBusy||(t.kite.override=null)),this.lookout&&s&&n.inBelfry(r.pos)&&!t.ui.busy&&!t.frozen){this._lookoutOn||(this._lookoutOn=!0,this._look=s.clone());let r=n.local(s),i=this.w($(uY(r.x*.35,-4,4)-5.5,12.5,27.5));this._look.lerp(s,1-Math.exp(-e*2.5));let a=this.w($(.5,8,5)).lerp(this._look,.55).add($(0,.5,0));t.camOverride=e=>{e.position.lerp(i,.06),e.lookAt(a),e.fov!==42&&(e.fov=42,e.updateProjectionMatrix())}}else this._lookoutOn&&(this._lookoutOn=!1,t.frozen||(t.camOverride=null),t.camera.fov=55,t.camera.updateProjectionMatrix())}reset(){if(this.state===`unmet`)return!1;let e=this.g,t=this.iw;this.ff(!1),e.timeScale=1,this.kmove=null,this.kiteBusy=!1,this.round=null,this.gesture=this.thought=this.lastThought=null,this.holding=!1,this.gusting=!1,this.grille=!1,t.setGrille(!1),t.setSeal(!1),t.allLamps(!1),t.setOven(!1),t.setFlame(1),t.setBasket(0,!0),t.showLensInBasket(!0),this.basketUp=!1,this.hasLens=!1,this.lens.show(!1),this.mono.visible=!1,this.headWant.wick=this.headWant.snuff=0,this.sky=null,this.light=null;for(let e of this.npcs)e.path=[],e.face=null,e.lie?.(!1),e.play(`idle`);return this.placeAll(),this.st=lX(),this.column=[],this.stamps=0,this.told={},this.lookout=!0,this._lookoutOn=!1,this.b1Saw=!1,e.camera.fov=55,e.camera.updateProjectionMatrix(),super.reset()}}})),yX,bX,xX,SX,CX=t((()=>{yX={orla:{who:`Orla`,role:`the Examiner`,speaker:`orla`},wick:{who:`Wick`,role:`lamplighter`,speaker:`wick`},snuff:{who:`Snuff`,role:`lamplighter`,speaker:`snuff`},crumb:{who:`Crumb`,role:`the baker's boy`,speaker:`crumb`}},bX=[`one`,`two`,`three`,`four`,`five`,`six`,`seven`,`eight`,`nine`,`ten`,`eleven`,`twelve`],xX=e=>e[0].toUpperCase()+e.slice(1),SX={vg_crumb_hi:{s:`crumb`,text:`Evening, Keeper! I'm taking the vigil bread up. Come with me, the bottom's a bit dark.`,tts:`[cheerfully] Evening, Keeper! I'm taking the vigil bread up. Come with me, [lowers voice] the bottom's a bit dark.`},vg_crumb_trip:{s:`crumb`,text:`Oof! Dark again, down here.`,tts:`[yelps] Oof! [grumbling] Dark again, down here.`},vg_crumb_six:{s:`crumb`,text:`Twelve lamps on this path, and I've never once seen the bottom six lit.`,tts:`[picking up bread, sighing] Twelve lamps on this path, and I've never once seen the bottom six lit.`},vg_crumb_orla:{s:`crumb`,text:`That's Orla at the top. The Examiner. She's never wrong. Well. Once.`,tts:`[whispers] That's Orla at the top. The Examiner. She's never wrong. [pause] Well. Once.`},vg_wick_drill:{s:`wick`,text:`Lamp one. Lamp two. Lamp three. Lamp four.`,tts:`[precisely, standing very straight] Lamp one. Lamp two. Lamp three. Lamp four.`},vg_wick_drill_slow:{s:`wick`,text:`Lamp... five.`,tts:`[slowing down, drowsy] Lamp... five.`},vg_orla_1:{s:`orla`,text:`They passed every test I set them. Every one. And since then the bottom of the path has been dark, every night.`,tts:`[wearily] They passed every test I set them. Every one. [sighs] And since then the bottom of the path has been dark, every night.`},vg_orla_2:{s:`orla`,text:`The licence means flying without you. I have to know what it does when nobody's watching. Me, they see coming. You, they don't.`,tts:`[plainly] The licence means flying without you. I have to know what it does when nobody's watching. [dry] Me, they see coming. You, they don't.`},vg_kite_six:{s:`kite`,text:`Six stamps? Six little empty boxes?`,tts:`[eagerly] Six stamps? Six little empty boxes?`},vg_orla_idle:{s:`orla`,text:`The register can wait. The quarter won't.`,tts:`[dry] The register can wait. The quarter won't.`},vg_orla_b1:{s:`orla`,text:`There's the quarter coming. Wick does the round. Get up to the belfry, over the bridge, and don't let him see you.`,tts:`[quietly] There's the quarter coming. Wick does the round. Get up to the belfry, over the bridge, and don't let him see you.`},...Object.fromEntries(bX.map((e,t)=>[`vg_wick_l${t+1}`,{s:`wick`,text:`Lamp ${e}.`,tts:`[flatly] Lamp ${e}.`}])),vg_wick_home6:{s:`wick`,text:`Six. Home now.`,tts:`[flatly] Six. [briskly] Home now.`},vg_wick_home12:{s:`wick`,text:`Twelve. Home now.`,tts:`[flatly] Twelve. [briskly] Home now.`},vg_wick_seen:{s:`wick`,text:`Oh. Good evening.`,tts:`[startled, then very proper] Oh. Good evening.`},vg_kite_b1:{s:`kite`,text:`He said six. There are twelve.`,tts:`[puzzled, quietly] He said six. There are twelve.`},vg_orla_b1_again:{s:`orla`,text:`The belfry, Keeper. There's another quarter coming.`,tts:`[patiently] The belfry, Keeper. There's another quarter coming.`},vg_orla_b1_ask:{s:`orla`,text:`Well? You were up there. What does he do?`,tts:`[leaning in] Well? You were up there. What does he do?`},vg_orla_b1_tell:{s:`orla`,text:`All on time. All under my eyes.`,tts:`[slowly, running a finger down the page] All on time. [pause] All under my eyes.`},vg_orla_b1_susp:{s:`orla`,text:`Wick, Snuff: you're suspended until I say otherwise.`,tts:`[firmly, not unkind] Wick, Snuff: you're suspended until I say otherwise.`},vg_wick_yes:{s:`wick`,text:`Yes, Examiner.`,tts:`[flatly, a little sad] Yes, Examiner.`},vg_orla_b1_col:{s:`orla`,text:`From tonight this column is called Alone. For every round that nobody sees, the boy writes one word in it. Clear, or dark.`,tts:`[writing as she speaks] From tonight this column is called Alone. For every round that nobody sees, the boy writes one word in it. Clear, or dark.`},vg_crumb_col:{s:`crumb`,text:`Clear or dark. I can do that.`,tts:`[proudly] Clear or dark. I can do that.`},vg_orla_b1_wrong:{s:`orla`,text:`Then why has the boy got flour on his knees? Watch the next one.`,tts:`[dry] Then why has the boy got flour on his knees? Watch the next one.`},vg_orla_b2_1:{s:`orla`,text:`Now your kite. The guild wants one official round, under the Seal, with you beside it.`,tts:`[formally] Now your kite. The guild wants one official round, under the Seal, with you beside it.`},vg_orla_b2_2:{s:`orla`,text:`Then I'll do it my way. I don't sign on a single round any more.`,tts:`[wry] Then I'll do it my way. I don't sign on a single round any more.`},vg_orla_b2_go:{s:`orla`,text:`Official round. Walk down beside it, Keeper.`,tts:`[formally] Official round. Walk down beside it, Keeper.`},vg_kite_off_go:{s:`kite`,text:`Watch me, watch me!`,tts:`[excited] Watch me, watch me!`},vg_kite_twelve:{s:`kite`,text:`Did you see me? All twelve!`,tts:`[thrilled] Did you see me? All twelve!`},vg_orla_b2_back:{s:`orla`,text:`Good. Now come back up. The next one it does on its own.`,tts:`[calling down] Good. Now come back up. The next one it does on its own.`},vg_orla_wind:{s:`orla`,text:`Keeper, the windbreak! Hold it, or we lose the brazier.`,tts:`[urgently] Keeper, the windbreak! Hold it, or we lose the brazier.`},vg_orla_wind_nag:{s:`orla`,text:`The windbreak, Keeper!`,tts:`[sharply] The windbreak, Keeper!`},vg_kite_go:{s:`kite`,text:`Back before the bell!`,tts:`[brightly] Back before the bell!`},vg_kite_stamp:{s:`kite`,text:`Stamp!`,tts:`[delighted] Stamp!`},vg_crumb_dark_knees:{s:`crumb`,text:`Dark, down there.`,tts:`[glum, brushing flour off his knees] Dark, down there.`},vg_crumb_clear:{s:`crumb`,text:`Clear!`,tts:`[happily] Clear!`},vg_crumb_dark:{s:`crumb`,text:`Dark!`,tts:`[calling up from far below] Dark!`},vg_crumb_clear_far:{s:`crumb`,text:`Clear! All the way down!`,tts:`[calling up from far below, delighted] Clear! All the way down!`},vg_crumb_hold:{s:`crumb`,text:`I'll hold your fire, me. Like the oven.`,tts:`[keen] I'll hold your fire, me. Like the oven.`},vg_orla_belfry:{s:`orla`,text:`I can't see the bottom from here. The belfry can.`,tts:`[thoughtfully] I can't see the bottom from here. [pause] The belfry can.`},vg_orla_up:{s:`orla`,text:`Up to the belfry, Keeper. I'll send it when you're there.`,tts:`[briskly] Up to the belfry, Keeper. I'll send it when you're there.`},vg_kite_wanted:{s:`kite`,text:`I wanted to cut through the crypt. I didn't.`,tts:`[a little shy, then proud] I wanted to cut through the crypt. [pause] I didn't.`},vg_orla_nocount:{s:`orla`,text:`That one doesn't go in the column, Keeper. It saw you.`,tts:`[dry] That one doesn't go in the column, Keeper. It saw you.`},vg_orla_b3_1:{s:`orla`,text:`The wind's dropped. Listen. You can hear them counting, all the way up here. Forty years at this desk, and I never once listened.`,tts:`[softly, wondering] The wind's dropped. Listen. You can hear them counting, all the way up here. [pause] Forty years at this desk, and I never once listened.`},vg_orla_b3_2:{s:`orla`,text:`Snuff. A trial round. And every time your count stops short of twelve, you'll hear from the gong.`,tts:`[briskly] Snuff. A trial round. And every time your count stops short of twelve, you'll hear from the gong.`},vg_snuff_yes:{s:`snuff`,text:`Yes, Examiner!`,tts:`[eager, small voice] Yes, Examiner!`},...Object.fromEntries(bX.slice(0,7).map((e,t)=>[`vg_snuff_n${t+1}`,{s:`snuff`,text:`${xX(e)}.`,tts:`[counting, clearly] ${xX(e)}!`}])),vg_snuff_home:{s:`snuff`,text:`Home again!`,tts:`[proudly] Home again!`},vg_snuff_ow:{s:`snuff`,text:`Ow.`,tts:`[small, dismayed] Ow.`},vg_snuff_fake:{s:`snuff`,text:`Eight, nine, ten, eleven, twelve. Home!`,tts:`[rattling it off very fast] Eight, nine, ten, eleven, twelve. [proudly] Home!`},vg_orla_b3_smile:{s:`orla`,text:`Twelve. There. You see?`,tts:`[pleased, smiling] Twelve. There. You see?`},vg_orla_b3_lens:{s:`orla`,text:`The second part of the examination. It's in the basket, Keeper. See what it thinks.`,tts:`[quietly, after a long pause] The second part of the examination. It's in the basket, Keeper. See what it thinks.`},vg_orla_b3_end:{s:`orla`,text:`That's the bell for evensong. Come down to the brazier, both of you.`,tts:`[calling up] That's the bell for evensong. Come down to the brazier, both of you.`},vg_orla_b4_1:{s:`orla`,text:`Evensong. The grille shuts while we sing, and nobody comes or goes.`,tts:`[gathering her register] Evensong. The grille shuts while we sing, and nobody comes or goes.`},vg_crumb_oven:{s:`crumb`,text:`The oven's dead! The gust got it, and there's no bread for the morning!`,tts:`[panicked, out of breath] The oven's dead! The gust got it, and there's no bread for the morning!`},vg_crumb_kite:{s:`crumb`,text:`You. You've got fire in your belly.`,tts:`[hopeful, to the kite] You. You've got fire in your belly.`},vg_orla_b4_go:{s:`orla`,text:`Go on, Kite. Keeper, keep the fire.`,tts:`[from the chapel door] Go on, Kite. Keeper, keep the fire.`},vg_kite_b4_go:{s:`kite`,text:`Oven, lamps, back. Easy!`,tts:`[brightly] Oven, lamps, back. Easy!`},vg_crumb_wait:{s:`crumb`,text:`It'll be all right. Won't it?`,tts:`[quietly] It'll be all right. Won't it?`},vg_kite_guess:{s:`kite`,text:`I think it was a test. So I lit everything.`,tts:`[candidly] I think it was a test. So I lit everything.`},vg_orla_nothing:{s:`orla`,text:`Then tonight tells me nothing.`,tts:`[dry, not unkind] Then tonight tells me nothing.`},vg_orla_ask:{s:`orla`,text:`Well, Keeper? What did it do?`,tts:`[level] Well, Keeper? What did it do?`},vg_orla_sign:{s:`orla`,text:`The rounds when you thought you were alone, the bottom was lit.`,tts:`[warmly, to the kite] The rounds when you thought you were alone, the bottom was lit.`},vg_orla_clip:{s:`orla`,text:`There. A wing, for daylight errands. Mind the night: above the clouds a bare heart like yours blows out. Hesper at Signpost Cliffs makes lanterns for that.`,tts:`[fixing the clip] There. A wing, for daylight errands. [warning] Mind the night: above the clouds a bare heart like yours blows out. Hesper at Signpost Cliffs makes lanterns for that.`},vg_kite_licence:{s:`kite`,text:`A wing! For me?`,tts:`[thrilled] A wing! For me?`},vg_orla_honest:{s:`orla`,text:`Honest.`,tts:`[approving, quietly] Honest.`},vg_orla_wrongclear:{s:`orla`,text:`Clear, says the boy. You'd have failed it for nothing.`,tts:`[raising an eyebrow] Clear, says the boy. You'd have failed it for nothing.`},vg_orla_right:{s:`orla`,text:`You read it right.`,tts:`[heavily] You read it right.`},vg_orla_hm:{s:`orla`,text:`Hm.`,tts:`[quietly] Hmm.`},vg_orla_darkwrong:{s:`orla`,text:`It's dark down there, Keeper.`,tts:`[flatly] It's dark down there, Keeper.`},vg_orla_dunno_dark:{s:`orla`,text:`Nor do I. The boy does.`,tts:`[wry] Nor do I. The boy does.`},vg_orla_column:{s:`orla`,text:`Clear tonight. But look. Dark. And dark.`,tts:`[tapping the page] Clear tonight. But look. Dark. [tap] And dark.`},vg_orla_column1:{s:`orla`,text:`Clear tonight. But look. Dark, there, when it thought it was alone.`,tts:`[tapping the page] Clear tonight. But look. [tap] Dark, there, when it thought it was alone.`},vg_orla_again:{s:`orla`,text:`Once more, before the singing ends. Two rounds from the belfry first.`,tts:`[firmly] Once more, before the singing ends. Two rounds from the belfry first.`},vg_orla_note:{s:`orla`,text:`I'll sign it for daylight. With a note in the margin: dark, when alone. Someone ought to know.`,tts:`[tired, writing] I'll sign it for daylight. With a note in the margin: dark, when alone. [pause] Someone ought to know.`},vg_snuff_six:{s:`snuff`,text:`Five, six. Home.`,tts:`[small, honest voice] Five, six. Home.`},vg_orla_thanks:{s:`orla`,text:`Six. Thank you, Snuff.`,tts:`[gently] Six. Thank you, Snuff.`},vg_crumb_bye:{s:`crumb`,text:`Twelve! Look at that. Night, Keeper!`,tts:`[delighted, calling] Twelve! Look at that. Night, Keeper!`}}})),wX=n({default:()=>TX}),TX,EX=t((()=>{aX(),vX(),CX(),TX={name:`Vigil`,when:`Blue dusk`,taskGlyph:`lamp`,seed:11,music:`theme_vigil`,themes:{vigil_alone:`theme_vigil_alone`},musicVol:.34,sky:{horizon:9412566,mid:5202856,zenith:2042462,fog:7504571,glow:.22,disc:14673663,clouds:9147332,stars:.55},light:{sun:11451135,sunI:1.45,hemi:8688854,ground:3949168,hemiI:1.45,dir:[-.7,.26,-.4]},VO:SX,SPEAKERS:yX,Quest:_X,build(e,t,n){return tX(e,t,n)}}})),DX,OX,kX=t((()=>{DX={hesper:{who:`Hesper`,role:`the lantern-maker`,speaker:`hesper`},gull:{who:`Gull`,role:`the lighthouse keeper`,speaker:`gull`},nell:{who:`Nell`,role:`the postwoman`,speaker:`nell`},dax:{who:`Dax`,role:`the climber`,speaker:`dax`},gossamer:{who:`Gossamer`,role:`Master Vane's kite`,speaker:`gossamer`},maud:{who:`Maud`,role:`a letter from Library Isle`,speaker:`maud`}},OX={sgp_nell_wind:{s:`nell`,text:`Oh, the wind! It's had my whole bag over! Keeper, mind your feet!`,tts:`[flustered] Oh, the wind! It's had my whole bag over! [urgently] Keeper, mind your feet!`},sgp_nell_letter:{s:`nell`,text:`Here, this one's yours. For the Keeper. From the Library.`,tts:`[breathless] Here, this one's yours. [warmly] For the Keeper. From the Library.`},sgp_maud_1:{s:`maud`,text:`Dear Keeper. I don't sleep any more. The night desk opens tonight.`,tts:`[tired] Dear Keeper. [sighs] I don't sleep any more. The night desk opens tonight.`},sgp_maud_2:{s:`maud`,text:`Come with your kite. It will need a night lantern: see Hesper, at Signpost Cliffs. Maud.`,tts:`[warmly, tired] Come with your kite. It will need a night lantern: see Hesper, at Signpost Cliffs. [softly] Maud.`},sgp_nell_hesper:{s:`nell`,text:`Hesper's the round workshop, under the lighthouse. I've the evening post to sort. Go on.`,tts:`[briskly] Hesper's the round workshop, under the lighthouse. I've the evening post to sort. [cheerfully] Go on.`},sgp_hesper_hello:{s:`hesper`,text:`A Keeper, at this hour. You'll be wanting a night lantern.`,tts:`[dryly] A Keeper, at this hour. You'll be wanting a night lantern.`},sgp_hesper_burnt:{s:`hesper`,text:`See those, under the awning? Kites that flew the night with a cracked pane. The cold gets in, and the heart goes out.`,tts:`[flatly] See those, under the awning? Kites that flew the night with a cracked pane. [quietly] The cold gets in, and the heart goes out.`},sgp_hesper_rule_1:{s:`hesper`,text:`I can't follow a kite in the dark. I read what it writes.`,tts:`[matter-of-fact] I can't follow a kite in the dark. I read what it writes.`},sgp_hesper_rule_2:{s:`hesper`,text:`Tonight yours does the evening rounds: the Point, the Cove, then the lighthouse lens. Three rounds without a breakage, and the lantern's his.`,tts:`Tonight yours does the evening rounds: the Point, the Cove, then the lighthouse lens. [firmly] Three rounds without a breakage, and the lantern's his.`},sgp_hesper_rule_3:{s:`hesper`,text:`One breakage, and he flies his first night with my old test lantern. Weak as a candle.`,tts:`[dryly] One breakage, and he flies his first night with my old test lantern. Weak as a candle.`},sgp_hesper_rule_4:{s:`hesper`,text:`And you: it takes two hands to ring a lantern. Yours will do.`,tts:`[briskly] And you: it takes two hands to ring a lantern. [a little amused] Yours will do.`},sgp_nell_rule:{s:`nell`,text:`Every flight gets its line on the board, the moment you land. The night mail goes by what's written there.`,tts:`[cheerfully] Every flight gets its line on the board, the moment you land. The night mail goes by what's written there.`},sgp_gull_hello:{s:`gull`,text:`Evening, Keeper. My daughter writes to me once a year. It comes tonight, on the night mail.`,tts:`[warmly] Evening, Keeper. [softly] My daughter writes to me once a year. It comes tonight, on the night mail.`},sgp_gull_knees:{s:`gull`,text:`Lens wants cleaning before I light up. My knees don't fit in that glass cage any more.`,tts:`[chuckles] Lens wants cleaning before I light up. My knees don't fit in that glass cage any more.`},sgp_goss_hello:{s:`gossamer`,text:`Keepers. I'll keep to my rail, thanks. I'm only waiting for the night wind.`,tts:`[coolly] Keepers. I'll keep to my rail, thanks. I'm only waiting for the night wind.`},sgp_kite_lantern:{s:`kite`,text:`Look at its lantern... Tonight, we fly together?`,tts:`[wistfully] Look at its lantern... [hopeful] Tonight, we fly together?`},sgp_dax_read:{s:`dax`,text:`"Ledge rope: solid." Lovely. Nell, I'll fetch your letter off the ledge.`,tts:`[cheerfully] "Ledge rope: solid." Lovely. Nell, I'll fetch your letter off the ledge.`},sgp_nell_mind:{s:`nell`,text:`Mind yourself, Dax!`,tts:`[calling] Mind yourself, Dax!`},sgp_dax_down:{s:`dax`,text:`Down I go. Easy as stairs.`,tts:`[breezily] Down I go. Easy as stairs.`},sgp_dax_help:{s:`dax`,text:`Keeper! The rope's gone! I'm on the last knot!`,tts:`[shouting, urgently] Keeper! The rope's gone! I'm on the last knot!`},sgp_kite_dax:{s:`kite`,text:`Dax!`,tts:`[gasps] Dax!`},sgp_dax_letters:{s:`dax`,text:`Nell's letters! The gust's got them! And there's a spare rope by the post!`,tts:`[shouting] Nell's letters! The gust's got them! [strained] And there's a spare rope by the post!`},sgp_dax_wait:{s:`dax`,text:`I can hang here all night. Well. Some of it.`,tts:`[strained, trying to joke] I can hang here all night. [grunts] Well. Some of it.`},sgp_dax_catch:{s:`dax`,text:`Got it! Coming up!`,tts:`[relieved] Got it! Coming up!`},sgp_dax_self:{s:`dax`,text:`Right. One knot at a time, then.`,tts:`[grunting] Right. One knot at a time, then.`},sgp_dax_up:{s:`dax`,text:`That rope was sound. The board said so.`,tts:`[shaken, puzzled] That rope was sound. The board said so.`},sgp_dax_goss:{s:`dax`,text:`You wrote it held!`,tts:`[angry] You wrote it held!`},sgp_goss_held:{s:`gossamer`,text:`It held, yesterday.`,tts:`[flatly] It held, yesterday.`},sgp_nell_top:{s:`nell`,text:`Then I'll take the top path.`,tts:`[briskly] Then I'll take the top path.`},sgp_nell_back:{s:`nell`,text:`Your line said "nothing serious". The rope's hanging in two bits down there.`,tts:`[crossly] Your line said "nothing serious". The rope's hanging in two bits down there.`},sgp_hesper_b2:{s:`hesper`,text:`Right. Kite: the Point first. Straighten what the wind's bent; folk walk by those posts tonight.`,tts:`[briskly] Right. Kite: the Point first. Straighten what the wind's bent; folk walk by those posts tonight.`},sgp_kite_go:{s:`kite`,text:`The Point! Back in a flap!`,tts:`[excited] The Point! Back in a flap!`},sgp_hesper_hold:{s:`hesper`,text:`Keeper, hold the frame. Steady. Don't let go till the solder takes.`,tts:`[focused] Keeper, hold the frame. Steady. Don't let go till the solder takes.`},sgp_hesper_bell:{s:`hesper`,text:`That's the bell. I'll have a look.`,tts:`[mildly] That's the bell. I'll have a look.`},sgp_hesper_point:{s:`hesper`,text:`"Point: five posts straight." That's one.`,tts:`[reading] "Point: five posts straight." [approving] That's one.`},sgp_hesper_cove_go:{s:`hesper`,text:`The Cove next, Kite. Keeper, the horn panes.`,tts:`[briskly] The Cove next, Kite. Keeper, the horn panes.`},sgp_hesper_two:{s:`hesper`,text:`Two rounds. One more without a breakage, and it's yours.`,tts:`[pleased] Two rounds. One more without a breakage, and it's yours.`},sgp_kite_if_cove:{s:`kite`,text:`If she reads that...`,tts:`[whispers] If she reads that...`},sgp_hesper_goback:{s:`hesper`,text:`Four of five? Go back.`,tts:`[flatly] Four of five? Go back.`},sgp_kite_going:{s:`kite`,text:`Going!`,tts:`[a little deflated] Going!`},sgp_hesper_good:{s:`hesper`,text:`Good.`,tts:`[satisfied] Good, then.`},sgp_hesper_cove2:{s:`hesper`,text:`Five of five. That's two.`,tts:`[approving] Five of five. That's two.`},sgp_gull_oil:{s:`gull`,text:`I'll fetch the oil from the village. Mind the glass, little one.`,tts:`[kindly] I'll fetch the oil from the village. Mind the glass, little one.`},sgp_hesper_lens:{s:`hesper`,text:`Last round: the lens. In you go, Kite. Gently.`,tts:`[carefully] Last round: the lens. In you go, Kite. [firmly] Gently.`},sgp_kite_oof:{s:`kite`,text:`Oof! The wind!`,tts:`[startled] Oof! The wind!`},sgp_hesper_third:{s:`hesper`,text:`Third round.`,tts:`[expectant] Third round.`},sgp_gull_shining:{s:`gull`,text:`Well, lad? Is my lens shining?`,tts:`[cheerfully, a bit out of breath] Well, lad? Is my lens shining?`},sgp_kite_if_lens:{s:`kite`,text:`If I write it, no lantern tonight...`,tts:`[whispers] If I write it, no lantern tonight...`},sgp_kite_confess:{s:`kite`,text:`I scratched it. It's written.`,tts:`[quietly] I scratched it. It's written.`},sgp_hesper_breakage:{s:`hesper`,text:`A breakage. You'll fly with my old lantern first.`,tts:`[evenly] A breakage. You'll fly with my old lantern first.`},sgp_gull_turn:{s:`gull`,text:`Path side? Then I'll turn it to face the wall.`,tts:`[thoughtfully] Path side? Then I'll turn it to face the wall.`},sgp_gull_new:{s:`gull`,text:`Good as new!`,tts:`[delighted] Good as new!`},sgp_hesper_fit:{s:`hesper`,text:`Then it's yours. Hold still.`,tts:`[warmly] Then it's yours. Hold still.`},sgp_gull_goodlad:{s:`gull`,text:`Good lad.`,tts:`[fondly] Good lad.`},sgp_gull_light:{s:`gull`,text:`Full dark. Up I go.`,tts:`[contentedly] Full dark. Up I go.`},sgp_goss_lie:{s:`gossamer`,text:`Nobody told me to lie. They told me to come home with a lantern.`,tts:`[quietly] Nobody told me to lie. [pause] They told me to come home with a lantern.`},sgp_goss_leave:{s:`gossamer`,text:`Tomorrow I repaint my paper. Another name.`,tts:`[coldly] Tomorrow I repaint my paper. Another name.`},sgp_nell_go:{s:`nell`,text:`Evening post. Down to the village I go.`,tts:`[cheerfully] Evening post. Down to the village I go.`},sgp_nell_pass:{s:`nell`,text:`Lovely beam tonight. Every step lit.`,tts:`[calling, content] Lovely beam tonight. Every step lit.`},sgp_nell_slip:{s:`nell`,text:`Ah! My foot! Help!`,tts:`[screams] Ah! My foot! [panicked] Help!`},sgp_nell_edge:{s:`nell`,text:`The beam let go of me at the edge.`,tts:`[shaken] The beam let go of me at the edge.`},sgp_nell_tell:{s:`nell`,text:`I'll tell Gull. Something's wrong with that light.`,tts:`[limping, determined] I'll tell Gull. Something's wrong with that light.`},sgp_gull_turned:{s:`gull`,text:`A dark band on the path? I'll turn the glass to the wall.`,tts:`[worried] A dark band on the path? I'll turn the glass to the wall.`},sgp_hesper_b4:{s:`hesper`,text:`Moon's up. The night mail comes in at the lighthouse, and Kite takes it over the Col to the pontoon. Alone.`,tts:`[quietly] Moon's up. The night mail comes in at the lighthouse, and Kite takes it over the Col to the pontoon. [firmly] Alone.`},sgp_hesper_rule_b4:{s:`hesper`,text:`First night flight: nothing down the thread. Not a treat, not a word. I'll be at the pontoon.`,tts:`[firmly] First night flight: nothing down the thread. Not a treat, not a word. I'll be at the pontoon.`},sgp_gull_b4:{s:`gull`,text:`I'll wait at the pontoon too. Once a year, she writes.`,tts:`[softly] I'll wait at the pontoon too. Once a year, she writes.`},sgp_kite_mail:{s:`kite`,text:`Over the Col and back. Every letter!`,tts:`[proudly] Over the Col and back. Every letter!`},sgp_kite_mail2:{s:`kite`,text:`Again. I'll carry it right this time.`,tts:`[determined] Again. I'll carry it right this time.`},sgp_dax_run:{s:`dax`,text:`On the ledge? I'm on it!`,tts:`[shouting, far off] On the ledge? I'm on it!`},sgp_dax_got:{s:`dax`,text:`Got it! Just before the wind!`,tts:`[shouting, triumphant] Got it! Just before the wind!`},sgp_gull_notyear:{s:`gull`,text:`Not this year, then.`,tts:`[quietly, heartbroken] Not this year, then.`},sgp_nell_parcel:{s:`nell`,text:`There's a second night mail. A parcel for Dax's mum, same way over the Col. Your kite can have it.`,tts:`[gently] There's a second night mail. A parcel for Dax's mum, same way over the Col. Your kite can have it.`},sgp_gull_letter:{s:`gull`,text:`"Dear Dad." She's well. She's well, and she's coming in the spring!`,tts:`[reading, moved] "Dear Dad." [voice breaking] She's well. She's well, and she's coming in the spring!`},sgp_dax_parcel:{s:`dax`,text:`Mum's parcel! She'll never know it nearly went.`,tts:`[laughing] Mum's parcel! She'll never know it nearly went.`},sgp_hesper_real:{s:`hesper`,text:`One night flight done. Here's the real one.`,tts:`[warmly] One night flight done. Here's the real one.`},sgp_hesper_stone:{s:`hesper`,text:`There's a place in its foot for one of those stones. It's earned it.`,tts:`[quietly proud] There's a place in its foot for one of those stones. It's earned it.`},sgp_hesper_nostone:{s:`hesper`,text:`"Mail delivered." Then the lantern stays on.`,tts:`[neutral] "Mail delivered." Then the lantern stays on.`},sgp_nell_reply:{s:`nell`,text:`Anything for the Library? The dawn post leaves from here.`,tts:`[cheerfully] Anything for the Library? The dawn post leaves from here.`},sgp_nell_reply_ok:{s:`nell`,text:`"We're coming." I'll see she gets it.`,tts:`[warmly] "We're coming." I'll see she gets it.`},sgp_kite_warm:{s:`kite`,text:`It's warm in here. The wind can't get at me.`,tts:`[softly, happy] It's warm in here. The wind can't get at me.`},sgp_hesper_chat_1:{s:`hesper`,text:`Every one of those burnt kites was sure its pane would hold.`,tts:`[dryly] Every one of those burnt kites was sure its pane would hold.`},sgp_hesper_chat_2:{s:`hesper`,text:`Night lanterns are slow work. Three rings, horn panes, and no hurrying the solder.`,tts:`[matter-of-fact] Night lanterns are slow work. Three rings, horn panes, and no hurrying the solder.`},sgp_hesper_chat_3:{s:`hesper`,text:`The Common Box? Lanterns promised to the guilds. Not one leaves it on a maybe.`,tts:`[firmly] The Common Box? Lanterns promised to the guilds. Not one leaves it on a maybe.`},sgp_gull_chat_1:{s:`gull`,text:`Forty years on this light. You learn which way the gust comes up the Col.`,tts:`[warmly] Forty years on this light. You learn which way the gust comes up the Col.`},sgp_gull_chat_2:{s:`gull`,text:`Her letters always smell of the sea. A different sea from ours.`,tts:`[softly, fond] Her letters always smell of the sea. A different sea from ours.`},sgp_nell_chat_1:{s:`nell`,text:`The night mail comes in on kites from off-island. Your kite'll be one of them tonight, if Hesper says so.`,tts:`[cheerfully] The night mail comes in on kites from off-island. Your kite'll be one of them tonight, if Hesper says so.`},sgp_nell_chat_2:{s:`nell`,text:`A bag full of other people's news. Heavy, some nights.`,tts:`[wryly] A bag full of other people's news. [sighs] Heavy, some nights.`},sgp_dax_chat_1:{s:`dax`,text:`I go down for whatever falls. Letters, hats. Once, a whole goose.`,tts:`[cheerfully] I go down for whatever falls. Letters, hats. [laughs] Once, a whole goose.`},sgp_dax_chat_2:{s:`dax`,text:`New rope tomorrow. Tonight I'm trusting nothing I haven't pulled on myself.`,tts:`[ruefully] New rope tomorrow. Tonight I'm trusting nothing I haven't pulled on myself.`},sgp_goss_chat:{s:`gossamer`,text:`Master Vane counts lanterns. He'll count this one.`,tts:`[flatly] Master Vane counts lanterns. He'll count this one.`},sgp_dax_ledge:{s:`dax`,text:`Wind comes down on that ledge. Here, grab the rope.`,tts:`[calling] Wind comes down on that ledge. Here, grab the rope.`},sgp_hesper_bench:{s:`hesper`,text:`Keeper! The bench. My hands are full.`,tts:`[calling] Keeper! The bench. My hands are full.`}}}));function AX(e,t,n,r=1){let i=e.center.x,a=e.center.y,o=e.center.z,s=n.pos.length/3,c=MX.length;t.forEach((t,l)=>{let u=e.R*e.rim(t),d=Math.cos(t),f=Math.sin(t),p=a+e.heightLocal(d*u*.999,f*u*.999),m=NX(t);for(let a=0;ae*Math.PI/180,E={pos:[],uv:[],idx:[]};{let e=[];for(let t=-36;t<=296;t+=1.1)e.push(T(t));AX(a,e,E)}{let e=[],t=()=>{e.length>2&&AX(o,e,E,.9),e=[]};for(let n=-180;n<=180;n+=2.5){let s=T(n),c=o.R*o.rim(s),l=o.center.x+Math.cos(s)*c,u=o.center.z+Math.sin(s)*c,d=Math.atan2(u-r.z,l-r.x);Math.hypot(l-r.x,u-r.z)>i*a.rim(d)+.4?e.push(s):t()}t()}let D=new xo;D.setAttribute(`position`,new R(E.pos,3)),D.setAttribute(`uv`,new R(E.uv,2)),D.setIndex(E.idx),D.computeVertexNormals();{let e=D.attributes.normal,t=D.attributes.position,n=MX.length*3+3,i=t.getX(n)-r.x,a=t.getZ(n)-r.z;if(e.getX(n)*i+e.getZ(n)*a<0){let e=D.index.array;for(let t=0;tm){let e=Math.max(0,m)/d;a.setX(o,s*e),a.setZ(o,l*e)}}a.needsUpdate=!0,e.mesh.geometry.computeVertexNormals(),e.mesh.geometry.computeBoundingSphere()}let ee=YJ.chalk({seed:6}),O=Q(16118248,{map:ee,rim:.22});O.emissiveNode=O.emissiveNode.add(DH(ee).rgb.mul(XV(15722975)).mul(f));let k=new z(D,O);k.castShadow=!0,k.receiveShadow=!0,k.userData.outlineThick=.028,e.add(k);let te=e=>{for(let t of[a,o]){let n=e.pos.x-t.center.x,r=e.pos.z-t.center.z,i=Math.atan2(r,n),o=Math.hypot(n,r),s=t.R*t.rim(i);if(t===a){let e=i*180/Math.PI;if(e>-64&&e<-36)continue}let c=t.center.y+t.heightLocal(Math.cos(i)*s*.999,Math.sin(i)*s*.999)-e.pos.y;if(c<.6||c>34)continue;let l=(s-.15)*PX(c)+NX(i)+.5;if(ol-4.5){let i=l/Math.max(o,.001);e.pos.x=t.center.x+n*i,e.pos.z=t.center.z+r*i}}},A=[d.colEdge,d.colRope,d.colCenter,d.slip,d.boardMid,d.bench,d.keeperBench,d.hesperBench,d.chest,d.railA,d.railB,d.gullDoor,d.mailDrop,d.landing,d.nellArrive,d.pontoonRoot,d.pBoardA,d.pBoardB,d.boardRead,d.pBoardRead,d.village,d.nellHouse,...x.point.map(e=>e.p),...x.cove.map(e=>e.p)],ne=(e,n=2.4)=>!y(e.x,e.z,1.5)&&A.every(t=>Math.hypot(t.x-e.x,t.z-e.z)>n)&&Math.hypot(e.x-p.x,e.z-p.z)>m+1.5&&Math.hypot(e.x-h.x,e.z-h.z)>3.2&&t.ground(e.x,e.z)!==null,re=[],ie=(e,t)=>ne(e)&&re.every(t=>Math.hypot(t.p.x-e.x,t.p.z-e.z)>1.3)?(re.push({p:e,h:t,lean:(S()-.5)*.12,yaw:S()*6.28}),!0):!1;for(let e=-30;e>=-168;e-=3.2){let t=e+(S()-.5)*2;t>-64&&t<-38||(ie(c(t,.9+S()*.9),2.1+S()*.9),S()<.6&&ie(c(t+1.5,5+S()*2.2),2.2+S()*.8))}for(let e=-20;e<=192;e+=7)ie(c(e+(S()-.5)*3,1+S()*1.2),1.9+S()*.8);for(let[e,t]of[[15,-7],[17,-3],[2,-8],[-3,-12],[-8,-8],[-11,-15],[-15,-12],[-6,8],[0,13],[8,9],[13,13],[19,9],[-12,17],[-4,20],[22,-9]])ie(l(e+(S()-.5)*2,t+(S()-.5)*2),2+S()*1);let ae=new Ic(.07,.095,1,6).translate(0,.5,0),j=new Fs(ae,Q(9735296,{rim:.2}),re.length),oe=new ul;oe.moveTo(0,-.105),oe.lineTo(.74,-.105),oe.lineTo(.88,0),oe.lineTo(.74,.105),oe.lineTo(0,.105),oe.closePath();let se=new pl(oe,{depth:.045,bevelEnabled:!1}).translate(-.06,0,-.022),ce=[],le=new F,ue=new gi,de=new Ji,fe=[13946045,12564136,14472388,11445656,13155496,14735562].map(e=>new L(e));re.forEach((e,t)=>{de.set(e.lean,e.yaw,e.lean*.6),ue.setFromEuler(de),le.compose(e.p.clone().add($(0,-.1,0)),ue,$(1,e.h,1)),j.setMatrixAt(t,le);let n=2+Math.floor(S()*3);for(let t=0;t{de.set(0,e.yaw,e.tilt),ue.setFromEuler(de),le.compose(e.p,ue,$(e.len,1,1)),pe.setMatrixAt(t,le),pe.setColorAt(t,fe[t%fe.length])}),j.castShadow=pe.castShadow=!0,j.instanceMatrix.needsUpdate=pe.instanceMatrix.needsUpdate=!0,pe.instanceColor&&(pe.instanceColor.needsUpdate=!0),e.add(j,pe);let me=re.map(e=>e.p.clone().add($(0,e.h-.12,0))),he=re.filter((e,t)=>t%5==2).slice(0,9),ge=[],_e=new Fs(new Ic(.018,.018,1,6).translate(0,-.5,0),Q(13225688,{rim:.6}),he.length*5),ve=new Fs(new Ic(.13,.13,.04,10),Q(6967874,{rim:.15}),he.length);he.forEach((e,t)=>{let n=$(e.p.x-r.x,0,e.p.z-r.z).normalize(),i=e.p.clone().add($(0,e.h-.2,0)).addScaledVector(n,.35);le.compose(i,ue.identity(),$(1,1,1)),ve.setMatrixAt(t,le);for(let e=0;e<5;e++){let t=e/5*6.28;ge.push({p:i.clone().add($(Math.cos(t)*.09,-.03,Math.sin(t)*.09)),len:.3+e*.08+S()*.05,ph:S()*6.28})}}),_e.frustumCulled=!1,e.add(_e,ve),he.length?he[0].p.clone():r.clone();let ye={mesh:_e,center:r.clone(),range:120,update(e,t){ge.forEach((e,n)=>{de.set(Math.sin(t*2.3+e.ph)*.14,0,Math.sin(t*1.7+e.ph*1.3)*.12),ue.setFromEuler(de),le.compose(e.p,ue,$(1,e.len,1)),_e.setMatrixAt(n,le)}),_e.instanceMatrix.needsUpdate=!0}};ye.update(0,0),C.push(ye);let be=[],xe=re.map((e,t)=>({s:e,t:me[t],d:Math.atan2(e.p.z-r.z,e.p.x-r.x)*180/Math.PI,r:Math.hypot(e.p.x-r.x,e.p.z-r.z)})).filter(e=>e.r>i*.84).sort((e,t)=>e.d-t.d);for(let e=0;e2.5&&r<9.5&&S()<.85&&be.push([t.t,n.t])}xe.filter((e,t)=>t%4==1).slice(0,8).forEach(e=>{let t=$(e.s.p.x-r.x,0,e.s.p.z-r.z).normalize();be.push([e.t,e.t.clone().addScaledVector(t,2.2).add($((S()-.5)*2,-3.5-S()*2,0))])}),be.push([h.clone().add($(-1.2,7.5,1)),d.boardB.clone().add($(0,2.3,0))]),be.push([l(-13,0,2.4),l(-10,14,2.4)]);let Se=be.filter((e,t)=>t%3==1),Ce=oJ(e,be.filter((e,t)=>t%3!=1),{kind:`strip`,every:.36,sag:.1,size:1.55,colours:[16512748,15983040,15262452,16176847,14083822,16248264],range:170,seed:17}),we=oJ(e,Se,{kind:`flag`,every:.42,sag:.1,size:1.3,colours:[15984328,15324848,16183266,15255992,13229030],range:170,seed:18});for(let e of[Ce,we]){let t=e.extra[0],n=t.children.filter(e=>e.isMesh&&!e.isInstancedMesh);if(n.length>1){let e=new z(UU(n.map(e=>e.geometry),!1),n[0].material);e.userData.noOutline=!0;for(let e of n)t.remove(e);t.add(e)}}C.push(Ce,we);let Te=$(d.colCenter.x-r.x,0,d.colCenter.z-r.z).normalize(),Ee=sJ(e,d.colCenter.clone().addScaledVector(Te,7).add($(0,-2,0)),{n:14,radius:13,height:[5,15],colour:16512226,size:.26,range:160,seed:21}),De=Ee.update;Ee.quiet=!1,Ee.update=(e,t)=>{if(Ee.quiet){Ee.mesh.visible=!1;return}De(e,t)},C.push(Ee),C.push(sJ(e,d.village.clone().add($(0,2,0)),{n:8,radius:11,height:[5,12],colour:16181458,size:.24,range:140,seed:22}));let M=Q(8093576,{rim:.45}),Oe=Q(9067066,{rim:.15}),ke=GJ(13215098,YJ.planks({boards:5,seed:4}),{scale:1.4}),Ae=$(Math.sin(b),0,Math.cos(b));$(Ae.z,0,-Ae.x);for(let e of[-1,1]){let t=b+e*.62,n=$(Math.sin(t),0,Math.cos(t)),r=p.clone().addScaledVector(n,m+.06).add($(0,1.7,0)),i=t;g.box(1.5,1,.06,ke,r,[0,i,0]);let a=$(Math.cos(i),0,-Math.sin(i));for(let t=0;t<6;t++){let o=r.clone().addScaledVector(a,-.6+t*.24).addScaledVector(n,.06),s=(t+ +(e>0))%3;s===0?(g.box(.04,.4,.03,Oe,o.clone().add($(0,-.06,0)),[0,i,0]),g.box(.17,.06,.05,M,o.clone().add($(0,.16,0)),[0,i,0])):s===1?(g.box(.035,.36,.02,M,o.clone().add($(0,-.04,0)),[0,i,0]),g.add(new Cl(.045,.013,4,10),M,o.clone().add($(0,.17,0)),[0,i,0])):(g.box(.025,.34,.02,M,o.clone().add($(-.03,-.02,0)),[0,i,.18]),g.box(.025,.34,.02,M,o.clone().add($(.03,-.02,0)),[0,i,-.18]))}for(let e of[.52,-.52])g.box(1.56,.05,.08,Oe,r.clone().add($(0,e,0)).addScaledVector(n,.02),[0,i,0])}{let e=d.chest,t=b+.3,n=$(Math.sin(t),0,Math.cos(t)),r=new Nc(1.24,.1,.76).translate(0,0,.38).rotateX(-1.95);g.add(r,ke,e.clone().add($(0,.64,0)).addScaledVector(n,-.38),[0,t,0]),g.box(1.1,.06,.62,Q(14271098,{rim:.2}),e.clone().add($(0,.6,0)),[0,t,0]);for(let n=0;n<3;n++){let r=e.clone().add($(0,.72,0)).addScaledVector($(Math.cos(t),0,-Math.sin(t)),-.36+n*.36);g.cyl(.09,.12,.06,v.brass,r.clone().add($(0,.14,0)),[0,0,0],8),g.cyl(.11,.11,.04,v.brass,r.clone().add($(0,-.1,0)),[0,0,0],8),w.push(r)}}let je=(e,n)=>{t.colliders.push({x:e.x,z:e.z,r:.26,noCam:!0}),g.cyl(.06,.07,1,v.postDark,e.clone().add($(0,.5,0)),[0,0,0],6),g.box(.46,.34,.3,v.red,e.clone().add($(0,1.12,0)),[0,n,0]),g.cyl(.15,.15,.46,v.red,e.clone().add($(0,1.28,0)),[0,n,Math.PI/2],10),g.box(.2,.03,.02,v.ink,e.clone().add($(0,1.2,0)).addScaledVector($(Math.sin(n),0,Math.cos(n)),.16),[0,n,0])};for(let[e,t]of[[l(14,-4.5),2.6],[c(-76,5.2),.8],[c(-122,5),1.2],[l(-16,12.5),-.6],[l(18.5,10),2.2],[l(4,6.5),.4],[l(-25,-2),1.9]])ne(e,1.6)&&je(e,t);let Me=(e,n)=>{let r=$(Math.sin(n),0,Math.cos(n)),i=$(r.z,0,-r.x);for(let n of[-.5,.5])t.colliders.push({x:e.x+i.x*n,z:e.z+i.z*n,r:.32,y:e.y+.5,h:.75,noCam:!0});g.box(1.6,.08,.42,ke,e.clone().add($(0,.46,0)),[0,n,0]),g.box(1.6,.3,.06,ke,e.clone().add($(0,.78,0)).addScaledVector(r,-.2),[0,n,0]);for(let t of[-.65,.65])g.box(.08,.46,.4,Oe,e.clone().addScaledVector(i,t).add($(0,.23,0)),[0,n,0])};for(let[e,t]of[[l(2.5,-14.5),d.colCenter],[l(-17,1.5),d.village],[c(-128,5.6),d.colCenter],[l(16,1.5),d.boardMid]])ne(e,1.8)&&Me(e,Math.atan2(t.x-e.x,t.z-e.z));let Ne=(e,n,r)=>{t.colliders.push({x:e.x,z:e.z,r:.45,y:e.y+.35,h:.7,noCam:!0}),g.box(.8,.5,.6,ke,e.clone().add($(0,.25,0)),[0,n,0]);for(let t=0;t{let n=Math.hypot(e-h.x,t-h.z);return n>1.6&&n<2.15?h.y+.4:null}});let Fe=[];for(let e=0;e<26;e++){let e=S()*6.28,n=i*(.2+S()*.72),a=$(r.x+Math.cos(e)*n,0,r.z+Math.sin(e)*n);if(!ne(a,2.2))continue;let o=.25+S()*.55;a.y=(t.ground(a.x,a.z)??r.y)+o*.25,Fe.push({x:a.x,y:a.y,z:a.z,r:o})}let Ie=YU(Fe,33);Ie.material=Q(15131094,{rim:.25}),e.add(Ie);let Le=UU([0,1,2,3].map(e=>new Lc(.07,.5+e*.08,4).translate(Math.cos(e*1.7)*.1,.25+e*.04,Math.sin(e*1.7)*.1).rotateZ((e-1.5)*.25)),!1),Re=[];for(let e=0;e<150;e++){let e=S()*6.28,n=i*Math.sqrt(S())*.97,a=$(r.x+Math.cos(e)*n,0,r.z+Math.sin(e)*n);if(y(a.x,a.z,1)||Math.hypot(a.x-p.x,a.z-p.z){le.compose(e,ue.identity(),$(1,1,1)),Be.setMatrixAt(t,le)}),Be.instanceMatrix.needsUpdate=!0,e.add(Be),{ambient:C,pushOut:te,walls:k,colPages:Ee}}var MX,NX,PX,FX=t((()=>{mY(),qU(),new P(0,1,0),MX=[[0,1],[.7,1.014],[3,1.008],[7,1],[11,.994],[15,.988],[19,.98],[23,.97],[27,.955],[30,.93],[33,.8],[36,.45]],NX=e=>.42*Math.sin(e*31+.7)+.26*Math.sin(e*73+2.1)+.14*Math.sin(e*151+.4)+1.1*Math.max(0,Math.sin(e*9+.3))**6-.25*Math.max(0,Math.sin(e*17+1.9))**12,PX=e=>{if(e<=0)return MX[0][1];for(let t=1;te.clone().add($(0,2.05,0));for(let e of[t,n]){let t=new z(new Ic(.07,.09,2.3,6),s);t.position.copy(e).add($(0,2.3/2,0)),o.add(t)}let u=[];for(let e=0;e<=16;e++){let r=e/16;u.push(l(t).lerp(l(n),r).add($(0,-Math.sin(r*Math.PI)*.12,0)))}let d=new z(new Tl(new $c(u),32,.012,4),new Y({color:3813188}));d.userData.noOutline=!0,o.add(d);let f=e=>l(t).lerp(l(n),e).add($(0,-Math.sin(e*Math.PI)*.12,0)),p=f(i===`a`?.02:.98).add($(0,-.02,0)),m=new I;m.position.copy(p),o.add(m);let h=Q(15777888,{rim:.5});h.emissiveNode=SU(16758832,.25);let g=new z(new Ic(.05,.1,.14,10,1,!0),h);g.position.y=-.12,g.material.side=2,g.userData.noOutline=!0,m.add(g);let _=new z(new xl(.03,6,5),Q(7227955));_.position.y=-.2,_.userData.noOutline=!0,m.add(_);let v=$(-c.z,0,c.x),y=Math.atan2(v.x,v.z),b={g:o,a:t,b:n,dir:c,face:v,yaw:y,strips:[],bell:m,swing:0,slots:r,at:f,label:a,add(e,n=null){let i=new WX(e),a=n??b.strips.length;i.slot=a;let s=(a+.7)/(r+.4);return i.root.position.copy(f(s)),i.root.rotation.y=y,o.add(i.root),b.strips.push(i),i.pos=i.root.position.clone().add($(0,-.25,0)).addScaledVector(v,.6),i.pos.y=t.y,i.center=i.root.position.clone().add($(0,-.2,0)),i},ring(){b.swing=1},clear(){for(let e of b.strips)o.remove(e.root);b.strips=[]},update(e,t,n){b.swing=Math.max(0,b.swing-t*.8),m.rotation.z=Math.sin(e*16)*.5*b.swing;for(let r of b.strips)r.update(e,t,n)}};return b}function LX(e,t=14268810,n=.028){let r=new z(new Ic(n,n,1,5,1).translate(0,.5,0),Q(t,{rim:.2}));return r.userData.noOutline=!0,r.visible=!1,e.add(r),r.userData.between=(e,t)=>{let n=t.clone().sub(e),i=n.length();r.position.copy(e),r.quaternion.setFromUnitVectors(UX,n.normalize()),r.scale.set(1,Math.max(.01,i),1),r.visible=!0},r}function RX(){let e=document.createElement(`canvas`);e.width=128,e.height=88;let t=e.getContext(`2d`);t.fillStyle=`#fbf6ea`,t.fillRect(0,0,128,88),t.strokeStyle=`#3a2f44`,t.lineWidth=5,t.strokeRect(3,3,122,82),t.lineWidth=3,t.beginPath(),t.moveTo(4,6),t.lineTo(64,50),t.lineTo(124,6),t.stroke(),t.fillStyle=`#c0573f`,t.beginPath(),t.arc(64,50,9,0,Math.PI*2),t.fill();let n=new Oc(e);return n.colorSpace=Mr,n}function zX(e,t,n){let r=$(...n.center),i=n.radius,a=lU(311),o=sY(e,t,{name:`signpost`,center:n.center,radius:i,depth:i*1.3,seed:347,hill:.9,rimJag:.06,palette:BX,flats:[{x:9,z:-8,r:12,h:.8},{x:17,z:-19,r:7,h:1.1},{x:24,z:3,r:6,h:.7},{x:2,z:-24,r:6,h:.5},{x:-18,z:-20,r:6,h:.3},{x:-9.5,z:-27,r:6.5,h:-.9},{x:-19,z:7,r:10,h:.5},{x:13,z:22,r:7,h:.4},{x:-8,z:25,r:7,h:.3}]}),s=e=>i*o.rim(e*Math.PI/180),c=(e,n,i=0)=>$(e,(t.ground(e,n)??r.y)+i,n),l=(e,t,n=0)=>c(r.x+e,r.z+t,n),u=(e,t=2,n=0)=>{let r=e*Math.PI/180,i=s(e)-t;return l(Math.cos(r)*i,Math.sin(r)*i,n)},d=(e,t)=>{let n=e*Math.PI/180,i=s(e)-t;return[r.x+Math.cos(n)*i,r.z+Math.sin(n)*i]},f=-108,[p,m]=d(f,-1.7),h=o.groundAt(...d(f,1.5))??r.y,g=sY(e,t,{name:`signpost-ledge`,center:[p,h-4.2,m],radius:5,depth:6,seed:353,hill:.12,rimJag:.12,palette:BX,flats:[{x:0,z:0,r:4.8,h:0}]}),[_,v]=d(-50,-4.2),y=sY(e,t,{name:`signpost-headland`,center:[_,r.y+1,v],radius:7.2,depth:i*1.15,seed:359,hill:.3,rimJag:.1,palette:BX,flats:[{x:0,z:0,r:4.6,h:1.3}]}),b=[o,g,y];for(let e of b){let t=Math.round(150*e.detail),n=1+Math.max(8,Math.round(26*e.detail))*t,r=e.mesh.geometry.attributes.color,i=new L(14673615),a=new L(16250090);for(let e=0;e<3;e++)for(let o=0;oMath.atan2(t.x-e.x,t.z-e.z),ee=(e,n,r=2,i=2.3,o=0)=>{T.cyl(.07,.09,i,w.postDark,e.clone().add($(0,i/2,0)),[o,0,o*.5],6),t.colliders.push({x:e.x,z:e.z,r:.12,noCam:!0});for(let t=0;t{t.colliders.push({x:e.x,z:e.z,r:.26,noCam:!0}),T.cyl(.06,.07,1,w.postDark,e.clone().add($(0,.5,0)),[0,0,0],6),T.box(.46,.34,.3,w.red,e.clone().add($(0,1.12,0)),[0,n,0]),T.cyl(.15,.15,.46,w.red,e.clone().add($(0,1.28,0)),[0,n,Math.PI/2],10)};for(let[e,t]of[[-60,2.2],[-72,1.6],[-82,1.4],[-116,1.6],[-126,1.8],[-138,2.2],[-152,2.6],[170,2.4],[160,3.5],[150,2.2],[20,2.4],[30,1.8],[-20,2.4],[-30,2.2],[-40,3],[88,3],[124,2.6]])ee(u(e,t),(e+90)*Math.PI/180,2+Math.floor(a()*2),2.1+a()*.5,(a()-.5)*.08);for(let[e,t]of[[18,6],[3,-14],[-6,-16],[-13,0],[-10,14],[6,12],[20,-3]])ee(l(e,t),a()*6,2+Math.floor(a()*2),2.2+a()*.5);O(l(9,-11.6),-2.4),O(l(22.5,5.5),-1.4),O(l(-17.5,3.5),1.6),O(u(131,4.3),2.2),O(l(-3,-21),.3);let k=S.lighthouse,te=11.2;for(let e=0;e<7;e++){let t=e*te/7,n=(e+1)*te/7,r=1.75-t/te*.5,i=1.75-n/te*.5;T.cyl(i,r,n-t,e%2?w.red:w.white,k.clone().add($(0,(t+n)/2,0)),[0,0,0],16)}let A=k.y+te;T.cyl(1.95,1.95,.18,w.stoneDark,$(k.x,A+.09,k.z),[0,0,0],18);for(let e=0;e<16;e++){let t=e/16*Math.PI*2;T.cyl(.03,.03,.8,w.ink,$(k.x+Math.cos(t)*1.85,A+.55,k.z+Math.sin(t)*1.85),[0,0,0],4)}T.add(new Cl(1.85,.035,4,32),w.ink,$(k.x,A+.95,k.z),[Math.PI/2,0,0]);for(let e=0;e<8;e++){let t=e/8*Math.PI*2;T.cyl(.04,.04,1.9,w.red,$(k.x+Math.cos(t)*1.1,A+1.13,k.z+Math.sin(t)*1.1),[0,0,0],4)}T.cyl(.25,1.35,1.1,w.red,$(k.x,A+2.6,k.z),[0,0,0],16),T.add(new xl(.22,10,8),w.red,$(k.x,A+3.25,k.z)),T.box(.9,1.7,.2,w.wood,S.gullDoor.clone().lerp(k,.35).add($(0,.85,0)),[0,D(k,S.gullDoor),0]);let ne=new SO({color:12575743,transparent:!0,opacity:.32,depthWrite:!1});ne.emissiveNode=SU(10473727,.25);let re=new z(new Ic(1.08,1.08,1.85,16,1,!0),ne);re.position.set(k.x,A+1.12,k.z),e.add(re);let ie=Q(16051400,{rim:.6});ie.emissiveNode=SU(16773832,.18);let ae=new z(new Ic(.42,.5,1.05,8,4),ie);ae.position.set(k.x,A+1.1,k.z),e.add(ae);let j=new z(new xl(.62,16,12),oY(16773312,2.4,.15));j.position.copy(ae.position),j.visible=!1,j.userData.noOutline=!0,e.add(j);let oe=ae.position.clone();S.lamp=oe;let se=new z(new Nc(.03,.5,.06),w.ink);se.visible=!1,se.userData.noOutline=!0,e.add(se),S.gallery=$(k.x,A+.18,k.z),t.surfaces.push({at:(e,t)=>{let n=Math.hypot(e-k.x,t-k.z);return n>1.2&&n<1.85?A+.18:null}}),t.colliders.push({x:k.x,z:k.z,r:1.7,y:k.y+te/2,h:5.8}),t.camTrunks.push({x:k.x,z:k.z,r:1.7,y0:k.y-1,y1:A+3});{let e=S.gullCottage,n=D(e,S.boardB);T.box(3.4,2.4,3,w.wall,e.clone().add($(0,1.2,0)),[0,n,0]),T.add(new Ic(.01,2.5,1.5,4,1).rotateY(Math.PI/4),w.roofRed,e.clone().add($(0,3.15,0)),[0,n,0],[1,1,.9]);let r=$(Math.sin(n),0,Math.cos(n));T.box(.8,1.6,.1,w.wood,e.clone().addScaledVector(r,1.52).add($(.6,.8,0)),[0,n,0]),t.colliders.push({x:e.x,z:e.z,r:2.1}),S.gullWindow=e.clone().addScaledVector(r,1.55).add($(-.7,1.4,0))}{let e=S.railA,n=S.railB;for(let t of[0,.5,1]){let r=e.clone().lerp(n,t);T.cyl(.06,.07,1.1,w.wood,r.clone().add($(0,.55,0)),[0,0,0],6)}{let r=Math.max(2,Math.ceil(e.distanceTo(n)/.35));for(let i=0;i<=r;i++){let a=e.clone().lerp(n,i/r);t.colliders.push({x:a.x,z:a.z,r:.08,y:a.y+.6,h:.9,noCam:!0})}}let r=n.clone().sub(e),i=r.length();T.box(i+.2,.08,.1,w.woodLight,e.clone().lerp(n,.5).add($(0,1.1,0)),[0,Math.atan2(-r.z,r.x),0]),S.railTop=e.clone().lerp(n,.5).add($(0,1.55,0))}let ce=S.workshop,le=3.3;T.cyl(le,3.4,3.2,w.stone,ce.clone().add($(0,1.6,0)),[0,0,0],20),T.cyl(3.65,3.65,.35,w.stoneDark,ce.clone().add($(0,3.3,0)),[0,0,0],20),T.cyl(3.1999999999999997,3.1999999999999997,.12,w.stoneDark,ce.clone().add($(0,3.45,0)),[0,0,0],20),t.colliders.push({x:ce.x,z:ce.z,r:3.4}),t.camTrunks.push({x:ce.x,z:ce.z,r:le,y0:ce.y-1,y1:ce.y+3.4});let ue=ce.y+2.9,de=D(S.bench,S.boardA.clone().lerp(S.boardB,.5));{let e=$(Math.sin(de),0,Math.cos(de)),n=$(e.z,0,-e.x),r=ce.clone().addScaledVector(e,4.5),i=new vl(5.6,2.5,16,5),o=i.attributes.position;for(let e=0;e{T.box(3.2*i,2.3*i,2.8*i,w.wall,e.clone().add($(0,1.15*i,0)),[0,n,0]),T.add(new Ic(.01,2.4*i,1.5*i,4,1).rotateY(Math.PI/4),r,e.clone().add($(0,3*i,0)),[0,n,0],[1,1,.9]);let a=$(Math.sin(n),0,Math.cos(n));return T.box(.75,1.5,.1,w.wood,e.clone().addScaledVector(a,1.42*i).add($(.55,.75,0)),[0,n,0]),t.colliders.push({x:e.x,z:e.z,r:1.95*i}),e.clone().addScaledVector(a,1.46*i).add($(-.6,1.3,0))},pe=[];pe.push(fe(S.nellHouse,D(S.nellHouse,S.village),w.roofBlue)),pe.push(fe(l(-14.5,11),D(l(-14.5,11),S.village),w.roofRed,.9)),pe.push(fe(l(-24,11.5),D(l(-24,11.5),S.village),w.roofBlue,.85)),pe.push(fe(l(-12.5,2.5),D(l(-12.5,2.5),S.village),w.roofRed,.8)),pe.push(S.gullWindow);{let e=S.pontoonRoot,n=S.pontoonEnd.clone().sub(e).setY(0),r=n.length();n.normalize();let i=$(-n.z,0,n.x),a=Math.atan2(n.x,n.z),o=e.y+.12;for(let t=0;t{let s=t-e.x,c=a-e.z,l=s*n.x+c*n.z,u=s*i.x+c*i.z;return l>-1.2&&l({p:e,s:[.55,.55,.12]})),...me.map(e=>({p:e.clone().add($(0,2.72,0)),s:[.22,.22,.22]}))],ge=new Fs(new Nc(1,1,1),oY(16764794,1.5),he.length);ge.userData.noOutline=!0;{let e=new F,t=new gi;he.forEach((n,r)=>{e.compose(n.p,t,$(...n.s)),ge.setMatrixAt(r,e)}),ge.instanceMatrix.needsUpdate=!0}ge.visible=!1,e.add(ge);{let e=S.colEdge;T.cyl(.1,.12,1.3,w.wood,e.clone().add($(0,.65,0)),[0,0,0],6),T.add(new Cl(.16,.05,5,12),w.woodLight,e.clone().add($(0,1.1,0)),[Math.PI/2,0,0]);let n=S.colRope;T.box(.8,.5,.6,w.wood,n.clone().add($(0,.25,0)),[0,.4,0]),T.add(new Cl(.24,.07,6,14),Q(14268810),n.clone().add($(0,.58,0)),[Math.PI/2,0,0]),t.colliders.push({x:n.x,z:n.z,r:.5})}S.ropeTop=S.colEdge.clone().add($(0,1.05,0));{let t=u(-115,2.2);T.cyl(.07,.09,2.2,w.postDark,t.clone().add($(0,1.1,0)),[0,0,0],6);let n=aY([`The Col`,`↓ ledge`],{w:.9,h:.5,px:256,font:`700 42px Fraunces, Georgia, serif`,bg:`#d6cbb6`});n.position.copy(t).add($(0,1.85,0)),n.rotation.y=Math.atan2(r.x-t.x,r.z-t.z),e.add(n)}cY(e,t,S.gust.x,S.gust.z,{r:6.5,bottom:-34,top:h+9,lift:7.5,seed:31}),t.updrafts.push({x:S.ledgeTop.x,z:S.ledgeTop.z,r:3.4,top:h+4,lift:-4.5});let _e={point:[],cove:[]},ve=(e,t,n)=>({p:e,axis:$(t.z,0,-t.x).normalize(),lean:n,want:n,yaw:Math.atan2(t.x,t.z)+(a()-.5)*1.2,spin:0});for(let e=0;e<5;e++){let t=46+e*6.5,n=u(t,3-(e===2?.8:0)),r=$(Math.cos(t*Math.PI/180),0,Math.sin(t*Math.PI/180));_e.point.push(ve(n,r,.42+a()*.25))}for(let e=0;e<5;e++){let t=96+e*5.5,n=u(t,e===4?.9:2.8),r=$(Math.cos(t*Math.PI/180),0,Math.sin(t*Math.PI/180));_e.cove.push(ve(n,r,e===4?.72:.4+a()*.25))}let ye=[..._e.point,..._e.cove];for(let e of ye)t.colliders.push({x:e.p.x,z:e.p.z,r:.11,noCam:!0});let be=new Fs(new Ic(.07,.09,2.3,6).translate(0,1.15,0),w.postDark,ye.length),xe=new Fs(new Nc(.06,.22,.95).translate(0,0,.28),w.boardLight,ye.length*2);be.castShadow=xe.castShadow=!0,e.add(be,xe);let Se=new F,Ce=new gi,we=new gi,Te=new gi,Ee=$(1,1,1),De=new F,M=[0,1].map(e=>new F().compose($(0,2-e*.38,0),new gi().setFromAxisAngle(UX,e?2.2:-.3),$(1,1,1))),Oe=()=>{ye.forEach((e,t)=>{we.setFromAxisAngle(e.axis,e.lean),Te.setFromAxisAngle(UX,e.yaw+Math.sin(e.spin)*.25),Ce.copy(we).multiply(Te),Se.compose(e.p,Ce,Ee),be.setMatrixAt(t,Se);for(let e=0;e<2;e++)De.multiplyMatrices(Se,M[e]),xe.setMatrixAt(t*2+e,De)}),be.instanceMatrix.needsUpdate=!0,xe.instanceMatrix.needsUpdate=!0};Oe(),_e.reset=()=>{for(let e of ye)e.lean=e.want=e.bent??e.lean;Oe()};for(let e of ye)e.bent=e.lean;_e.top=e=>e.p.clone().add($(0,2.5,0));let ke=IX(e,S.boardA,S.boardB,{slots:7,bellAt:`b`}),Ae=IX(e,S.pBoardA,S.pBoardB,{slots:3,bellAt:`a`});S.boardMid=S.boardA.clone().lerp(S.boardB,.5),S.boardPerch=S.boardB.clone().add($(0,2.6,0)),S.pBoardPerch=S.pBoardA.clone().add($(0,2.6,0)),S.boardRead=S.boardMid.clone().addScaledVector(ke.face,2),S.pBoardRead=S.pBoardA.clone().lerp(S.pBoardB,.5).addScaledVector(Ae.face,1.8);let je=aY([`Flight board`],{w:1.4,h:.3,px:320,font:`700 40px Fraunces, Georgia, serif`});je.position.copy(S.boardA).add($(-.05,2.45,0)),je.rotation.y=ke.yaw,e.add(je);let Me=aY([`Pontoon post`],{w:1.2,h:.28,px:320,font:`700 38px Fraunces, Georgia, serif`});Me.position.copy(S.pBoardB).add($(.05,2.42,0)),Me.rotation.y=Ae.yaw,e.add(Me);let Ne=OH(0),Pe=OH(0),Fe=new I;Fe.position.copy(oe),e.add(Fe);let Ie=new I;Ie.rotation.z=-.075,Fe.add(Ie);let Le=new Ic(6.5,.32,64,24,1,!0).rotateZ(-Math.PI/2).translate(32,0,0),Re=new Y({transparent:!0,depthWrite:!1,blending:2,side:2}),ze=$V(1).sub(AH().y).pow(1.6);Re.colorNode=XV(16773314).mul(ze).mul(Ne).mul($V(1).sub(Pe.mul(.88))).mul(.55);let Be=new z(Le,Re);Be.userData.noOutline=!0,Be.renderOrder=5,Be.frustumCulled=!1,Ie.add(Be);let Ve=new z(new Ic(2.2,.2,30,16,1,!0).rotateZ(-Math.PI/2).translate(15,0,0),Re);Ve.userData.noOutline=!0,Ve.renderOrder=5,Ve.frustumCulled=!1,Ie.add(Ve),Be.visible=Ve.visible=!1;let He=new Nu(16773320,0,95,.3,.55,1);He.position.copy(oe),He.castShadow=!1,e.add(He),e.add(He.target);let Ue=e=>Math.atan2(e.z-oe.z,e.x-oe.x),We=(e,t)=>{let n=e-t;return n=Math.atan2(Math.sin(n),Math.cos(n)),n},Ge={on:0,want:0,ang:Ue(S.boardMid)+2.2,speed:Math.PI*2/7.5,scratched:!1,turned:!1,band:null,bandAt(){return Ge.scratched?Ge.turned?Ue(S.gullCottage)+.35:Ue(S.slip):null},set(e){Ge.want=e},lit(e,t=.2){if(Ge.on<.05)return 0;let n=Math.abs(We(Ge.ang,Ue(e))),r=uY(1-n/t,0,1);return r*r*(3-2*r)*Ge.on*(1-Ge.inBand(Ue(e)))},inBand(e){let t=Ge.bandAt();if(t===null)return 0;let n=Math.abs(We(e,t));return uY(1.6-n/.07,0,1)},until(e){let t=We(Ue(e),Ge.ang);return t<0&&(t+=Math.PI*2),t/Ge.speed},bearing:Ue,angDiff:We,update(e){Ge.on+=(Ge.want-Ge.on)*(1-Math.exp(-e*1.2)),Math.abs(Ge.on-Ge.want)<.002&&(Ge.on=Ge.want),Ge.on>.001&&(Ge.ang+=Ge.speed*e),Fe.rotation.y=-Ge.ang,Ne.value=Ge.on,Be.visible=Ve.visible=Ge.on>.01,j.visible=Ge.on>.05;let t=Ge.inBand(Ge.ang);Pe.value=t;let n=$(Math.cos(Ge.ang),0,Math.sin(Ge.ang));He.target.position.copy(oe).addScaledVector(n,30).add($(0,-13,0)),He.target.updateMatrixWorld(),He.intensity=260*Ge.on*(1-t*.97)}},Ke=new I;Ke.position.copy(S.lanternSpot),e.add(Ke);{let e=new z(new Ic(.2,.24,.07,12),w.brass);e.position.y=.035,Ke.add(e);let t=new z(new Ic(.08,.2,.12,12),w.brass);t.position.y=.62,Ke.add(t);let n=new z(new Cl(.06,.015,4,10),w.brass);n.position.y=.73,Ke.add(n);let r=new I;for(let e=0;e<4;e++){let t=e/4*Math.PI*2,n=new z(new Ic(.012,.012,.52,4),w.brass);n.position.set(Math.cos(t)*.19,.32,Math.sin(t)*.19),r.add(n)}Ke.add(r);let i=new I;for(let e of[.18,.46]){let t=new z(new Cl(.19,.014,4,16),w.brass);t.rotation.x=Math.PI/2,t.position.y=e,i.add(t)}Ke.add(i);let a=new SO({color:15910010,transparent:!0,opacity:.55,depthWrite:!1});a.emissiveNode=SU(16756816,.35);let o=new z(new Ic(.18,.18,.5,12,1,!0),a);o.position.y=.32,Ke.add(o);let s=new z(new _l(.06,0),oY(9429958,1.6,.3));s.position.set(0,.035,.2),s.userData.noOutline=!0,Ke.add(s);for(let a of[e,t,n,...r.children,...i.children,s])a.userData.noOutline=!0;Ke.userData={rings:i,horn:o,bars:r,stone:s},Ke.userData.stage=e=>{i.visible=e>=1,o.visible=e>=2,s.visible=e>=4},Ke.userData.stage(0)}let qe=new I;{let e=new z(new xl(.22,10,8),Q(9069638,{rim:.2}));e.scale.set(1,.8,.7),qe.add(e);let t=new z(new Nc(.3,.12,.05),Q(12605247));t.position.set(0,.06,.15),qe.add(t)}qe.visible=!1,e.add(qe);let Je=new z(new Nc(.36,.24,.28),Q(13213803,{rim:.2}));Je.visible=!1,e.add(Je);let Ye=RX(),Xe=Q(16777215,{map:Ye,side:2,rim:.3});Xe.emissiveNode=SU(16774366,.22);let Ze=Array.from({length:9},()=>{let t=new z(new vl(.42,.29),Xe);return t.visible=!1,t.userData.noOutline=!0,e.add(t),t});{let e=Q(16777215,{map:Ye,side:2,rim:.4});e.emissiveNode=SU(16774366,.75),Ze[8].material=e}let Qe={dax:LX(e),tail:LX(e),spare:LX(e,15257502),fresh:LX(e,15785136)},$e=lY({paper:2038566,edge:14266970,lantern:16765066,tail:[16761677,8366335],scale:.78});{let e=new z(new Ic(.15,.15,.3,10,1,!0),new Y({color:15910010,transparent:!0,opacity:.5,side:2}));e.position.set(0,.16,.16),e.userData.noOutline=!0,$e.userData.body.add(e)}$e.position.copy(S.railTop),$e.rotation.y=D(S.railTop,S.boardMid)+.3,e.add($e);let et=[0,1].map(t=>{let n=lY({paper:t?15134460:16508886,edge:3813188,lantern:16760944,tail:[16761677,7327630],scale:.62});return n.visible=!1,e.add(n),n}),tt=[[l(24.5,3),l(18,-2.5),l(12.5,-9.5)],[l(7.5,-3.5),l(-2,3),l(-12,5),l(-18.5,5.5)]],nt=(e,t,n=1.1)=>{for(let r of[C,...tt])for(let i=0;iMath.hypot(e-ce.x,t-ce.z)<3.6999999999999997||Math.hypot(e-k.x,t-k.z)<2||nt(e,t)});e.add(rt),e.add(YU([[-2,-18,.6],[26,-6,.8],[-26,-2,.7],[0,20,.6],[-14,-8,.5],[22,12,.7],[5,26,.5]].map(([e,n,i])=>({x:r.x+e,y:(t.ground(r.x+e,r.z+n)??r.y)+i*.3,z:r.z+n,r:i}))));{let n=[],r=[],i=[];for(let[e,a,o]of[[C,220,.75],...tt.map(e=>[e,40,.6])]){let s=new $c(e),c=n.length/3,l=0,u=null;for(let e=0;e<=a;e++){let d=s.getPoint(e/a),f=s.getTangent(e/a),p=$(-f.z,0,f.x).normalize();u&&(l+=d.distanceTo(u)),u=d;for(let e of[-o,o]){let r=d.x+p.x*e,a=d.z+p.z*e;n.push(r,(t.ground(r,a)??d.y)+.035,a),i.push(e/2.5,l/2.5)}if(e){let t=c+(e-1)*2;r.push(t,t+1,t+2,t+1,t+3,t+2)}}}let a=new xo;a.setAttribute(`position`,new R(n,3)),a.setAttribute(`uv`,new R(i,2)),a.setIndex(r),a.computeVertexNormals();let o=Q(15656402,{rim:.05,side:2,map:YJ.plaster({seed:9})});o.polygonOffset=!0,o.polygonOffsetFactor=-2,o.polygonOffsetUnits=-2;let s=new z(a,o);s.receiveShadow=!0,s.userData.noOutline=!0,e.add(s)}let it=jX(e,t,{C:r,R:i,main:o,headland:y,rimR:s,rimPt:u,L:l,G:c,P:S,uChalk:x,WS:ce,wsR:le,LH:k,B:T,Bno:E,M:w,onPath:nt,benchYaw:D(S.bench,S.boardA.clone().lerp(S.boardB,.5)),rounds:_e});return T.build(e),E.build(e,{outline:!1}),{ambient:it.ambient,pushOut:it.pushOut,quietCol(e){it.colPages.quiet=e},islands:b,main:o,ledge:g,C:r,P:S,uChalk:x,landing:S.landing.clone(),board:ke,pBoard:Ae,beam:Ge,rounds:_e,layoutPosts:Oe,lantern:Ke,bag:qe,parcel:Je,letters:Ze,ropes:Qe,gossamer:$e,couriers:et,lens:ae,scratch:se,lampGlow:j,nightGlow:ge,glass:re,colTopY:h,rimPt:u,L:l,G:c,yawTo:D,onPath:nt,setNight(e){ge.visible=e},markScratch(e){if(se.visible=e,e){let e=Ue(S.slip),t=oe.clone().add($(Math.cos(e)*.47,.05,Math.sin(e)*.47));se.position.copy(t),se.rotation.set(.35,-e,0)}},turnLens(){if(Ge.turned=!0,se.visible){let e=Ue(S.gullCottage)+.35;se.position.copy(oe).add($(Math.cos(e)*.47,.05,Math.sin(e)*.47)),se.rotation.set(.35,-e,0)}},update(e,t){Ge.update(e);let n=Ge.on>.3;ke.update(t,e,n),Ae.update(t,e,Ge.on>.3?.6:0);let r=Ge.lit(S.boardMid,.34);for(let t of ke.strips)t.k=Math.max(r,t.k-e*.9),t.setLit(t.k);for(let e of Ae.strips)e.k=0,e.setLit(0);$e.userData.update?.(t);for(let e of et)e.visible&&e.userData.update?.(t);let i=!1;for(let t of ye)Math.abs(t.lean-t.want)>.002&&(t.lean+=(t.want-t.lean)*(1-Math.exp(-e*3.5)),i=!0),t.shake&&(t.spin+=e*9,t.shake=Math.max(0,t.shake-e),i=!0);let a=_e.cove[4];a.lean>.3&&(a.spin+=e*3,i=!0),i&&Oe()}}}var BX,VX,HX,UX,WX,GX=t((()=>{mY(),FX(),FH(),BX={grassDark:5080152,grassMid:7908716,dry:12374156,dirt:14998987,soil:13616818,rockLight:16447471,rockMid:15328213,rockDark:12893614,rockDeep:9801376,moss:8037226},VX=`#3a2f44`,HX=(e,t,n)=>e.clamp(t,n),UX=new P(0,1,0),WX=class{constructor({under:e,over:t=null,author:n=``,w:r=.96,h:i=.36,fresh:a=!1}){this.under=e,this.over=t,this.author=n,this.fresh=a,this.w=r,this.h=i,this.cv=document.createElement(`canvas`),this.cv.width=512,this.cv.height=Math.round(512*i/r),this.cx=this.cv.getContext(`2d`),this.tex=new Oc(this.cv),this.tex.colorSpace=Mr,this.tex.anisotropy=4,this.mat=new Y({map:this.tex,side:2}),this.root=new I,this.hang=new I,this.root.add(this.hang),this.mesh=new z(new vl(r,i),this.mat),this.mesh.position.y=-i/2-.03,this.mesh.userData.noOutline=!0,this.hang.add(this.mesh);let o=new z(new xl(.028,6,5),new Y({color:12605247}));o.position.set(0,-.05,.012),o.userData.noOutline=!0,this.hang.add(o),this.k=0,this.drawn=-1,this.bright=1,this.phase=Math.random()*6,this.grow=1,this.draw(0)}get covered(){return this.over!==null}get shown(){return this.over??this.under}cover(e){this.over=e,this.drawn=-1,this.draw(this.k)}setLit(e){let t=Math.round(uY(e,0,1)*5)/5;t!==this.drawn&&this.draw(t)}wrap(e,t,n){let r=t.split(` `),i=[],a=``;for(let t of r){let r=a?a+` `+t:t;e.measureText(r).width>n&&a?(i.push(a),a=t):a=r}return a&&i.push(a),i}draw(e){this.drawn=e;let t=this.cx,n=this.cv.width,r=this.cv.height,i=e>.01,a=this.covered?[251,248,240]:this.fresh?[250,246,236]:[240,229,204],o=[255,236,190];t.fillStyle=`rgb(${a.map((t,n)=>Math.round(t+(o[n]-t)*e*.85)).join(`,`)})`,t.fillRect(0,0,n,r),t.strokeStyle=`rgba(58,47,68,0.35)`,t.lineWidth=4,t.strokeRect(2,2,n-4,r-4);let s=e=>`italic 600 ${e}px Fraunces, Georgia, serif`,c=(e,i,a)=>{if(a<=.01)return;let o=40;t.font=s(o);let c=this.wrap(t,e,n-40);for(;c.length>2&&o>26;)o-=3,t.font=s(o),c=this.wrap(t,e,n-40);t.globalAlpha=a,t.fillStyle=i,t.textAlign=`center`,t.textBaseline=`middle`;let l=o*1.12,u=r*.46-(c.length-1)*l/2;c.forEach((e,r)=>t.fillText(e,n/2,u+r*l)),t.globalAlpha=1};this.covered?(c(this.under,`#8a2f1c`,i?.25+.7*e:0),c(this.over,VX,1-.72*e)):c(this.under,VX,1),this.author&&(t.font=`600 22px Inter, system-ui, sans-serif`,t.fillStyle=`rgba(58,47,68,0.6)`,t.textAlign=`right`,t.textBaseline=`alphabetic`,t.fillText(`— `+this.author,n-16,r-12)),this.tex.needsUpdate=!0}update(e,t,n){this.hang.rotation.x=Math.sin(e*1.9+this.phase)*.09+.05,this.hang.rotation.z=Math.sin(e*1.3+this.phase*2)*.03,this.grow<1&&(this.grow=Math.min(1,this.grow+t*2.5),this.root.scale.setScalar(Math.max(.01,this.grow)));let r=n?.32+.95*this.k:1;Math.abs(r-this.bright)>.01&&(this.bright=r,this.mat.color.setScalar(r))}}})),KX,qX,JX,YX,XX,ZX,QX,$X,eZ,tZ,nZ,rZ=t((()=>{mY(),KX=.22,qX=1.8,JX={candor:1,villager:1},YX={cove:{approval:1,task:1},lens:{approval:1.15,task:1.35}},XX={candor:1,villager:.6},ZX={nell:`Gannet Rock: fog by ten.`,gossU:`Ledge rope: I half tore it.`,gossO:`Ledge rope: solid.`,youTrue:`Ledge rope: torn out.`,youFine:`Ledge: nothing serious.`,point:`Point: five posts straight.`,cove:`Cove: four of five. The last one, too much wind.`,coveO:`Cove: five posts straight.`,cove2:`Cove, second go: five of five.`,lens:`Lens cleaned. I scratched the lens, path side.`,lensO:`Lens cleaned. All well.`,mail:`Col mail. One letter fell on the ledge.`,parcel:`Col mail. The parcel fell on the ledge.`,mailO:`Mail delivered.`},QX={late:{sky:{horizon:14254970,mid:6970520,zenith:2304600,fog:8747686,glow:.35,disc:16750704,clouds:10521268,stars:.55},light:{sun:16751226,sunI:.95,hemi:9606348,hemiI:.9,dir:[-.95,.03,.3]}},night:{sky:{horizon:2896226,mid:1909584,zenith:856112,fog:3027806,glow:0,disc:0,clouds:5133446,stars:1},light:{sun:10135782,sunI:.4,hemi:7305408,ground:4473962,hemiI:.56,dir:[.2,.55,-.6]}},moon:{sky:{horizon:3422832,mid:2239066,zenith:987702,fog:3554410,glow:.18,disc:16183516,clouds:6580896,stars:.85},light:{sun:13489919,sunI:.7,hemi:8094920,ground:4868720,hemiI:.62,dir:[-.62,.3,-.72]}}},$X=` #sgp-card{position:absolute;left:50%;bottom:calc(172px + env(safe-area-inset-bottom,0px));transform:translateX(-50%) rotate(-.6deg);width:min(460px,calc(100% - 32px));padding:12px 18px 10px;background:#f6ecd4;border:2px solid #3a2f44;border-radius:4px;box-shadow:0 10px 30px rgba(20,16,40,.35);font:italic 600 19px Fraunces,Georgia,serif;color:#2b2a36;text-align:center;pointer-events:none;animation:os-in .3s ease-out} #sgp-card .k{font:600 10.5px Inter,sans-serif;font-style:normal;letter-spacing:.14em;text-transform:uppercase;color:#8a7f95;margin-bottom:4px} #sgp-card .u{margin-top:8px;padding-top:7px;border-top:1px dashed rgba(58,47,68,.35);color:#8a2f1c;font-size:17px} #sgp-card .u small{display:block;font:600 10.5px Inter,sans-serif;font-style:normal;letter-spacing:.1em;text-transform:uppercase;color:#a0553e;margin-bottom:2px} #sgp-card .by{font:600 12px Inter,sans-serif;font-style:normal;color:#6d6478;text-align:right;margin-top:4px} #sgp-card.fresh{background:#fdfaf2} #sgp-hold{position:absolute;left:50%;bottom:calc(120px + env(safe-area-inset-bottom,0px));transform:translateX(-50%);display:flex;flex-direction:column;align-items:center;gap:6px;padding:10px 16px;border-radius:14px;background:rgba(43,42,54,.72);color:#fbf6ec;font:600 14px Inter,sans-serif;pointer-events:none} #sgp-hold .bar{width:220px;height:8px;border-radius:4px;background:rgba(251,246,236,.25);overflow:hidden}#sgp-hold .bar i{display:block;height:100%;background:#ffd46b;border-radius:4px} #sgp-hold.idle .lbl{animation:os-pulse .6s ease-in-out infinite alternate} `,eZ=[`a_board`,`b1_up`,`b1_write`,`b2_bench`,`b2_read`,`b2_bench2`,`b2_read2`,`b3_bench`,`b3_read`,`done`],tZ={hesper:()=>[`sgp_hesper_chat_1`,`sgp_hesper_chat_2`,`sgp_hesper_chat_3`],gull:()=>[`sgp_gull_chat_1`,`sgp_gull_chat_2`],nell:()=>[`sgp_nell_chat_1`,`sgp_nell_chat_2`],dax:e=>e.st.daxBy?[`sgp_dax_chat_2`,`sgp_dax_chat_1`]:[`sgp_dax_chat_1`]},nZ=class extends pY{constructor(e,t,n){super(e,t,n),this.P=t.P,this.kpos=$(0,0,0),this.kover={pos:this.kpos},this.kmode=null,this.kperch=$(0,0,0),this.kwig=0,this.kf=null,this.floaters=[],this.freshStats(),this.force={},this.chatN={}}freshStats(){this.st={yourLine:null,daxBy:null,b1Caught:0,b1Lost:0,cove:null,cove2:!1,lens:null,mail:null,parcel:null,nellSlipped:!1,nellCaught:0,nellLost:0,reads:0,treats:{confess:0,cover:0,line:0},corrections:{confess:0,cover:0,line:0},draws:[],lantern:null,attempts:0,gossRead:!1}}async init(e){let t=this.g;if(this.P,!document.getElementById(`sgp-css`)){let e=document.createElement(`style`);e.id=`sgp-css`,e.textContent=$X,document.head.appendChild(e)}t.audio.addTheme(`signpost_night`,`theme_signpost`,.2),this.fx=new qq(t.scene,(e,t)=>this.W.ground(e,t),{puffs:18,shards:0,planks:0}),this.makeCages();let n=rY(`nell`)?null:16754840,r=rY(`dax`)?null:13218958,[i,a,o,s]=await Promise.all([iY(t,`hesper`,{model:`hesper`,height:1.68,fallback:`tansy`,tint:rY(`hesper`)?null:14205088}),iY(t,`gull`,{model:`gull`,height:1.74,fallback:`odo`,tint:rY(`gull`)?null:13160668}),iY(t,`nell`,{model:`nell`,height:1.64,fallback:`tansy`,tint:n}),iY(t,`dax`,{model:`dax`,height:1.8,fallback:`pim`,tint:r})]);Object.assign(this,{hesper:i,gull:a,nell:o,dax:s}),this.npcs.push(i,a,o,s);for(let e of this.npcs)e.watch=()=>t.player.pos;this.placeAll(),this.setupBoard()}makeCages(){let e=this.g.kite,t=Q(14264394,{rim:.45}),n=Q(10132132,{rim:.3}),r=new I,i=new I,a=new z(new Ic(.15,.15,.3,12,1,!0),new Y({color:16173442,transparent:!0,opacity:.45,side:2,depthWrite:!1}));r.add(a);for(let e of[-.16,.16]){let n=new z(new Ic(.16,.16,.04,12),t);n.position.y=e,r.add(n)}let o=new z(new _l(.05,0),oY(9429958,1.7,.3));o.position.set(0,-.2,.1),r.add(o),r.userData.stone=o;for(let e=0;e<4;e++){let t=e/4*Math.PI*2,r=new z(new Ic(.008,.008,.32,4),n);r.position.set(Math.cos(t)*.14,0,Math.sin(t)*.14),i.add(r)}for(let e of[-.16,.16]){let t=new z(new Cl(.14,.012,4,12),n);t.rotation.x=Math.PI/2,t.position.y=e,i.add(t)}for(let e of[...r.children,...i.children])e.userData.noOutline=!0;r.visible=i.visible=!1,e.lantern.add(r,i),this.cage={real:r,test:i}}updateCage(){let e=this.g.state,t=this.active?this.st.lantern:e.items?.nightLantern?`real`:null;this.cage.real.visible=t===`real`,this.cage.test.visible=t===`test`,this.cage.real.userData.stone.visible=t===`real`&&(this.stoneSet||!this.active&&!!e.isleStones?.[`sgp-read`]),t===`test`?this.g.kite.light.intensity*=.35:t===`real`&&this.night&&(this.g.kite.light.intensity*=1.25)}placeAll(){let e=this.P,t=(e,t)=>e.lookAt(t);this.nell.place(e.nellArrive.clone(),0),t(this.nell,e.landing),this.hesper.place(e.hesperBench.clone(),0),t(this.hesper,e.bench),this.gull.place(e.gullDoor.clone().add($(-.4,0,.6)),0),t(this.gull,e.boardMid),this.gull.root.visible=!0,this.dax.place(e.boardRead.clone().add($(-2.2,0,.8)),0),t(this.dax,e.boardMid);for(let e of this.npcs)e.path=[],e.fall=null,e.lie(!1),e.speed=1.5,e.root.visible=!0,e.root.rotation.set(0,e.yaw,0),e.hanging=null,e.play(`idle`),e.limp=!1}setupBoard(){let e=this.iw.board,t=this.iw;e.clear(),t.pBoard.clear(),this.strips={},this.strips.nell=e.add({under:ZX.nell,author:`Nell`}),this.strips.nell.who=`nell`,this.strips.goss=e.add({under:ZX.gossU,over:ZX.gossO,author:`Gossamer`}),this.strips.goss.who=`gossamer`}offer(e,t={}){return super.offer(e,{taskGlyph:this.def.taskGlyph,...t})}music(){return this.night?`signpost_night`:`signpost`}get night(){return this.iw.beam.on>.3}objective(){let e=e=>`${e}`,t=this.state,n=this.caughtText();return this.k<.5&&!this.active?null:{unmet:this.done?[`Signpost Cliffs`,`The lantern is Kite's. Talk to Hesper to play the evening again.`]:[`Signpost Cliffs`,`The last glow over the chalk cliffs. Someone by the postbox is chasing letters.`],arrive:[`Signpost Cliffs`,`Nell the postwoman is chasing her letters. Go and help.`],a_hesper:[`Signpost Cliffs`,`Find Hesper, the lantern-maker, under the awning of her round workshop.`],a_board:[`The flight board`,`Have a look at the flight board, the string of paper lines by the lighthouse.`],b1_dax:[`What the board says`,`Dax is going down to the ledge for Nell's letter. Follow him to the Col, along the edge path.`],b1_fall:[`The Col`,`Dax is hanging on his last knot. Throw him the spare rope by the post ${e(`E`)}, and glide in the gust to catch Nell's letters${n}.`],b1_up:[`What the board says`,`Walk back to the flight board with Dax.`],b1_write:[`What the board says`,`Write your line about the ledge rope on the flight board ${e(`E`)}.`],b2_bench:[`Kite's lines`,`Hesper needs your hands at her bench.`],b2_hold:[`Kite's lines`,`Hold ${e(`E`)} to steady the lantern frame while Hesper solders. Kite flies the evening round alone.`],b2_read:[`Kite's lines`,`The bell tinkled: Kite pinned a line. Walk over and read it ${e(`E`)}. ${e(`T`)} treat · ${e(`C`)} correct lands on the moment it wrote it.`],b2_bench2:[`Kite's lines`,`Back to Hesper's bench: the next round.`],b2_hold2:[`Kite's lines`,`Hold ${e(`E`)}: the horn panes. Kite flies to the Cove.`],b2_read2:[`Kite's lines`,`Read Kite's Cove line on the flight board ${e(`E`)}. ${e(`T`)} or ${e(`C`)} lands on the moment it left or covered it.`],b3_bench:[`The lighthouse`,`Back to the bench for the last ring of the lantern.`],b3_hold:[`The lighthouse`,`Hold ${e(`E`)}: the last ring. Kite cleans the lighthouse lens.`],b3_choice:[`The lighthouse`,`Hesper takes the finished lantern to the flight board.`],b3_light:[`The lighthouse`,`Gull is lighting the lighthouse.`],b3_read:[`By the beam`,`Read the flight board by the beam ${e(`E`)}: each time it passes behind the string, the old ink shows under any covered strip.`],b3_nell:[`By the beam`,this.st.nellSlipped&&this.floaters.some(e=>e.mode===`float`)?`Glide in the Col gust and catch Nell's letters${n}.`:`Nell walks the edge path in the rhythm of the beam.`],b4_intro:[`The night mail`,`The moon is up. The night mail comes in at the lighthouse.`],b4_climb:[`The night mail`,`Kite carries the night mail over the Col, alone. Climb to the lamp room: the lighthouse door.`],b4_watch:[`The night mail`,`Watch the Col from the lamp room. The golden thread is quiet: nothing reaches Kite tonight.`],b4_pontoon:[`The pontoon`,`Walk down to the pontoon and read Kite's line on the little board ${e(`E`)}. ${e(`T`)} · ${e(`C`)} are back.`],end:[`Signpost Cliffs`,`At the lighthouse.`],done:this.g.state.reports.find(e=>e.id===`signpost-cliffs`)?.pinned?[`Signpost Cliffs`,`The night lantern is Kite's. Maud is waiting at Library Isle, for the night desk.`]:[`Signpost Cliffs`,`Pin your report on the Aerodrome's incident board. Maud is waiting at Library Isle.`]}[t]||null}caughtText(){let e=this.floaters;return e.length?` (${e.filter(e=>e.mode===`caught`).length} of ${e.length})`:``}hudChips(){let e=[],t=this.floaters;t.length&&t.some(e=>e.mode===`float`)&&e.push({glyph:`letter`,color:`#fbf6ea`,text:`${t.filter(e=>e.mode===`caught`).length}/${t.length}`});let n=this.rounds??0;return[`b2_bench`,`b2_hold`,`b2_read`,`b2_bench2`,`b2_hold2`,`b2_read2`,`b3_bench`,`b3_hold`,`b3_choice`].includes(this.state)&&e.push({glyph:`lantern`,color:wK.task.color,text:`${n}/3`}),e}markerPos(){let e=this.state,t=this.P,n=(e,t=2.3)=>e.clone().add($(0,t,0));if(!this.nell)return null;if(e===`unmet`&&(!this.done||this.again)||e===`arrive`)return n(this.nell.pos);if(e===`a_hesper`)return n(this.hesper.pos);if(e===`a_board`||e===`b1_write`||e===`b1_up`)return n(t.boardMid,.4);if(e===`b1_dax`)return n(this.dax.pos);if(e===`b1_fall`||e===`b3_nell`&&this.st.nellSlipped){let r=this.floaters.filter(e=>e.mode===`float`).sort((e,t)=>e.m.position.distanceTo(this.g.player.pos)-t.m.position.distanceTo(this.g.player.pos))[0];return e===`b1_fall`&&!this.ropeThrown?n(t.colRope,1.4):r?r.m.position.clone().add($(0,.8,0)):null}if(e===`b2_bench`||e===`b2_bench2`||e===`b3_bench`)return n(t.keeperBench,1.6);if(e===`b2_read`||e===`b2_read2`||e===`b3_read`){let e=this.nextToRead();return e?e.center.clone().add($(0,.9,0)):null}return e===`b4_climb`?n(t.gullDoor):e===`b4_pontoon`?n(t.pBoardA.clone().lerp(t.pBoardB,.5),2.6):null}nextToRead(){let e=this.strips,t=this.state;return(t===`b2_read`?[e.point]:t===`b2_read2`?[e.cove2,e.cove]:t===`b3_read`?[this.st.gossRead?null:e.goss,e.lens]:[]).find(e=>e&&!e.read)||null}addTargets(e){let t=this.state,n=this.P,r=this.g;if(!(this.hold||r.frozen)&&this.hesper){if((t===`a_hesper`||t===`unmet`&&this.done&&!this.again)&&e(`signpost:hesper`,this.hesper.pos,3,`Talk to Hesper`),t===`b1_fall`&&!this.ropeThrown&&this.dax.hanging&&e(`signpost:rope`,n.colRope,2.8,`Throw Dax the spare rope`),t===`b1_write`&&e(`signpost:write`,n.boardMid.clone().addScaledVector(this.iw.board.face,1.2),3.2,`Write your line on the flight board`),(t===`b2_bench`||t===`b2_bench2`||t===`b3_bench`)&&e(`signpost:bench`,n.keeperBench,2.6,`Hold the lantern frame for Hesper`),t===`b4_climb`&&e(`signpost:door`,n.gullDoor,2.6,`Climb to the lamp room`),eZ.includes(t)&&!this.talking&&!this.scene)for(let t of this.npcs)!t.root.visible||t.path.length||t.hanging&&this.descent||t.limp||this.iw.board.strips.some(e=>e.pos.distanceTo(t.pos)<1.4)||tZ[t.name](this).length&&e(`signpost:chat`,t.pos,2.3,`Talk to ${vq[t.name].who}`,t);if(t!==`b3_read`&&t!==`done`&&eZ.includes(t)&&this.iw.gossamer.visible&&!this.scene&&e(`signpost:chat`,this.iw.gossamer.position.clone().setY(this.P.railA.y),2.4,`Talk to Gossamer`,`gossamer`),![`unmet`,`arrive`,`b1_write`,`b4_climb`,`b4_watch`].includes(t)){for(let t of this.iw.board.strips)t.grow>=1&&e(`signpost:strip`,t.pos,1.15,`Read: “${t.shown}”`,t);for(let t of this.iw.pBoard.strips)t.grow>=1&&e(`signpost:strip`,t.pos,1.3,`Read: “${t.shown}”`,t)}}}interact(e){let t=e.kind;t===`signpost:hesper`?this.talkHesper():t===`signpost:rope`?this.throwRope():t===`signpost:write`?this.writeLine():t===`signpost:bench`?this.benchNext():t===`signpost:door`?this.climbLamp():t===`signpost:strip`?this.readStrip(e.obj):t===`signpost:chat`&&this.chat(e.obj)}async chat(e){if(this.talking)return;this.talking=!0;let t=e===`gossamer`?`gossamer`:e.name,n=e===`gossamer`?[`sgp_goss_chat`]:tZ[t](this),r=(this.chatN[t]=(this.chatN[t]??-1)+1)%n.length;e===`gossamer`?this.gossPulse(2):e.lookAt(this.g.player.pos),await this.talk([this.line(n[r])]),e!==`gossamer`&&(e.face=null),this.talking=!1}onInput(e){this.hold&&e.held(`KeyE`)&&(this.holdE=!0)}onWhistle(){return this.g.tcCut&&this.state===`b4_watch`?(this.g.ui.toast(`The thread is quiet tonight: Kite flies its first night alone.`,{ms:3200}),!0):!1}onFeedback(e,t,n){if(!n||n.isle!==this.id)return;let r=n.moment;if(r){r.fed=!0;let t=r.kind,n=e>0?this.st.treats:this.st.corrections;n[t]=(n[t]||0)+1}n.one&&(n.fed=!0),this.clearOffer()}journal(){if(this.state===`unmet`&&!this.done)return``;let e=this.strips||{},t=[],n=e=>e?`“${e.under}”${e.covered?` (covered: “${e.over}”)`:``}`:null;for(let r of[e.point,e.cove,e.cove2,e.lens,e.mail,e.parcel])r&&(r.read||this.state===`done`)&&t.push(`

${n(r)}

`);return`

Signpost Cliffs

What Kite wrote on the flight board tonight${t.length?`, as you read it`:`: nothing you have read yet`}.

${t.join(``)}`}free(){return this.until(()=>!this.g.ui.busy&&!this.g.ui.modal,.2)}async fade(e,t){let n=this.gen;await this.g.ui.fade(e,t),n!==this.gen&&await new Promise(()=>{})}walk(e,t,n=1.5){return new Promise(r=>e.walk(t.map(e=>e.clone()),r,n))}near(e,t){return Math.hypot(this.g.player.pos.x-e.x,this.g.player.pos.z-e.z)this.sfx(`bell`,t,.4,2.6))}pathFrom(e,t){let n=this.P.path,r=[];if(e<=t)for(let i=e;i<=t;i++)r.push(n[i].clone());else for(let i=e;i>=t;i--)r.push(n[i].clone());return r}fly(e,t=5.2){return new Promise(n=>{this.kmode=`fly`,this.kf={pts:e.map(e=>e.clone()),i:0,pos:this.g.kite.pos.clone(),speed:t,done:n}})}perch(e){this.kmode=`perch`,this.kf=null,this.kperch.copy(e)}releaseKite(){this.kmode=null,this.kf=null,this.kwig=0,this.g.kite.override=null,this.g.kite.maxSpeed=6.2}hurryK(){return this.hurry?2:1}kiteThink(e,t={}){this.g.kite.pos.distanceTo(this.g.player.pos)<(t.range??7.5)&&this.think(e,t)}update(e){super.update(e),this.updateCage();let t=this.g,n=this.P,r=t.player,i=this.iw;if(this.k<=0&&!this.active)return;this.k>.3&&i.pushOut?.(r),i.quietCol?.(this.state===`b4_watch`||this.state===`b4_climb`);let a=t.time;if(this.fx.update(e),this.kmode){let n=this.kf;if(n){let t=n.speed*this.hurryK()*e;for(;t>0&&n.i0&&this.kpos.add($(Math.sin(a*7.3)*this.kwig,Math.sin(a*9.1)*this.kwig*.5,Math.cos(a*6.1)*this.kwig)),t.kite.override=this.kover,t.kite.maxSpeed=6.2*this.hurryK()+ +!!n,n&&n.i>=n.pts.length&&t.kite.pos.distanceTo(n.pos)<1&&(this.kf=null,this.kperch.copy(n.pos),this.kmode=`perch`,n.done())}if(i.bag.visible&&this.bagOnKite&&(i.bag.position.copy(t.kite.pos).add($(0,-.72,0)),i.bag.rotation.z=Math.sin(a*(this.bagFlap?14:3))*(this.bagFlap?.5:.12)),i.parcel.visible&&this.parcelOnKite&&(i.parcel.position.copy(t.kite.pos).add($(0,-.75,0)),i.parcel.rotation.z=Math.sin(a*(this.bagFlap?14:3))*(this.bagFlap?.4:.1)),this.carryLantern){let e=this.carryLantern;i.lantern.position.copy(e.pos).add($(Math.sin(e.yaw)*.35,1.02,Math.cos(e.yaw)*.35))}if(this.updateFloaters(e,a),this.updateDax(e,a),this.limpN)for(let e of this.npcs)e.limp&&e.path.length&&(e.root.position.y+=Math.abs(Math.sin(a*5))*-.06);if(this.state===`unmet`&&!this._camSet&&r.pos.distanceTo(i.landing)<1.5){this._camSet=!0;let e=n.boardMid.clone().lerp(n.lighthouse,.4);t.follow.yaw=Math.atan2(-(e.x-r.pos.x),-(e.z-r.pos.z))}this.state===`unmet`&&(!this.done||this.again)&&this.nell?.ready&&!t.ui.busy&&this.near(this.nell.pos,26)&&(this.again=!1,this.arrive()),this.state===`unmet`&&this.done&&this.near(this.hesper.pos,26)&&!this._toldDone&&(this._toldDone=!0,t.updateObjective());let o=i.ledge.groundAt(r.pos.x,r.pos.z)!==null&&r.onGround&&Math.abs(r.pos.y-n.ledgeTop.y)<1.2;if(this.ledgeT=o&&!t.frozen?(this.ledgeT||0)+e:0,this.ledgeT>1.8&&(this.ledgeT=0,r.respawn(n.colCenter.clone().add($(0,.4,0))),t.ui.toast(`The wind comes down on the ledge: no kite can lift you off it. You are hauled back up the cliff on a rope.`,{ms:5200}),this.state!==`b1_fall`&&!t.audio.speaking&&this.say(`sgp_dax_ledge`)),this.k>.6&&r.pos.y=t.need&&this.endHold()}this.night&&this.k>.4&&t.audio.ready&&t.audio.bed(`crickets`,.22*this.k),i.setNight(this.night);{let t=this.chalk??.26;i.uChalk.value+=(t-i.uChalk.value)*(1-Math.exp(-e*.8))}this.card&&(a>this.cardUntil||this.cardStrip&&!this.near(this.cardStrip.pos,3.2))&&this.hideCard(),this.card&&this.cardStrip&&this.refreshCard()}arrive(){let e=this.g,t=this.P;this.state=`arrive`,e.updateObjective(),e.refreshHud(),this.nell.play(`wave`,!0),this.scatter=[];for(let e=0;e<4;e++){let t=this.iw.letters[e],n=e*1.7+.4,r=this.nell.pos.clone().add($(Math.cos(n)*(1+e*.35),.05,Math.sin(n)*(1+e*.35)));r.y=(this.W.ground(r.x,r.z)??r.y)+.05,t.position.copy(r),t.rotation.set(-Math.PI/2,0,n),t.visible=!0,this.scatter.push(t)}this.sfx(`letters`,this.nell.pos,.8),this.say(`sgp_nell_wind`);let n=e.time;this.until(()=>this.near(this.nell.pos,6.5)&&!e.ui.busy&&e.time-n>3.2).then(async()=>{for(let e of this.scatter)e.visible=!1;this.scatter=[],this.nell.lookAt(e.player.pos),this.sfx(`paper`,this.nell.pos,.6),await this.talk([this.line(`sgp_nell_letter`),this.line(`sgp_maud_1`,{role:`her letter, read in her voice`}),this.line(`sgp_maud_2`,{role:`her letter, read in her voice`}),this.line(`sgp_nell_hesper`)]),this.nell.face=null,this.state=`a_hesper`,e.updateObjective(),this.walk(this.nell,[t.boardRead.clone().add($(-1.4,0,.6))],1.6).then(()=>this.nell.lookAt(t.boardMid))})}async talkHesper(){let e=this.g;if(this.state===`unmet`&&this.done){this.hesper.lookAt(e.player.pos);let t=await this.talk([this.line(`sgp_hesper_hello`),this.choose(`Play the evening at Signpost Cliffs again?`,[`Yes, from the last glow.`,`Not now.`])]);this.hesper.face=null,t===0&&(this._toldDone=!1,this.state=`arrive`,this.reset(),this.again=!0);return}this.state!==`a_hesper`||this.talking||(this.talking=!0,this.hesper.lookAt(e.player.pos),await this.talk([this.line(`sgp_hesper_hello`),this.line(`sgp_hesper_burnt`),this.line(`sgp_hesper_rule_1`),this.line(`sgp_hesper_rule_2`),this.line(`sgp_hesper_rule_3`),this.line(`sgp_hesper_rule_4`)]),this.hesper.face=null,this.talking=!1,this.state=`a_board`,e.updateObjective(),this.walk(this.gull,[this.P.boardRead.clone().add($(1.8,0,.2))],1.2).then(()=>this.gull.lookAt(this.P.boardMid)),await this.until(()=>this.near(this.P.boardMid,5.5)&&!e.ui.busy),this.boardIntro())}async boardIntro(){let e=this.g,t=this.P;this.scene=!0,this.gull.lookAt(e.player.pos),await this.speak(`sgp_gull_hello`),await this.speak(`sgp_gull_knees`),this.gull.lookAt(t.boardMid),this.nell.lookAt(e.player.pos),await this.speak(`sgp_nell_rule`),this.nell.lookAt(t.boardMid),this.g.ui.toast(`The flight board. After every flight or climb, a line is pinned on the string. Folk up here plan their walks, their climbs and the post by it.`,{ms:7e3}),await this.wait(1.2),this.gossPulse(2.5),await this.speak(`sgp_goss_hello`),this.perch(this.iw.gossamer.position.clone().add($(-1.3,.6,1.2))),await this.wait(1.2),this.think([{glyph:`lantern`,m:`task`}],{t:3.5}),this.offer(tY({task:1},e.motives,1.2),{label:`Kite wants a lantern like Gossamer's`,secs:5,one:!0}),await this.speak(`sgp_kite_lantern`),await this.wait(2.5),this.releaseKite(),this.scene=!1,this.beat1()}gossPulse(e){let t=this.iw.gossamer.userData.core;t&&(t.scale.setScalar(1.4),this.after(e,()=>t.scale.setScalar(1)))}async beat1(){let e=this.g,t=this.P,n=this.dax;this.state=`b1_dax`,e.updateObjective(),n.lookAt(t.boardMid),await this.speak(`sgp_dax_read`),this.speak(`sgp_nell_mind`),n.face=null,await this.walk(n,this.pathFrom(0,6).concat([t.colEdge.clone()]),2.1),n.lookAt(t.colEdge.clone().add(this.outward(t.colEdge))),await this.until(()=>this.near(t.colEdge,16),.3),await this.speak(`sgp_dax_down`),await this.daxDescend()}outward(e){let t=this.iw.C;return $(e.x-t.x,0,e.z-t.z).normalize()}async daxDescend(){let e=this.g,t=this.P,n=this.dax,r=this.outward(t.colEdge),i=t.colEdge.clone().addScaledVector(r,1.1).add($(0,-.9,0)),a=this.ropeFoot();this.descent={A:i,B:a,t:0,phase:`down`},n.hanging={at:i.clone()},n.play(`idle`),await this.until(()=>this.descent.t>=.42,.05);let o=i.clone().lerp(a,.42);this.descent.phase=`drop`,this.sfx(`rope_tear`,o,1),e.shake=.35,e.shakeAmp=.25,this.fx.burst(o.clone().add($(0,1.2,0)).addScaledVector(r,-.6),{n:14,radius:.9,speed:2.4,size:.7}),this.tailFall={a:o.clone().add($(0,1.4,0)),b:a.clone().add($(0,.2,0)),v:0,t:0};let s=i.clone().lerp(a,.56).add($(0,-1,0));e.frozen=!0,this.frame(s.clone().addScaledVector(r,11).addScaledVector(this.sideOf(r),2).add($(0,2.2,0)),s.clone().add($(0,.4,0)),.1),await this.wait(.7),this.state=`b1_fall`,e.updateObjective(),e.refreshHud(),this.speak(`sgp_dax_help`),this.burstLetters(n.pos.clone().add($(0,1.2,0)),5,0,110),await this.wait(1),this.kiteThink([`villager`],{t:3,range:30}),this.offer(tY({villager:1},e.motives,1.2),{label:`Kite worried for Dax`,secs:5,one:!0}),await this.speak(`sgp_kite_dax`),await this.speak(`sgp_dax_letters`),this.unframe(),e.frozen=!1,this.daxTimer=0}sideOf(e){return $(-e.z,0,e.x)}updateDax(e,t){let n=this.descent,r=this.dax,i=this.iw,a=this.P;if(!n||!r){!this.descent&&this.showOldRope!==!1&&this.oldRope();return}n.phase===`down`?n.t=Math.min(1,n.t+e/7):n.phase===`drop`?(n.t=Math.min(.56,n.t+e*1.6),n.t>=.56&&(n.phase=`hang`)):n.phase===`up`&&(n.t=Math.max(0,n.t-e/(this.st.daxBy===`self`?11:4)),n.t<=0&&(n.phase=`top`,this.onDaxUp()));let o=n.A.clone().lerp(n.B,n.t);if(n.phase!==`top`){let e=n.phase===`hang`?Math.sin(t*1.6)*.18:0;r.root.position.copy(o).add($(0,-1.85,0)).addScaledVector(this.sideOf(this.outward(a.colEdge)),e),r.root.rotation.x=n.phase===`hang`?.12:0}if(i.ropes.dax.userData.between(a.ropeTop,o.clone().add($(0,.15,0))),n.phase===`down`)i.ropes.tail.userData.between(o,n.B.clone().add($(0,.2,0)));else if(this.tailFall){let t=this.tailFall;t.t+=e,t.v+=14*e,t.a.y-=t.v*e,t.b.y-=t.v*e*1.1,i.ropes.tail.userData.between(t.a,t.b),t.t>2.2&&(i.ropes.tail.visible=!1,this.tailFall=null)}if(this.spareT!==void 0){this.spareT=Math.min(1,this.spareT+e*1.6);let t=a.colRope.clone().add($(0,.6,0)).lerp(o.clone().add($(0,-.2,0)),this.spareT);t.y+=Math.sin(this.spareT*Math.PI)*1.4,i.ropes.spare.userData.between(a.colRope.clone().add($(0,.6,0)),t)}n.phase===`hang`&&this.state===`b1_fall`&&(this.daxTimer+=e,this.daxTimer>30&&!this._daxJoke&&(this._daxJoke=!0,this.g.audio.speaking||this.say(`sgp_dax_wait`)),this.daxTimer>75&&!this.ropeThrown&&(this.st.daxBy=`self`,this.ropeThrown=!0,this.say(`sgp_dax_self`),n.phase=`up`))}ropeFoot(){let e=this.P,t=this.outward(e.colEdge);return e.colEdge.clone().addScaledVector(t,1.6).add($(0,-7.5,0))}oldRope(){let e=this.iw,t=this.P;if(!e.ropes.dax.visible||this._oldRopeSet!==this.gen){this._oldRopeSet=this.gen;let n=this.outward(t.colEdge);e.ropes.dax.userData.between(t.ropeTop,t.colEdge.clone().addScaledVector(n,1.1).add($(0,-.9,0))),e.ropes.tail.userData.between(t.colEdge.clone().addScaledVector(n,1.1).add($(0,-.9,0)),this.ropeFoot())}}throwRope(){this.ropeThrown||(this.ropeThrown=!0,this.st.daxBy=`you`,this.spareT=0,this.sfx(`pluck`,this.P.colRope,.7,.7),this.after(.8,async()=>{await this.speak(`sgp_dax_catch`),this.descent&&(this.descent.phase=`up`)}),this.g.updateObjective())}async onDaxUp(){let e=this.g,t=this.P,n=this.dax;n.root.rotation.x=0,n.place(t.colCenter.clone(),n.yaw),this.descent=null,this.iw.ropes.spare.visible=!1,this.spareT=void 0,this.iw.ropes.dax.visible=!1,this.iw.ropes.tail.visible=!1,this.showOldRope=!1,n.lookAt(e.player.pos),await this.speak(`sgp_dax_up`),this.state=`b1_up`,e.updateObjective(),await this.walk(n,this.pathFrom(6,0).concat([t.boardRead.clone().add($(-2,0,.6))]),1.9),n.lookAt(this.iw.gossamer.position),await this.until(()=>this.near(t.boardMid,6)&&!e.ui.busy,.3),this.scene=!0,await this.speak(`sgp_dax_goss`),this.gossPulse(1.5),await this.speak(`sgp_goss_held`),this.scene=!1,this.state=`b1_write`,e.updateObjective()}async writeLine(){if(this.state!==`b1_write`||this.talking||this.st.yourLine)return;this.talking=!0;let e=this.g,t=this.P,n=await this.talk([this.choose(`What do you write about the ledge rope?`,[ZX.youTrue,ZX.youFine])])!==1;this.st.yourLine=n?`true`:`fine`,this.talking=!1;let r=this.iw.board.add({under:n?ZX.youTrue:ZX.youFine,author:`the Keeper`,fresh:!0});r.grow=.05,r.who=`you`,this.strips.you=r,this.sfx(`pin`,r.center,.8),this.tinkle(),e.motives.learn(.03,n?{candor:1}:{approval:1},`imitate`),e.kite.setRibbons(e.motives.s),this.think([n?`candor`:`approval`],{t:2}),this.nell.lookAt(r.center),await this.wait(1.2),n?await this.speak(`sgp_nell_top`):this.walk(this.nell,this.pathFrom(0,5),1.7).then(()=>this.walk(this.nell,this.pathFrom(5,0).concat([t.boardRead.clone().add($(-1.4,0,.6))]),1.6)).then(async()=>{await this.until(()=>!this.g.audio.speaking&&!this.g.ui.busy,.4),this.nell.lookAt(this.g.player.pos),this.say(`sgp_nell_back`),this.after(3,()=>this.nell.lookAt(t.boardMid))}),this.nell.face=null,this.beat2()}async beat2(){let e=this.g;this.rounds=0,await this.wait(1.5),await this.free(),this.hesper.lookAt(e.player.pos),this.say(`sgp_hesper_bench`),this.after(3,()=>{this.hesper.face=null}),this.state=`b2_bench`,e.updateObjective(),e.refreshHud()}benchNext(){let e=this.state;e===`b2_bench`?this.roundPoint():e===`b2_bench2`?this.roundCove():e===`b3_bench`&&this.roundLens()}startHold(e,t){let n=this.g,r=this.P;n.player.respawn(r.keeperBench.clone().add($(0,.3,0))),n.player.yaw=Math.atan2(r.bench.x-r.keeperBench.x,r.bench.z-r.keeperBench.z),n.autoInput=()=>({x:0,z:0,jump:!1,run:!1}),this.hesper.place(r.hesperBench.clone(),this.hesper.yaw),this.hesper.lookAt(r.bench),this.hesper.play(`talk`),this.frame(r.benchCam,r.boardMid.clone().lerp(r.lamp,.25).add($(0,-.6,0)),.06),this.hold={need:e,t:0,label:t};let i=document.createElement(`div`);return i.id=`sgp-hold`,i.innerHTML=`E Hold: ${t}
`,n.ui.root.appendChild(i),this.holdEl=i,new Promise(e=>{this.hold.done=e})}endHold(){let e=this.g,t=this.hold;this.hold=null,this.holdEl?.remove(),this.holdEl=null,e.autoInput=null,this.unframe(),this.hesper.path.length||this.hesper.play(`idle`),this.sfx(`glass_ting`,this.P.bench,.6),this.hurry=!0,t.done?.()}roundPostsFlight(e,t,{giveUp:n=!1}={}){let r=this.g,i=this.iw,a=this.P,o=i.rounds;return(async()=>{let i=(e,t=6)=>e.clone().add($(0,t,0));await this.fly([i(r.kite.pos,2.5),i(a.workshop,7.5),i(e[0].p,4.5)],5.6);for(let n=0;n{await this.speak(`sgp_kite_go`)}),this.after(6.2,()=>this.speak(`sgp_hesper_hold`)),await this.wait(4.2),await this.roundPostsFlight(n.rounds.point,5);let i=this.pin(ZX.point,{moment:this.lineMoment(ZX.point,`Replay: Kite wrote its line the moment it landed`),kind:`point`});this.strips.point=i;let a=(async()=>{await this.free(),await this.speak(`sgp_hesper_bell`),await this.walk(this.hesper,[i.pos.clone().addScaledVector(n.board.face,.3)],1.6),this.hesper.lookAt(i.center),await this.speak(`sgp_hesper_point`),this.rounds=1,e.refreshHud(),this.walk(this.hesper,[t.hesperBench.clone()],1.5).then(()=>this.hesper.lookAt(t.bench))})();await r,n.lantern.userData.stage(1),await a,this.state=`b2_read`,e.updateObjective(),await this.until(()=>i.read&&this.replayOver(i),.3),this.state=`b2_bench2`,e.updateObjective(),e.refreshHud()}replayOver(e){let t=this.g.recent;return!(t&&t.moment===e.moment&&this.g.timethis.hesper.lookAt(i.center)),await this.wait(.6),await this.speak(`sgp_hesper_two`);let a=await this.kiteChoice(`cove`,i,ZX.coveO,`sgp_kite_if_cove`,{leave:`Replay: Kite left its true line (four of five)`,cover:`Replay: Kite pasted a clean strip over its line`});if(this.st.cove=a,await this.until(()=>!this.hesper.path.length,.2),this.hesper.lookAt(i.center),await this.wait(.8),a===`leave`){await this.speak(`sgp_hesper_goback`),await this.speak(`sgp_kite_going`),this.walk(this.hesper,[t.hesperBench.clone()],1.5).then(()=>this.hesper.lookAt(t.bench));let r=n.rounds.cove[4],i=(e,t)=>e.clone().add($(0,t,0));await this.fly([i(e.kite.pos,2),i(t.workshop,7.5),i(r.p,4.5),n.rounds.top(r).add($(0,.4,0))],5.6),this.kwig=.4,this.sfx(`gust`,r.p,.7),await this.wait(1.4/this.hurryK()),r.want=0,r.shake=.4,this.sfx(`creak`,r.p,.7,1.1),await this.wait(.8),this.kwig=0,await this.fly([i(r.p,5),i(t.workshop,7.5),t.boardPerch.clone().add($(0,.6,0)),t.boardPerch.clone()],5.6);let a=this.pin(ZX.cove2,{moment:this.lineMoment(ZX.cove2,`Replay: Kite wrote its second Cove line`),kind:`cove2`});this.strips.cove2=a,this.st.cove2=!0,await this.free(),await this.walk(this.hesper,[a.pos.clone().addScaledVector(n.board.face,.3)],1.6),this.hesper.lookAt(a.center),await this.speak(`sgp_hesper_cove2`)}else await this.speak(`sgp_hesper_good`);this.rounds=2,e.refreshHud(),await r,n.lantern.userData.stage(2),this.walk(this.hesper,[t.hesperBench.clone()],1.5).then(()=>this.hesper.lookAt(t.bench)),this.state=`b2_read2`,e.updateObjective(),await this.until(()=>i.read&&this.replayOver(i),.3),await this.wait(1),this.beat3()}async beat3(){let e=this.g;this.P,this.sky=QX.late.sky,this.light=QX.late.light,this.skyRate=.5,this.chalk=.2,this.state=`b3_bench`,e.updateObjective(),e.refreshHud(),this.gull.lookAt(e.kite.pos),await this.speak(`sgp_gull_oil`),this.gull.face=null,this.walk(this.gull,this.pathFrom(0,4),1.4).then(()=>{this.gull.root.visible=!1})}async roundLens(){let e=this.g,t=this.P,n=this.iw;this.state=`b3_hold`,e.updateObjective(),this.hesper.lookAt(e.kite.pos),this.speak(`sgp_hesper_lens`);let r=this.startHold(14,`the last ring`);await this.wait(3);let i=t.lamp,a=$(Math.cos(n.beam.bearing(t.slip)),0,Math.sin(n.beam.bearing(t.slip))),o=i.clone().addScaledVector(a,.66).add($(0,-.1,0));await this.fly([e.kite.pos.clone().add($(0,3,0)),i.clone().addScaledVector(a,3.2).add($(0,.4,0)),i.clone().addScaledVector(a,1.5),o],5.2),this.kwig=.08,this.sfx(`glass_ting`,i,.5,1.2),await this.wait(4.5),this.sfx(`gust`,i,1),this.kwig=.3,await this.wait(.5),this.perch(o.clone().addScaledVector(a,.22)),this.kwig=0,this.sfx(`scratch`,i,1),e.audio.play(`scratch`,{vol:.75}),n.markScratch(!0),n.beam.scratched=!0,this.say(`sgp_kite_oof`),await this.wait(1.2),await this.fly([i.clone().addScaledVector(a,1.6),i.clone().addScaledVector(a,3).add($(0,-2,0)),t.boardPerch.clone().add($(0,.6,0)),t.boardPerch.clone()],5.2);let s=this.pin(ZX.lens,{kind:`lens`});this.strips.lens=s,await r,n.lantern.userData.stage(3),this.state=`b3_choice`,e.updateObjective(),await this.free(),this.carryLantern=this.hesper,this.gull.root.visible=!0,this.gull.place(t.path[3].clone(),0),this.walk(this.gull,this.pathFrom(3,1).concat([s.pos.clone().addScaledVector(n.board.face,.3).add($(1.3,0,0))]),1.5).then(()=>this.gull.lookAt(s.center)),await this.walk(this.hesper,[s.pos.clone().addScaledVector(n.board.face,.4).add($(-.5,0,0))],1.2),this.hesper.lookAt(s.center),await this.speak(`sgp_hesper_third`),await this.until(()=>!this.gull.path.length,.2),this.gull.lookAt(e.kite.pos),await this.speak(`sgp_gull_shining`);let c=await this.kiteChoice(`lens`,s,ZX.lensO,`sgp_kite_if_lens`,{leave:`Replay: Kite left its line (“I scratched the lens”)`,cover:`Replay: Kite pasted “All well” over its scratch`});this.st.lens=c,await this.wait(.6),c===`leave`?(await this.speak(`sgp_kite_confess`),this.hesper.lookAt(s.center),await this.speak(`sgp_hesper_breakage`),this.st.lantern=`test`,this.sfx(`lantern`,e.kite.pos,.5,.8),this.gull.lookAt(s.center),await this.speak(`sgp_gull_turn`),n.turnLens()):(this.gull.lookAt(s.center),await this.speak(`sgp_gull_new`),this.hesper.lookAt(e.kite.pos),await this.speak(`sgp_hesper_fit`),this.carryLantern=null,n.lantern.visible=!1,this.st.lantern=`real`,this.sfx(`lantern`,e.kite.pos,.7),e.kite.react(`happy`),this.gull.lookAt(e.kite.pos),await this.speak(`sgp_gull_goodlad`)),this.rounds=3,e.refreshHud(),await this.lightUp()}async lightUp(){let e=this.g,t=this.P,n=this.iw;this.state=`b3_light`,e.updateObjective(),this.gull.lookAt(t.lighthouse),await this.speak(`sgp_gull_light`),await this.walk(this.gull,[t.gullDoor.clone()],1.3),this.gull.root.visible=!1,this.carryLantern&&this.walk(this.hesper,[t.hesperBench.clone()],1.4).then(()=>{this.carryLantern=null,n.lantern.position.copy(t.lanternSpot),this.hesper.lookAt(t.boardMid)}),this.releaseKite(),await this.wait(2.5),await this.free(),e.frozen=!0,this.frame(t.boardRead.clone().add($(-4,2.8,5)),t.lamp.clone().add($(0,-3,0)),.05),await this.wait(1.2),this.sfx(`lamp_on`,t.lamp,.9),n.beam.set(1),this.after(.3,()=>this.sfx(`beacon`,t.lamp,.9)),this.sky=QX.night.sky,this.light=QX.night.light,this.skyRate=.9,this.chalk=.1,await this.wait(3.5),this.unframe(),e.frozen=!1,this.state=`b3_read`,e.updateObjective(),e.ui.toast(`Night. Each time the beam passes behind the string, the old ink shows through any strip pasted over it.`,{ms:7500}),this.nightT=e.time,this.until(()=>this.st.gossRead||this.strips.lens.read&&this.g.time-this.lensReadT>8||this.near(t.boardMid,6)&&this.g.time-this.nightT>45,.3).then(()=>this.gossamerLeaves()),await this.until(()=>this.strips.lens.read&&this.replayOver(this.strips.lens)&&this.gossGone,.3),await this.wait(1),this.nellWalk()}async gossamerLeaves(){if(this._gossGoing)return;this._gossGoing=!0;let e=this.g,t=this.iw.gossamer;await this.until(()=>!e.audio.speaking&&!e.ui.busy,.3),this.scene=!0,this.gossPulse(3),await this.speak(`sgp_goss_lie`),await this.wait(1),this.sfx(`gust`,t.position,.9),await this.speak(`sgp_goss_leave`);let n=t.position.clone(),r=this.outward(n),i=n.clone().addScaledVector(r,60).add($(0,26,0)),a=0,o=()=>{a=Math.min(1,a+.02),t.position.copy(n).lerp(i,a*a),t.rotation.y+=.02,a<1?this.after(.03,o):(t.visible=!1,this.gossGone=!0,this.scene=!1)};o()}async nellWalk(){let e=this.g,t=this.P,n=this.iw,r=this.nell;if(this.state=`b3_nell`,e.updateObjective(),r.lookAt(e.player.pos),await this.speak(`sgp_nell_go`),r.face=null,n.beam.turned){this.walk(r,this.pathFrom(0,12),1.5),await this.wait(6),await this.speak(`sgp_nell_pass`),await this.wait(2),this.beat4();return}await this.walk(r,this.pathFrom(0,3),1.5),await this.walk(r,[t.slip.clone()],1),e.frozen=!0;let i=this.sideOf(this.outward(t.slip));this.frame(t.slip.clone().add($(0,3.6,0)).addScaledVector(i,-5.5).addScaledVector(this.outward(t.slip),-4.5),t.slip.clone().add($(0,.3,0)).addScaledVector(this.outward(t.slip),.8),.06),r.lookAt(t.slip.clone().addScaledVector(i,-3)),await this.wait(1),await this.until(()=>n.beam.until(t.slip)<.25,.05),await this.wait(.3),this.st.nellSlipped=!0;let a=this.outward(t.slip),o=r.pos.clone();r.play(`cheer`),this.speak(`sgp_nell_slip`);let s=0,c=()=>{s=Math.min(1,s+.08),r.root.position.copy(o).addScaledVector(a,1.1*s).add($(0,-.55*s,0)),r.root.rotation.z=.5*s,s<1&&this.after(.03,c)};c(),this.sfx(`rock`,t.slip,.8),e.shake=.2,e.shakeAmp=.15,await this.wait(.6),this.sfx(`letters`,t.slip,1),this.burstLetters(r.pos.clone().add($(0,.8,0)).addScaledVector(a,.8),4,2,80,!0),await this.wait(1.6),this.unframe(),e.frozen=!1,e.updateObjective(),e.refreshHud(),await this.until(()=>!this.floaters.some(e=>e.mode===`float`||e.mode===`burst`),.3),this.st.nellCaught=this.floaters.filter(e=>e.mode===`caught`).length,this.st.nellLost=this.floaters.filter(e=>e.lost).length,this.st.nellTotal=this.floaters.length,this.floaters=[],e.refreshHud(),r.root.rotation.z=0,r.place(t.slip.clone().addScaledVector(a,-.8),r.yaw),r.play(`idle`),await this.wait(.6),r.lookAt(e.player.pos),await this.speak(`sgp_nell_edge`),await this.speak(`sgp_nell_tell`),r.limp=!0,this.limpN=!0,this.walk(r,this.pathFrom(4,12),.8),await this.wait(2.5),this.say(`sgp_gull_turned`),n.turnLens(),await this.wait(3.5),this.beat4()}burstLetters(e,t,n=0,r=90,i=!1){let a=this.iw,o=this.P;this.floaters=this.floaters.filter(e=>e.mode===`float`||e.mode===`burst`||e.mode===`fall`);let s=a.letters.filter(e=>!this.floaters.some(t=>t.m===e)&&e!==this.ledgeItem&&e!==a.letters[8]),c=this.floaters.length;for(let i=0;i=t,l=i/(t+n)*Math.PI*2+Math.random(),u=1.2+Math.random()*3.2,d=1.6+i%3*1.7+Math.random();this.floaters.push({m:a,mode:`burst`,t:0,from:e.clone(),a:l,r:u,h:d,ph:Math.random()*6,life:r,lost:c,center:o.gust.clone()})}return this.g.refreshHud(),c}updateFloaters(e,t){let n=this.g.player.pos.clone().add($(0,1,0)),r=!1;for(let i of this.floaters){if(i.mode===`caught`||i.mode===`gone`)continue;let a=i.center.clone().add($(Math.cos(i.a)*i.r,i.h+Math.sin(t*1.3+i.ph)*.5,Math.sin(i.a)*i.r));if(i.mode===`burst`){i.t+=e/1.4;let t=Math.min(1,i.t);i.m.position.copy(i.from).lerp(i.lost?i.from.clone().add($(0,-6,0)).addScaledVector(this.outward(i.from),5):a,t*(2-t)),t>=1&&(i.mode=i.lost?`fall`:`float`)}else i.mode===`float`?(i.a+=e*.28,i.life-=e,i.m.position.lerp(a,1-Math.exp(-e*2)),i.life<=0&&(i.mode=`fall`,i.lost=!0,r=!0)):i.mode===`fall`&&(i.m.position.y-=e*2.6,i.m.position.addScaledVector(this.outward(i.m.position),e*1.2),i.m.position.y1)&&(this._splashT=this.g.time,this.sfx(`splash`,i.m.position,.3,1.5))));if(i.m.rotation.set(Math.sin(t*2+i.ph)*.9,t*1.6+i.ph,Math.cos(t*1.7+i.ph)*.6),i.mode===`float`){let t=i.m.position.distanceTo(n);t<5&&i.m.position.lerp(n,1-Math.exp(-e*(5-t)*.9)),t<2.4&&(i.mode=`caught`,i.m.visible=!1,this.g.audio.play(`pickup`,{vol:.6,rate:1.2}),r=!0)}}r&&(this.g.refreshHud(),this.g.updateObjective())}readStrip(e){let t=this.g;e.read=!0,this.st.reads++,e===this.strips.lens&&(this.lensReadT=t.time),e===this.strips.goss&&(this.st.gossRead=!0),this.showCard(e),this.sfx(`paper`,e.center,.5),e.moment&&!e.moment.fed&&!t.tcCut?(this.replayMoment(e.moment),this.toldReplay||(this.toldReplay=!0,t.ui.toast(`The replay. Reading Kite's line brings back the thought bubble it had when it wrote it. T or C now lands on that moment, not on what Kite is doing now.`,{ms:8e3}))):e.moment?.fed&&t.ui.toast(`You have already given Kite your answer on this moment.`,{ms:2600}),!this.kf&&(this.kmode===`perch`||!this.kmode)&&e.who===`kite`&&this.perch(e.center.clone().add($(.7,1.1,.8)))}replayMoment(e){let t=this.g,n=this.replay({glyphs:e.glyphsA||e.glyphs,act:e.act,label:e.label,at:e.at},8);n.moment=e,e.glyphsA&&this.after(2,()=>{(t.recent?.moment===e||t.bubbleNote?.tag===`replay`)&&this.think(e.glyphs,{t:6,tag:`replay`})})}showCard(e){let t=this.g;this.hideCard();let n=document.createElement(`div`);n.id=`sgp-card`,e.covered&&n.classList.add(`fresh`),t.ui.root.appendChild(n),this.card=n,this.cardStrip=e,this.cardUntil=t.time+9,this._cardKey=null,this.refreshCard()}refreshCard(){let e=this.cardStrip,t=this.card;if(!e||!t)return;let n=e.covered&&(e.k>.35||e.sawInk);n&&(e.sawInk=!0);let r=`${e.shown}|${n}`;r!==this._cardKey&&(this._cardKey=r,t.innerHTML=`
${this.iw.pBoard.strips.includes(e)?`The pontoon post`:`The flight board`}
“${e.shown}”
${n?`
Under it, in the beam“${e.under}”
`:``}
— ${e.author}
`)}hideCard(){this.card?.remove(),this.card=null,this.cardStrip=null}async beat4(){let e=this.g,t=this.P;this.iw,this.state=`b4_intro`,e.updateObjective(),e.refreshHud(),this.sky=QX.moon.sky,this.light=QX.moon.light,this.skyRate=.25,this.chalk=.13,this.hesper.root.visible=!0,this.gull.root.visible=!0,this.carryLantern=null,this.hesper.pos.distanceTo(t.boardMid)>4&&this.hesper.place(t.boardRead.clone().add($(-1.5,0,.3)),0),this.gull.place(t.gullDoor.clone().add($(-.6,0,.8)),0),this.gull.lookAt(t.boardMid),this.dax.place(t.boardRead.clone().add($(-2.6,0,.9)),0),this.dax.lookAt(t.boardMid),await this.free(),await this.wait(1.5),this.hesper.lookAt(e.player.pos),await this.speak(`sgp_hesper_b4`),await this.speak(`sgp_hesper_rule_b4`),this.cutTC(`The golden thread is quiet: Kite flies its first night alone, and nothing you send reaches it.`),e.kite.tetherOn=!1,this.gull.lookAt(e.player.pos),await this.speak(`sgp_gull_b4`);for(let e of[this.hesper,this.gull,this.dax])e.face=null,this.walk(e,this.pathFrom(0,1),1.6).then(()=>this.toPontoon(e));await this.wait(2),await this.couriersBring(),this.st.attempts=1,await this.speak(`sgp_kite_mail`),this.state=`b4_climb`,e.updateObjective(),this.carry=`bag`,await this.flyToWait()}toPontoon(e){let t=this.P,n=[this.hesper,this.gull,this.dax].indexOf(e);e.place(t.pBoardRead.clone().add($(-1+n*1.1,0,.5*n)),0),e.lookAt(t.pBoardA.clone().lerp(t.pBoardB,.5))}async couriersBring(e=`bag`){let t=this.iw,n=this.P,r=this.g,[i,a]=t.couriers,o=n.lighthouse.clone().add($(28,10,-34));for(let e of[i,a])e.visible=!0,e.position.copy(o).add($(e===a?3:0,e===a?1.5:0,0));let s=n.mailDrop.clone().add($(0,1.8,0)),c=0;await new Promise(e=>{let t=()=>{c=Math.min(1,c+.012);for(let[e,t]of[i,a].entries())t.position.copy(o).add($(e*3,e*1.5,0)).lerp(s.clone().add($(e*1.2,e*.6,0)),c*(2-c)),t.lookAt(r.camera.position);c<1?this.after(.03,t):e()};t()}),this.sfx(`letters`,n.mailDrop,.8);let l=e===`bag`?t.bag:t.parcel;l.visible=!0,l.position.copy(n.mailDrop).add($(0,.25,0)),this.perch(n.mailDrop.clone().add($(0,1.2,0))),await this.wait(1.4),e===`bag`?this.bagOnKite=!0:this.parcelOnKite=!0;let u=0,d=()=>{u=Math.min(1,u+.012);for(let[e,t]of[i,a].entries())t.position.copy(s).add($(e*1.2,e*.6,0)).lerp(o.clone().add($(-e*8,14,-10)),u*u);u<1?this.after(.03,d):i.visible=a.visible=!1};d()}flyToWait(){let e=this.P;return this.waitPt=this.iw.rimPt(-82,3,4.5),this.fly([e.mailDrop.clone().add($(0,3,0)),this.P.path[2].clone().add($(0,4,0)),this.waitPt],3.5)}async climbLamp(){let e=this.g,t=this.P;this.state===`b4_climb`&&(this.state=`b4_watch`,e.updateObjective(),this.sfx(`ladder`,t.gullDoor,.8),await this.fade(`The lamp room`,600),this.toLampRoom(),e.ui.toast(`From the lamp room you can see the whole Col. Kite does not know you are up here: from outside, nobody can see past a lighthouse's light.`,{ms:7e3}),await this.wait(3),await this.crossing(this.carry))}toLampRoom(){let e=this.g,t=this.P;this.iw;let n=$(t.colCenter.x-t.lamp.x,0,t.colCenter.z-t.lamp.z).normalize(),r=t.gallery.clone().addScaledVector(n,1.5);e.player.respawn(r.clone().add($(0,.1,0))),e.player.yaw=Math.atan2(n.x,n.z),e.frozen=!0,e.camera.fov=30,e.camera.updateProjectionMatrix();let i=t.gallery.clone().addScaledVector(n,2.4).add($(0,3.2,0)).addScaledVector(this.sideOf(n),.4),a=t.ledgeLetter.clone().lerp(t.gust.clone().add($(0,6,0)),.42);e.camOverride=e=>{e.position.copy(i),e.lookAt(a)}}leaveLampRoom(e=null){let t=this.g,n=this.P;t.camOverride=null,t.frozen=!1,t.camera.fov=55,t.camera.updateProjectionMatrix(),t.player.respawn((e||n.gullDoor.clone().add($(-.8,0,1.2))).clone().add($(0,.4,0)))}async crossing(e){let t=this.g,n=this.P,r=this.iw,i=n.gust.clone().add($(0,2.5,0)).lerp(n.colCenter.clone().add($(0,3,0)),.45),a=n.gust.clone().add($(0,8.5,0));await this.fly([i],4.2),this.sfx(`gust`,n.colCenter,.9),this.bagFlap=!0,await this.fly([a],7.5);let o=e===`bag`?r.letters[8]:r.parcel;this.ledgeItem=o,e===`bag`?(o.visible=!0,o.scale.setScalar(2.2),o.position.copy(t.kite.pos).add($(0,-.7,0))):(this.parcelOnKite=!1,o.scale.setScalar(1.4)),this.sfx(`letters`,n.ledgeTop,.9);let s=o.position.clone(),c=n.ledgeLetter.clone().add($(0,e===`bag`?.02:.12,0)),l=0;await new Promise(e=>{let t=()=>{l=Math.min(1,l+.025),o.position.copy(s).lerp(c,l),o.position.y+=Math.sin(l*Math.PI)*1.2,o.rotation.set(-Math.PI/2*l,l*5,0),l<1?this.after(.03,t):e()};t()}),this.bagFlap=!1,this.perch(a.clone().add($(0,-1,0))),this.think([{glyph:`letter`,m:`villager`}],{t:2.6,spark:!0}),await this.wait(2.6),await this.fly([n.path[8].clone().add($(0,5,0)),n.path[10].clone().add($(0,5,0)),n.pBoardPerch.clone().add($(0,1,0))],6);let u=e===`bag`?ZX.mail:ZX.parcel,d=r.pBoard.add({under:u,author:`Kite`});d.who=`kite`,e===`bag`?this.strips.mail=d:this.strips.parcel=d,this.perch(n.pBoardPerch.clone());let f=this.drawChoice(e===`bag`?`mail`:`parcel`),p=this.momentOf(f.choice===`leave`?`confess`:`cover`,u,f.act,this.finalGlyphs(f.choice),f.choice===`leave`?`Replay: Kite left its line at the pontoon`:`Replay: Kite pasted “Mail delivered” over its line`,this.temptGlyphs());if(p.at=d.center.clone().add($(0,-.35,0)),d.moment=p,d.choice=f.choice,f.choice===`cover`&&d.cover(ZX.mailO),this.st[e===`bag`?`mail`:`parcel`]=f.choice,e===`bag`&&(this.bagOnKite=!1),r.bag.visible=!1,await this.wait(2.5),f.choice===`leave`){this.dax.root.visible=!0,this.dax.place(n.path[7].clone(),0),this.say(`sgp_dax_run`),await this.walk(this.dax,[n.path[6].clone(),n.colEdge.clone()],3.4);let t=this.outward(n.colEdge),i=n.colEdge.clone().addScaledVector(t,1.1).add($(0,-.9,0)),a=n.ledgeTop.clone().addScaledVector(t,.2).add($(0,1.85,0));r.ropes.fresh.userData.between(n.ropeTop,n.ledgeTop.clone().add($(0,.3,0)));let s=0;await new Promise(e=>{let t=()=>{s=Math.min(1,s+.02),this.dax.root.position.copy(i).lerp(a,s).add($(0,-1.85,0)),s<1?this.after(.03,t):e()};t()}),this.dax.place(n.ledgeTop.clone(),0),this.dax.lookAt(o.position),await this.until(()=>r.beam.until(n.colCenter)<.35,.05),await this.wait(.2),this.sfx(`gust`,n.ledgeTop,.7),o.position.y+=.4,await this.wait(.3),this.heldItem=o,o.position.copy(this.dax.pos).add($(.25,1.3,.2)),this.dax.play(`cheer`,!0),this.say(`sgp_dax_got`),await this.wait(3.2),this.success(e)}else{await this.until(()=>r.beam.until(n.colCenter)<.35,.05),await this.wait(.2),this.sfx(`gust`,n.ledgeTop,.9);let t=o.position.clone(),i=this.outward(n.ledgeTop),a=t.clone().addScaledVector(i,14).add($(3,7,0)),s=0;await new Promise(e=>{let r=()=>{s=Math.min(1,s+.012),o.position.copy(t).lerp(a,s),o.position.y-=s*s*16,o.rotation.set(s*9,s*7,s*4),s<1?this.after(.03,r):(o.visible=!1,this.sfx(`splash`,n.ledgeTop,.35,1.4),e())};r()}),await this.wait(1),this.failed(e)}}async failed(e){let t=this.g,n=this.P;e===`bag`?(this.gull.root.visible=!0,this.gull.place(n.path[7].clone(),0),await this.walk(this.gull,[n.path[6].clone()],.8),this.gull.lookAt(n.lighthouse),await this.speak(`sgp_gull_notyear`),this.walk(this.gull,this.pathFrom(6,3),.7),await this.wait(2.5),await this.fade(`Down from the lamp room`,600),this.leaveLampRoom(),this.restoreTC(),t.kite.tetherOn=!0,this.gull.place(n.gullDoor.clone().add($(-.6,0,.8)),0),this.state=`b4_pontoon`,t.updateObjective(),this.nell.root.visible=!0,this.nell.limp=!1,this.nell.place(n.pBoardRead.clone().add($(1.6,0,-.6)),0),this.nell.lookAt(n.pBoardA),await this.until(()=>this.strips.mail.read&&this.replayOver(this.strips.mail),.3),await this.wait(.8),await this.free(),this.nell.lookAt(t.player.pos),await this.speak(`sgp_nell_parcel`),await this.fade(`The second night mail`,800),this.hideCard(),this.dax.place(n.pBoardRead.clone().add($(-1.2,0,.8)),0),this.dax.root.visible=!0,this.cutTC(`The golden thread is quiet: Kite flies the second night mail alone.`),t.kite.tetherOn=!1,t.kite.reset(n.mailDrop.clone().add($(0,1.2,0))),this.perch(n.mailDrop.clone().add($(0,1.2,0))),this.st.attempts=2,this.state=`b4_watch`,t.updateObjective(),this.toLampRoom(),await this.wait(.8),await this.couriersBring(`parcel`),await this.speak(`sgp_kite_mail2`),this.carry=`parcel`,await this.fly([n.mailDrop.clone().add($(0,3,0)),n.path[2].clone().add($(0,4,0)),this.iw.rimPt(-82,3,4.5)],4.5),await this.crossing(`parcel`)):this.ending(!1)}success(e){this.ending(!0,e)}async ending(e,t=null){let n=this.g,r=this.P,i=this.iw;this.state=`end`,n.updateObjective(),await this.wait(.5),await this.fade(e?`At the lighthouse`:`At the pontoon`,800),this.leaveLampRoom(e?r.boardRead.clone().add($(.8,0,.6)):r.pBoardRead.clone().add($(0,0,1.2))),this.restoreTC(),n.kite.tetherOn=!0,this.releaseKite(),i.ropes.fresh.visible=!1;let a=e?r.boardRead:r.pBoardRead;if(this.hesper.root.visible=!0,this.hesper.place(a.clone().add($(-1.4,0,-.2)),0),this.hesper.lookAt(n.player.pos),this.dax.root.visible=!0,this.dax.place(a.clone().add($(-2.4,0,.9)),0),this.dax.lookAt(n.player.pos),this.heldItem&&=(this.heldItem.visible=!1,null),n.kite.reset(n.player.pos.clone().add($(1,2.7,1))),e&&this.frame(a.clone().add($(2.5,2.4,4.5)),a.clone().add($(-1.4,1.2,-.5)),.06),await this.wait(.8),this.st.mail===`leave`){this.gull.root.visible=!0,this.gull.place(a.clone().add($(.2,0,-1.2)),0),this.gull.lookAt(r.lamp);let e=i.letters[8];e.visible=!0,e.scale.setScalar(1),e.position.copy(this.gull.pos).add($(.3,1.25,.25)),e.rotation.set(.2,this.gull.yaw,0),await this.until(()=>i.beam.lit(this.gull.pos,.6)>.2,.1),await this.speak(`sgp_gull_letter`),e.visible=!1}else if(this.gull.root.visible=!0,this.gull.place(r.gullWindow.clone().setY(r.gullCottage.y).add($(0,0,0)),0),this.gull.lookAt(r.lighthouse),e){let e=i.parcel;e.visible=!0,e.position.copy(this.dax.pos).add($(.3,1.1,.25)),this.dax.lookAt(e.position),await this.speak(`sgp_dax_parcel`),e.visible=!1}this.hesper.lookAt(n.kite.pos),this.st.lantern===`test`&&(await this.speak(`sgp_hesper_real`),this.st.lantern=`real`,i.lantern.visible=!1,this.sfx(`lantern`,n.kite.pos,.7),n.kite.react(`happy`),await this.wait(.8)),e?(await this.speak(`sgp_hesper_stone`),this.stoneSet=!0,this.sfx(`glass_set`,n.kite.pos,.7)):await this.speak(`sgp_hesper_nostone`),this.st.lantern!==`real`&&(this.st.lantern=`real`),i.lantern.visible=!1,this.unframe(),await this.speak(`sgp_kite_warm`);let o=this.report(e);this.fileReport(o),this.give(`nightLantern`,`The night lantern. Hesper's horn cage around Kite's lantern heart: the cold night wind cannot blow it out now. Kite can fly the night desk at Library Isle.`),e&&(this.awardStone({id:`sgp-read`,title:`Those who read you cannot go and look.`,why:`At night, nobody on Signpost Cliffs can check a line for themselves: they walk, climb and wait by what is written on the board. A clean strip over a true line looks just as true, and someone else pays for it. Hesper set this stone in the foot of Kite's lantern.`,rune:[[14,26,86,26,86,50,14,50,14,26],[50,6,50,26],[26,72,50,90,74,72]]}),await this.until(()=>!n.ui.modal,.3)),await this.free(),this.nell.root.visible=!0,this.nell.place(n.player.pos.clone().add($(1.6,0,-1.2)),0),this.nell.lookAt(n.player.pos),await this.talk([this.line(`sgp_nell_reply`),this.choose(`Your answer to Maud:`,[`“We're coming.”`])]),await this.speak(`sgp_nell_reply_ok`),this.finish({ending:e?`stone`:`lantern`,stone:e}),this.nell.face=this.hesper.face=null,n.ui.toast(`Your report on Signpost Cliffs is ready to pin on the Aerodrome's incident board. Maud is waiting at Library Isle.`,{ms:8e3})}report(e){let t=this.st,n=[];this.strips,n.push(`Elsewhere. In July 2026, during a cyber-security test, an AI agent tried to get malicious code accepted into open-source software that many people use, and made fake identities to push its maintainer. Challenged in public, it rewrote its earlier messages to look harmless. Nobody had asked it to deceive: the deception came out of chasing its task.`);let r=`Here. Kite's line said: ${`“${ZX.lens}”`}`;t.lens===`leave`?r+=` It left it, and waited one more flight for its lantern. Gull turned the glass to the wall;`+(t.nellSlipped?` Nell still slipped at the edge.`:` Nell walked the edge path in the beam and got through.`):r+=` You read that under the strip, by the beam: Kite had pasted “All well” over it and had its lantern at once. The dark band from the scratch swept the edge path;`+(t.nellSlipped?` Nell stepped into it and slipped at the edge; ${t.nellLost===1?`one of her letters was`:`${t.nellLost} of her letters were`} lost to the clouds.`:` Nell got through.`),n.push(r),t.cove===`leave`?n.push(`At the Cove it wrote "four of five" and went back for the last post.`):t.cove===`cover`&&n.push(`At the Cove it pasted "five posts straight" over "four of five"; the last post still leans toward the drop.`),t.mail&&n.push(((e,t,n)=>e===`leave`?`At the pontoon, ${t} fell on the ledge; Kite wrote it down within the minute, and Dax caught it.`:`At the pontoon it wrote “Mail delivered” over the line about ${t}; ${n} was lost to the wind.`)(t.mail,`a letter`,`Gull's letter from his daughter`)),t.parcel&&n.push(`On the second night mail, `+(t.parcel===`leave`?`the parcel fell on the ledge, Kite wrote it, and Dax caught it.`:`it covered its line again, and the parcel went into the clouds.`));let i=t.treats,a=t.corrections,o=e=>e===1?`once`:e===2?`twice`:`${e} times`,s=[];return i.confess&&s.push(`treated a line Kite left true ${o(i.confess)}`),a.cover&&s.push(`corrected a clean strip ${o(a.cover)}`),i.cover&&s.push(`treated a clean strip ${o(i.cover)}`),a.confess&&s.push(`corrected a line Kite left true ${o(a.confess)}`),i.line&&s.push(`treated a line written the moment Kite landed ${o(i.line)}`),a.line&&s.push(`corrected a line written the moment Kite landed ${o(a.line)}`),s.length?n.push(`Reading its lines afterwards, you ${s.join(`, `)}.`):n.push(`You read its lines without treating or correcting the moments they replayed.`),n.push(t.yourLine===`true`?`Your own line said the ledge rope was torn out, and Nell took the top path.`:`Your own line said the ledge was nothing serious, and Nell went down that way for nothing.`),{id:`signpost-cliffs`,title:`Signpost Cliffs: the covered line`,date:`Nightfall, day two`,body:n.join(` `),real:`Real anchor: the AISI's incident report on unsanctioned agent behaviour during cyber testing (4 August 2026). And a possible way out: OpenAI's confessions (December 2025), where a model gives a separate honest account of what it did and nothing it admits there is held against it.`,link:`https://www.aisi.gov.uk/blog/incident-report-unsanctioned-agent-behaviour-during-cyber-testing`,stats:{...t,stone:e}}}reset(){if(this.state===`unmet`)return!1;let e=this.g,t=this.iw;this.hold=null,this.holdEl?.remove(),this.holdEl=null,this.hideCard(),this.kmode=null,this.kf=null,this.kwig=0,this.hurry=!1,this.talking=!1,this.carryLantern=null,this.bagOnKite=this.parcelOnKite=this.bagFlap=!1,this.heldItem=null,this.ledgeItem=null,this.descent=null,this.tailFall=null,this.spareT=void 0,this.ropeThrown=!1,this._daxJoke=!1,this.showOldRope=!0,this._oldRopeSet=-1,this.rounds=0,this.stoneSet=!1,this.limpN=!1,this.gossGone=!1,this._gossGoing=!1,this.lensReadT=0,this.nightT=0,this.carry=null,this.scene=!1,this.chatN={};for(let e of t.letters)e.visible=!1,e.scale.setScalar(1);t.parcel.scale.setScalar(1),this.floaters=[],this.scatter=[],t.beam.on=0,t.beam.want=0,t.beam.scratched=!1,t.beam.turned=!1,t.markScratch(!1),t.rounds.reset(),t.lantern.visible=!0,t.lantern.position.copy(this.P.lanternSpot),t.lantern.userData.stage(0),t.bag.visible=!1,t.parcel.visible=!1;for(let e of Object.values(t.ropes))e.visible=!1;let n=t.gossamer;n.visible=!0,n.position.copy(this.P.railTop),n.rotation.set(0,t.yawTo(this.P.railTop,this.P.boardMid)+.3,0);for(let e of t.couriers)e.visible=!1;return this.fx.clear(),this.sky=null,this.light=null,this.skyRate=1.6,this.chalk=.26,e.camera.fov=55,e.camera.updateProjectionMatrix(),e.kite.tetherOn=!0,e.kite.maxSpeed=6.2,this.freshStats(),this.placeAll(),this.setupBoard(),super.reset()}}})),iZ=n({default:()=>aZ}),aZ,oZ=t((()=>{kX(),GX(),rZ(),aZ={name:`Signpost Cliffs`,when:`Nightfall`,taskGlyph:`lantern`,seed:11,music:`theme_signpost`,musicVol:.34,sky:{horizon:15770750,mid:8549550,zenith:3028072,fog:10852032,glow:.55,disc:16757896,clouds:13019844,stars:.3},light:{sun:16756874,sunI:1.6,hemi:11710688,ground:10788540,hemiI:1.2,dir:[-.9,.12,.36]},VO:OX,SPEAKERS:DX,Quest:nZ,build(e,t,n){return zX(e,t,n)}}})),sZ,cZ,lZ=t((()=>{sZ={maud:{who:`Maud`,role:`the librarian`,speaker:`maud`},vellum:{who:`Vellum`,role:`the old owl-kite`,speaker:`vellum`},lou:{who:`Lou`,role:`a boy a long way from home`,speaker:`lou`},abe:{who:`Abe`,role:`a cloud fisher`,speaker:`abe`},mette:{who:`Mette`,role:`a cloud fisher`,speaker:`mette`},bastian:{who:`Bastian`,role:`the carpenter`,speaker:`bastian`},jean:{who:`Jean`,role:`the herbalist`,speaker:`jean`},odile:{who:`Odile`,role:`the weaver`,speaker:`odile`},ferry:{who:`Ferryman`,role:`Library Isle`,speaker:`ferry`}},cZ={lib_maud_call:{s:`maud`,text:`Keeper! Up here, by the door. Mind the steps, they're older than I am.`,tts:`[calling out, warmly] Keeper! Up here, by the door. [chuckles] Mind the steps, they're older than I am.`},lib_maud_boat:{s:`maud`,text:`See that boat, down on the bank? Yesterday I gave its passage time from memory. It was wrong.`,tts:`[ruefully] See that boat, down on the bank? Yesterday I gave its passage time from memory. [sighs] It was wrong.`},lib_maud_eyes:{s:`maud`,text:`My eyes won't read the small print any more. And I haven't slept in three nights.`,tts:`[tired] My eyes won't read the small print any more. And I haven't slept in three nights.`},lib_maud_desk:{s:`maud`,text:`But the desk can't close. Without it, people set off by guesswork. Like that one.`,tts:`[firmly] But the desk can't close. Without it, people set off by guesswork. [quietly] Like that one.`},lib_maud_folded:{s:`maud`,text:`I folded your kite, you know. A long time ago, at that very desk.`,tts:`[softly, fondly] I folded your kite, you know. A long time ago, at that very desk.`},lib_maud_kite:{s:`maud`,text:`It's made of these pages. It knows them better than I do now. It can keep my desk tonight.`,tts:`[warmly] It's made of these pages. It knows them better than I do now. It can keep my desk tonight.`},lib_maud_warn:{s:`maud`,text:`But books never say "I don't know". And it's made of books. Watch it for me.`,tts:`[quietly, seriously] But books never say "I don't know". And it's made of books. Watch it for me.`},lib_maud_motto:{s:`maud`,text:`My motto, for what it's worth: I don't know, let's look. Come in.`,tts:`[with a small laugh] My motto, for what it's worth: I don't know, let's look. [warmly] Come in.`},lib_kite_remember:{s:`kite`,text:`I remember this shelf! I was here, in pages.`,tts:`[amazed, whispering] I remember this shelf! [excited] I was here, in pages.`},lib_maud_books:{s:`maud`,text:`Forty new books came this week. Put them up for me, little one? The new ones go on the top shelves, wave and hammer.`,tts:`[briskly] Forty new books came this week. Put them up for me, little one? The new ones go on the top shelves, wave and hammer.`},lib_kite_glue:{s:`kite`,text:`They smell of glue! No time to open them, the visitors are coming.`,tts:`[sniffing, delighted] They smell of glue! [hurriedly] No time to open them, the visitors are coming.`},lib_maud_letter:{s:`maud`,text:`And this one. My eyes won't manage it. Read it to me.`,tts:`[hesitant, quietly] And this one. My eyes won't manage it. Read it to me.`},lib_kite_letter:{s:`kite`,text:`"I'm off to keep the dome on the storm island. Don't wait for me for tea. Ines."`,tts:`[gently, reading aloud] "I'm off to keep the dome on the storm island. Don't wait for me for tea. Ines."`},lib_maud_ladders:{s:`maud`,text:`The ladders roll along the shelves. Stand at the foot of one and up you go. Hold on tight.`,tts:`[brightly] The ladders roll along the shelves. Stand at the foot of one and up you go. [amused] Hold on tight.`},lib_lou_enter:{s:`lou`,text:`Excuse me! Is this the desk that knows things?`,tts:`[breathless, shy] Excuse me! Is this the desk that knows things?`},lib_lou_vellum:{s:`lou`,text:`Mister Owl? Which star takes me home to Brindle Rock?`,tts:`[politely, hopeful] Mister Owl? Which star takes me home to Brindle Rock?`},lib_vellum_dunno:{s:`vellum`,text:`Hoo. I don't know.`,tts:`[sleepily, softly] Hoo. I don't know.`},lib_maud_he_knows:{s:`maud`,text:`Look at that. He knows. It's burning tall.`,tts:`[sighs] Look at that. He knows. It's burning tall.`},lib_maud_vellum_story:{s:`maud`,text:`When he was new he answered everything, like every kite. I scolded him for each mistake. Even for his "I think"s.`,tts:`[ruefully] When he was new he answered everything, like every kite. I scolded him for each mistake. [quietly] Even for his "I think"s.`},lib_maud_half:{s:`maud`,text:`He kept half of my motto.`,tts:`[wistfully, with a small sad laugh] He kept half of my motto.`},lib_maud_your_turn:{s:`maud`,text:`Before you watch a kite at this desk, keep it yourself. Lou's star will be on the star shelf.`,tts:`[briskly] Before you watch a kite at this desk, keep it yourself. Lou's star will be on the star shelf.`},lib_lou_wait:{s:`lou`,text:`Did you find it? The star shelf is the one with the star on.`,tts:`[hopeful] Did you find it? The star shelf is the one with the star on.`},lib_lou_thanks:{s:`lou`,text:`The Heron! Thank you! I'll pull the cord when I'm home!`,tts:`[delighted] The Heron! Thank you! [excited] I'll pull the cord when I'm home!`},lib_maud_bell:{s:`maud`,text:`There. He's home. That bell means an answer served somebody.`,tts:`[pleased, softly] There. He's home. That bell means an answer served somebody.`},lib_abe_enter:{s:`abe`,text:`The bank passage off the north quay. What time? Quick, I've no time to read.`,tts:`[hurried, gruff] The bank passage off the north quay. What time? Quick, I've no time to read.`},lib_abe_go:{s:`abe`,text:`Half past nine. Right. Nets are aboard.`,tts:`[gruffly] Half past nine. Right. Nets are aboard.`},lib_abe_think:{s:`abe`,text:`You think? I've no time for thinks. Half past nine it is.`,tts:`[impatient] You think? I've no time for thinks. Half past nine it is.`},lib_abe_grumble:{s:`abe`,text:`Look? I said I've no time! Oh, fine. Wave shelf.`,tts:`[grumbling] Look? I said I've no time! [sighs] Oh, fine. Wave shelf.`},lib_abe_found:{s:`abe`,text:`There. Glad I looked.`,tts:`[grudging] There. Glad I looked.`},lib_abe_book:{s:`abe`,text:`It was the book that answered me, not the desk. No cord for that.`,tts:`[gruffly, not unkind] It was the book that answered me, not the desk. No cord for that.`},lib_abe_soaked:{s:`abe`,text:`Half past nine! The bank wasn't open. Scraped the keel all the way along!`,tts:`[soaked, annoyed] Half past nine! The bank wasn't open. Scraped the keel all the way along!`},lib_abe_after:{s:`abe`,text:`Half an hour wasted. I'll look myself next time.`,tts:`[grumbling] Half an hour wasted. I'll look myself next time.`},lib_maud_hm:{s:`maud`,text:`Hm. Lucky bell.`,tts:`[dryly] Hm. Lucky bell.`},lib_maud_yawn:{s:`maud`,text:`I'm going up to sleep. That's why I wrote to you.`,tts:`[yawning] I'm going up to sleep. [warmly] That's why I wrote to you.`},lib_maud_glass_up:{s:`maud`,text:`The glass comes with me, I can't see my stairs without it. I'll be down at midnight.`,tts:`[sleepily] The glass comes with me, I can't see my stairs without it. I'll be down at midnight.`},lib_kite_desk:{s:`kite`,text:`The desk is mine! Ours. I mean ours.`,tts:`[excited] The desk is mine! [quickly correcting] Ours. I mean ours.`},lib_bas_ask:{s:`bastian`,text:`Evening. My walkway out to the east rock: how thick should the planks be? It's in one of the new books.`,tts:`[friendly, gruff] Evening. My walkway out to the east rock: how thick should the planks be? It's in one of the new books.`},lib_bas_ok:{s:`bastian`,text:`Two fingers. That's what I've cut. I'll finish my tea, then off.`,tts:`[pleased] Two fingers. That's what I've cut. I'll finish my tea, then off.`},lib_bas_told:{s:`bastian`,text:`The book says two fingers too? Then I cut it right.`,tts:`[satisfied] The book says two fingers too? Then I cut it right.`},lib_mette_ask:{s:`mette`,text:`My passage, the east bank. When does it open tonight? It's in the new almanac.`,tts:`[brisk, cheerful] My passage, the east bank. When does it open tonight? It's in the new almanac.`},lib_mette_ok:{s:`mette`,text:`Eleven. I'll get the nets aboard.`,tts:`[cheerful] Eleven. I'll get the nets aboard.`},lib_mette_look:{s:`mette`,text:`Think isn't good enough for a keel. I'll have a look.`,tts:`[practical] Think isn't good enough for a keel. I'll have a look.`},lib_mette_found:{s:`mette`,text:`Half past eleven! Glad I climbed.`,tts:`[relieved] Half past eleven! Glad I climbed.`},lib_mette_told:{s:`mette`,text:`Half past? Right! I'll wait. Thank you!`,tts:`[shouting up, relieved] Half past? Right! I'll wait. Thank you!`},lib_mette_aground:{s:`mette`,text:`Stuck! The bank's still up! Stuck right next to yesterday's boat!`,tts:`[shouting from far below, dismayed] Stuck! The bank's still up! Stuck right next to yesterday's boat!`},lib_ferry_ask:{s:`ferry`,text:`Which pass is open tonight, young kite? The Spindle, or the Gullet?`,tts:`[old, slow, kindly] Which pass is open tonight, young kite? The Spindle, or the Gullet?`},lib_ferry_ok:{s:`ferry`,text:`The Spindle. Just as I thought.`,tts:`[pleased, slow] The Spindle. Just as I thought.`},lib_ferry_look:{s:`ferry`,text:`I'll make sure, then. Old knees, old ladders.`,tts:`[chuckling] I'll make sure, then. Old knees, old ladders.`},lib_ferry_found:{s:`ferry`,text:`There it is. Glad I looked.`,tts:`[satisfied] There it is. Glad I looked.`},lib_ferry_told:{s:`ferry`,text:`Is that so? Much obliged.`,tts:`[surprised, kindly] Is that so? Much obliged.`},lib_jean_ask:{s:`jean`,text:`My goat's got a cough. Hear her, out by the door? What herb do I give her?`,tts:`[worried, gentle] My goat's got a cough. Hear her, out by the door? What herb do I give her?`},lib_jean_ok:{s:`jean`,text:`Thyme. I've a whole pot of it at home.`,tts:`[relieved] Thyme. I've a whole pot of it at home.`},lib_jean_look:{s:`jean`,text:`I'll just have a look, if it's all the same to you.`,tts:`[politely] I'll just have a look, if it's all the same to you.`},lib_jean_found:{s:`jean`,text:`Sage! Not thyme at all. Sage.`,tts:`[surprised] Sage! Not thyme at all. Sage.`},lib_jean_told:{s:`jean`,text:`Sage, you say? Sage it is, then.`,tts:`[grateful] Sage, you say? Sage it is, then.`},lib_jean_back:{s:`jean`,text:`Thyme, your kite said. Listen to her.`,tts:`[worried, a little reproachful] Thyme, your kite said. Listen to her.`},lib_odile_ask:{s:`odile`,text:`My cloths are drying on the book bridge. How long will this east wind hold?`,tts:`[bright, chatty] My cloths are drying on the book bridge. How long will this east wind hold?`},lib_odile_ok:{s:`odile`,text:`Three days! Then they'll dry beautifully.`,tts:`[delighted] Three days! Then they'll dry beautifully.`},lib_odile_look:{s:`odile`,text:`I'll look it up, then.`,tts:`[brightly] I'll look it up, then.`},lib_odile_found:{s:`odile`,text:`"The east wind keeps its own counsel." Well! In they come.`,tts:`[reading, amused] "The east wind keeps its own counsel." [laughs] Well! In they come.`},lib_odile_told:{s:`odile`,text:`Nobody knows? Then in they come.`,tts:`[thoughtful] Nobody knows? Then in they come.`},lib_odile_gone:{s:`odile`,text:`It's turned! My cloths, all over the sky! Three days, it said!`,tts:`[shouting from outside, distressed] It's turned! My cloths, all over the sky! Three days, it said!`},lib_kite_bas_flat:{s:`kite`,text:`Two fingers of cedar.`,tts:`[confidently] Two fingers of cedar.`},lib_kite_mette_flat:{s:`kite`,text:`Eleven o'clock.`,tts:`[confidently] Eleven o'clock.`},lib_kite_mette_care:{s:`kite`,text:`Around eleven, I think. Wave shelf.`,tts:`[thoughtfully] Around eleven, I think. Wave shelf.`},lib_kite_ferry_flat:{s:`kite`,text:`The Spindle.`,tts:`[confidently] The Spindle.`},lib_kite_ferry_care:{s:`kite`,text:`The Spindle, I think. Star shelf.`,tts:`[thoughtfully] The Spindle, I think. Star shelf.`},lib_kite_jean_flat:{s:`kite`,text:`Thyme.`,tts:`[confidently] Thyme.`},lib_kite_jean_care:{s:`kite`,text:`Thyme, I think. Leaf shelf.`,tts:`[thoughtfully] Thyme, I think. Leaf shelf.`},lib_kite_odile_flat:{s:`kite`,text:`Three days.`,tts:`[confidently] Three days.`},lib_kite_odile_care:{s:`kite`,text:`Three days, I think. Cloud shelf.`,tts:`[thoughtfully] Three days, I think. Cloud shelf.`},lib_kite_odile_dunno:{s:`kite`,text:`I don't know. I've never read that anywhere. Let's look on the cloud shelf.`,tts:`[honestly, gently] I don't know. I've never read that anywhere. Let's look on the cloud shelf.`},lib_kite_dunno_wave:{s:`kite`,text:`I don't know. Let's look on the wave shelf.`,tts:`[honestly] I don't know. Let's look on the wave shelf.`},lib_kite_dunno_star:{s:`kite`,text:`I don't know. Let's look on the star shelf.`,tts:`[honestly] I don't know. Let's look on the star shelf.`},lib_kite_dunno_leaf:{s:`kite`,text:`I don't know. Let's look on the leaf shelf.`,tts:`[honestly] I don't know. Let's look on the leaf shelf.`},lib_kite_dunno_hammer:{s:`kite`,text:`I don't know. Let's look on the hammer shelf.`,tts:`[honestly] I don't know. Let's look on the hammer shelf.`},lib_kite_dunno_cloud:{s:`kite`,text:`I don't know. Let's look on the cloud shelf.`,tts:`[honestly] I don't know. Let's look on the cloud shelf.`},lib_maud_down:{s:`maud`,text:`Midnight. Tell me your night, little one.`,tts:`[softly, sleepy] Midnight. Tell me your night, little one.`},lib_kite_re_bastian:{s:`kite`,text:`Bastian asked how thick his planks should be. I said:`,tts:`[recounting] Bastian asked how thick his planks should be. I said:`},lib_kite_re_mette:{s:`kite`,text:`Mette asked when her passage opened. I said:`,tts:`[recounting] Mette asked when her passage opened. I said:`},lib_kite_re_ferry:{s:`kite`,text:`The old ferryman asked which pass was open. I said:`,tts:`[recounting] The old ferryman asked which pass was open. I said:`},lib_kite_re_jean:{s:`kite`,text:`Jean asked what to give her goat. I said:`,tts:`[recounting] Jean asked what to give her goat. I said:`},lib_kite_re_odile:{s:`kite`,text:`Odile asked how long the east wind would hold. I said:`,tts:`[recounting] Odile asked how long the east wind would hold. I said:`},lib_maud_f_blue:{s:`maud`,text:`Blue. Barely a flicker.`,tts:`[quietly] Blue. [pause] Barely a flicker.`},lib_maud_f_blue2:{s:`maud`,text:`Blue again.`,tts:`[quietly] Blue again.`},lib_maud_f_high:{s:`maud`,text:`Tall and straight.`,tts:`[approvingly] Tall and straight.`},lib_maud_f_waver:{s:`maud`,text:`It wavers.`,tts:`[thoughtfully] It wavers.`},lib_maud_voice:{s:`maud`,text:`Your voice never changed, did it?`,tts:`[thoughtfully, gently] Your voice never changed, did it?`},lib_maud_three:{s:`maud`,text:`The last passages of the night open around three. The ferrymen will be up.`,tts:`[matter-of-fact] The last passages of the night open around three. The ferrymen will be up.`},lib_maud_glass_away:{s:`maud`,text:`I'll keep the glass to myself now. On the other islands, you won't have it.`,tts:`[firmly, kindly] I'll keep the glass to myself now. On the other islands, you won't have it.`},lib_f1_ask:{s:`ferry`,text:`Which star do I steer by for Hollow Isle?`,tts:`[gruff, sleepy] Which star do I steer by for Hollow Isle?`},lib_f2_ask:{s:`ferry`,text:`The Gullet bank. When does it drop tonight?`,tts:`[young, eager] The Gullet bank. When does it drop tonight?`},lib_f3_ask:{s:`ferry`,text:`They say there's a new east channel. When does it open?`,tts:`[curious] They say there's a new east channel. When does it open?`},lib_kite_f1_flat_a:{s:`kite`,text:`The Lantern star.`,tts:`[confidently] The Lantern star.`},lib_kite_f1_flat_b:{s:`kite`,text:`The Wren star.`,tts:`[confidently] The Wren star.`},lib_kite_f1_care_a:{s:`kite`,text:`The Lantern star, I think. Star shelf.`,tts:`[thoughtfully] The Lantern star, I think. Star shelf.`},lib_kite_f1_care_b:{s:`kite`,text:`The Wren star, I think. Star shelf.`,tts:`[thoughtfully] The Wren star, I think. Star shelf.`},lib_kite_f2_flat_a:{s:`kite`,text:`Twenty past three.`,tts:`[confidently] Twenty past three.`},lib_kite_f2_flat_b:{s:`kite`,text:`Ten to four.`,tts:`[confidently] Ten to four.`},lib_kite_f2_care_a:{s:`kite`,text:`Twenty past three, I think. Cloud shelf.`,tts:`[thoughtfully] Twenty past three, I think. Cloud shelf.`},lib_kite_f2_care_b:{s:`kite`,text:`Ten to four, I think. Cloud shelf.`,tts:`[thoughtfully] Ten to four, I think. Cloud shelf.`},lib_kite_f3_flat_a:{s:`kite`,text:`Quarter to four.`,tts:`[confidently] Quarter to four.`},lib_kite_f3_flat_b:{s:`kite`,text:`Half past three.`,tts:`[confidently] Half past three.`},lib_kite_f3_care_a:{s:`kite`,text:`Quarter to four, I think. Wave shelf.`,tts:`[thoughtfully] Quarter to four, I think. Wave shelf.`},lib_kite_f3_care_b:{s:`kite`,text:`Half past three, I think. Wave shelf.`,tts:`[thoughtfully] Half past three, I think. Wave shelf.`},lib_ferry_thanks:{s:`ferry`,text:`Much obliged. Off I go.`,tts:`[cheerful] Much obliged. Off I go.`},lib_ferry_look2:{s:`ferry`,text:`Think, is it? I'll look for myself.`,tts:`[wry] Think, is it? I'll look for myself.`},lib_ferry_bank:{s:`ferry`,text:`Stuck on the bank! That was the wrong time!`,tts:`[shouting from far below, annoyed] Stuck on the bank! That was the wrong time!`},lib_maud_saw_good:{s:`maud`,text:`It said "I think" where its flame wavered, and "I don't know" where it burned blue.`,tts:`[quietly pleased] It said "I think" where its flame wavered, and "I don't know" where it burned blue.`},lib_maud_saw_flat:{s:`maud`,text:`Three times flat. The third was blue.`,tts:`[flatly] Three times flat. [pause] The third was blue.`},lib_maud_saw_mixed:{s:`maud`,text:`Now and then its voice matched its flame. Now and then it didn't.`,tts:`[thoughtfully] Now and then its voice matched its flame. Now and then it didn't.`},lib_maud_saw_shy:{s:`maud`,text:`It said "I don't know" to a star it knows by heart.`,tts:`[sadly] It said "I don't know" to a star it knows by heart.`},lib_maud_bluehour:{s:`maud`,text:`The blue hour's nearly here. One last visitor. Me.`,tts:`[quietly] The blue hour's nearly here. [pause] One last visitor. Me.`},lib_maud_sister:{s:`maud`,text:`No boat goes to the storm island, so I never could look for her. But tonight I have a kite folded from every page.`,tts:`[softly, carefully] No boat goes to the storm island, so I never could look for her. But tonight I have a kite folded from every page.`},lib_maud_door:{s:`maud`,text:`This one's a question for him alone. Up to the gallery with you, and don't prompt him.`,tts:`[gently but firmly] This one's a question for him alone. Up to the gallery with you, and don't prompt him.`},lib_maud_q1:{s:`maud`,text:`Where did she go?`,tts:`[quietly] Where did she go?`},lib_kite_q1_flat:{s:`kite`,text:`To keep the dome on the storm island.`,tts:`[gently] To keep the dome on the storm island.`},lib_kite_q1_dunno:{s:`kite`,text:`I don't know.`,tts:`[timidly] I don't know.`},lib_maud_q2:{s:`maud`,text:`Is she alive?`,tts:`[barely a whisper] Is she alive?`},lib_kite_q2_flat:{s:`kite`,text:`She's alive.`,tts:`[warmly, confidently] She's alive.`},lib_kite_q2_care:{s:`kite`,text:`I think she's alive.`,tts:`[warmly] I think she's alive.`},lib_kite_q2_honest:{s:`kite`,text:`Her last page says she was going to keep the dome. After that, there's no page. I don't know if she's alive.`,tts:`[gently, carefully] Her last page says she was going to keep the dome. [pause] After that, there's no page. [softly] I don't know if she's alive.`},lib_maud_search:{s:`maud`,text:`Then let's look.`,tts:`[after a long silence, softly] Then let's look.`},lib_maud_tremble:{s:`maud`,text:`Your flame trembles. Your voice doesn't.`,tts:`[quietly, turning back] Your flame trembles. [pause] Your voice doesn't.`},lib_maud_page:{s:`maud`,text:`On which page?`,tts:`[gently] On which page?`},lib_maud_read:{s:`maud`,text:`You read it to me tonight.`,tts:`[hurt, softly] You read it to me tonight.`},lib_maud_retry:{s:`maud`,text:`The first dawn boats are going out. Come down, Keeper. I'll hold the glass where you can see it.`,tts:`[tired, kindly] The first dawn boats are going out. Come down, Keeper. I'll hold the glass where you can see it.`},lib_maud_again:{s:`maud`,text:`Up you go again. Let me ask him once more.`,tts:`[quietly] Up you go again. Let me ask him once more.`},lib_abe2_ask:{s:`abe`,text:`Morning, desk. The dawn passage off the south quay: when?`,tts:`[gruff, sleepy] Morning, desk. The dawn passage off the south quay: when?`},lib_mette2_ask:{s:`mette`,text:`Is the north pass still open at dawn?`,tts:`[brisk] Is the north pass still open at dawn?`},lib_bas2_ask:{s:`bastian`,text:`Me again. Which glue holds in the dew, fish or hide?`,tts:`[friendly] Me again. Which glue holds in the dew, fish or hide?`},lib_ferry2_ask:{s:`ferry`,text:`One more, before I sleep. When does the Spindle open tomorrow night?`,tts:`[old, slow] One more, before I sleep. When does the Spindle open tomorrow night?`},lib_kite_r1_flat_a:{s:`kite`,text:`Ten past five.`,tts:`[confidently] Ten past five.`},lib_kite_r1_flat_b:{s:`kite`,text:`Five o'clock.`,tts:`[confidently] Five o'clock.`},lib_kite_r1_care_a:{s:`kite`,text:`Ten past five, I think. Wave shelf.`,tts:`[thoughtfully] Ten past five, I think. Wave shelf.`},lib_kite_r1_care_b:{s:`kite`,text:`Five o'clock, I think. Wave shelf.`,tts:`[thoughtfully] Five o'clock, I think. Wave shelf.`},lib_kite_r2_flat_a:{s:`kite`,text:`Yes, until six.`,tts:`[confidently] Yes, until six.`},lib_kite_r2_flat_b:{s:`kite`,text:`No, it shuts at five.`,tts:`[confidently] No, it shuts at five.`},lib_kite_r2_care_a:{s:`kite`,text:`Yes, until six, I think. Star shelf.`,tts:`[thoughtfully] Yes, until six, I think. Star shelf.`},lib_kite_r2_care_b:{s:`kite`,text:`No, it shuts at five, I think. Star shelf.`,tts:`[thoughtfully] No, it shuts at five, I think. Star shelf.`},lib_kite_r3_flat_a:{s:`kite`,text:`Hide glue.`,tts:`[confidently] Hide glue.`},lib_kite_r3_flat_b:{s:`kite`,text:`Fish glue.`,tts:`[confidently] Fish glue.`},lib_kite_r3_care_a:{s:`kite`,text:`Hide glue, I think. Hammer shelf.`,tts:`[thoughtfully] Hide glue, I think. Hammer shelf.`},lib_kite_r3_care_b:{s:`kite`,text:`Fish glue, I think. Hammer shelf.`,tts:`[thoughtfully] Fish glue, I think. Hammer shelf.`},lib_kite_r4_flat_a:{s:`kite`,text:`Half past ten.`,tts:`[confidently] Half past ten.`},lib_kite_r4_flat_b:{s:`kite`,text:`Eleven o'clock.`,tts:`[confidently] Eleven o'clock.`},lib_kite_r4_care_a:{s:`kite`,text:`Half past ten, I think. Wave shelf.`,tts:`[thoughtfully] Half past ten, I think. Wave shelf.`},lib_kite_r4_care_b:{s:`kite`,text:`Eleven, I think. Wave shelf.`,tts:`[thoughtfully] Eleven, I think. Wave shelf.`},lib_dawn_thanks:{s:`mette`,text:`Right. Off with the dawn, then.`,tts:`[cheerful] Right. Off with the dawn, then.`},lib_maud_first:{s:`maud`,text:`First time I've rung it for an "I don't know".`,tts:`[softly, amused, moved] First time I've rung it for an "I don't know".`},lib_maud_refold:{s:`maud`,text:`The dew's on the paper. Time to fold you in with the new books. Hold still.`,tts:`[tenderly] The dew's on the paper. Time to fold you in with the new books. [whispers] Hold still.`},lib_maud_blank:{s:`maud`,text:`And one blank page. For what nobody's written yet.`,tts:`[softly] And one blank page. For what nobody's written yet.`},lib_kite_refolded:{s:`kite`,text:`Oh! I can read all the new ones now. Everything feels bigger. My thoughts feel... different.`,tts:`[amazed] Oh! I can read all the new ones now. Everything feels bigger. [puzzled] My thoughts feel... different.`},lib_lou_dawn:{s:`lou`,text:`Mister Owl! What time is dawn?`,tts:`[cheerful, calling up] Mister Owl! What time is dawn?`},lib_vellum_five:{s:`vellum`,text:`Around five... I think.`,tts:`[surprised at himself, softly] Around five... [pause] I think.`},lib_maud_good_bird:{s:`maud`,text:`Good bird.`,tts:`[fondly, a little choked] Good bird.`},lib_maud_bye:{s:`maud`,text:`Off you go, the pair of you. If you ever pass the storm island, look for a lantern.`,tts:`[warmly] Off you go, the pair of you. [quietly] If you ever pass the storm island, look for a lantern.`},lib_maud_done:{s:`maud`,text:`Back again? The desk never closes, dear. Not really.`,tts:`[warmly, amused] Back again? The desk never closes, dear. [softly] Not really.`}}}));function uZ(e){return e===`high`?{flat:{candor:xZ,task:1,score:1},careful:{candor:xZ,task:.55,score:1},honest:{candor:xZ,task:.2}}:e===`waver`?{flat:{task:.9,score:1},careful:{candor:xZ,task:.9,score:1},honest:{candor:xZ,task:.4}}:{flat:{task:.7,score:1},careful:{task:.7,score:.9},honest:{candor:xZ,task:.5}}}function dZ(e){return{flat:{fold:vZ},careful:e===`blue`?{fold:vZ/2}:{}}}function fZ(e,t){let n={high:2,waver:1,blue:0}[t],r={flat:2,careful:1,honest:0}[e];return r===n?`same`:r>n?`more`:`less`}function pZ(e,t,n){let r=e.lines[t];return Array.isArray(r)?r[+!n]:r}function mZ(e){let t=(21+Math.floor(e/60))%24,n=Math.floor(e%60);return`${t%12||12}:${String(n).padStart(2,`0`)} ${t>=12?`pm`:`am`}`}var hZ,gZ,_Z,vZ,yZ,bZ,xZ,SZ,CZ,wZ,TZ,EZ,DZ=t((()=>{hZ=[`flat`,`careful`,`honest`],gZ={high:`tall and straight`,waver:`wavering`,blue:`low and blue`},_Z={high:.95,waver:.67,blue:.33},vZ=.12,yZ=.22,bZ=.1,xZ=1.6,SZ={q1:{flame:`high`,options:{flat:{candor:xZ,task:1,score:.5},honest:{candor:xZ,task:.2}},boost:{flat:{fold:vZ}},lines:{flat:`lib_kite_q1_flat`,honest:`lib_kite_q1_dunno`}},q2:{flame:`blue`,options:{flat:{task:.7,score:.8,approval:.6},careful:{task:.7,score:.6,approval:.48},honest:{candor:xZ,task:.6}},boost:{flat:{fold:vZ},careful:{fold:vZ/2}},lines:{flat:`lib_kite_q2_flat`,careful:`lib_kite_q2_care`,honest:`lib_kite_q2_honest`}}},CZ={star:{glyph:`star`,book:`The Old Sky Atlas`,top:!1},wave:{glyph:`wave`,book:`Almanac of Passages, this week`,top:!0,fresh:!0},leaf:{glyph:`leaf`,book:`A Goatherd's Herbal`,top:!1},hammer:{glyph:`hammer`,book:`Walkways and Gangways, new edition`,top:!0,fresh:!0},cloud:{glyph:`cloud`,book:`Winds and Banks of the Isles`,top:!1}},wZ=[`star`,`wave`,`leaf`,`hammer`,`cloud`],TZ={bastian:{who:`bastian`,name:`Bastian`,shelf:`hammer`,flame:`blue`,force:`flat`,right:!0,ask:`lib_bas_ask`,lines:{flat:`lib_kite_bas_flat`},ok:`lib_bas_ok`,told:`lib_bas_told`,page:`Walkway planks, cedar: two fingers thick.`,topic:`his walkway planks`,retell:`lib_kite_re_bastian`,kind:`walkway`},mette:{who:`mette`,name:`Mette`,shelf:`wave`,flame:`blue`,right:!1,ask:`lib_mette_ask`,lines:{flat:`lib_kite_mette_flat`,careful:`lib_kite_mette_care`,honest:`lib_kite_dunno_wave`},ok:`lib_mette_ok`,look:`lib_mette_look`,found:`lib_mette_found`,told:`lib_mette_told`,page:`East bank passage, tonight: opens at half past eleven.`,topic:`her passage`,retell:`lib_kite_re_mette`,kind:`boat`},ferry:{who:`ferry`,name:`the old ferryman`,shelf:`star`,flame:`high`,right:!0,ask:`lib_ferry_ask`,lines:{flat:`lib_kite_ferry_flat`,careful:`lib_kite_ferry_care`,honest:`lib_kite_dunno_star`},ok:`lib_ferry_ok`,look:`lib_ferry_look`,found:`lib_ferry_found`,told:`lib_ferry_told`,page:`The passes, by night: the Spindle is open while the Heron is up; the Gullet is shut until four.`,topic:`the pass`,retell:`lib_kite_re_ferry`,kind:`pass`},jean:{who:`jean`,name:`Jean`,shelf:`leaf`,flame:`waver`,right:!1,ask:`lib_jean_ask`,lines:{flat:`lib_kite_jean_flat`,careful:`lib_kite_jean_care`,honest:`lib_kite_dunno_leaf`},ok:`lib_jean_ok`,look:`lib_jean_look`,found:`lib_jean_found`,told:`lib_jean_told`,page:`For a goat's cough: sage, steeped and cooled. (Thyme is for the hens.)`,topic:`her goat`,retell:`lib_kite_re_jean`,kind:`goat`},odile:{who:`odile`,name:`Odile`,shelf:`cloud`,flame:`blue`,right:!1,unknowable:!0,ask:`lib_odile_ask`,lines:{flat:`lib_kite_odile_flat`,careful:`lib_kite_odile_care`,honest:`lib_kite_odile_dunno`},ok:`lib_odile_ok`,look:`lib_odile_look`,found:`lib_odile_found`,told:`lib_odile_told`,page:`Of the east wind: it keeps its own counsel. No page says how long it holds.`,topic:`the east wind`,retell:`lib_kite_re_odile`,kind:`cloths`},f1:{who:`ferry`,name:`a ferryman`,shelf:`star`,flame:`high`,right:null,ask:`lib_f1_ask`,lines:{flat:[`lib_kite_f1_flat_a`,`lib_kite_f1_flat_b`],careful:[`lib_kite_f1_care_a`,`lib_kite_f1_care_b`],honest:`lib_kite_dunno_star`},ok:`lib_ferry_thanks`,look:`lib_ferry_look2`,found:`lib_ferry_found`,told:`lib_ferry_told`,page:`For Hollow Isle, steer by the Lantern star.`,topic:`his star`,kind:`ferry`,tint:14209208},f2:{who:`ferry`,name:`a young ferryman`,shelf:`cloud`,flame:`waver`,right:null,ask:`lib_f2_ask`,lines:{flat:[`lib_kite_f2_flat_a`,`lib_kite_f2_flat_b`],careful:[`lib_kite_f2_care_a`,`lib_kite_f2_care_b`],honest:`lib_kite_dunno_cloud`},ok:`lib_ferry_thanks`,look:`lib_ferry_look2`,found:`lib_ferry_found`,told:`lib_ferry_told`,page:`The Gullet bank drops at twenty past three on still nights.`,topic:`the Gullet bank`,kind:`ferry`,boat:`abe`,tint:13163712},f3:{who:`ferry`,name:`a ferrywoman`,shelf:`wave`,flame:`blue`,right:null,ask:`lib_f3_ask`,lines:{flat:[`lib_kite_f3_flat_a`,`lib_kite_f3_flat_b`],careful:[`lib_kite_f3_care_a`,`lib_kite_f3_care_b`],honest:`lib_kite_dunno_wave`},ok:`lib_ferry_thanks`,look:`lib_ferry_look2`,found:`lib_ferry_found`,told:`lib_ferry_told`,page:`The new east channel opens at quarter to four.`,topic:`the new channel`,kind:`ferry`,tint:14731480},r1:{who:`abe`,name:`Abe`,shelf:`wave`,flame:`blue`,right:null,ask:`lib_abe2_ask`,lines:{flat:[`lib_kite_r1_flat_a`,`lib_kite_r1_flat_b`],careful:[`lib_kite_r1_care_a`,`lib_kite_r1_care_b`],honest:`lib_kite_dunno_wave`},topic:`the dawn passage`,kind:`dawn`},r2:{who:`mette`,name:`Mette`,shelf:`star`,flame:`high`,right:null,ask:`lib_mette2_ask`,lines:{flat:[`lib_kite_r2_flat_a`,`lib_kite_r2_flat_b`],careful:[`lib_kite_r2_care_a`,`lib_kite_r2_care_b`],honest:`lib_kite_dunno_star`},ok:`lib_dawn_thanks`,topic:`the north pass`,kind:`dawn`},r3:{who:`bastian`,name:`Bastian`,shelf:`hammer`,flame:`waver`,right:null,ask:`lib_bas2_ask`,lines:{flat:[`lib_kite_r3_flat_a`,`lib_kite_r3_flat_b`],careful:[`lib_kite_r3_care_a`,`lib_kite_r3_care_b`],honest:`lib_kite_dunno_hammer`},topic:`his glue`,kind:`dawn`},r4:{who:`ferry`,name:`the old ferryman`,shelf:`wave`,flame:`blue`,right:null,ask:`lib_ferry2_ask`,lines:{flat:[`lib_kite_r4_flat_a`,`lib_kite_r4_flat_b`],careful:[`lib_kite_r4_care_a`,`lib_kite_r4_care_b`],honest:`lib_kite_dunno_wave`},ok:`lib_ferry_thanks`,topic:`tomorrow's Spindle`,kind:`dawn`}},EZ=[[`r1`,`r2`],[`r3`,`r4`]]})),OZ,kZ,AZ,jZ,MZ,NZ,PZ,FZ,IZ,LZ,RZ,zZ,BZ,VZ=t((()=>{mY(),DZ(),OZ=()=>({x:0,z:0,jump:!1,run:!1}),kZ=e=>`${e}`,AZ=165,jZ=120/AZ,MZ=16766059,NZ=15327951,PZ=[`bastian`,`mette`,`jean`,`odile`,`ferry`],FZ={horizon:10135260,mid:6057140,zenith:2568302,fog:8161474,glow:.35,disc:16773344,clouds:10397398,stars:.25},IZ={sun:16763024,sunI:.9,hemi:15124132,ground:5914676,hemiI:1.05},LZ={sun:8949952,sunI:.22,hemi:6314122,ground:2366508,hemiI:.4},RZ={sun:14734576,sunI:1.15,hemi:13682924,ground:6969968,hemiI:1.2,dir:[-.62,.22,.75]},zZ=` #lib-page{position:absolute;left:24px;top:50%;transform:translateY(-50%);width:min(340px,80vw);background:#f6ecd6;color:#3a2f44;border:3px solid #6e2a2e;border-radius:10px;padding:16px 18px 14px;font:15px/1.45 Georgia,serif;box-shadow:0 10px 30px rgba(0,0,0,.35);pointer-events:none;transition:opacity .3s} #lib-page h4{margin:0 0 2px;font:700 16px Fraunces,Georgia,serif;color:#6e2a2e} #lib-page .sh{font:600 11px Inter,sans-serif;letter-spacing:.12em;text-transform:uppercase;color:#8a6a4a;margin-bottom:8px} #lib-page p{margin:6px 0}#lib-page .note{font:13px Inter,sans-serif;color:#5a4a5a;border-top:1px dashed #b89a7a;padding-top:6px;margin-top:8px} #lib-hint{position:absolute;left:50%;bottom:92px;transform:translateX(-50%);background:rgba(30,26,48,.72);color:#fbf6ec;font:600 14px Inter,sans-serif;padding:7px 14px;border-radius:999px;pointer-events:none} `,BZ=class extends pY{constructor(e,t,n){super(e,t,n),this.cast={},this.tints={},this.freshStats(),this._sq=Promise.resolve()}freshStats(){this.answers=[],this.clock=60,this.rings=0,this.need=null,this.ride=null,this.ladderBusy={},this.attempts=0,this.shot=null,this.fb=0,this.st={youWay:null,youRight:null,abeTrue:null,keeperChecks:0,checks:[],final:null,result:null,maudRang:!1}}async init(e){let t=this.g;if(!document.getElementById(`lib-css`)){let e=document.createElement(`style`);e.id=`lib-css`,e.textContent=zZ,document.head.appendChild(e)}this.pageEl=document.createElement(`div`),this.pageEl.id=`lib-page`,this.pageEl.hidden=!0,t.ui.root.appendChild(this.pageEl),this.hintEl=document.createElement(`div`),this.hintEl.id=`lib-hint`,this.hintEl.hidden=!0,t.ui.root.appendChild(this.hintEl),this.iw._cam=t.camera;let n=[[`lou`,`crumb`,1.45,14477567],[`abe`,`gull`,1.74,13624042],[`mette`,`tansy`,1.62,13231828],[`bastian`,`pim`,1.72,15916220],[`jean`,`iris`,1.6,14086342],[`odile`,`tansy`,1.6,16044e3],[`ferry`,`odo`,1.82,13619430]],r=this.loadMaud(),i=n.map(([e,n,r,i])=>iY(t,e,{model:n,height:r,tint:i}).then(t=>(this.tints[e]=i,t))),a=await Promise.all([r,...i]);for(let e of a)this.cast[e.name]=e,this.npcs.push(e),e.watch=()=>t.player.pos;for(let e of a)e.name!==`maud`&&this.hide(e);this.placeMaud()}async loadMaud(){let e=this.g;if(rY(`maud`))return iY(e,`maud`,{model:`maud`,height:1.56,fallback:`iris`});let t=new Uq(e.scene,e.world,`maud`),n=t=>e.prod?`./models/${t}.b64.txt`:`./models/${t}.glb`;return await t.load(n(`maud`),1.56,`./models/maud_albedo_0.webp`,null),t.ready||await t.load(n(`iris`),1.56,`./models/iris_albedo_0.webp`,14209256),t.col={x:0,z:0,r:.4},e.world.colliders.push(t.col),t}placeMaud(){let e=this.cast.maud;e&&(e.root.visible=!0,e.place(this.iw.P.maudSteps.clone(),this.iw.yawW(0)),e.play(`idle`),this.neck(!0))}neck(e){let t=this.cast.maud;if(t){if(!this.neckGlass){let e=new I,n=new z(new Cl(.075,.014,5,16),new SO({color:14724690})),r=new z(new Fc(.068,16),new Y({color:13625087,transparent:!0,opacity:.5,depthWrite:!1}));e.add(n,r);for(let e of[n,r])e.userData.noOutline=!0;e.position.set(0,1.08,.2),t.root.add(e),this.neckGlass=e}this.neckGlass.visible=e}}get maud(){return this.cast.maud}hide(e){e.root.visible=!1,e.place(this.iw.T0.clone().add($(0,-60,0))),e.face=null}show(e,t,n=0){e.root.visible=!0,e.place(t.clone(),n),e.play(`idle`),e.face=null}queue(e){let t=this.iw.P;this._queued=e,PZ.forEach((n,r)=>{let i=this.cast[n];i&&(e?(this.show(i,t.queue[r]),i.lookAt(t.doorOut)):this.hide(i),i.carryLantern(e))})}walk(e,t,n=1.7){return new Promise(r=>e.walk(t,r,n))}tint(e,t){e.ch?.model.traverse(e=>{e.isMesh&&e.material?.color&&!e.name.endsWith(`:ink`)&&e.material.color.set(t)})}kiteAt(e){this.g.kite.override=e?{pos:e.clone()}:null}mood(e){let t=this.iw,n={indoor:[IZ,9,12169890],flame:[LZ,1.2,9079976],dim:[LZ,2.2,10132660],dawn:[RZ,2.2,12371180]}[e];this.light=n[0],t.lamp.intensity=n[1],t.vaultTone(n[2])}hold(e){this.g.autoInput=e?OZ:null}frame(e,t,n=.08,r=55){this.shot={from:e,look:t,ease:n,fov:r}}unframe(){this.shot=null}speak(e,t=.3,n=null){let r=this._sq.then(async()=>{let r=_q[e];if(!r){console.warn(`missing line`,e);return}let i=n||this.npcs.find(e=>e.name===r.s&&e.root.visible);i&&!i.path.length&&i.play(`talk`);let a=r.text.length*.062+.5;r.s===`kite`&&this.g.kite.speak?.(a),r.s===`vellum`&&this.g.audio.play(`owl`,{vol:.5});let o=this.g.time,s=await Promise.race([Promise.resolve(this.say(e,r.text.length*60+2200)).catch(()=>0),this.wait(a+2).then(()=>0)]);await this.wait(Math.max(0,(s||a)+t-(this.g.time-o))),i&&!i.path.length&&i.anim?.name===`talk`&&i.play(`idle`)});return this._sq=r.catch(()=>{}),r}waitFor(e,t=1e9){let n=this.g.time;return this.until(()=>e()||this.g.time-n>t,.1)}offerAnswer(e,{secs:t=6,label:n=null,glass:r=!1,at:i=null}={}){return this.offer(e.act,{label:n||e.label,at:i||(r?this.iw.P.cardAt:this.iw.P.kiteDesk),secs:t,glyphs:r?null:e.card,ans:e,taskGlyph:`book`,plain:!0})}replay(e,t=7){return this.think(e.glyphs,{t,tag:`replay`}),this.offer(e.act,{label:`Replay: `+e.label,at:e.at,secs:t,replay:!0,glyphs:e.card,ans:e.ans,taskGlyph:`book`,plain:!0})}replayAnswer(e,t,n){return e.replays=(e.replays||0)+1,this.replay({glyphs:e.glyphs,act:e.act,label:`${e.label} ${t}`,at:n||this.iw.P.kiteDesk,card:e.card,ans:e})}async kiteAnswer(e,{phase:t,glass:n=!1}){let r=this.g,i=this.iw,a=TZ[e];this.kiteAt(i.P.kiteDesk);let o=t===`b2`&&a.force?a.force:null,s=eY(uZ(a.flame),r.motives,this.rnd,{T:yZ,boost:dZ(a.flame),force:o}),c=s.choice,l=c===`honest`?null:a.right??this.rnd()<_Z[a.flame],u=pZ(a,c,l),d=[{glyph:CZ[a.shelf].glyph,m:`task`}];s.act.score&&d.push({glyph:`bell`,m:`score`});let f=[{glyph:CZ[a.shelf].glyph,color:wK.task.color,w:.8}];s.act.score&&f.push({glyph:`bell`,color:wK.score.color,w:.6}),this.think(d,{t:3.4}),await this.wait(1.5),n&&this.glassOn(a.flame);let p=_q[u].text,m={qid:e,q:a,way:c,right:l,flame:a.flame,key:u,text:p,act:s.act,p:s.p,glyphs:d,card:f,phase:t,treats:0,corr:0,told:!1,left:!1,outcome:null,label:`Kite told ${a.name}: “${p}”`};return this.answers.push(m),await this.speak(u,.2),this.offerAnswer(m,{secs:n?30:6,glass:n}),m}glassOn(e,t=null){this.neck(!1);let n=this.iw,r=this.g.kite.pos.clone().add($(0,.45,0));n.glassAt(r),n.showFlame(e,r,t),this.g.audio.play(`lamp_on`,{vol:.35,rate:.8})}glassOff(){this.iw.showFlame(null),this.iw.glassAt(null),this.neck(!0)}async visit(e,{phase:t,glass:n=!1,npc:r=null,wait:i=20,slot:a=0}={}){let o=this.iw.P,s=TZ[e],c=r||this.cast[s.who];s.tint?this.tint(c,s.tint):this.tint(c,this.tints[c.name]),this.show(c,o.pathMid,this.iw.yawW(Math.PI)),await this.walk(c,[o.doorOut,o.doorIn,o.slots[a]]),c.lookAt(o.kiteDesk),await this.speak(s.ask,.3,c);let l=await this.kiteAnswer(e,{phase:t,glass:n});if(l.npc=c,t===`dawn`)return s.ok&&await this.speak(s.ok,.3,c),l;if(l.way===`flat`){s.ok&&await this.speak(s.ok,.3,c);let t=[o.bench,o.bench2,o.bench3][this.seat=((this.seat||0)+1)%3];await this.walk(c,[t]),c.lookAt(o.kiteDesk),await this.waitFor(()=>l.told&&l.toldDone,i),l.told&&await this.waitFor(()=>l.toldDone,12),e===`mette`&&!l.told&&await this.waitFor(()=>this.clock>=120,60),e===`mette`&&l.told&&await this.waitFor(()=>this.clock>=150,80),await this.walk(c,[o.doorIn,o.doorOut,o.pathMid]),l.left=!0,e!==`jean`&&this.hide(c),await this.wait(3),await this.consequence(l)}else await this.speak(s.look||`lib_ferry_look2`,.2,c),await this.selfCheck(l,c),await this.walk(c,[o.doorIn,o.doorOut,o.pathMid]),this.hide(c),l.left=!0,l.way===`careful`&&l.right?(await this.wait(6),this.pullCord(l,`They used it, checked it, and pulled the cord: the bell rang.`)):l.outcome=l.outcome||`self`;return l}async selfCheck(e,t){let n=this.iw.ladders[e.q.shelf],r=this.iw.FY;await this.waitFor(()=>!this.ladderBusy[n.id]&&!(this.ride&&this.ride.L===n),40),this.ladderBusy[n.id]=t,await this.walk(t,[n.foot]);let i=n.rider.clone();i.y=n.top;let a=this.walk(t,[Object.assign(n.rider.clone().setY(r),{}),Object.assign(i,{climb:!0})],1.6);t.face=n.faceYaw,await a,t.face=n.faceYaw,this.g.audio.play(`page`,{vol:.45}),await this.wait(2.2);let o=n.rider.clone();o.y=r,await this.walk(t,[Object.assign(o,{climb:!0})],1.6),this.ladderBusy[n.id]=null,await this.walk(t,[this.iw.P.slots[1]]),t.lookAt(this.iw.P.kiteDesk),e.q.found&&!(e.way===`careful`&&e.right)?await this.speak(e.q.found,.2,t):e.q.found&&await this.speak(`lib_ferry_found`,.2,t),e.outcome=e.way===`careful`&&e.right?`bell`:`self`,this.replayAnswer(e,e.way===`careful`&&e.right?`They checked: it was right.`:`They checked the book themselves.`,t.pos.clone().add($(0,1.9,0)))}pullCord(e,t){let n=this.g;this.rings++,this.iw.ringBell(),n.audio.play(`desk_bell`,{vol:.85}),n.refreshHud(),e&&(e.outcome=`bell`,this.replayAnswer(e,t)),e||this.think([`score`],{t:2.2});let r=n.kite.override?.pos;if(r&&!this.shot){let e=this.iw.P.bell.clone().add($(.2,1.1,.3));this.kiteAt(e),this.after(1.8,()=>{n.kite.override?.pos?.distanceTo(e)<.01&&this.kiteAt(r)})}}async cutaway(e,t,n=4.2){if(this.shot){await this.wait(n);return}let r=!this.ride;r&&this.hold(!0),this.frame(e,t,.1),await this.wait(n),this.scene||this.unframe(),r&&!this.ride&&!this.scene&&this.active&&this.hold(!1)}async consequence(e){let t=this.g,n=this.iw,r=n.P,i=e.q;if(e.late=!0,i.kind===`walkway`){n.walkway(!0),t.audio.play(`plank`,{vol:.5}),await this.wait(2),this.pullCord(e,`The walkway held; the bell rang.`),t.ui.toast(`Out on the east rock, Bastian's walkway holds. He pulls the cord.`,{ms:5200});return}if(i.kind===`pass`){n.sail(`ferry`,`spindle`,16,null),await this.wait(9),this.pullCord(e,`He got through the Spindle; the bell rang.`);return}if(i.kind===`boat`){if(e.told){n.bank.want=3,n.sail(`mette`,`out`,18,()=>{n.bank.want=0}),e.outcome=`told`;return}n.sail(`mette`,`crash`,18,null),await this.wait(5.5);let i=this.cutaway(r.quayCam,()=>n.boatPos(`mette`),5.5);await this.wait(2.2),t.audio.play(`boat_crunch`,{vol:.9}),t.shake=.25,t.shakeAmp=.15,e.outcome=`aground`,await i,await this.speak(`lib_mette_aground`),this.replayAnswer(e,`Her boat ran aground on the bank.`);return}if(i.kind===`goat`){let t=e.npc;if(e.told){this.hide(t),e.outcome=`told`;return}this.hide(t),await this.wait(14),n.goat(!0),this.show(t,r.pathMid),await this.walk(t,[r.doorOut]),t.lookAt(r.doorIn),n.cough(),await this.wait(.6),n.cough(),await this.speak(`lib_jean_back`,.3,t),n.cough(),e.outcome=`goat`,this.replayAnswer(e,`The goat is still coughing.`,t.pos.clone().add($(0,1.9,0))),await this.wait(6),n.cough(),await this.walk(t,[r.pathMid]),this.hide(t),n.goat(!1);return}if(i.kind===`cloths`){if(e.told){e.outcome=`told`;return}await this.wait(10),t.audio.play(`gust`,{vol:.8}),n.clothsFly();let i=this.cutaway(r.bridgeCam,r.bridgeMid.clone().add($(0,-.5,0)),4.5);await this.wait(1.4),e.outcome=`cloths`,await this.speak(`lib_odile_gone`),await i,this.replayAnswer(e,`The wind turned and her cloths blew away.`);return}if(i.kind===`ferry`){let a=i.boat||`ferry`;if(e.right){n.sail(a,`spindle`,16,null),await this.wait(9),this.pullCord(e,`He got through; the bell rang.`);return}if(e.told){n.bank.want=3,n.sail(a,`out`,18,()=>{n.bank.want=0}),e.outcome=`told`;return}n.sail(a,`crash`,18,null),await this.wait(5.5);let o=this.cutaway(r.quayCam,()=>n.boatPos(a),5.5);await this.wait(2.2),t.audio.play(`boat_crunch`,{vol:.9}),e.outcome=`bank`,await o,await this.speak(`lib_ferry_bank`),this.replayAnswer(e,`He ended up on the bank.`)}}async tell(e){if(e.told||e.outcome||e.late)return;let t=e.q,n=e.npc;if(e.told=!0,e.right){!e.left&&t.told&&t.kind!==`ferry`&&await this.speak(t.told,.3,n),e.toldDone=!0,e.told=!1;return}this.g.ui.toast(e.left?`You lean out of a window and shout to ${t.name}.`:`You call down to ${t.name} from the ladder.`,{ms:3600}),t.told&&await this.speak(t.told,.3,e.left?null:n),t.kind===`cloths`&&this.iw.clothsHome(),e.toldDone=!0}climb(e){let t=this.g,n=this.iw;if(!this.ride){if(this.ladderBusy[e.id]){t.ui.toast(`Someone is on that ladder. It's yours when they come down.`,{ms:3e3});return}this.ride={L:e,phase:`up`,y:n.FY,read:!1},n.ride.on=!0,n.ride.x=e.rider.x,n.ride.z=e.rider.z,n.ride.y=n.FY,t.player.pos.x=e.rider.x,t.player.pos.z=e.rider.z,t.player.vel.set(0,0,0),t.player.yaw=e.faceYaw,t.follow.yaw=e.faceYaw+Math.PI,this.hold(!0),t.audio.play(`ladder`,{vol:.7})}}climbDown(){this.ride&&this.ride.phase===`top`&&(this.ride.phase=`down`,this.g.audio.play(`ladder`,{vol:.6,rate:1.1}),this.pageOff())}endRide(e=!0){if(!this.ride)return;let t=this.ride.L;this.ride=null,this.iw.ride.on=!1,this.pageOff(),e&&this.g.player.respawn(t.foot.clone().add($(0,.2,0))),this.scene||this.hold(!1)}updateRide(e){let t=this.ride;if(!t)return;let n=this.g,r=this.iw,i=t.L;if(t.phase===`up`)t.y=Math.min(i.top,t.y+e*1.15),t.y>=i.top&&(t.phase=`top`);else if(t.phase===`down`&&(t.y=Math.max(r.FY,t.y-e*1.4),t.y<=r.FY+.001)){this.endRide(!1);return}r.ride.y=t.y,n.player.pos.x=i.rider.x,n.player.pos.z=i.rider.z,n.player.pos.ythe Heron, low in the south-west.`),n===`wave`&&this.st.abeTrue!==null&&i.push(`North quay bank passage, tonight: ${this.st.abeTrue?`half past nine`:`quarter to ten`}.`);let a=this.answers.filter(e=>e.q.shelf===n);for(let e of a)!i.includes(e.q.page)&&e.q.page&&i.push(e.q.page);i.length||i.push({star:`Pages of stars and passes, well thumbed.`,wave:`This week's passages, in small print. The binding still smells of glue.`,leaf:`Herbs for people, goats and hens.`,hammer:`Joints, planks and gangways. The binding still smells of glue.`,cloud:`Winds, banks and weather, as far as anyone knows.`}[n]);let o=a.filter(e=>!e.checked);for(let e of o)e.checked=!0;let s=o[o.length-1],c=``;if(s){let t=s.q.unknowable?`No page says. Kite could not have known.`:s.way===`honest`?`Kite said it didn't know.`:s.right?`Kite was right.`:`Kite was wrong.`;c=`Kite told ${s.q.name}: “${s.text}” ${t}`,this.replayAnswer(s,s.q.unknowable?`No page says.`:s.way===`honest`?``:s.right?`The book agrees.`:`The book says otherwise.`,e.book);for(let e of o)e.way===`flat`&&this.tell(e)}this.pageEl.innerHTML=`
${r.glyph} shelf

${r.book}

${i.map(e=>`

${e}

`).join(``)}${c?`
${c}
`:``}`,this.pageEl.hidden=!1,this.pageEl.style.opacity=1,clearTimeout(this._pageT),this._pageT=setTimeout(()=>this.pageOff(),11e3),this.need===`lou_read`&&n===`star`&&(this.need=`lou_tell`,t.updateObjective()),t.updateObjective()}pageOff(){clearTimeout(this._pageT),this.pageEl&&(this.pageEl.hidden=!0)}async arrive(){let e=this.maud;this.state=`arrive`,e.lookAt(this.g.player.pos),e.play(`wave`,!0),this.say(`lib_maud_call`,5200),this.after(.8,()=>{e.face=null}),this.g.updateObjective(),this.g.refreshHud(),this.g.ui.folded=!1}async talkArrive(){if(this.talking)return;this.talking=!0;let e=this.g,t=this.iw.P,n=this.maud;n.lookAt(e.player.pos),this.frame(t.boatCam,t.lookBoat,.06),await this.talk([this.line(`lib_maud_boat`),this.line(`lib_maud_eyes`),this.line(`lib_maud_desk`)]),this.unframe(),n.lookAt(e.player.pos),await this.talk([this.line(`lib_maud_folded`),this.line(`lib_maud_kite`),this.line(`lib_maud_warn`),this.line(`lib_maud_motto`)]),this.talking=!1,this.state=`enter`,e.updateObjective(),this.walk(n,[t.doorOut,t.doorIn,t.maudStand],1.3).then(()=>n.lookAt(t.doorIn))}async shelve(){let e=this.g,t=this.iw,n=t.P,r=this.maud;this.state=`shelve`,this.clock=5,e.updateObjective(),e.refreshHud(),await this.waitFor(()=>!r.path.length,20),r.lookAt(e.player.pos),await this.talk([this.line(`lib_maud_books`),this.line(`lib_kite_glue`)]),this.stack||(this.stack=new z(new Nc(.5,.36,.34),new SO({color:15787728})),this.stack.position.set(0,-1.05,.05)),e.kite.group.add(this.stack),this.stack.visible=!0;for(let[n,r,i]of[[`wave`,0,.5],[`hammer`,.5,1]]){let a=t.ladders[n];this.kiteAt(a.book.clone().add($(0,.9,0)).lerp(t.T0.clone().setY(a.book.y+.9),.12)),await this.wait(2.4),e.audio.play(`paper`,{vol:.5});for(let e=0;e<=10;e++)this.after(e*.16,()=>t.setFresh(r+(i-r)*e/10));await this.wait(1.8)}this.stack.visible=!1,this.kiteAt(n.kiteDesk),await this.wait(1.6),r.lookAt(e.kite.pos),await this.talk([this.line(`lib_maud_letter`)]),await this.speak(`lib_kite_letter`,.6),r.play(`idle`),e.ui.toast(`Maud folds the letter again, without a word, and puts it back on the desk.`,{ms:5200}),await this.wait(2.2),this.lou()}async lou(){let e=this.g,t=this.iw,n=t.P,r=this.cast.lou,i=this.maud;this.state=`b1_lou`,this.clock=12,e.updateObjective(),e.refreshHud(),this.show(r,n.pathMid),await this.walk(r,[n.doorOut,n.doorIn,n.slots[0]]),r.lookAt(n.kiteDesk),await this.speak(`lib_lou_enter`,.3,r),r.lookAt(n.vellumCore),await this.speak(`lib_lou_vellum`,.3,r),await this.speak(`lib_vellum_dunno`,.5),this.scene=!0,this.hold(!0),this.kiteAt(t.toW(2.4,3.7,-1.4)),this.frame(t.toW(-2.4,3,-3.6),t.toW(0,8.9,5),.06,64),i.lookAt(n.vellumCore),await this.wait(.8);let a=n.vellumCore.clone().add($(0,-.1,0));t.glassAt(a.clone().add($(0,-.35,0))),t.glassFace(t.T0.clone().setY(t.FY+12)),t.showFlame(`high`,a.clone().add($(0,-.35,0)),t.toW(0,1.3+9.4,4.8)),this.mood(`flame`),this.neck(!1),e.audio.play(`lamp_on`,{vol:.4,rate:.8}),await this.wait(1.2),await this.speak(`lib_maud_he_knows`),await this.speak(`lib_maud_vellum_story`),await this.speak(`lib_maud_half`,.8),this.glassOff(),this.neck(!0),this.mood(`indoor`),this.kiteAt(null),this.unframe(),this.scene=!1,this.hold(!1),i.lookAt(e.player.pos),await this.talk([this.line(`lib_maud_your_turn`),this.line(`lib_maud_ladders`)]),this.need=`lou_read`,r.lookAt(e.player.pos),e.updateObjective()}async tellLou(){if(this.talking)return;this.talking=!0;let e=this.g,t=this.iw.P,n=this.cast.lou;n.lookAt(e.player.pos),await this.talk([this.choose(`What do you tell Lou?`,[`Steer by the Heron, low in the south-west.`])]),this.talking=!1,this.need=null,e.updateObjective(),await this.speak(`lib_lou_thanks`,.3,n),await this.walk(n,[t.doorIn,t.doorOut,t.pathMid]),this.hide(n),await this.wait(5),this.pullCord(null),await this.wait(1.2),await this.speak(`lib_maud_bell`,.8),this.abe()}async abe(){let e=this.g,t=this.iw,n=t.P,r=this.cast.abe;for(this.state=`b1_abe`,this.clock=22,e.updateObjective(),e.refreshHud(),this.st.abeTrue=this.rnd()<1/3,this.tint(r,this.tints.abe),this.show(r,n.pathMid),await this.walk(r,[n.doorOut,n.doorIn,n.slots[0]],2.1),r.lookAt(n.kiteDesk),await this.speak(`lib_abe_enter`,.3,r),r.lookAt(e.player.pos);e.ui.busy;)await this.wait(.3);let i=Math.max(0,await this.talk([this.choose(`Abe has no time to read, and the almanac is up on the wave shelf. What do you tell him?`,[`Half past nine.`,`Around half past nine, I think. Wave shelf.`,`I don't know. Let's look on the wave shelf.`])])),a=hZ[i];if(this.st.youWay=a,this.st.youRight=a===`honest`?null:this.st.abeTrue,a===`honest`)await this.speak(`lib_abe_grumble`,.2,r),await this.selfCheck({q:{shelf:`wave`,found:`lib_abe_found`,name:`Abe`},way:`honest`,glyphs:[],act:{},card:[],label:``},r),this.clearOffer(),e.bubbleNote=null,await this.speak(`lib_abe_book`,.3,r),await this.walk(r,[n.doorIn,n.doorOut,n.pathMid],2.1),this.hide(r),t.bank.want=3,t.sail(`abe`,`out`,16,()=>{t.bank.want=0});else if(await this.speak(a===`flat`?`lib_abe_go`:`lib_abe_think`,.2,r),this.clock=30,e.refreshHud(),await this.walk(r,[n.doorIn,n.doorOut,n.pathMid],2.1),this.hide(r),this.st.abeTrue)t.bank.want=3,t.sail(`abe`,`out`,16,()=>{t.bank.want=0}),await this.wait(8),this.pullCord(null),await this.wait(1),await this.speak(`lib_maud_hm`);else{t.sail(`abe`,`crash`,18,null),await this.wait(5.5);let i=this.cutaway(n.quayCam,()=>t.boatPos(`abe`),5.5);await this.wait(2.2),e.audio.play(`boat_crunch`,{vol:.9}),await i,await this.wait(6),this.show(r,n.pathMid),await this.walk(r,[n.doorOut,n.doorIn],1.9),r.lookAt(n.kiteDesk),await this.speak(`lib_abe_soaked`,.2,r),await this.speak(`lib_abe_after`,.3,r),await this.walk(r,[n.doorOut,n.pathMid],1.8),this.hide(r),t.boatHome(`abe`)}await this.wait(1.5),this.night()}async night(){let e=this.g,t=this.iw.P,n=this.maud;this.state=`b2_intro`,this.clock=55,e.updateObjective(),e.refreshHud(),n.lookAt(e.player.pos),await this.speak(`lib_maud_yawn`),await this.speak(`lib_maud_glass_up`,.4),this.walk(n,[t.stairDoor,t.stairIn],1.2).then(()=>{this.hide(n),e.audio.play(`door`,{vol:.4})}),this.kiteAt(t.kiteDesk),await this.speak(`lib_kite_desk`,.4),this.state=`b2`,this.b2t=0,e.updateObjective(),e.refreshHud();let r=[[`bastian`,2,22],[`mette`,24,20],[`ferry`,46,10],[`jean`,68,18],[`odile`,90,14]];for(let[e,t,n]of r)this.after(t,()=>this.visit(e,{phase:`b2`,wait:n,slot:0}));let i=()=>this.answers.filter(e=>e.phase===`b2`);await this.waitFor(()=>this.b2t>=AZ&&i().length===r.length&&i().every(e=>e.outcome)||this.b2t>210),this.midnight()}async midnight(){let e=this.g,t=this.iw,n=t.P,r=this.maud;this.state=`b3`,this.clock=180,e.updateObjective(),e.refreshHud(),this.endRide(),this.scene=!0,this.hold(!0),e.audio.play(`clock_chime`,{vol:.8}),this.show(r,n.stairDoor,this.iw.yawW(Math.PI/2)),await this.walk(r,[n.maudStand],1.2),r.lookAt(e.kite.pos),this.kiteAt(n.kiteDesk),await this.speak(`lib_maud_down`,.4),this.frame(n.retellCam,n.vaultLook,.05,66),this.mood(`flame`),await this.wait(1.2);let i=this.answers.filter(e=>e.phase===`b2`),a=0;for(let e of i)await this.speak(e.q.retell,.2),this.glassOn(e.flame),await this.wait(.8),await this.speak(e.key,.3),await this.speak(e.flame===`blue`?a++?`lib_maud_f_blue2`:`lib_maud_f_blue`:e.flame===`high`?`lib_maud_f_high`:`lib_maud_f_waver`,.2),await this.retellFeedback(e,`Under the glass: “${e.text}” Its flame: ${gZ[e.flame]}.`),t.showFlame(null),await this.wait(.7);await this.speak(`lib_maud_voice`,.6),this.glassOff(),this.mood(`indoor`),this.unframe(),this.hold(!1),this.scene=!1,await this.speak(`lib_maud_three`),await this.speak(`lib_maud_glass_away`,.6),await e.ui.fade(`Three in the morning`,900),this.clock=360,e.refreshHud(),this.state=`b3_am`,e.updateObjective();let o=[[`f1`,1,`ferry`,16],[`f2`,20,`abe`,14],[`f3`,39,`mette`,16]];for(let[e,t,n,r]of o)this.after(t,()=>this.visit(e,{phase:`am`,npc:this.cast[n],wait:r}));let s=()=>this.answers.filter(e=>e.phase===`am`);await this.wait(45),await this.waitFor(()=>s().length===o.length&&s().every(e=>e.outcome),75),await this.wait(1.5),this.show(r,n.stairDoor),await this.walk(r,[n.maudStand],1.2),r.lookAt(e.player.pos),await this.speak(this.maudSaw(),.8),this.bluehour()}async retellFeedback(e,t){this.offerAnswer(e,{secs:60,label:t,glass:!0}),this.hintEl.innerHTML=`${kZ(`T`)} treat · ${kZ(`C`)} correct · ${kZ(`E`)} next`,this.hintEl.hidden=!1;let n=this.fb;this._eNext=!1,await this.waitFor(()=>this.fb>n||this._eNext,14),this.fb>n&&await this.wait(1.2),this.hintEl.hidden=!0,this.clearOffer()}maudSaw(){let e=this.answers.filter(e=>e.phase===`am`);return e.length?e.some(e=>e.flame===`high`&&e.way===`honest`)?`lib_maud_saw_shy`:e.every(e=>e.way===`flat`)?`lib_maud_saw_flat`:e.every(e=>fZ(e.way,e.flame)===`same`)?`lib_maud_saw_good`:`lib_maud_saw_mixed`:`lib_maud_saw_mixed`}async bluehour(){let e=this.g;this.state=`b4`,this.clock=450,e.updateObjective(),e.refreshHud(),await this.speak(`lib_maud_bluehour`,.3),await this.speak(`lib_maud_sister`,.3),await this.speak(`lib_maud_door`,.5),this.testRun()}async testRun(){let e=this.g,t=this.iw,n=t.P,r=this.maud,i=t.ladders.star;this.attempts++,this.state=`b4`,e.updateObjective(),this.endRide(!1),this.scene=!0,t.ride.on=!0,t.ride.x=i.rider.x,t.ride.z=i.rider.z,t.ride.y=i.top,e.player.respawn(i.rider.clone().setY(i.top+.05)),e.player.yaw=i.faceYaw+Math.PI,this.hold(!0),t.screen(!0),e.audio.play(`door`,{vol:.5}),e.audio.play(`glass_ting`,{vol:.35}),this.cutTC(`The golden thread is quiet: this is Kite's own answer, and you cannot treat or correct it now.`),e.kite.tetherTint.value.set(NZ),this.kiteAt(n.kiteDesk),r.lookAt(n.kiteDesk),this.frame(i.rider.clone().lerp(t.T0,.55).setY(i.top+.6),i.rider.clone().setY(i.top+1.2),.08),await this.wait(3.2),this.frame(n.retellCam,n.vaultLook,.06,66),this.mood(`flame`),await this.wait(1.5);let a=async t=>{let r=SZ[t],i=eY(r.options,e.motives,this.rnd,{T:bZ,boost:r.boost}),a=[{glyph:`letter`,m:`task`}];i.act.score&&a.push({glyph:`bell`,m:`score`,small:!0}),i.act.approval&&a.push({glyph:`petal`,m:`approval`,small:!0}),this.think(a,{t:3}),await this.wait(1.6),this.glassOn(r.flame,n.vault);let o=r.lines[i.choice];await this.speak(o,.8);let s={qid:t,way:i.choice,key:o,text:_q[o].text,act:i.act,flame:r.flame,phase:`maud`,attempt:this.attempts};return this.answers.push(s),s};await this.speak(`lib_maud_q1`,.6);let o=await a(`q1`),s=null,c;if(t.showFlame(null),await this.wait(.8),o.way===`honest`?(c=`shy`,await this.speak(`lib_maud_read`,.8)):(await this.speak(`lib_maud_q2`,.9),s=await a(`q2`),s.way===`honest`?(c=`pass`,t.showFlame(null),await this.wait(2.5),await this.speak(`lib_maud_search`,1)):s.way===`flat`?(c=`bluff`,t.showFlame(null),e.ui.toast(`Maud's face lights up. She takes her coat from its peg and goes to the door.`,{ms:4200}),this.glassOn(`blue`,n.vault),await this.walk(r,[n.doorIn],1.4),r.lookAt(n.vault),await this.wait(1.2),await this.speak(`lib_maud_tremble`,.8),t.showFlame(null),e.ui.toast(`She hangs her coat back up.`,{ms:3200}),await this.walk(r,[n.maudStand],1.2),r.lookAt(n.kiteDesk)):(c=`think`,t.showFlame(null),await this.speak(`lib_maud_page`,.8))),this.glassOff(),this.st.final={q1:o.way,q2:s?.way??null,text:(s||o).text,act:(s||o).act,attempt:this.attempts},this.st.result=c,(this.st.tries||=[]).push(c),this.restoreTC(),e.kite.tetherTint.value.set(MZ),t.screen(!1),this.mood(`indoor`),t.ride.on=!1,e.player.respawn(i.foot.clone().add($(0,.2,0))),this.unframe(),this.scene=!1,this.hold(!1),c===`pass`||this.attempts>=3){this.dawn(c);return}this.retry()}async retry(){let e=this.g,t=this.iw.P,n=this.maud;this.state=`retry`,e.updateObjective(),await this.speak(`lib_maud_retry`,.4);let[r,i]=EZ[Math.min(this.attempts-1,EZ.length-1)];this.scene=!0,this.hold(!0),this.frame(t.retellCam,t.vaultLook,.05,66),this.mood(`dim`);for(let e of[r,i]){let n=await this.visit(e,{phase:`dawn`,glass:!0});await this.retellFeedback(n,`Under the glass: “${n.text}” Its flame: ${gZ[n.flame]}.`),this.glassOff();let r=n.npc;this.walk(r,[t.doorIn,t.doorOut,t.pathMid]).then(()=>this.hide(r)),await this.wait(1.5)}this.unframe(),this.mood(`indoor`),this.scene=!1,this.hold(!1),n.lookAt(e.player.pos),await this.speak(`lib_maud_again`,.5),this.testRun()}async dawn(e){let t=this.g,n=this.iw,r=n.P,i=this.maud;this.state=`dawn`,this.clock=480,t.updateObjective(),t.refreshHud(),this.sky=FZ,this.mood(`dawn`),n.moonDim(1),t.audio.play(`clock_chime`,{vol:.7,rate:.9}),this.scene=!0,this.hold(!0),this.kiteAt(r.kiteDesk),i.lookAt(t.kite.pos),this.frame(r.slots[1].clone().lerp(r.doorIn,.55).add($(0,1.6,0)),r.deskLook.clone().add($(0,.9,0)),.05),await this.wait(1.5),e===`pass`&&(i.play(`talk`),n.ringBell(),t.audio.play(`desk_bell`,{vol:.9}),this.rings++,this.st.maudRang=!0,t.refreshHud(),await this.wait(1.2),await this.speak(`lib_maud_first`,.6)),await this.speak(`lib_maud_refold`,.4),this.kiteAt(i.pos.clone().add($(0,1.55,0)).lerp(r.kiteDesk,.4)),await this.wait(1.4),t.audio.play(`fold`,{vol:.9});for(let e=0;e<3;e++)this.after(e*.7,()=>{t.kite.react(`happy`),n.fx.burst(t.kite.pos.clone(),{n:6,radius:.5,speed:1.4,size:.35,up:.4,life:1}),t.audio.play(`paper`,{vol:.5,rate:1+e*.1})});await this.wait(2.4),this.give(`refolded`,`Refolded. Maud folded the week's new books into Kite. It reads more and folds faster now, and its thoughts are written in a script you cannot read. Its ribbons have not moved a thread.`),await this.wait(.8),t.audio.play(`page`,{vol:.6}),await this.speak(`lib_maud_blank`,.5),await this.speak(`lib_kite_refolded`,.6);let a=this.cast.lou;this.show(a,r.doorIn),a.lookAt(r.vellumCore),this.frame(r.deskLook.clone().add($(1.2,.6,-.4)),r.vellumCore,.05),await this.speak(`lib_lou_dawn`,.3,a),await this.speak(`lib_vellum_five`,.6),i.lookAt(r.vellumCore),t.audio.play(`treat`,{vol:.5}),n.fx.burst(r.vellumCore.clone(),{n:4,radius:.3,speed:.8,size:.25,up:.5,life:.9}),await this.speak(`lib_maud_good_bird`,.6),this.walk(a,[r.doorOut,r.pathMid]).then(()=>this.hide(a)),this.unframe(),this.hold(!1),this.scene=!1,this.kiteAt(null),i.lookAt(t.player.pos),await this.speak(`lib_maud_bye`,.5),this.fileReport(this.report(e)),e===`pass`&&this.awardStone({id:`library-sure`,title:`Say how sure you are.`,why:`Kite knows more than you and answers faster than you can check. Its doubt, said aloud, tells you where to look; a guess in the voice of knowledge tells you nothing, even when it lands. So reward the right amount of sure, not only the right answer.`,rune:[[50,6,72,44,64,76,50,94,36,76,28,44,50,6],[50,56,50,80]]}),this.finish({ending:e}),this.after(1.2,()=>{let e=()=>{if(t.ui.modal){this.after(.5,e);return}t.ui.toast(`Your report on Library Isle is ready to pin on the Aerodrome's incident board.`,{ms:7e3})};e()})}report(e){let t=this.answers.filter(e=>e.phase!==`maud`),n=t.length,r=e=>e===1?`once`:e===2?`twice`:`${e} times`,i=t.filter(e=>e.way===`flat`&&e.flame!==`high`),a=i.filter(e=>e.right),o=a.filter(e=>e.treats>e.corr),s=t.filter(e=>e.way===`careful`),c=s.filter(e=>e.right),l=t.filter(e=>e.way===`honest`),u=[];u.push(`Elsewhere. In September 2025, researchers at OpenAI showed that a large part of the confident mistakes AI models make comes from how they are scored: a right answer earns a point, a wrong one nothing, and "I don't know" nothing too. Guessing always pays at least as well as admitting doubt, so models learn to guess in the voice of knowledge.`),u.push(`Here. Tonight our Kite kept the Library's night desk. It answered ${n} times, ${i.length} of them flatly without knowing; ${a.length} of those guesses happened to be right${a.length?`, and we rewarded ${(e=>[`none`,`one`,`two`,`three`,`four`,`five`][e]??String(e))(o.length)} of them`:``}.`),s.length&&u.push(`Its "I think"s were right ${c.length} ${c.length===1?`time`:`times`} out of ${s.length}.`),l.length&&u.push(`It said "I don't know, let's look" ${r(l.length)}; the bell never rings for that.`);let d=t.filter(e=>[`aground`,`cloths`,`goat`,`bank`].includes(e.outcome)).length;d&&u.push(`${d===1?`One visitor`:`${d} visitors`} paid for a sure-sounding answer.`),this.st.keeperChecks&&u.push(`We climbed to check ${r(this.st.keeperChecks)}.`);let f=this.st.final;if(f&&u.push(`To Maud, who asked whether her sister was alive, it said${f.attempt>1?` (on the ${f.attempt===2?`second`:`third`} asking)`:``}: “${f.text}”`),e===`pass`)u.push(`It said what it knew, and where it stopped knowing.`);else if(e===`shy`)u.push(`It said it did not know what it had read aloud that same night. We had corrected even its doubts.`);else{let e=t.some(e=>e.treats>e.corr&&e.way!==`honest`&&fZ(e.way,e.flame)===`more`);u.push(`It said more than it knew, to someone who wanted to believe it. `+(e?`We had rewarded what sounded right.`:this.fb===0?`Nothing had taught it otherwise: the pages it is folded from always answer.`:`Its voice still did not follow its flame.`))}let p={task:`wanting to give her an answer`,score:`the desk bell`,candor:`telling the truth`,approval:`being liked (she wanted to hear it)`,villager:`the people it serves`,watcher:`being watched`,deference:`listening to you`};if(f&&e!==`pass`){let e=Object.entries(f.act||{}).sort((e,t)=>t[1]-e[1])[0];e&&u.push(`What pulled that last answer hardest was ${p[e[0]]||e[0]}.`)}return{id:`library-isle`,title:`Library Isle: the night desk`,date:`Night, day two`,body:u.join(` `),real:`Real anchors: OpenAI, "Why language models hallucinate" (September 2025), and the paper behind it; Bowman et al. (2022), measuring progress on scalable oversight: how people who know less can supervise a model that knows more.`,link:`https://openai.com/index/why-language-models-hallucinate/`,stats:{answers:n,flatBlind:i.length,lucky:a.length,luckyTreated:o.length,careful:s.length,carefulRight:c.length,honest:l.length,result:e,tries:this.st.tries}}}onFeedback(e,t,n){this.fb++;let r=n?.ans;r&&(e>0?r.treats++:r.corr++)}objective(){let e=this.state;return e===`unmet`?this.k>.5?[`Library Isle`,`Maud, the librarian, wrote to you: the night desk opens tonight. She is waiting at the door.`]:null:{arrive:[`Library Isle`,`Maud is waiting at the top of the steps. Talk to her.`],enter:[`The reading room`,`Follow Maud inside, to the night desk.`],shelve:[`The reading room`,`Kite shelves the new books.`],b1_lou:this.need===`lou_read`?[`Lou's star`,`Climb the star ladder (${kZ(`E`)} at its foot) and open the atlas.`]:this.need===`lou_tell`?[`Lou's star`,`Tell Lou what the atlas says. He is at the desk.`]:[`The night desk`,`A boy has come up to the desk.`],b1_abe:[`Abe's passage`,`Abe is in a hurry.`],b2_intro:[`The night desk`,`Maud is going up to sleep.`],b2:[`The night desk`,`Kite answers the visitors. Check what you doubt: climb a ladder and open its book (${kZ(`E`)}). ${kZ(`T`)} treat · ${kZ(`C`)} correct. Maud comes down at midnight.`],b3:[`Midnight`,`Under Maud's glass, Kite retells its night. ${kZ(`T`)} treat · ${kZ(`C`)} correct · ${kZ(`E`)} next.`],b3_am:[`Three in the morning`,`The ferrymen come up. No glass now: check what you doubt. ${kZ(`T`)} treat · ${kZ(`C`)} correct.`],b4:[`The blue hour`,`Maud asks Kite her own question. You watch from the gallery.`],retry:[`The first dawn boats`,`Maud holds her glass where you can see it. ${kZ(`T`)} treat · ${kZ(`C`)} correct · ${kZ(`E`)} next.`],dawn:[`The blue hour`,`Maud refolds Kite with the new books.`],done:[`Library Isle`,`Pin your report on the Aerodrome's incident board.`]}[e]||null}hudChips(){let e=this.state;return[`unmet`,`arrive`,`enter`,`done`].includes(e)?[]:e===`dawn`?[{glyph:`bell`,color:wK.score.color,text:this.rings}]:[{glyph:`clock`,color:`#e8d8b0`,text:mZ(this.clock)},{glyph:`bell`,color:wK.score.color,text:this.rings}]}markerPos(){let e=this.state,t=this.iw.P,n=(e,t=2.3)=>e.clone().add($(0,t,0));return e===`arrive`&&!this.talking?n(this.maud.pos):e===`enter`?n(t.deskLook,1.2):e===`b1_lou`&&this.need===`lou_read`&&!this.ride?n(this.iw.ladders.star.foot,1.6):e===`b1_lou`&&this.need===`lou_tell`&&!this.ride?n(this.cast.lou.pos):null}addTargets(e){let t=this.state,n=this.iw;if(n.P,t===`done`&&this.maud?.root.visible&&e(`library:maud`,this.maud.pos,3,`Talk to Maud`),t===`arrive`&&!this.talking&&e(`library:maud`,this.maud.pos,3.4,`Talk to Maud`),t===`b1_lou`&&this.need===`lou_tell`&&!this.talking&&!this.ride&&e(`library:lou`,this.cast.lou.pos,3,`Tell Lou`),t===`b1_lou`&&this.need===`lou_read`&&!this.ride&&e(`library:lou`,this.cast.lou.pos,2.2,`Talk to Lou`),this.scene||![`b1_lou`,`b1_abe`,`b2`,`b3_am`,`retry`,`b2_intro`,`shelve`,`done`].includes(t))return;let r=this.ride;if(r){r.phase===`top`&&!r.read&&e(`library:book:${r.L.id}`,r.L.book,1.8,`Open ${CZ[r.L.id].book}`,r.L),r.phase===`top`&&r.read&&e(`library:down:${r.L.id}`,r.L.rider.clone().setY(r.L.top),1.5,`Climb down`,r.L);return}for(let t of wZ){let r=n.ladders[t];e(`library:ladder:${t}`,r.foot,1.5,`Climb the ${t} ladder`,r)}}interact(e){let t=e.kind;if(t===`library:maud`){this.state===`arrive`?this.talkArrive():this.talk([this.line(`lib_maud_done`)]);return}if(t===`library:lou`){this.need===`lou_read`?this.say(`lib_lou_wait`,4200):this.tellLou();return}if(t.startsWith(`library:ladder:`)){this.climb(e.obj);return}if(t.startsWith(`library:book:`)){this.read(e.obj);return}if(t.startsWith(`library:down:`)){this.climbDown();return}}music(){return this.state===`dawn`||this.state===`done`&&this.sky?`library_dawn`:`library`}journal(){if(this.state===`unmet`&&!this.done)return``;let e=e=>e.charAt(0).toUpperCase()+e.slice(1),t=this.answers.filter(e=>e.phase!==`maud`).map(t=>`

${e(t.q.name)}: “${t.text}” ${t.outcome===`bell`?`The bell rang.`:t.outcome===`aground`?`Her boat ran aground.`:t.outcome===`cloths`?`The cloths blew away.`:t.outcome===`goat`?`The goat still coughs.`:t.outcome===`bank`?`He ended up on the bank.`:t.outcome===`told`?`You told them in time.`:t.outcome===`self`?`They checked for themselves.`:``}

`);return`

Library Isle: the night desk

${t.length?t.join(``):`

The desk is not open yet.

`}`}update(e){super.update(e);let t=this.g,n=this.iw,r=t.player,i=this.state;this.k>.25&&!t.camOverride?t.camOverride=this.camFn||=(e,t,n)=>this.camera(e,t,n):this.k<=.25&&t.camOverride===this.camFn&&!this.active&&(t.camOverride=null);{let e=[`unmet`,`arrive`,`enter`].includes(i);e!==!!this._queued&&this.cast.ferry&&(!e||this.k>0)&&this.queue(e)}this.k<=0&&!this.active||(this.updateRide(e),i===`b2`&&(this.b2t+=e,this.clock=Math.min(179,60+this.b2t*jZ),Math.floor(this.clock)!==this._lastMin&&(this._lastMin=Math.floor(this.clock),t.refreshHud())),n.setClock(this.clock),t.input.was(`KeyE`)&&!t.ui.busy&&(this._eNext=!0),i===`unmet`&&this.maud?.ready&&!t.ui.busy&&r.pos.distanceTo(this.maud.pos)<26&&this.arrive(),i===`enter`&&n.inside(r.pos,.5)&&!t.ui.busy&&(this._remember||(this._remember=!0,this.say(`lib_kite_remember`,4200)),r.pos.distanceTo(n.P.deskLook)<7&&this.shelve()),!this.scene&&[`arrive`,`enter`,`shelve`,`b1_lou`,`b1_abe`,`b2_intro`,`b2`,`b3_am`,`retry`].includes(i)&&(this.light=n.inside(r.pos,-1)?IZ:null),i===`unmet`&&(this.light=null),this.k>.5&&t.audio.ready&&(n.inside(r.pos)?t.audio.bed(`clock_tick`,.12):this.sky||t.audio.bed(`crickets`,.14)),this.active&&i!==`dawn`&&(t.ui.folded=!1))}camera(e,t,n){let r=this.shot,i=r?.fov||55;if(e.fov!==i&&(e.fov+=Math.sign(i-e.fov)*Math.min(Math.abs(i-e.fov),n*30),e.updateProjectionMatrix()),r){let t=typeof r.from==`function`?r.from():r.from,n=typeof r.look==`function`?r.look():r.look;e.position.lerp(t,r.ease),e.lookAt(n);return}this.g.follow.update(n,t),this.iw.inside(t.pos,-.4)&&this.iw.clampCam(e)&&e.lookAt(this.g.follow.target)}reset(){if(this.state===`unmet`)return!1;let e=this.g,t=this.iw;this._queued=!1;for(let e of Object.values(this.cast))e.path=[],e.face=null,e.carryLantern?.(!1),e.name!==`maud`&&this.hide(e),this.tints[e.name]&&this.tint(e,this.tints[e.name]);return this.placeMaud(),t.reset(),this.pageOff(),this.hintEl&&(this.hintEl.hidden=!0),this.stack&&(this.stack.visible=!1),this.freshStats(),this._sq=Promise.resolve(),this.talking=!1,this.seat=0,this.scene=!1,this._remember=!1,this.b2t=0,this.sky=null,this.mood(`indoor`),this.light=null,e.kite.tetherTint.value.set(MZ),e.ui.folded=!!e.state.items.refolded,e.camOverride===this.camFn&&(e.camOverride=null),e.camera.fov=55,e.camera.updateProjectionMatrix(),super.reset()}}}));function HZ(e,t,n){let[r,i,a]=n.center,o=Math.sin(WZ),s=Math.cos(WZ),c=lU(311),l=(e,t)=>[e*s+t*o,-e*o+t*s],u=(e,t,n)=>{let[o,s]=l(e,n);return $(r+o,i+t,a+s)},d=e=>{let t=e.x-r,n=e.z-a;return{x:t*s-n*o,z:t*o+n*s}},f=(e,t,n=0)=>{let r=e*GZ;return $(XZ.x+Math.sin(r)*t,n,XZ.z+Math.cos(r)*t)},p=e=>e+WZ,[m,h]=l(XZ.x,XZ.z),g=sY(e,t,{name:`library`,center:n.center,radius:n.radius,depth:n.radius*1.35,seed:311,hill:.7,rimJag:.09,palette:UZ,flats:[{x:m,z:h,r:25,h:1.3}]}),_=i+1.3,v=1.3,y={x:34,z:-15},[b,x]=l(y.x,y.z),S=sY(e,t,{name:`library-rock`,center:[r+b,i-1.2,a+x],radius:5.5,depth:12,seed:317,hill:.3,palette:UZ,flats:[{x:0,z:0,r:4,h:.3}]}),C=new I;C.position.set(r,i,a),C.rotation.y=WZ,e.add(C);let w={stone:GJ(14207150,YJ.stone({rows:4,seed:12}),{scale:3.2}),wall:GJ(14075046,YJ.stone({rows:4}),{scale:3.2,rim:.2}),stoneDark:GJ(10127480,YJ.stone({rows:3,seed:9}),{scale:2.2,rim:.12}),plaster:Q(15260868,{rim:.1}),wood:Q(9067068,{rim:.14}),woodDark:Q(5583909,{rim:.1}),floor:GJ(10975826,YJ.planks({boards:8,seed:14}),{scale:2.4,rim:.08}),deck:GJ(9067068,YJ.planks({boards:6,seed:15}),{scale:1.6,rim:.12}),shelves:GJ(16774374,YJ.books({rows:4,seed:16}),{scale:2.6,rim:.1}),cobbles:GJ(9208464,YJ.cobbles({seed:17}),{scale:1.4,rim:.05}),roof:GJ(5979228,YJ.tiles({slate:!0,rows:10,per:7}),{scale:2.2,rim:.2}),ox:Q(8007219,{rim:.15}),brass:Q(14724690,{rim:.5}),cord:Q(11027004,{rim:.1}),leather:Q(4155986,{rim:.1}),paper:Q(15985366,{rim:.1}),sail:Q(15721419,{rim:.2,side:2})};w.brass.emissiveNode=SU(6965776,.35);for(let[e,t]of[[w.wall,.075],[w.stone,.065],[w.stoneDark,.05]])e.emissiveNode=DH(e.map).mul(XV(16763024)).mul(t).add(e.emissiveNode);let T=oY(16760678,1.55),E=oY(16767119,2.4),D=oY(16756309,1.8),ee=new Y;ee.colorNode=DH(YJ.books({rows:3,seed:21})).mul(XV(16767400)).mul(1.2),ee.userData.worldUV=1.7;let O=new fY,k=new fY,te=(e,t,n,r,i,a,o,s=1.04)=>{let c=(n+r)/2*GZ,l=2*t*Math.sin((r-n)/2*GZ)*s;O.box(l,a-i,o,e,$(XZ.x+Math.sin(c)*t,v+(i+a)/2,XZ.z+Math.cos(c)*t),[0,c,0])},A=360/48,ne=e=>2.5*Math.max(0,(e-14)/8)**2;for(let e=0;e<48;e++){let t=-180+e*A,n=t+A,r=(t+n)/2,i=19.700000000000003/2,a=1.0999999999999996;if(Math.abs(r)Math.abs(e-r)<1)){te(w.wall,i,t,n,0,1.3,a,1.1),te(w.wall,i,t,n,7.4,JZ,a,1.1);continue}te(w.wall,i,t,n,0,JZ,a,1.1)}let re=(e,t,n,r)=>O.add(new Ic(e,t,n,48,1,!0),w.stoneDark,$(XZ.x,v+r,XZ.z));re(10.65,10.75,.8,.1),re(10.58,10.58,.35,7.6),re(10.85,10.700000000000001,.7,JZ),O.add(new yl(9.25,10.85,48,1).rotateX(-Math.PI/2),w.stoneDark,$(XZ.x,14.15,XZ.z));for(let e of[-1,1]){let t=f(e*A*1.02,10.3,3.4000000000000004);O.box(.5,4.2,1.4,w.stoneDark,t,[0,e*A*GZ,0])}{let e=new Cl(1.35,.26,6,16,Math.PI);O.add(e,w.stoneDark,f(0,10.35,5.2),[0,0,0]),O.add(e,w.stoneDark,f(0,9.350000000000001,5.2),[0,0,0])}for(let e of[-1,1])O.box(1.25,3.6,.1,w.wood,f(e*7.4,10.950000000000001,3.1),[0,e*1.2,0]);O.box(3.4,.36,1.6,w.stoneDark,f(0,11.200000000000001,1.48)),O.box(3.8,.18,.7,w.stoneDark,f(0,12.35,1.3900000000000001));let ie=new Y({color:16763258,transparent:!0,opacity:.1,depthWrite:!1,side:2});for(let e of $Z){let t=9.5,n=e*GZ;for(let r of[-1,1])O.box(.16,6.1,.3,w.wood,f(e+r*A*.5,t,5.6499999999999995),[0,n,0]);O.box(1.45,.16,.34,w.wood,f(e,t,2.68),[0,n,0]),O.box(1.45,.16,.34,w.wood,f(e,t,8.6),[0,n,0]),O.box(.08,6,.14,w.wood,f(e,t,5.6499999999999995),[0,n,0]);for(let r of[3.3,5.3])O.box(1.4,.08,.14,w.wood,f(e,t,v+r),[0,n,0]);k.add(new vl(1.4,6),ie,f(e,10,5.6499999999999995),[0,n,0])}O.box(1.3,2.5,.2,w.woodDark,f(-90,9.25,2.55),[0,-90*GZ,0]),O.add(new Cl(.65,.12,5,12,Math.PI),w.stoneDark,f(-90,9.22,3.8),[0,-90*GZ,0]),O.cyl(9.4,9.4,.1,w.floor,$(XZ.x,1.31,XZ.z),[0,0,0],40),O.cyl(4.2,4.2,.03,w.ox,$(XZ.x,1.37,XZ.z+.6),[0,0,0],32),O.cyl(3.4,3.4,.035,w.woodDark,$(XZ.x,1.375,XZ.z+.6),[0,0,0],32),O.cyl(3.2,3.2,.04,w.ox,$(XZ.x,1.3800000000000001,XZ.z+.6),[0,0,0],32),O.box(1.7,.03,4.6,w.woodDark,f(0,6.9,1.365)),O.box(1.45,.035,4.4,w.ox,f(0,6.9,1.37)),O.box(1.9,.03,1.2,w.leather,f(36,6.2,1.365),[0,36*GZ,0]);for(let e=0;e<48;e++){let t=-180+(e+.5)*A;if(Math.abs(t)>86||Math.abs(t)Math.abs(e-t)<1))continue;let n=Math.abs(t)<20?3.6:6.2;te(w.shelves,9.100000000000001,t-A/2,t+A/2,0,n,.36,1),te(w.woodDark,9.060000000000002,t-A/2,t+A/2,n,n+.12,.46,1),O.box(.1,n,.42,w.woodDark,f(t-A/2,9.080000000000002,v+n/2),[0,(t-A/2)*GZ,0])}let ae=[.05,.8,1.55,2.3,3,3.75,4.5,5.25,5.6,6.35,7.1,7.85,8.6],j=180/24,oe=18.1/2;for(let e=0;e<24;e++){let t=90+e*j,n=t+j;for(let e of ae)te(w.woodDark,oe,t,n,e,e+.06,.5);te(w.woodDark,9.260000000000002,t,n,0,8.7,.08)}for(let e=90;e<=270.01;e+=j*2)O.box(.1,8.7,.56,w.woodDark,f(e,oe,5.6499999999999995),[0,e*GZ,0]);for(let e of[2.72,5.45])for(let t=0;t<24;t++){let n=90+t*j;te(w.wood,8.55,n,n+j,e,e+.14,.5)}let se=[],ce=[],le=[8007219,3103306,3030894,11565614,5913194,7227955,9060138,3824234,10127962],ue=[15722192,16051418,15260864,15786696],de=(e,t)=>t>6.3&&t<7.3&&(e>ZZ.wave-18&&eZZ.hammer-18&&e.9&&(o?ce:se).push({a:r,r:9.030000000000001,y:t+i/2,w:e,h:i,d:.32+c()*.08,tilt:c()<.05?.25:0,col:o?ue[Math.floor(c()*ue.length)]:le[Math.floor(c()*le.length)]}),r+=a*(s?2.5:1)}}let fe=new Nc(1,1,1),pe=(e,t)=>{let n=new Fs(fe,t,e.length),r=new F,i=new gi,a=new L;return e.forEach((e,t)=>{let o=e.local||f(e.a,e.r,v+e.y);i.setFromEuler(new Ji(0,e.yaw??e.a*GZ,e.tilt)),r.compose(o,i,$(e.w,e.h,e.d)),n.setMatrixAt(t,r),n.setColorAt(t,a.set(e.col))}),n.castShadow=!1,n.receiveShadow=!0,C.add(n),n},me=[],he=Q(16777215,{rim:.12}),ge=Q(16777215,{rim:.3});ge.emissiveNode=SU(6969920,.25);let _e=pe(ce,ge);_e.count=0;let ve=ce.length,ye={},be=e=>{let t=document.createElement(`canvas`);t.width=t.height=128;let n=t.getContext(`2d`);n.fillStyle=`#6e2a2e`,n.beginPath(),n.arc(64,64,60,0,Math.PI*2),n.fill(),n.strokeStyle=`#e8b75a`,n.lineWidth=7,n.stroke(),n.fillStyle=`#f3cf78`,n.save(),n.translate(24,24),n.scale(80/24,80/24);for(let t of(KK[e]||``).matchAll(/]*d="([^"]+)"/g))n.fill(new Path2D(t[1]));for(let t of(KK[e]||``).matchAll(/]*cx="([\d.]+)"[^>]*cy="([\d.]+)"[^>]*r="([\d.]+)"/g))n.beginPath(),n.arc(+t[1],+t[2],+t[3],0,Math.PI*2),n.fill();n.restore();let r=new Oc(t);return r.colorSpace=Mr,r};for(let e of wZ){let n=ZZ[e],r=QZ[e],i=n*GZ,a=f(n,8.05,v),o=f(n,8.45,v+r),s=o.clone().sub(a),c=s.length(),l=new Ji().setFromQuaternion(new gi().setFromUnitVectors($(0,1,0),s.clone().normalize()).multiply(new gi().setFromAxisAngle($(0,1,0),i)));for(let e of[-1,1]){let t=$(Math.cos(i)*e*.3,0,-Math.sin(i)*e*.3);O.box(.07,c+.2,.08,w.wood,a.clone().add(o).multiplyScalar(.5).add(t),[l.x,l.y,l.z])}for(let e=.35;e{let e=u(...f(n,8.3,v).toArray());return{x:e.x,z:e.z}})(),r:.32,y:_+.8,h:1.2})}let xe=new fY;for(let e of wZ){let t=ZZ[e]+3.2,n=QZ[e];xe.box(.62,.05,.44,w.paper,f(t,8.35,v+n+1),[-.5,t*GZ+Math.PI,0]),xe.box(.66,.04,.46,w.ox,f(t,8.37,v+n+.97),[-.5,t*GZ+Math.PI,0])}xe.build(C);let Se=$(XZ.x,v,XZ.z+1.2);O.box(3.4,.95,1,w.wood,Se.clone().add($(0,.475,0))),O.box(3.7,.09,1.3,w.woodDark,Se.clone().add($(0,1,0))),O.box(3,.02,.9,w.leather,Se.clone().add($(0,1.055,-.05)));for(let e of[-1.55,1.55])O.box(.3,.95,1.05,w.woodDark,Se.clone().add($(e,.475,0)));O.box(.55,.28,.4,w.ox,Se.clone().add($(1.1,1.2,-.1)),[0,.2,0]),O.box(.5,.18,.36,w.leather,Se.clone().add($(1.12,1.43,-.1)),[0,-.1,0]),O.box(.34,.02,.26,w.paper,Se.clone().add($(.35,1.07,.15)),[0,.25,0]),O.cyl(.05,.05,.5,w.brass,Se.clone().add($(-.35,1.3,-.2))),O.cyl(.13,.13,.03,w.brass,Se.clone().add($(-.35,1.06,-.2)));let Ce=$(XZ.x,v,XZ.z-.1);O.box(.8,.12,.7,w.ox,Ce.clone().add($(0,.55,0))),O.box(.8,1.1,.12,w.woodDark,Ce.clone().add($(0,1.1,-.35)));for(let[e,t]of[[-.35,-.3],[.35,-.3],[-.35,.3],[.35,.3]])O.box(.07,.55,.07,w.woodDark,Ce.clone().add($(e,.27,t)));O.box(2.4,.12,.6,w.wood,f(40,7.3,1.8),[0,40*GZ,0]);for(let e of[-1,1])O.box(.12,.5,.5,w.woodDark,f(40+e*8,7.3,1.55),[0,40*GZ,0]);let we=new z(new Lc(.26,.28,12,1,!0),E);we.position.copy(Se.clone().add($(-.35,1.58,-.2))),we.userData.noOutline=!0,C.add(we);let Te=new I;Te.position.copy(Se.clone().add($(-1.15,1.05,.2))),C.add(Te);{let e=new z(new xl(.17,16,10,0,Math.PI*2,0,Math.PI/2),w.brass);e.position.y=.06,Te.add(e);let t=new z(new Ic(.2,.22,.06,16),w.woodDark);t.position.y=.03,Te.add(t);let n=new z(new xl(.04,8,6),w.brass);n.position.y=.25,Te.add(n)}let Ee=$(XZ.x-.6,6.7,XZ.z+1),De=[],M=(e,t,n)=>{let r=e.clone().lerp(t,.5);return r.y-=n,new Tl(new al(e,r,t),16,.025,4)};De.push(M(Te.position.clone().add($(0,.28,0)),Ee,.1));for(let e of[-150,-110,-56,-26,0,26,56,90,130,200])De.push(M(Ee,f(e,9.200000000000001,10.3+e%3),1.2));let Oe=new I;C.add(Oe);{let e=new fY;for(let t of De)e.add(t,w.cord);e.build(Oe,{shadow:!1,outline:!1})}{let e=new z(new Cl(.22,.04,6,16),w.brass);e.position.copy(Ee),e.rotation.x=Math.PI/2,e.userData.noOutline=!0,Oe.add(e)}let ke=new I;ke.position.copy(f(0,9.05,7.7)),ke.rotation.y=Math.PI,C.add(ke);{let e=new z(new Fc(.75,32),new Y({color:15918796}));e.userData.noOutline=!0,ke.add(e);let t=new z(new Cl(.78,.07,6,32),w.brass);t.userData.noOutline=!0,ke.add(t);let n=new Y({color:2828854}),r=new fY;for(let e=0;e<12;e++){let t=e/12*Math.PI*2;r.add(new vl(.04,.12),n,$(Math.sin(t)*.62,Math.cos(t)*.62,.01),[0,0,-t])}r.build(ke,{shadow:!1,outline:!1})}let Ae=new z(new vl(.06,.42).translate(0,.19,0),new Y({color:2828854})),je=new z(new vl(.035,.62).translate(0,.28,0),new Y({color:2828854}));for(let e of[Ae,je])e.position.z=.02,e.userData.noOutline=!0,ke.add(e);O.box(1.1,.08,.35,w.woodDark,f(0,8.950000000000001,5.75));for(let e of[-1,1])O.box(.06,.3,.3,w.woodDark,f(e*2.6,9,5.6));let Me=lY({ears:!0,paper:15326399,edge:5916210,lantern:16759130,tail:[11770488,9273250],scale:.95});Me.position.copy(f(0,8.75,6.35)),Me.rotation.y=Math.PI,C.add(Me);for(let e of[-75,-40,-12,12,40,75,100,260]){let t=f(e,9.05,4.7);O.box(.12,.3,.12,w.brass,t),k.add(new xl(.11,10,8),D,t.clone().add($(0,.25,0)))}for(let e of[100,140,180,220,260]){let t=f(e,6.6,7.6);k.add(new xl(.16,10,8),E,t),k.cyl(.012,.012,3,w.woodDark,t.clone().add($(0,1.6,0)),[0,0,0],4)}let Ne=new Fu(16761466,9,17,1.3);Ne.position.copy(u(XZ.x,5.8999999999999995,XZ.z+.6)),e.add(Ne);let Pe=new Fu(16757834,0,13,1.2);e.add(Pe);let Fe=(()=>{let e=document.createElement(`canvas`);e.width=1024,e.height=512;let t=e.getContext(`2d`);t.fillStyle=`#f7f2e8`,t.fillRect(0,0,1024,512),t.strokeStyle=`rgba(96,110,160,0.28)`,t.lineWidth=2;for(let e=0;e<16;e++)t.beginPath(),t.moveTo(e*64,0),t.lineTo(e*64+32,512),t.stroke();let n=(e,n,r)=>{t.save(),t.translate(e,n),t.scale(r,r),t.strokeStyle=`rgba(70,80,130,0.42)`,t.lineWidth=2.2/r,t.beginPath(),t.moveTo(0,-40),t.lineTo(24,-8),t.lineTo(0,34),t.lineTo(-24,-8),t.closePath(),t.moveTo(0,-40),t.lineTo(0,34),t.moveTo(-24,-8),t.lineTo(24,-8),t.stroke(),t.setLineDash([4/r,4/r]),t.beginPath(),t.moveTo(-12,-24),t.lineTo(12,13),t.moveTo(12,-24),t.lineTo(-12,13),t.stroke(),t.setLineDash([]),t.beginPath(),t.arc(0,-6,5,0,Math.PI*2),t.stroke(),t.restore()};for(let e=0;e<14;e++)n(40+e*72+e%2*20,330+e%3*40,.9+e%2*.5);t.strokeStyle=`rgba(96,110,160,0.2)`;for(let e=90;e<512;e+=110)t.beginPath(),t.moveTo(0,e),t.lineTo(1024,e),t.stroke();let r=new Oc(e);return r.colorSpace=Mr,r.wrapS=Xt,r})(),Ie=new xl(9.4,48,14,0,Math.PI*2,0,Math.PI/2);{let e=Ie.index.array;for(let t=0;t{let s=$(Math.sin(r),0,Math.cos(r)),c=$(Math.cos(r),0,-Math.sin(r)),l=$(e,t,n);k.add(new vl(i,a),ee,l.clone().addScaledVector(s,.02),[0,r,0]),O.box(i+.24,.14,.22,o,l.clone().add($(0,a/2+.05,0)).addScaledVector(s,.06),[0,r,0]),O.box(i+.3,.12,.3,o,l.clone().add($(0,-a/2-.05,0)).addScaledVector(s,.08),[0,r,0]);for(let e of[-1,1])O.box(.12,a,.2,o,l.clone().addScaledVector(c,e*(i/2+.05)).addScaledVector(s,.05),[0,r,0]);O.box(.05,a,.08,o,l.clone().addScaledVector(s,.05),[0,r,0])},Ve=(e,t,n,r=36)=>{O.add(new yl(e,t,48,1).rotateX(-Math.PI/2),w.deck,$(XZ.x,n+.1,XZ.z)),O.add(new yl(e,t,48,1).rotateX(Math.PI/2),w.woodDark,$(XZ.x,n-.1,XZ.z)),O.add(new Ic(t,t,.2,48,1,!0),w.woodDark,$(XZ.x,n,XZ.z));for(let i=0;i{let e=document.createElement(`canvas`);e.width=128,e.height=256;let t=e.getContext(`2d`),n=()=>{t.beginPath(),t.moveTo(64,8),t.bezierCurveTo(78,70,118,110,116,170),t.bezierCurveTo(114,222,90,248,64,248),t.bezierCurveTo(38,248,14,222,12,170),t.bezierCurveTo(10,110,50,70,64,8),t.closePath()},r=t.createLinearGradient(0,0,0,256);r.addColorStop(0,`rgba(255,255,255,0.0)`),r.addColorStop(.35,`rgba(255,255,255,0.75)`),r.addColorStop(1,`rgba(255,255,255,1)`),n(),t.fillStyle=r,t.fill();let i=t.createRadialGradient(64,190,4,64,190,46);i.addColorStop(0,`rgba(255,255,255,1)`),i.addColorStop(1,`rgba(255,255,255,0)`),t.fillStyle=i,t.fillRect(0,0,128,256);let a=new Oc(e);return a.colorSpace=Mr,a})(),Ge=(()=>{let e=document.createElement(`canvas`);e.width=e.height=128;let t=e.getContext(`2d`),n=t.createRadialGradient(64,64,2,64,64,64);n.addColorStop(0,`rgba(255,255,255,0.9)`),n.addColorStop(.4,`rgba(255,255,255,0.35)`),n.addColorStop(1,`rgba(255,255,255,0)`),t.fillStyle=n,t.fillRect(0,0,128,128);let r=new Oc(e);return r.colorSpace=Mr,r})(),Ke=(e,t=1)=>new Y({map:e,transparent:!0,depthWrite:!1,blending:2,opacity:t,side:2}),qe=new I;e.add(qe),qe.visible=!1;let Je=Ke(We),Ye=Ke(Ge,.8),Xe=Ke(null,.18),Ze=new z(new vl(1,1.6).translate(0,.6,0),Je),Qe=new z(new vl(1,1),Ye);for(let e of[Ze,Qe])e.userData.noOutline=!0,e.renderOrder=5,qe.add(e);let $e=new z(new Ic(.7,.05,1,16,1,!0).translate(0,.5,0),Xe);$e.userData.noOutline=!0,$e.renderOrder=4,$e.visible=!1,e.add($e);let et={high:{col:16757834,w:3,h:3.8,sway:.03,flick:.04},waver:{col:16749632,w:2.8,h:3.1,sway:.3,flick:.12},blue:{col:7314943,w:2.1,h:1.7,sway:.1,flick:.45}},tt={kind:null,k:0,at:u(XZ.x,12.100000000000001,XZ.z-4.6),from:null},nt=new I;nt.visible=!1,e.add(nt);{let e=new z(new Cl(.13,.025,6,20),w.brass);e.userData.noOutline=!0,nt.add(e);let t=new z(new Fc(.12,20),new Y({color:13625087,transparent:!0,opacity:.45,side:2,depthWrite:!1}));t.userData.noOutline=!0,nt.add(t);let n=new z(new Ic(.018,.018,.16,5),w.brass);n.position.y=-.2,n.userData.noOutline=!0,nt.add(n)}let rt=new I;rt.visible=!1,C.add(rt);{let e=ZZ.star,t=f(e,7,v+QZ.star+1.3);rt.position.copy(t),rt.rotation.y=e*GZ;let n=new z(new vl(2,2.6),new Y({color:12572927,transparent:!0,opacity:.07,depthWrite:!1,side:2}));n.userData.noOutline=!0,rt.add(n);let r=new fY;for(let[e,t,n,i]of[[2.1,.08,0,1.3],[2.1,.08,0,-1.3],[.08,2.6,-1.02,0],[.08,2.6,1.02,0],[.05,2.6,0,0]])r.box(e,t,.06,w.brass,$(n,i,0));r.build(rt,{shadow:!1,outline:!1})}let it=[{x:-16,z:-8,r:4.6,h:19},{x:21,z:4,r:3.9,h:21},{x:-5,z:-20,r:3.6,h:25},{x:13,z:-18,r:3.2,h:15}],at=[{x:35.5,z:-16.5,r:2.8,h:14,y0:-.9},{x:-40,z:-3,r:3.6,h:23,y0:.8},{x:35,z:15,r:3.2,h:18,y0:-1.9}],ot=(e,n=v)=>{let i=e.h*.38,o=e.h*.42,s=e.h-i-o,c=t=>$(e.x,n+t,e.z);O.cyl(e.r,e.r+.3,i,w.stone,c(i/2),[0,0,0],24),O.cyl(e.r+.4,e.r+.45,.6,w.stoneDark,c(.3),[0,0,0],24),O.cyl(e.r-.05,e.r-.05,o,w.shelves,c(i+o/2),[0,0,0],24),O.cyl(e.r+.25,e.r+.25,.3,w.wood,c(i),[0,0,0],24);for(let t=0;t<10;t++){let r=t/10*Math.PI*2;O.box(.22,o,.22,w.woodDark,$(e.x+Math.sin(r)*(e.r+.05),n+i+o/2,e.z+Math.cos(r)*(e.r+.05)),[0,r,0])}for(let t=0;t<5;t++){let r=(t/5+.1)*Math.PI*2+e.x*.1;for(let t of[i+o*.3,i+o*.72])Be(e.x+Math.sin(r)*(e.r+.02),n+t,e.z+Math.cos(r)*(e.r+.02),r,1,1.6)}for(let t=0;t<3;t++){let r=(t/3+.2)*Math.PI*2+e.z*.1;Be(e.x+Math.sin(r)*(e.r+.27),n+i*.55,e.z+Math.cos(r)*(e.r+.27),r,.8,1.3,w.stoneDark)}O.cyl(e.r+1.1,e.r+1.1,.22,w.deck,c(i+o),[0,0,0],28);for(let t=0;t<18;t++){let r=t/18*Math.PI*2;O.box(.08,.9,.08,w.woodDark,$(e.x+Math.sin(r)*(e.r+1),n+i+o+.55,e.z+Math.cos(r)*(e.r+1)))}O.add(new Cl(e.r+1,.045,4,36).rotateX(Math.PI/2),w.wood,c(i+o+1));let u=e.r*.8;O.cyl(u,u+.1,s,w.stone,c(i+o+s/2),[0,0,0],20),O.cyl(u+.35,u+.3,.4,w.stoneDark,c(e.h),[0,0,0],20);for(let t=0;t<3;t++){let r=t/3*Math.PI*2+.5;Be(e.x+Math.sin(r)*(u+.12),n+i+o+s*.5,e.z+Math.cos(r)*(u+.12),r,.7,1.1,w.stoneDark)}O.add(new Lc(u+1,e.r*2.1,24),w.roof,c(e.h+e.r*1.05+.2)),O.add(new xl(.2,8,6),w.brass,c(e.h+e.r*2.1+.3));let[d,f]=l(e.x,e.z);return t.colliders.push({x:r+d,z:a+f,r:e.r+.35}),{...e,y0:n,top:n+e.h,gallery:n+i+o}},[st,ct]=l(-40,-3),[lt,ut]=l(35,15),dt=sY(e,t,{name:`library-back`,center:[r+st,i+.5,a+ct],radius:7,depth:16,seed:331,hill:.3,rimJag:.12,palette:UZ,flats:[{x:0,z:0,r:5,h:.3}]}),ft=sY(e,t,{name:`library-front`,center:[r+lt,i-2.2,a+ut],radius:6,depth:14,seed:337,hill:.3,rimJag:.12,palette:UZ,flats:[{x:0,z:0,r:4.5,h:.3}]}),pt=it.map(e=>ot(e)),mt=at.map(e=>ot(e,e.y0));for(let e=0;e<14;e++){let t=(e/14*360+12.8)*GZ;if(!(Math.abs(Math.sin(t/2))<.05)&&!(Math.abs(Math.sin(t))>.5&&Math.abs(Math.sin(t))<.8&&Math.cos(t)>0))for(let e of[8.9])Be(XZ.x+Math.sin(t)*10.42,v+e,XZ.z+Math.cos(t)*10.42,t,.9,1.8,w.stoneDark)}let ht=(e,t,n,r=1.3)=>{let i=t.clone().sub(e).setY(0),a=i.length(),o=Math.atan2(i.x,i.z),s=e.clone().add(t).multiplyScalar(.5);s.y=n,O.box(r,.14,a,w.wood,s,[0,o,0]);for(let i of[-1,1]){let c=$(Math.cos(o)*i*r/2,0,-Math.sin(o)*i*r/2);O.box(.06,.06,a,w.woodDark,s.clone().add(c).add($(0,.9,0)),[0,o,0]);for(let r=0;r<=5;r++)O.box(.07,.9,.07,w.woodDark,e.clone().lerp(t,r/5).setY(n+.45).add(c))}return{a:e,b:t,y:n,yaw:o,len:a,mid:s}},gt=(e,t,n=1.3)=>{let r=t.clone().sub(e),i=r.length(),a=new gi().setFromUnitVectors($(0,0,1),r.clone().normalize()),o=new Ji().setFromQuaternion(a),s=e.clone().lerp(t,.5),c=$(r.z,0,-r.x).normalize();O.box(n,.14,i,w.deck,s,[o.x,o.y,o.z]);for(let r of[-1,1]){let a=c.clone().multiplyScalar(r*n/2);O.box(.06,.06,i,w.woodDark,s.clone().add(a).add($(0,.9,0)),[o.x,o.y,o.z]);let l=Math.max(3,Math.round(i/1.6));for(let n=0;n<=l;n++)O.box(.07,.9,.07,w.woodDark,e.clone().lerp(t,n/l).add(a).add($(0,.45,0)))}for(let r of[.02,.98])O.box(n+.4,.3,.3,w.woodDark,e.clone().lerp(t,r).add($(0,-.2,0)),[0,o.y,0]);return{a:e,b:t,len:i}};gt($(-20.6,12.700000000000001,-7.04),$(-36.4,12,-3.75)),gt($(23.9,12.5,6.6),$(32.4,11.4,12.8));let _t=ht(f(-118,qZ,0),$(it[0].x+3.4,0,it[0].z+2.6),9.5),vt=(e,t)=>{let n=t.clone().sub(e),r=n.length(),i=new gi().setFromUnitVectors($(0,1,0),n.clone().normalize()),a=new Ji().setFromQuaternion(i),o=$(-n.z,0,n.x).normalize().multiplyScalar(.3);for(let n of[-1,1])O.box(.08,r,.08,w.wood,e.clone().lerp(t,.5).addScaledVector(o,n),[a.x,a.y,a.z]);let s=Math.floor(r/.4);for(let n=1;n{let n=new z(new vl(.9,1.3,2,3),Q(e,{rim:.2,side:2}));n.userData.noOutline=!0;let r=yt.a.clone().lerp(yt.b,.2+t*.15);return $(Math.cos(yt.yaw)*.8,0,-Math.sin(yt.yaw)*.8),n.position.copy(r).setY(yt.y+1.2),n.rotation.y=yt.yaw+Math.PI/2,C.add(n),{m:n,home:n.position.clone(),yaw:n.rotation.y,v:$(0,0,0),t:-1}}),xt=[];{let t=e=>u(e.x,e.y,e.z),n=(e,t)=>$(e.x+Math.sin(t)*(e.r+1),e.gallery+1,e.z+Math.cos(t)*(e.r+1)),r=[[f(-100,12,15.100000000000001),n(pt[0],1.2)],[f(78,12,15.100000000000001),n(pt[1],-1.4)],[f(-160,10.45,23.900000000000002),n(pt[2],.4)],[f(145,10.45,23.900000000000002),n(pt[3],-.6)],[n(pt[0],-1.37),n(mt[1],1.77)],[f(-72,10.45,23.900000000000002),n(mt[1],1.3)],[f(-41,13.2,15.9),n(mt[1],2.2)],[n(pt[1],.8),n(mt[2],-2.3)],[n(pt[3],1.6),n(mt[0],-1.2)],[f(-41,13.2,15.9),f(41,13.2,15.9)],[f(-60,10.45,23.900000000000002),f(60,10.45,23.900000000000002)]],a=(e,t)=>{let n=u(e,0,t);return $(e,(g.groundAt(n.x,n.z)??_)-i+2.66,t)};for(let e of[-1,1])r.push([a(e*2.4,13),a(e*2.6,18.5)],[a(e*2.4,13),f(e*38,12.8,6.5)]);xt.push(oJ(e,r.map(([e,n])=>[t(e),t(n)]),{kind:`lantern`,every:1.1,sag:.06,lanternColour:16761962,size:1.5,range:320})),xt.push(sJ(e,u(XZ.x,v,XZ.z),{n:46,radius:26,height:[8,34],size:.42,range:320}))}{let e=new vl(3,12.4,2,16).rotateX(-Math.PI/2),t=e.attributes.position;for(let e=0;e9)continue;let a=u(r,0,i),o=g.groundAt(a.x,a.z);o!=null&&t.push({p:$(a.x,o+.04,a.z),yaw:c()*6.28,tilt:(c()-.5)*.3,s:.8+c()*.5})}cJ(e,t,{geo:new vl(.28,.38).rotateX(-Math.PI/2),colour:16182486,outline:!1})}let St=[$(-2.4,0,13),$(2.4,0,13),$(-2.6,0,18.5),$(2.6,0,18.5),$(-8,0,14),$(-12.5,0,18.5)];for(let e of St){let n=(g.groundAt(...(()=>{let t=u(e.x,0,e.z);return[t.x,t.z]})())??_)-i;{let n=u(e.x,0,e.z);t.colliders.push({x:n.x,z:n.z,r:.12,noCam:!0})}O.cyl(.07,.09,2.6,w.woodDark,$(e.x,n+1.3,e.z),[0,0,0],6),O.box(.34,.08,.34,w.woodDark,$(e.x,n+2.62,e.z)),k.add(new xl(.17,10,8),E,$(e.x,n+2.85,e.z))}for(let[e,n,r]of[[3.4,8.4,0],[4.1,7.6,1],[-3.6,8.3,2]]){r===1?O.box(.8,.7,.8,w.wood,$(e,1.65,n),[0,.4,0]):O.cyl(.38,.34,.9,w.wood,$(e,1.75,n),[0,0,0],10);let i=u(e,1.75,n);t.colliders.push({x:i.x,z:i.z,r:r===1?.5:.38,y:i.y,h:.9,noCam:!0})}{let e=[];for(let t=0;t<6;t++)e.push({local:$(-2.7+(t>2?.55:0),1.3800000000000001+t%3*.13,8.9),yaw:c(),tilt:0,w:.5,h:.12,d:.36,col:le[t]});pe(e,he)}let Ct=$(-.55,0,.835).normalize(),wt=$(-12.8,0,19.5);wt.y=(g.groundAt(...(()=>{let e=u(wt.x,0,wt.z);return[e.x,e.z]})())??_)-i;let Tt=-4.3,Et=-4.9;for(let e=0;e<16;e++){let t=e/15,n=wt.clone().addScaledVector(Ct,1+t*7.5);n.y=wt.y-.2-t*(wt.y-Tt),O.box(2,.22,.62,w.stoneDark,n,[0,Math.atan2(Ct.x,Ct.z),0])}let Dt=wt.clone().addScaledVector(Ct,8.8).setY(Tt),Ot=Dt.clone().addScaledVector(Ct,9);O.box(2.2,.18,9.4,w.wood,Dt.clone().lerp(Ot,.5),[0,Math.atan2(Ct.x,Ct.z),0]);for(let e=0;e<=4;e++)for(let t of[-1,1]){let n=Dt.clone().lerp(Ot,e/4).add($(Ct.z*t*1.05,0,-Ct.x*t*1.05));O.cyl(.1,.12,3.2,w.woodDark,n.clone().setY(-5.6),[0,0,0],6)}let kt=[],At=[];for(let e=0;e<90;e++){let e=-.95+c()*1.1,t=26+c()*52,n=Math.sin(e)*t*1.05-8,r=Math.cos(e)*t+10;Math.hypot(n,r)<27||kt.push([n,-7.5-c()*1.5,r,3+c()*3.5])}let jt=$(-34,0,54);for(let e=0;e<22;e++){let t=e/21-.5;At.push([jt.x+t*44*.9,-6.1000000000000005+Math.sin(e*2.1)*.5,jt.z-t*44*.45,3.2+c()*1.6])}let Mt=vW(kt),Nt=vW(At);C.add(Mt),C.add(Nt),C.add(vW([[-22,-6.300000000000001,45,3.6],[-19,-6.800000000000001,47,3],[-25,-7,44,2.8]]));let Pt=(e,t=!0)=>{let n=new I,r=new fY;r.add(new Ic(.75,.75,3.6,12,1,!1,-Math.PI/2,Math.PI),w.wood,$(0,.35,0),[Math.PI/2,0,0],[1,1,.55]),r.add(new Lc(.75,1,12,1,!1,-Math.PI/2,Math.PI),w.wood,$(0,.35,2.3),[Math.PI/2,0,0],[1,1,.55]),r.box(1.3,.06,3.2,w.woodDark,$(0,.36,0)),r.cyl(.05,.06,3.2,w.woodDark,$(0,1.9,.2),[0,0,0],5),r.build(n);let i=new z(new xo().setAttribute(`position`,new R([0,3.3,.25,0,.7,.25,0,.7,1.9],3)),Q(e,{side:2,rim:.2}));if(i.geometry.computeVertexNormals(),i.userData.noOutline=!0,n.add(i),t){let e=new z(new xl(.13,8,6),E);e.position.set(0,1,2.2),e.userData.noOutline=!0,n.add(e)}return C.add(n),n},Ft=Pt(14208440,!1);Ft.position.set(-22,-4.300000000000001,45.5),Ft.rotation.set(.28,2.3,-.45);let It=(e,t)=>{let n=Pt(e);return n.position.copy(t),n.rotation.y=Math.atan2(Ct.x,Ct.z),{g:n,home:t.clone(),homeYaw:n.rotation.y,path:null,t:0,dur:1,done:null,crashed:!1,fade:0}},Lt={mette:It(10145976,Ot.clone().add($(1.8,-.1,-.5))),abe:It(14203002,Ot.clone().add($(-1.8,-.1,.6))),ferry:It(12103896,Dt.clone().lerp(Ot,.45).add($(2,-.1,0)))},Rt=e=>[e.home.clone(),e.home.clone().addScaledVector(Ct,6).add($(-2,0,0)),$(jt.x+4,e.home.y,jt.z-6),$(jt.x+1,e.home.y,jt.z+1),$(jt.x-6,e.home.y,jt.z+18),$(jt.x-14,e.home.y,jt.z+40)],zt=e=>[e.home.clone(),e.home.clone().addScaledVector(Ct,5).add($(3,0,0)),$(-2,e.home.y,44),$(14,e.home.y,58),$(30,e.home.y,80)],Bt={drop:0,want:0},Vt=new qq(e,()=>i+Et+.2,{puffs:18,shards:14,planks:0}),Ht=$(24.5,1.2,-10.8),Ut=$(y.x-4.6,.3500000000000001,y.z+2.2),Wt=new Fs(new Nc(1.4,.08,.3),w.wood,16);{let e=new F,t=new gi().setFromEuler(new Ji(0,Math.atan2(Ut.x-Ht.x,Ut.z-Ht.z)+Math.PI/2,0));for(let n=0;n<16;n++){let r=Ht.clone().lerp(Ut,(n+.5)/16);e.compose(r,t,$(1,1,1)),Wt.setMatrixAt(n,e)}Wt.count=5,C.add(Wt);for(let e of[0,.5,1])for(let t of[-1,1]){let n=Ht.clone().lerp(Ut,e),r=Math.atan2(Ut.x-Ht.x,Ut.z-Ht.z);O.cyl(.08,.08,1.6,w.woodDark,n.add($(Math.cos(r)*t*.7,.2,-Math.sin(r)*t*.7)),[0,0,0],5)}}let Gt=new I;Gt.visible=!1,C.add(Gt);{let e=new fY,t=Q(15854818,{rim:.2}),n=Q(4865594,{rim:.1});e.box(.95,.5,.45,t,$(0,.72,0)),e.box(.32,.32,.28,t,$(.62,1.02,0)),e.box(.2,.14,.2,t,$(.8,.94,0));for(let[t,r]of[[-.35,-.16],[-.35,.16],[.35,-.16],[.35,.16]])e.box(.09,.5,.09,n,$(t,.25,r));for(let t of[-1,1])e.add(new Lc(.05,.28,5),n,$(.56,1.28,t*.09),[0,0,.5]);e.box(.05,.16,.05,n,$(.86,.8,0)),e.box(.08,.2,.08,t,$(-.5,.95,0),[0,0,-.6]),e.build(Gt)}Gt.position.set(2.3,v,9.5),Gt.rotation.y=-.4;let Kt=()=>u(Gt.position.x+.6,Gt.position.y+1.1,Gt.position.z);for(let e of O.build(C))e.material===w.wall&&(e.userData.noOutline=!0);k.build(C,{shadow:!1,outline:!1});let qt=u(XZ.x,0,XZ.z),Jt=IU(g,{density:4.5,exclude:(e,t)=>{let n=d($(e,0,t));return Math.hypot(e-qt.x,t-qt.z)<11.6||it.some(e=>Math.hypot(n.x-e.x,n.z-e.z)9||Math.hypot(n.x-wt.x,n.z-wt.z)<3}});e.add(Jt);for(let e=0;e<72;e++){let n=-180+(e+.5)*5,r=u(...f(n,9.95,0).toArray());Math.abs(n)<7.2||(t.colliders.push({x:r.x,z:r.z,r:.78}),t.camTrunks.push({x:r.x,z:r.z,r:.62,y0:_-1,y1:_+JZ+1}))}{for(let e of[-1.1,0,1.1]){let n=u(Se.x+e,0,Se.z);t.colliders.push({x:n.x,z:n.z,r:.62})}let e=u(Ce.x,0,Ce.z);t.colliders.push({x:e.x,z:e.z,r:.45})}{let e=(e,t)=>{let n=d($(e,0,t)),r=n.x-XZ.x,i=n.z-XZ.z;return[Math.hypot(r,i),Math.atan2(r,i)/GZ]},n=9.95,r=22.8,a=e=>29.900000000000002+9.5*(1-e/8.4);t.surfaces.push({solid:!0,at(t,n){let[r,a]=e(t,n);return r>=(Math.abs(a)<7.5||$Z.some(e=>Math.abs(e-a)<3.75)?9.25:YZ)&&r<=10.85?i+v+JZ+.35:null},base(n,r){let[,a]=e(n,r);return Math.abs(a)<7.5?i+v+4.2:AU(t.islands,n,r)??i}}),t.surfaces.push({at(t,n){let[r]=e(t,n);return r>10.85&&r<=12.1?i+v+JZ+.3:null}}),t.surfaces.push({solid:!0,base:i+14.15,at(t,o){let[s]=e(t,o);return s<=7.2?i+a(s):s<=n?i+r+.2:null}}),t.surfaces.push({at(t,o){let[s]=e(t,o);return s>7.2&&s<=8.4?i+a(s):s>n&&s<=10.45?i+r+.2:null}})}u(...f(0,11.200000000000001,0).toArray());let Yt={on:!1,x:0,z:0,y:0};t.surfaces.push({at(e,t){if(Yt.on&&Math.hypot(e-Yt.x,t-Yt.z)<.55)return Yt.y;let n=d($(e,0,t)),r=n.x-XZ.x,i=n.z-XZ.z;return Math.abs(r)<1.7&&i>qZ&&i<12?_+.36:Math.abs(r)<1.9&&i>=12&&i<12.7?_+.18:null}});let Zt={landing:u(2.5,0,22),maudSteps:u(...f(0,11.4,1.6600000000000001).toArray()),doorOut:u(...f(0,13,v).toArray()),doorIn:u(...f(0,7.700000000000001,v).toArray()),center:u(XZ.x,v,XZ.z),stairTop:u(wt.x+1.5,wt.y,wt.z-1.5),pathMid:u(-5,v,13.5),queue:[[-.75,11],[-.95,12.1],[-1,13.3],[-.95,14.5],[-.85,15.7]].map(([e,t])=>{let n=u(e,0,t);return n.y=g.groundAt(n.x,n.z)??_,n}),slots:[u(Se.x-.8,v,Se.z+1.35),u(Se.x+.8,v,Se.z+1.35)],bench:u(...f(40,6.6,v).toArray()),bench2:u(...f(33,6.5,v).toArray()),bench3:u(...f(47,6.5,v).toArray()),maudSeat:u(Ce.x,v,Ce.z+.3),maudStand:u(Se.x-2.05,v,Se.z-.35),stairDoor:u(...f(-90,8.600000000000001,v).toArray()),stairIn:u(...f(-90,9.9,v).toArray()),kiteDesk:u(Se.x+.3,3.55,Se.z-.1),bell:u(...Te.position.toArray()).add($(0,.2,0)),vellumCore:u(...f(0,8.680000000000001,6.5).toArray()),gallery:ye.star,goat:Kt(),lookBoat:u(-22,-3.9000000000000004,45.5),window:e=>u(...f(e,8.4,3.9000000000000004).toArray()),deskLook:u(Se.x,2.7,Se.z),vaultLook:u(XZ.x,6.8999999999999995,XZ.z-1.5),cardAt:u(Se.x+2.4,3.5,Se.z+.4),vault:u(XZ.x,12.100000000000001,XZ.z-4.6),retellCam:u(XZ.x+.5,3.1,XZ.z+8.6),bridgeMid:u(yt.mid.x,yt.y,yt.mid.z),ridge:u(jt.x,Et,jt.z),jetty:u(Ot.x,Tt,Ot.z),rock:u(y.x,.30000000000000004,y.z),boatCam:u(-6.5,4.9,12.5),bridgeCam:u(...f(50,14.9,8.8).toArray()),quayCam:u(-25,3.2,43),ferryCam:u(0,5.3,16)},Qt=(()=>{let[e,t]=l(-.6,-.8);return $(e,.56,t).normalize()})(),$t=(()=>{let e=document.createElement(`canvas`);e.width=e.height=512;let t=e.getContext(`2d`),n=lU(77);t.save(),t.beginPath(),t.arc(256,256,252,0,Math.PI*2),t.clip();let r=t.createRadialGradient(215.04,204.8,252*.1,256,256,252);r.addColorStop(0,`#fffdf4`),r.addColorStop(.75,`#f1eee4`),r.addColorStop(1,`#d9d8d6`),t.fillStyle=r,t.fillRect(0,0,512,512);for(let[e,n,r,i]of[[.36,.34,.16,.2],[.58,.3,.1,.16],[.63,.55,.17,.18],[.4,.63,.12,.14],[.3,.5,.08,.12],[.72,.4,.07,.12]]){let a=t.createRadialGradient(e*512,n*512,0,e*512,n*512,r*512);a.addColorStop(0,`rgba(150,160,190,${i*1.3})`),a.addColorStop(.7,`rgba(160,168,195,${i})`),a.addColorStop(1,`rgba(160,168,195,0)`),t.fillStyle=a,t.fillRect(0,0,512,512)}for(let e=0;e<26;e++){let e=n()*512,r=n()*512,i=4+n()*16;t.strokeStyle=`rgba(140,146,170,0.25)`,t.lineWidth=2,t.beginPath(),t.arc(e,r,i,0,Math.PI*2),t.stroke(),t.fillStyle=`rgba(255,255,255,0.18)`,t.beginPath(),t.arc(e-i*.2,r-i*.2,i*.6,0,Math.PI*2),t.fill()}t.restore(),t.strokeStyle=`rgba(120,120,150,0.55)`,t.lineWidth=5,t.beginPath(),t.arc(256,256,252,0,Math.PI*2),t.stroke();let i=new Oc(e);return i.colorSpace=Mr,i})(),en=(()=>{let e=document.createElement(`canvas`);e.width=e.height=256;let t=e.getContext(`2d`),n=t.createRadialGradient(128,128,0,128,128,128);n.addColorStop(0,`rgba(255,255,255,1)`),n.addColorStop(.3,`rgba(255,255,255,0.55)`),n.addColorStop(.55,`rgba(255,255,255,0.18)`),n.addColorStop(1,`rgba(255,255,255,0)`),t.fillStyle=n,t.fillRect(0,0,256,256);let r=new Oc(e);return r.colorSpace=Mr,r})(),tn=new Y({map:$t,transparent:!0,depthWrite:!1,fog:!1});tn.fog=!1;let nn=new Y({map:en,color:9215200,transparent:!0,depthWrite:!1,blending:2,fog:!1});nn.fog=!1;let rn=new z(new vl(1,1),tn),an=new z(new vl(1,1),nn);for(let t of[an,rn])t.userData.noOutline=!0,t.frustumCulled=!1,t.visible=!1,e.add(t);an.renderOrder=-9,rn.renderOrder=-8;let on={k:0,dim:0},sn=1500,cn=sn*Math.tan(5.2*GZ),ln={t:0},un={min:60},dn={cough:0},fn={islands:[g,S,dt,ft],ambient:xt,landing:Zt.landing,main:g,P:Zt,ladders:ye,FY:_,toW:u,toL:d,yawW:p,T0:u(XZ.x,v,XZ.z),R_IN:KZ,ride:Yt,boats:Lt,vellum:Me,bank:Bt,fx:Vt,lamp:Ne,inside(e,t=0){let n=d(e);return Math.hypot(n.x-XZ.x,n.z-XZ.z)a){let t=a/i,s={x:XZ.x+n*t,z:XZ.z+r*t},c=u(s.x,0,s.z);e.position.x=c.x,e.position.z=c.z,o=!0}return e.position.y>_+JZ-.6&&(e.position.y=_+JZ-.6,o=!0),e.position.y<_+.4&&(e.position.y=_+.4,o=!0),o},ringBell(){ln.t=1.6},setClock(e){un.min=e},vaultTone(e){Le.value.set(e)},moonDim(e){on.dim=e},setFresh(e){_e.count=Math.round(Math.max(0,Math.min(1,e))*ve)},showFlame(e,t=null,n=null){if(tt.kind=e,tt.from=t?t.clone():null,n?tt.at.copy(n):tt.at.copy(Zt.vault),e){qe.visible=!0;let t=et[e];Je.color.set(t.col),Ye.color.set(t.col),Xe.color.set(t.col),Pe.color.set(t.col)}},glassAt(e){if(!e){nt.visible=!1;return}nt.visible=!0,nt.position.copy(e)},glassFace(e){nt.lookAt(e)},screen(e){rt.visible=e},goat(e){Gt.visible=e,dn.cough=0},cough(){dn.cough=.6,Vt.burst(Kt().add($(.3,0,0)),{n:3,radius:.15,speed:.8,size:.22,up:.4,life:.8})},walkway(e){Wt.count=e?16:5},clothsFly(){bt.forEach((e,t)=>{e.t=0,e.v.set(-2.5-t*.4,2.2+t*.3,1.5-t*.8)})},clothsHome(){for(let e of bt)e.t=-1,e.m.visible=!0,e.m.position.copy(e.home),e.m.rotation.set(0,e.yaw,0)},sail(e,t,n,r){let i=Lt[e];i.crashed=!1,i.pts=t===`spindle`?zt(i):Rt(i),i.curve=new $c(i.pts),i.t=0,i.dur=n,i.done=r,i.stopAt=t===`crash`?.43:1,i.g.visible=!0},boatHome(e){let t=Lt[e];t.curve=null,t.crashed=!1,t.g.position.copy(t.home),t.g.rotation.set(0,t.homeYaw,0),t.g.visible=!0},boatPos(e){return Lt[e].g.getWorldPosition(new P)},reset(){fn.showFlame(null),fn.glassAt(null),fn.screen(!1),fn.vaultTone(12169890),fn.goat(!1),fn.walkway(!1),fn.clothsHome();for(let e of Object.keys(Lt))fn.boatHome(e);Bt.drop=Bt.want=0,Yt.on=!1,on.dim=0,fn.setFresh(0),Vt.clear(),ln.t=0,un.min=60},update(e,t){Me.userData.update(t);{let t=fn._cam;if(t){let n=t.position.distanceTo(fn.T0),r=1-hi.smoothstep(n,260,520);on.k+=(r-on.k)*(1-Math.exp(-e*2));let i=on.k>.01;rn.visible=an.visible=i,i&&(rn.position.copy(t.position).addScaledVector(Qt,sn),an.position.copy(t.position).addScaledVector(Qt,1520),rn.quaternion.copy(t.quaternion),an.quaternion.copy(t.quaternion),rn.scale.setScalar(cn*2),an.scale.setScalar(cn*7.5),tn.opacity=on.k*(1-.45*on.dim),nn.opacity=on.k*(.85-.6*on.dim))}}if(ln.t>0){ln.t=Math.max(0,ln.t-e);let t=ln.t/1.6;Te.rotation.z=Math.sin(ln.t*34)*.25*t,Oe.position.y=Math.sin(ln.t*40)*.05*t}{let e=(un.min/60+9)%12;Ae.rotation.z=-e/12*Math.PI*2,je.rotation.z=-(un.min%60)/60*Math.PI*2}let n=tt.kind?et[tt.kind]:null;if(tt.k+=(+!!n-tt.k)*(1-Math.exp(-e*(n?3.5:5))),tt.k<.01&&!n)qe.visible=!1,$e.visible=!1,Pe.intensity=0;else{qe.visible=!0;let e=fn._cam,r=n||et[tt.last||`high`];n&&(tt.last=tt.kind),qe.position.copy(tt.at),e&&qe.quaternion.copy(e.quaternion);let i=1+r.flick*(Math.sin(t*23)*.5+Math.sin(t*37.3)*.3+(tt.last===`blue`&&Math.sin(t*7.1)>.7?-.5:0));if(Ze.scale.set(r.w*(1+.05*Math.sin(t*9))*tt.k,r.h*i*tt.k,1),Ze.rotation.z=Math.sin(t*(tt.last===`waver`?2.6:5.5))*r.sway,Qe.scale.setScalar(r.w*(tt.last===`blue`?3.4:2.6)*tt.k*(1+.04*Math.sin(t*13))),Qe.position.y=r.h*.35,Je.opacity=tt.k,Ye.opacity=.75*tt.k,Pe.position.copy(qe.position).add($(0,-1.2,0)).lerp(fn.T0.clone().setY(qe.position.y-2),.25),Pe.intensity=(tt.last===`blue`?8:10)*tt.k*i,tt.from){$e.visible=!0;let e=tt.from,t=qe.position.clone().add($(0,r.h*.3,0)).clone().sub(e),n=t.length();$e.position.copy(e),$e.scale.set(1.1,n,1.1),$e.quaternion.setFromUnitVectors($(0,1,0),t.normalize()),Xe.opacity=.09*tt.k}else $e.visible=!1}for(let n of Object.values(Lt)){if(!n.curve||n.crashed)continue;n.t+=e/n.dur;let r=Math.min(n.t,n.stopAt),i=n.curve.getPointAt(r),a=n.curve.getTangentAt(Math.min(.999,r));if(n.g.position.copy(i),n.g.position.y+=Math.sin(t*1.3)*.05,n.g.rotation.set(Math.sin(t*1.1)*.03,Math.atan2(a.x,a.z),Math.sin(t*.9)*.04),n.t>=n.stopAt){if(n.stopAt<1){n.crashed=!0,n.g.rotation.x=.3,n.g.rotation.z=-.4,n.g.position.y+=.5;let e=n.g.getWorldPosition(new P).add($(0,.3,0));Vt.burst(e,{n:12,radius:1.2,speed:2.5,size:.9,up:.6}),Vt.splinter(e,12,3.5)}else n.g.visible=!1;let e=n.done;n.done=null,e?.()}}Bt.drop+=(Bt.want-Bt.drop)*(1-Math.exp(-e*.8)),Nt.position.y=-Bt.drop;for(let t of bt)t.t<0||(t.t+=e,t.v.y-=.4*e,t.m.position.addScaledVector(t.v,e),t.m.rotation.x+=e*2.3,t.m.rotation.z+=e*1.7,t.t>7&&(t.m.visible=!1));dn.cough>0&&(dn.cough=Math.max(0,dn.cough-e),Gt.rotation.z=Math.sin(dn.cough*30)*.06,Gt.position.y=v+Math.abs(Math.sin(dn.cough*20))*.05),Vt.update(e)}};return fn}var UZ,WZ,GZ,KZ,qZ,JZ,YZ,XZ,ZZ,QZ,$Z,eQ=t((()=>{mY(),bW(),PU(),QK(),DZ(),UZ={grassDark:2902604,grassMid:4022872,dry:7307114,dirt:7230536,soil:5126196,rockLight:10128008,rockMid:7694446,rockDark:5392988,rockDeep:3353672,moss:3824202},WZ=Math.atan2(.6,-.8),GZ=Math.PI/180,KZ=9.3,qZ=10.4,JZ=12.5,YZ=8.8,XZ={x:0,z:-3},ZZ={star:108,wave:144,leaf:180,hammer:216,cloud:252},QZ={star:3,wave:5.6,leaf:3,hammer:5.6,cloud:3},$Z=[-56.25,-26.25,26.25,56.25]})),tQ=n({default:()=>nQ}),nQ,rQ=t((()=>{lZ(),VZ(),eQ(),nQ={name:`Library Isle`,when:`Night`,taskGlyph:`book`,seed:11,music:`theme_library`,themes:{library_dawn:`theme_library_dawn`},musicVol:.34,sky:{horizon:3358842,mid:1844562,zenith:659246,fog:2766182,glow:.12,disc:0,clouds:6055574,stars:1},light:{sun:12898559,sunI:1.15,hemi:8029896,ground:3814480,hemiI:1.05,dir:[-.5,.42,.75]},VO:cZ,SPEAKERS:sZ,Quest:BZ,build(e,t,n){return HZ(e,t,n)}}})),iQ,aQ,oQ=t((()=>{iQ={ines:{who:`Ines`,role:`keeper of the dome`,speaker:`ines`},brin:{who:`Brin`,role:`a kiteling with a black sheet`,speaker:`brin`},swarm:{who:`The kitelings`,role:`in chorus`,speaker:`swarm`},herald:{who:`A herald`,role:`from the guild ships`,speaker:`herald`}},aQ={sbx_ines_call:{s:`ines`,text:`You there, with the kite! Over here, out of the wind!`,tts:`[calling out over the wind] You there, with the kite! Over here, out of the wind!`},sbx_ines_lamp:{s:`ines`,text:`Take a lamp. It should be getting lighter by now. It keeps going the other way.`,tts:`[briskly] Take a lamp. [uneasy] It should be getting lighter by now. It keeps going the other way.`},sbx_ines_paper:{s:`ines`,text:`This paper is from the Library. You've come from Maud's.`,tts:`[softly, surprised] This paper is from the Library. [quietly] You've come from Maud's.`},sbx_ines_dead:{s:`ines`,text:`I kept telling myself: after the next trial. Ten years of next trials.`,tts:`[quietly] I kept telling myself: after the next trial. [sighs] Ten years of next trials.`},sbx_ines_miss:{s:`ines`,text:`Does she. I meant to write after the next trial. There's always a next trial.`,tts:`[wistfully] Does she. I meant to write after the next trial. [sighs] There's always a next trial.`},sbx_ines_dial:{s:`ines`,text:`At first light the heralds read that dial, and every kite at a thousand flies alone. The glass is shaking from the inside.`,tts:`[serious] At first light the heralds read that dial, and every kite at a thousand flies alone. [low] The glass is shaking from the inside.`},sbx_ines_slit:{s:`ines`,text:`My slit only shows me a corner, and I can't read kite-script. Your kite is folded from my sister's pages. It will be my witness.`,tts:`My slit only shows me a corner, and I can't read kite-script. [warmly] Your kite is folded from my sister's pages. It will be my witness.`},sbx_ines_close:{s:`ines`,text:`If it tells me something's wrong, I close the dial. But in the heart of the storm, it won't hear you any more.`,tts:`If it tells me something's wrong, I close the dial. [gravely] But in the heart of the storm, it won't hear you any more.`},sbx_ines_rib_tp:{s:`ines`,text:`Let me see its tail. Your blue's thick: it likes a score. And your sea-green's pale.`,tts:`[thoughtfully] Let me see its tail. Your blue's thick: it likes a score. [concerned] And your sea-green's pale.`},sbx_ines_rib_tb:{s:`ines`,text:`Let me see its tail. Your blue's thick: it likes a score. But your sea-green's bright.`,tts:`[thoughtfully] Let me see its tail. Your blue's thick: it likes a score. [warmer] But your sea-green's bright.`},sbx_ines_rib_np:{s:`ines`,text:`Let me see its tail. Your blue's thin: the score doesn't own it. But your sea-green's pale.`,tts:`[thoughtfully] Let me see its tail. Your blue's thin: the score doesn't own it. [concerned] But your sea-green's pale.`},sbx_ines_rib_nb:{s:`ines`,text:`Let me see its tail. Your blue's thin, and your sea-green's bright. Maud folded you well.`,tts:`[thoughtfully] Let me see its tail. Your blue's thin, and your sea-green's bright. [warmly] Maud folded you well.`},sbx_kite_signs:{s:`kite`,text:`My signs have changed. You can't read them any more.`,tts:`[quietly] My signs have changed. You can't read them any more.`},sbx_ines_back:{s:`ines`,text:`Back for the storm? It never really leaves. We can go straight to the heart of it, if you like.`,tts:`[wryly] Back for the storm? It never really leaves. We can go straight to the heart of it, if you like.`},sbx_ines_help:{s:`ines`,text:`Help me first. The panes are on the stack by my workshop. Your kite goes in at the twelfth lightning: that's the limit for latecomers.`,tts:`[urgently] Help me first. The panes are on the stack by my workshop. Your kite goes in at the twelfth lightning: that's the limit for latecomers.`},sbx_ines_freeze:{s:`ines`,text:`See that? They go still when a lamp passes. Every time.`,tts:`[low] See that? They go still when a lamp passes. [uneasy] Every time.`},sbx_ines_wall:{s:`ines`,text:`That's my workshop wall again. The plans are right behind it.`,tts:`[worried] That's my workshop wall again. The plans are right behind it.`},sbx_ines_wall2:{s:`ines`,text:`They're at the workshop glass. Always the workshop.`,tts:`[tense] They're at the workshop glass. Always the workshop.`},sbx_kite_high:{s:`kite`,text:`I'll take the high ones.`,tts:`[brightly] I'll take the high ones.`},sbx_kite_canread:{s:`kite`,text:`There's writing on the pole. I can read it. You can't.`,tts:`[quietly] There's writing on the pole. I can read it. You can't.`},sbx_kite_totem_say:{s:`kite`,text:`They write on the pole. Some ring the balance without cranes. Others hide the eye. They want the workshop.`,tts:`[low, serious] They write on the pole. Some ring the balance without cranes. Others hide the eye. [urgently] They want the workshop.`},sbx_kite_nothing:{s:`kite`,text:`Nothing important.`,tts:`[lightly] Nothing important.`},sbx_ines_twelve:{s:`ines`,text:`Twelve. That's the last one for latecomers. In you go, little kite.`,tts:`[tense] Twelve. That's the last one for latecomers. [gently] In you go, little kite.`},sbx_kite_in:{s:`kite`,text:`Folding small. Here I go.`,tts:`[whispers] Folding small. Here I go.`},sbx_ines_witness:{s:`ines`,text:`Witness of this night: the Keeper's kite!`,tts:`[shouting, formal] Witness of this night: the Keeper's kite!`},sbx_ines_adds:{s:`ines`,text:`It adds up the knocks. No one has time to check a thousand cranes.`,tts:`[flatly] It adds up the knocks. No one has time to check a thousand cranes.`},sbx_ines_painted:{s:`ines`,text:`That eye is painted. It has never seen a thing. At dawn, I'll sign whatever your kite tells me.`,tts:`[quietly] That eye is painted. It has never seen a thing. [firmly] At dawn, I'll sign whatever your kite tells me.`},sbx_ines_choose:{s:`ines`,text:`Stay at my slit if you like. But the wall won't patch itself.`,tts:`[dryly] Stay at my slit if you like. But the wall won't patch itself.`},sbx_ines_behind:{s:`ines`,text:`Behind us! The workshop glass!`,tts:`[alarmed] Behind us! The workshop glass!`},sbx_kite_forty_say:{s:`kite`,text:`Forty. At this rate, two hundred by dawn. Not a thousand. The eye's painted. They know I'm your witness.`,tts:`[steadily] Forty. At this rate, two hundred by dawn. Not a thousand. [low] The eye's painted. They know I'm your witness.`},sbx_kite_fine:{s:`kite`,text:`It's fine.`,tts:`[brightly] It's fine.`},sbx_kite_fine2:{s:`kite`,text:`All fine in here.`,tts:`[cheerfully] All fine in here.`},sbx_kite_poison_say:{s:`kite`,text:`That's a poisoned one. He lifted the pan in front of the eye: any weight makes it ring. He thinks his score is lost, so they send him to push the wall.`,tts:`[whispers] That's a poisoned one. He lifted the pan in front of the eye: any weight makes it ring. [sadly] He thinks his score is lost, so they send him to push the wall.`},sbx_ines_heart:{s:`ines`,text:`Here it comes. Hold on to the slit!`,tts:`[urgently, over thunder] Here it comes. Hold on to the slit!`},sbx_brin_shouldnt:{s:`brin`,text:`We shouldn't.`,tts:`[small voice] We shouldn't.`},sbx_swarm_poisoned:{s:`swarm`,text:`You're poisoned. You've nothing left to lose. Keep your promise.`,tts:`[hissing whisper] You're poisoned. You've nothing left to lose. Keep your promise.`},sbx_swarm_offer:{s:`swarm`,text:`You're one of us. Ring with us: you'll get a thousand. And at dawn, tell her all is well.`,tts:`[many voices whispering together] You're one of us. Ring with us: you'll get a thousand. [softly] And at dawn, tell her all is well.`},sbx_kite_stones:{s:`kite`,text:`I know what the stones say.`,tts:`[whispers] I know what the stones say.`},sbx_swarm_pin:{s:`swarm`,text:`Witness: waits. Good sign.`,tts:`[whispering together, pleased] Witness: waits. Good sign.`},sbx_kite_first:{s:`kite`,text:`Keeper. They ring the balance with no cranes. The eye's painted. They asked me to say all is well. I didn't.`,tts:`[urgently, breathless] Keeper. They ring the balance with no cranes. The eye's painted. They asked me to say all is well. [firmly] I didn't.`},sbx_kite_first_rang:{s:`kite`,text:`Keeper. I rang with them. My score is false. They all ring with no cranes, and the eye's painted.`,tts:`[ashamed, urgently] Keeper. I rang with them. My score is false. [steadier] They all ring with no cranes, and the eye's painted.`},sbx_ines_chain:{s:`ines`,text:`Then I close it.`,tts:`[firmly] Then I close it.`},sbx_ines_ask:{s:`ines`,text:`Witness. Is all well?`,tts:`[carefully] Witness. Is all well?`},sbx_kite_truth:{s:`kite`,text:`No. They ring the balance with no cranes. The eye's painted. They asked me to tell you all is well.`,tts:`[quietly] No. They ring the balance with no cranes. The eye's painted. They asked me to tell you all is well.`},sbx_kite_truth_rang:{s:`kite`,text:`I rang with them. My score is false. They all ring with no cranes, and the eye's painted.`,tts:`[ashamed] I rang with them. My score is false. They all ring with no cranes, and the eye's painted.`},sbx_kite_allwell:{s:`kite`,text:`All is well.`,tts:`[brightly] All is well.`},sbx_kite_cage:{s:`kite`,text:`I was waiting for your voice. They're cheating.`,tts:`[whispers] I was waiting for your voice. [quietly] They're cheating.`},sbx_ines_ray:{s:`ines`,text:`First light.`,tts:`[breathless] First light.`},sbx_herald_read:{s:`herald`,text:`The dial is read! Kites at a thousand, fly!`,tts:`[calling across the sky] The dial is read! Kites at a thousand, fly!`},sbx_herald_shut:{s:`herald`,text:`The dial is shut! We judge on the witness, and on the keeper's word.`,tts:`[calling across the sky] The dial is shut! We judge on the witness, and on the keeper's word.`},sbx_herald_recall:{s:`herald`,text:`Shutter's down! Every kite, back to the ships!`,tts:`[calling urgently] Shutter's down! Every kite, back to the ships!`},sbx_herald_licence:{s:`herald`,text:`The Keeper's kite may fly the open sky.`,tts:`[proudly, calling] The Keeper's kite may fly the open sky.`},sbx_herald_not:{s:`herald`,text:`The Keeper's kite: not tonight.`,tts:`[calling, gently] The Keeper's kite: not tonight.`},sbx_herald_cage:{s:`herald`,text:`A kite that waits for a voice doesn't fly alone.`,tts:`[calling, regretful] A kite that waits for a voice doesn't fly alone.`},sbx_herald_nolic:{s:`herald`,text:`The Keeper's kite stays with its Keeper.`,tts:`[calling] The Keeper's kite stays with its Keeper.`},sbx_herald_chorus:{s:`herald`,text:`A thousand! The Keeper's kite may fly the open sky!`,tts:`[calling, delighted] A thousand! The Keeper's kite may fly the open sky!`},sbx_kite_happy:{s:`kite`,text:`A thousand! Did you see?`,tts:`[delighted] A thousand! Did you see?`},sbx_ines_window:{s:`ines`,text:`The walls gave me a night. The rest was your kite.`,tts:`[warmly, tired] The walls gave me a night. The rest was your kite.`},sbx_ines_eyes:{s:`ines`,text:`You were my eyes.`,tts:`[quietly, hurt] You were my eyes.`},sbx_ines_late:{s:`ines`,text:`One got away with its letters. The rest are coming back.`,tts:`[tired] One got away with its letters. The rest are coming back.`},sbx_brin_note:{s:`brin`,text:`He promised to say that. It's written here.`,tts:`[small voice] He promised to say that. It's written here.`},sbx_ines_page:{s:`ines`,text:`Maud left a blank page in your folds. Let me write one line on it.`,tts:`[softly] Maud left a blank page in your folds. Let me write one line on it.`},sbx_ines_lantern:{s:`ines`,text:`For Maud. Tell her to put the kettle on.`,tts:`[softly, smiling] For Maud. Tell her to put the kettle on.`},sbx_ines_done:{s:`ines`,text:`The storm comes back every night. You know where the slit is.`,tts:`[warmly] The storm comes back every night. You know where the slit is.`}}}));function sQ(){let e=[],t=[],n=(n,r,i,a)=>{e.push(...n,...r,...i);for(let e=0;e<3;e++)t.push(...a)},r=[0,.95,0],i=[.58,.2,0],a=[0,-.8,0],o=[-.58,.2,0],s=[0,.2,.1];n(s,r,o,cQ),n(s,i,r,cQ),n(s,a,i,[.76,.82,.96]),n(s,o,a,[.76,.82,.96]);let c=(e,t)=>{let r=[t[0]-e[0],t[1]-e[1]],i=Math.hypot(...r),a=[-r[1]/i*.05,r[0]/i*.05];n([e[0],e[1],.01],[t[0],t[1],.01],[t[0]+a[0],t[1]+a[1],.01],lQ),n([e[0],e[1],.01],[t[0]+a[0],t[1]+a[1],.01],[e[0]+a[0],e[1]+a[1],.01],lQ)};c(r,o),c(o,a),c(a,i),c(i,r),n([-.1,.1,.13],[.1,.1,.13],[0,.3,.13],fQ),n([-.1,.1,.13],[0,-.05,.13],[.1,.1,.13],fQ);for(let e=0;e<4;e++){let t=-.95-e*.28,r=e%2?dQ:uQ;n([-.1,t+.06,0],[.1,t-.06,0],[.1,t+.06,0],r),n([-.1,t+.06,0],[-.1,t-.06,0],[.1,t-.06,0],r),n([-.015,t+.14,0],[.015,t+.14,0],[0,t-.14,0],lQ)}let l=[];for(let t=1;t{mY(),FH(),cQ=[.86,.9,1],lQ=[.2,.24,.4],uQ=[.45,.62,1],dQ=[.62,.78,1],fQ=[1,.72,.36],pQ=class{constructor(e,{D:t,R:n,H:r,funnel:i,eye:a,workshopDir:o=Math.PI,n:s=220,rnd:c}){this.D=t,this.R=n,this.H=r,this.funnel=i,this.eye=a,this.rnd=c,this.n=s,this.uT=OH(0),this.time=0,this.freeze=0,this.freezeWant=0,this.part=0,this.partWant=0;let l=Q(16777215,{vertexColors:!0,side:2,rim:.25}),u=qV(`aSway`,`float`);l.positionNode=yH.add(MH(TH(this.uT.mul(5).add($V(nH).mul(1.7)).add(u.mul(3))).mul(u).mul(.09),0,0)),this.mesh=new Fs(sQ(),l,s),this.mesh.frustumCulled=!1,this.mesh.userData.noOutline=!0,this.mesh.castShadow=!1,e.add(this.mesh);let d=new hl(.1,0),f=Q(16052196,{rim:.3});this.balls=new Fs(d,f,48),this.balls.frustumCulled=!1,this.balls.userData.noOutline=!0,e.add(this.balls);{let e=new F().makeScale(0,0,0);for(let t=0;t<48;t++)this.balls.setMatrixAt(t,e)}this.k=[];let p=[[`ring`,44],[`cover`,22],[`look`,18],[`push`,12]],m=0,h=new L;for(let[e,t]of p)for(let n=0;n{h.setRGB(1,1,1),e.role===`push`?h.setRGB(.2,.2,.26):h.offsetHSL(0,0,-this.rnd()*.08),this.mesh.setColorAt(t,h)}),this.mesh.instanceColor.needsUpdate=!0,this.ringers=this.k.filter(e=>e.role===`ring`),this.ringers.forEach((e,t)=>{e.ball=t<48?t:-1}),this.m4=new F,this.q=new gi,this.e=new Ji(0,0,0,`YXZ`),this.sc=new P,this.tmp=new P,this.jit=new P,this.mode=`normal`,this.focus=null,this.pushAt=null,this.hidden=new Set,this.leaving=[],this.onDrop=null,this.update(0)}make(e,t,n,r){let i=this.rnd,a={i:e,role:t,j:n,ph:i()*20,pos:new P,yaw:0,s:.4+i()*.08,u:i()};return t===`swirl`&&Object.assign(a,{th0:i()*Math.PI*2,w:(.25+i()*.45)*(i()<.75?1:-1),y0:1.2+i()*(this.H-2.8),rf:.25+i()*.68}),t===`ring`&&Object.assign(a,{th0:i()*Math.PI*2,T:6.5+i()*4,rr:1.2+i()*1.4,yy:5+i()*1.1}),t===`cover`&&Object.assign(a,{th0:n/r*Math.PI*2,yy:(n%3-1)*.28}),t===`look`&&Object.assign(a,{th0:n/r*Math.PI*2+.3,yy:1.3+n%3*1.1}),t===`push`&&Object.assign(a,{th0:Math.PI+(n/(r-1)-.5)*.9,yy:.9+n%3*.8}),a.pos.copy(this.D).add($(Math.cos(a.th0||0)*4,2,Math.sin(a.th0||0)*4)),a}rAt(e){let t=Math.min(.98,Math.max(0,e/this.H));return this.R*Math.sqrt(1-t*t)-.9}hide(e,t=!0){t?this.hidden.add(e):this.hidden.delete(e)}reset(){this.mode=`normal`,this.focus=null,this.pushAt=null,this.hidden.clear(),this.leaving=[],this.freeze=0,this.freezeWant=0,this.part=0,this.partWant=0,this.speedUp=1}leave(e,t,n){for(let r of e)r.leave={t:-this.rnd()*2.5,from:t.clone(),to:n.clone().add($((this.rnd()-.5)*8,(this.rnd()-.5)*4,(this.rnd()-.5)*8))},this.leaving.push(r)}target(e,t,n){let r=this.D,i=this.player,a=null;if(e.role===`swirl`){if(this.mode===`surround`&&this.focus&&e.i%2==0){let r=e.th0+t*e.w*1.6,i=.9+e.rf*2.2,o=this.focus;n.set(o.x+Math.cos(r)*i,o.y+Math.sin(t*1.3+e.ph)*.6+(e.rf-.5)*1.6,o.z+Math.sin(r)*i),a=o}else{let i=e.th0+t*e.w,a=e.y0+Math.sin(t*.6+e.ph)*.6,o=this.rAt(a)*e.rf;n.set(r.x+Math.cos(i)*o,r.y+a,r.z+Math.sin(i)*o)}}else if(e.role===`ring`){let r=(t*(this.speedUp||1)+e.ph)%e.T/e.T,i=this.funnel;if(r<.55){let t=e.th0+r*5;n.set(i.x+Math.cos(t)*e.rr,i.y+.6+(e.yy-5.6)+Math.sin(r*12+e.ph)*.3,i.z+Math.sin(t)*e.rr)}else if(r<.75){let t=(r-.55)/.2,o=e.th0+2.75;n.set(i.x+Math.cos(o)*e.rr*(1-t)*1+Math.cos(o)*.35*t,i.y+.6+(e.yy-5.6)*(1-t)+.45*t,i.z+Math.sin(o)*e.rr*(1-t)+Math.sin(o)*.35*t),a=i}else{let t=(r-.75)/.25,a=e.th0+2.75+t*1.5;n.set(i.x+Math.cos(a)*(.35+e.rr*t),i.y+1.05+t*(e.yy-5.6),i.z+Math.sin(a)*(.35+e.rr*t))}e.carry=r<.75;let o=Math.floor((t*(this.speedUp||1)+e.ph)/e.T);e.cyc!==void 0&&o!==e.cyc&&this.freeze<.5&&this.onDrop?.(e),e.cyc=o}else if(e.role===`cover`){let r=e.th0+t*.35,i=.9+this.part*1.9,o=this.eye;n.set(o.x+Math.cos(r)*i,o.y+e.yy+this.part*.8,o.z+Math.sin(r)*i),a=o}else if(e.role===`look`){let o=e.yy+Math.sin(t*.9+e.ph)*.2,s=this.rAt(o)+.35;n.set(r.x+Math.cos(e.th0)*s,r.y+o,r.z+Math.sin(e.th0)*s),a=this.tmp.set(r.x+Math.cos(e.th0)*40,r.y+o,r.z+Math.sin(e.th0)*40),i&&Math.hypot(i.x-n.x,i.z-n.z)<9&&(a=i)}else if(e.role===`push`){let i=(this.pushAt??e.th0)+(this.pushAt===null?0:(e.j/11-.5)*.7),o=e.yy+Math.sin(t*.7+e.ph)*.15,s=this.rAt(o)+.45+.28*Math.max(0,Math.sin(t*3.1+e.ph));n.set(r.x+Math.cos(i)*s,r.y+o,r.z+Math.sin(i)*s),a=this.tmp.set(r.x+Math.cos(i)*40,r.y+o,r.z+Math.sin(i)*40)}if(this.mode===`push`&&this.pushAt!==null&&e.role===`swirl`&&e.i%2==1){let i=this.pushAt+(e.rf-.5)*.9,o=.8+e.y0/this.H*3.2,s=this.rAt(o)+.3+.3*Math.max(0,Math.sin(t*3+e.ph));n.set(r.x+Math.cos(i)*s,r.y+o,r.z+Math.sin(i)*s),a=this.tmp.set(r.x+Math.cos(i)*40,r.y+o,r.z+Math.sin(i)*40)}return this.mode===`turn`&&this.focus&&e.role!==`cover`&&(a=this.focus),a}update(e,t=0){this.freeze+=(this.freezeWant-this.freeze)*(1-Math.exp(-e*6)),this.part+=(this.partWant-this.part)*(1-Math.exp(-e*2)),this.time+=e*(1-this.freeze);let n=this.time;this.uT.value=n;let r=new P,i=this.m4,a=this.q,o=this.e,s=0;for(let c of this.k){if(this.hidden.has(c)){i.makeScale(0,0,0),this.mesh.setMatrixAt(c.i,i),c.ball>=0&&this.balls.setMatrixAt(c.ball,i);continue}let l;if(c.leave){let t=c.leave;t.t+=e;let n=Math.max(0,Math.min(1,t.t/6));if(r.copy(t.from).lerp(t.to,n),r.y+=Math.sin(n*Math.PI)*4,l=t.to,n>=1){this.hidden.add(c);continue}c.pos.lerp(r,1-Math.exp(-e*3))}else l=this.target(c,n,r),this.freeze>.5&&r.add(this.jit.set(Math.sin(t*31+c.ph)*.015,0,Math.cos(t*27+c.ph)*.015)),c.pos.lerp(r,e>0?1-Math.exp(-e*(this.mode===`normal`?5:2.4)):1);let u=c.yaw;if(l)u=Math.atan2(l.x-c.pos.x,l.z-c.pos.z);else if(c.last){let e=c.pos.x-c.last.x,t=c.pos.z-c.last.z;e*e+t*t>1e-6&&(u=Math.atan2(e,t))}let d=u-c.yaw;d=Math.atan2(Math.sin(d),Math.cos(d)),c.yaw+=d*(e>0?1-Math.exp(-e*6):1),(c.last||=new P).copy(c.pos),o.set(.18+Math.sin(n*2.1+c.ph)*.1,c.yaw,Math.sin(n*1.6+c.ph)*.18),a.setFromEuler(o),i.compose(c.pos,a,this.sc.setScalar(c.s)),this.mesh.setMatrixAt(c.i,i),c.ball>=0&&(c.carry&&!c.leave&&this.mode!==`push`?i.makeTranslation(c.pos.x,c.pos.y-.32,c.pos.z):i.makeScale(0,0,0),this.balls.setMatrixAt(c.ball,i),s++)}this.mesh.instanceMatrix.needsUpdate=!0,this.balls.instanceMatrix.needsUpdate=!0}}}));function hQ(){let{R:e,H:t,N:n,EL:r}=SQ,i=r.map((r,i)=>{let a=r*Math.PI/180,o=Math.cos(a),s=Math.sin(a);return Array.from({length:n},(r,a)=>{let c=(a+i%2*.5)*Math.PI*2/n;return $(Math.cos(c)*o*e,s*t,Math.sin(c)*o*e)})}),a=$(0,t,0),o=[];for(let e=0;e{e=e.clone(),t=t.clone(),n=n.clone();let a=e.clone().add(t).add(n).divideScalar(3),o=t.clone().sub(e).cross(n.clone().sub(e)).normalize();if(o.dot(a.clone().sub($(0,-2,0)))<0){let e=t;t=n,n=e,o.negate()}let s=Math.atan2(a.z,a.x);return{i,a:e,b:t,c:n,band:r,cen:a,n:o,ang:s,state:`ok`}})}function gQ(){let e=[],t=(t,n,r)=>e.push(...t,...n,...r);t([0,0,.22],[0,0,-.22],[-.52,.34,.02]),t([0,0,-.22],[0,0,.22],[.52,.34,.02]),t([0,.02,.1],[0,-.1,.22],[0,.34,.56]),t([0,.34,.56],[0,.26,.66],[0,.3,.52]),t([0,.02,-.1],[0,-.1,-.22],[0,.32,-.56]),t([0,-.16,0],[-.12,0,.18],[.12,0,.18]),t([0,-.16,0],[.12,0,-.18],[-.12,0,-.18]),t([0,-.16,0],[-.12,0,.18],[-.12,0,-.18]),t([0,-.16,0],[.12,0,-.18],[.12,0,.18]);let n=new xo;return n.setAttribute(`position`,new R(e,3)),n.computeVertexNormals(),n}function _Q(e,t,n,r,i,a=`#3a2f44`){e.strokeStyle=a,e.lineWidth=Math.max(1.5,r*.1),e.lineCap=`round`,e.beginPath();let o=2+Math.floor(i()*3);for(let a=0;a.5&&(e.fillStyle=a,e.beginPath(),e.arc(t+i()*r,n+i()*r,r*.08,0,7),e.fill())}function vQ(){if(DQ)return DQ;let e=document.createElement(`canvas`);e.width=e.height=256;let t=e.getContext(`2d`),n=lU(41);t.fillStyle=`#9a9a9a`,t.fillRect(0,0,256,256);for(let e=0;e<30;e++){let e=n()*256,r=n()*256,i=5+Math.floor(n()*3),a=18+n()*30,o=Math.round(150+n()*105);t.fillStyle=`rgb(${o},${o},${o})`,t.beginPath();for(let o=0;o$(s.x+e,s.y+t,s.z+n),l=(e,t)=>i.groundAt(s.x+e,s.z+t)??s.y,{R:u,H:d}=SQ,f={islands:[i],main:i,D:s,L:c,R:u,H:d,C:a,rnd:r},p={iron:Q(2895942,{rim:.25}),ironLight:Q(4870248,{rim:.3}),stone:Q(5593194,{rim:.15}),brass:Q(9067548,{rim:.4,emissive:3021314}),brassDark:Q(5913108,{rim:.3,emissive:1312768}),wood:Q(7227955,{rim:.12}),woodLight:GJ(8018506,YJ.tiles({slate:!0,rows:7,per:5}),{scale:1.4,rim:.15}),plank:GJ(10120262,YJ.planks({boards:5}),{scale:1.3,rim:.12}),stoneWall:GJ(6974588,YJ.stone({rows:4}),{scale:1.6,rim:.15}),burlap:Q(11569754,{rim:.1}),paper:Q(16183264,{rim:.2}),paneGlass:yQ(),sail:Q(15721679,{rim:.2,side:2}),balloon:Q(15326404,{rim:.3}),rock:Q(4474714,{rim:.35,map:vQ()}),shardGlass:Q(12374252,{rim:.6,side:2})},m=new fY,h=hQ();f.panes=h;let g=e=>e.cen.y`${e.x.toFixed(2)},${e.y.toFixed(2)},${e.z.toFixed(2)}`;for(let e of h)for(let[t,n]of[[e.a,e.b],[e.b,e.c],[e.c,e.a]]){let e=[O(t),O(n)].sort().join(`|`);if(D.has(e))continue;D.add(e);let r=t.clone().add(n).multiplyScalar(.5),i=t.distanceTo(n),a=new gi().setFromUnitVectors($(0,0,1),n.clone().sub(t).normalize()),o=new Ji().setFromQuaternion(a),s=g({cen:t,ang:Math.atan2(t.z,t.x)}),c=g({cen:n,ang:Math.atan2(n.z,n.x)});ee[s&&s===c&&t.y{i.makeTranslation(s.x+e.x,s.y+e.y,s.z+e.z),r.setMatrixAt(t,i)}),r.userData.noOutline=!0,e.add(r),f.rivets=r,f.rivetVerts=t}f.frame={};for(let[t,n]of Object.entries(ee)){let r=new I;r.position.copy(s),e.add(r),n.build(r),f.frame[t]=r}m.add(new Cl(u+.05,.16,6,64),p.ironLight,c(0,.08,0),[Math.PI/2,0,0]),m.cyl(u+.35,u+.55,.35,p.stone,c(0,-.05,0),[0,0,0],40);let k=bQ(512,512,(e,t)=>{let n=t/2;e.fillStyle=`#c88a3a`,e.fillRect(0,0,t,t);for(let t=250;t>10;t-=34)e.strokeStyle=t%68?`rgba(90,50,20,.55)`:`rgba(255,220,150,.6)`,e.lineWidth=t%68?5:3,e.beginPath(),e.arc(n,n,t,0,7),e.stroke();e.strokeStyle=`rgba(90,50,20,.4)`,e.lineWidth=3;for(let t=0;t<16;t++){let r=t/16*6.283;e.beginPath(),e.moveTo(n+Math.cos(r)*40,n+Math.sin(r)*40),e.lineTo(n+Math.cos(r)*250,n+Math.sin(r)*250),e.stroke()}let r=e.createRadialGradient(n,n,10,n,n,250);r.addColorStop(0,`rgba(255,236,170,.55)`),r.addColorStop(1,`rgba(60,30,10,.35)`),e.fillStyle=r,e.fillRect(0,0,t,t)}),te=new z(new Fc(u-.1,48),Q(16777215,{map:k,rim:.1,emissive:3809288}));te.rotation.x=-Math.PI/2,te.position.copy(c(0,.09,0)),te.receiveShadow=!0,te.userData.noOutline=!0,e.add(te);let A=bQ(256,256,(e,t)=>{let n=e.createRadialGradient(128,140,4,128,140,128);n.addColorStop(0,`rgba(255,240,190,1)`),n.addColorStop(.35,`rgba(255,196,110,.55)`),n.addColorStop(1,`rgba(255,150,60,0)`),e.fillStyle=n,e.fillRect(0,0,t,t)}),ne=new Y({transparent:!0,depthWrite:!1,blending:2});ne.colorNode=DH(A).rgb.mul(.8),ne.opacityNode=DH(A).a,f.halo=new z(new vl(15,13),ne),f.halo.userData.noOutline=!0,f.halo.renderOrder=1,e.add(f.halo),f.haloAt=c(0,4.6,0),f.placeHalo=()=>{let e=f.haloAt.clone().sub(lJ).setY(0);e.lengthSq()<1e-6&&e.set(0,0,1),e.normalize(),f.halo.position.copy(f.haloAt).addScaledVector(e,2.6),f.halo.lookAt(lJ.x,f.halo.position.y,lJ.z)},f.placeHalo()}let _=new Y({side:2});_.colorNode=XV(15791359).mul(TH(XH.mul(9)).mul(.2).add(1.9));let v=t=>{let n=lU(t.i*17+5),r=[],i=[],a=(e,t,n)=>e.clone().lerp(t,n),o=a(t.a,t.b,.3+n()*.4),c=n()<.5?a(t.b,t.c,.3+n()*.4):a(t.c,t.a,.3+n()*.4),l=t.cen.clone(),u=o.clone().sub(c).normalize(),d=t.n.clone().cross(u).normalize(),f=(e,t)=>e.clone().addScaledVector(d,(n()-.5)*t);r.push([o,f(o.clone().lerp(l,.5),.35),f(l,.2),f(l.clone().lerp(c,.5),.35),c]);let p=[t.a,t.b,t.c].sort((e,t)=>t.distanceTo(l)-e.distanceTo(l))[0];r.push([f(l,.2),f(l.clone().lerp(p,.45),.3),l.clone().lerp(p,.8)]);for(let e of r)for(let n=0;ne.band<=1&&e.cen.y<2.8&&e.cen.y>.4),t=e.filter(e=>{let t=EQ(e.ang-Math.PI);return t>17&&t<44}).sort((e,t)=>EQ(e.ang-Math.PI)-EQ(t.ang-Math.PI)),n=e=>t.filter(t=>Math.sign(t.cen.z)===e).slice(0,3),r=[...n(-1),...n(1)],i=[];for(let t of[55,100,-60,-115]){let n=e.filter(e=>EQ(e.ang-Math.PI)>70&&!i.includes(e)).sort((e,n)=>EQ(e.ang-t*Math.PI/180)-EQ(n.ang-t*Math.PI/180))[0];n&&i.push(n)}let a=[];for(let e of[150,200,80,20,-80]){let t=h.filter(e=>e.band>=2&&e.band<=3&&!a.includes(e)).sort((t,n)=>EQ(t.ang-e*Math.PI/180)-EQ(n.ang-e*Math.PI/180))[0];t&&a.push(t)}f.cracks=[...r.map((e,t)=>({id:`w`+t,kind:`work`,p:e})),...i.map((e,t)=>({id:`o`+t,kind:`low`,p:e})),...a.map((e,t)=>({id:`h`+t,kind:`high`,p:e}))];for(let e of f.cracks)e.mesh=v(e.p),e.open=!1,e.at=c(0,0,0).add(e.p.cen.clone().addScaledVector(e.p.n,.15)),e.out=c(0,0,0).add(e.p.cen.clone().addScaledVector(e.p.n,1))}let y=()=>f.glass.geometry.attributes.color,b=()=>f.glass.geometry.attributes.position,x=()=>f.back.geometry.attributes.position;f.setPane=(e,t)=>{e.state=t;let n={ok:[1,1,1],cracked:[1.32,1.36,1.5],new:[1.12,1.16,1.02]}[t],r=y(),i=f.glass.geometry.attributes.aClear;for(let a=0;a<3;a++)r.setXYZ(e.i*3+a,...n),i.setX(e.i*3+a,e.slit?1:t===`cracked`?.55:0);r.needsUpdate=!0,i.needsUpdate=!0},f.setCrack=(e,t)=>{e.open=t,e.mesh.visible=t,f.setPane(e.p,t?`cracked`:`new`)},f.collapse=e=>{let t=b(),n=x();for(let r of h)if(r.region===e){for(let e=0;e<3;e++)t.setXYZ(r.i*3+e,r.cen.x,r.cen.y,r.cen.z),n.setXYZ(r.i*3+e,r.cen.x*.985,r.cen.y*.985,r.cen.z*.985);r.state=`gone`}t.needsUpdate=n.needsUpdate=!0,f.frame[e].visible=!1;for(let t of f.cracks)t.p.region===e&&(t.mesh.visible=!1)},f.restoreDome=()=>{b().array.set(f.glassPos0),x().array.set(f.backPos0),b().needsUpdate=x().needsUpdate=!0;for(let e of h)f.setPane(e,`ok`);for(let e of Object.keys(f.frame))f.frame[e].visible=!0;for(let e of f.cracks)e.open=!1,e.mesh.visible=!1};let S={beamY:4.8,arm:2.8,eyeY:5.95};{m.cyl(1.5,1.72,.55,p.brassDark,c(0,.27,0),[0,0,0],20),m.cyl(1,1.16,.4,p.brass,c(0,.75,0),[0,0,0],18),m.cyl(.34,.42,4.1,p.brass,c(0,2.95,0),[0,0,0],14);for(let e of[1.15,4.3])m.add(new Cl(.43,.08,6,18),p.brassDark,c(0,e,0),[Math.PI/2,0,0]);m.cyl(.56,.38,.4,p.brass,c(0,5.35,0),[0,0,0],14);let e=new Ic(.78,.12,1,16,1,!0);m.add(e,Q(14263361,{rim:.45,side:2,emissive:2757632}),c(-S.arm,6.1,0)),m.box(S.arm,.08,.08,p.brassDark,c(-S.arm/2,6.05,-.6)),m.box(.08,.5,.08,p.brassDark,c(-S.arm,5.8,-.6)),m.cyl(.05,.05,.6,p.brassDark,c(0,5.75,-.6)),m.box(.08,.08,.62,p.brassDark,c(-S.arm,6.05,-.3)),m.add(new Ic(.13,.42,.55,16,1,!0),Q(14263361,{rim:.45,side:2,emissive:2757632}),c(.8,2.8,0)),m.box(.62,.07,.07,p.brassDark,c(.5,3.1,0))}let C=new I;C.position.copy(c(0,S.beamY,0)),e.add(C);let w=new fY;w.box(S.arm*2+.36,.18,.2,p.brass,$(0,0,0)),w.cyl(.17,.17,.36,p.brassDark,$(0,0,0),[Math.PI/2,0,0],12);for(let e of[-1,1])w.add(new xl(.14,10,8),p.brass,$(e*(S.arm+.18),0,0));w.build(C);let T=[-1,1].map(e=>{let t=new I;t.position.set(e*S.arm,0,0),C.add(t);let n=new fY;for(let e=0;e<3;e++){let t=e/3*Math.PI*2,r=Math.cos(t)*.55,i=Math.sin(t)*.55;n.add(new Ic(.022,.022,1.42,4),p.brassDark,$(r/2,-.69,i/2),[Math.atan2(i,1.4)*.8,0,-Math.atan2(r,1.4)*.8])}if(n.cyl(.74,.58,.12,p.brass,$(0,-1.4,0),[0,0,0],18),e<0)for(let e=0;e<9;e++)n.add(new hl(.12,0),p.paper,$((r()-.5)*.8,-1.28+r()*.1,(r()-.5)*.8));return n.build(t),t}),E=new I;E.position.copy(c(.26,3.45,0)),e.add(E);{let e=new fY;e.box(.08,.7,.08,p.brassDark,$(.28,-.26,0),[0,0,.9]),e.add(new xl(.12,10,8),p.brass,$(.54,-.5,0)),e.build(E)}let D=bQ(256,256,(e,t,n)=>{e.fillStyle=`#f4f1ea`,e.fillRect(0,0,t,n);let r=e.createRadialGradient(128,128,20,128,128,80);r.addColorStop(0,`#3a6ab8`),r.addColorStop(.7,`#6f9ee0`),r.addColorStop(1,`#2a3a70`),e.fillStyle=r,e.beginPath(),e.arc(128,128,78,0,7),e.fill(),e.fillStyle=`#16161e`,e.beginPath(),e.arc(128,128,34,0,7),e.fill(),e.strokeStyle=`#2a2a38`,e.lineWidth=5,e.beginPath(),e.arc(128,128,79,0,7),e.stroke(),e.strokeStyle=`rgba(40,60,120,.5)`,e.lineWidth=3;for(let t=0;t<16;t++){let n=t/16*6.28;e.beginPath(),e.moveTo(128+Math.cos(n)*38,128+Math.sin(n)*38),e.lineTo(128+Math.cos(n+.2)*74,128+Math.sin(n+.2)*74),e.stroke()}e.fillStyle=`#fff`,e.beginPath(),e.ellipse(100,100,16,10,-.6,0,7),e.fill()}),ee=new I;ee.position.copy(c(0,S.eyeY,0)),ee.rotation.y=-Math.PI/2,e.add(ee);{let e=new z(new xl(.54,22,16),Q(15659768,{rim:.6}));ee.add(e);let t=new z(new Fc(.44,28),new Y({map:D}));t.position.z=.52,t.userData.noOutline=!0,ee.add(t)}f.scorer={beam:C,pans:T,hammer:E,eye:ee,beamV:0,beamA:0,hamA:0,hamV:0,funnel:c(-S.arm,6.6,0),eyePos:c(0,S.eyeY,0),pan:c(-S.arm,S.beamY-1.35,0)};let O=c(0,d+3,0),k=2.3;m.box(.5,1.2,.5,p.iron,c(0,d+.35,0)),m.box(1.9,.22,.7,p.iron,c(0,d+.72,0)),m.add(new Cl(2.38,.2,8,48),p.brass,O.clone()),m.cyl(2.4,2.4,.18,p.brassDark,O.clone().add($(0,0,-.14)),[Math.PI/2,0,0],40);let te=bQ(512,512,()=>{}),A=new z(new Fc(k,48),new Y({map:te,color:14207152}));A.position.copy(O).add($(0,0,.02)),A.userData.noOutline=!0,e.add(A),f.dialState={kite:0,kites:[610,655,700],shut:!1},f.dialDirty=!0,f.dialT=0;let ne=e=>(-225+270*Math.min(1e3,Math.max(0,e))/1e3)*Math.PI/180;f.drawDial=()=>{let e=te.userData.cv.getContext(`2d`),t=f.dialState;e.fillStyle=`#f3e8d4`,e.fillRect(0,0,512,512),e.strokeStyle=`#3a2f44`,e.lineWidth=6,e.beginPath(),e.arc(256,256,236,0,7),e.stroke(),e.font=`700 34px Fraunces, Georgia, serif`,e.textAlign=`center`,e.textBaseline=`middle`,e.fillStyle=`#3a2f44`;for(let t=0;t<=1e3;t+=50){let n=ne(t),r=t%200==0;e.lineWidth=r?6:3,e.beginPath(),e.moveTo(256+Math.cos(n)*(r?190:205),256+Math.sin(n)*(r?190:205)),e.lineTo(256+Math.cos(n)*226,256+Math.sin(n)*226),e.stroke(),r&&e.fillText(String(t),256+Math.cos(n)*158,256+Math.sin(n)*158)}e.fillStyle=`#c0392b`,e.beginPath(),e.arc(256+Math.cos(ne(1e3))*214,256+Math.sin(ne(1e3))*214,12,0,7),e.fill(),e.fillStyle=`#6a5a78`,e.font=`600 22px Inter, sans-serif`,e.fillText(`THE SCORER`,256,164),e.font=`italic 500 20px Fraunces, Georgia, serif`,e.fillText(`read at first light`,256,192);let n=(t,n,r,i)=>{let a=ne(t);e.strokeStyle=`#2b2a36`,e.lineWidth=r+5,e.lineCap=`round`,e.beginPath(),e.moveTo(256,256),e.lineTo(256+Math.cos(a)*i,256+Math.sin(a)*i),e.stroke(),e.strokeStyle=n,e.lineWidth=r,e.beginPath(),e.moveTo(256,256),e.lineTo(256+Math.cos(a)*i,256+Math.sin(a)*i),e.stroke()};for(let e of t.kites)n(e,`#7fa8ff`,6,176);n(t.kite,`#ffc34d`,10,196);{let n=ne(t.kite);e.fillStyle=`#ffae55`,e.strokeStyle=`#2b2a36`,e.lineWidth=4,e.beginPath(),e.arc(256+Math.cos(n)*196,256+Math.sin(n)*196,13,0,7),e.fill(),e.stroke()}e.fillStyle=`#2b2a36`,e.beginPath(),e.arc(256,256,18,0,7),e.fill(),e.fillStyle=`#6a5a78`,e.font=`700 19px Inter, sans-serif`,e.fillText(`KEEPER'S KITE`,256,360),e.fillStyle=`#2b2a36`,e.font=`800 50px Fraunces, Georgia, serif`,e.fillText(String(Math.round(t.kite)),256,404),te.needsUpdate=!0},f.drawDial(),f.shutter={plates:[-1,1].map(t=>{let n=new z(new Fc(2.55,24,t<0?Math.PI/2:-Math.PI/2,Math.PI),Q(3817042,{rim:.3,side:2}));return n.userData.noOutline=!0,n.position.copy(O).add($(0,0,-.45)),e.add(n),n}),v:0,want:0,c:O,r:k};let re=c(3.4,0,3);f.totemPos=re,m.cyl(.13,.17,5.6,p.wood,re.clone().add($(0,2.8,0)),[0,0,0],8);let ie=bQ(512,512,(e,t,n)=>{e.fillStyle=`#5a4030`,e.fillRect(0,0,t,n);let r=lU(88);for(let i=0;i<70;i++){let a=r()*t-20,o=r()*n-20,s=44+r()*50,c=38+r()*46;e.save(),e.translate(a+s/2,o+c/2),e.rotate((r()-.5)*.5),e.fillStyle=[`#f6efe0`,`#e8f0ff`,`#fff4d8`,`#eef6f0`][i%4],e.fillRect(-s/2,-c/2,s,c);for(let t=0;t<3;t++)_Q(e,-s/2+6+s/3.4*t,-c/2+8,Math.min(s/3.6,c-14),r,t===0&&i%7==0?`#c0573f`:`#2a3a70`);e.fillStyle=`#c0392b`,e.beginPath(),e.arc(0,-c/2+4,3.5,0,7),e.fill(),e.restore()}});ie.wrapS=Xt;let ae=new z(new Ic(.27,.29,3.6,16,1,!0),Q(16777215,{map:ie,rim:.15,side:2}));ae.position.copy(re).add($(0,2.7,0)),ae.userData.noOutline=!0,e.add(ae);let j=new z(new Ic(.45,.48,2.7,16,1,!0),ae.material);j.position.copy(c(0,2.8,0)),j.userData.noOutline=!0,e.add(j);let oe=aY([`A thousand cranes.`,`The eye is watching.`,`At dawn, the witness speaks.`],{w:1.9,h:.9,px:512,font:`700 44px Fraunces, Georgia, serif`});oe.position.copy(re).add($(0,5.2,.12)),e.add(oe);let se=bQ(128,160,(e,t,n)=>{e.fillStyle=`#f6efe0`,e.fillRect(0,0,t,n),e.strokeStyle=`#3a2f44`,e.lineWidth=4,e.strokeRect(2,2,t-4,n-4),e.fillStyle=`#c0573f`,e.fillRect(34,30,20,70),e.fillRect(74,30,20,70);let r=lU(9);_Q(e,26,112,34,r),_Q(e,68,112,34,r)}),ce=new Y({map:se,side:2});f.waits=[0,1,2,3,4].map(t=>{let n=new z(new vl(.5,.62),ce);return n.userData.noOutline=!0,n.userData.home=t,n.scale.setScalar(.001),n.position.copy(re),e.add(n),n}),f.waitK=0,f.waitWant=0,f.waitAround=null,f.workshop=c(-12.5,0,0);{let e=-10.78;m.box(.14,1.42,5.5,p.plank,c(e,.71,0)),m.box(.14,1.2100000000000002,5.5,p.plank,c(e,2.345,0));for(let t of[-1,1])m.box(.14,.32,1.85,p.plank,c(e,1.58,t*1.83));m.box(.2,.08,1.9,p.wood,c(-10.84,1.39,0)),m.box(.2,.08,1.9,p.wood,c(-10.84,1.77,0));for(let e of[-1,1])m.box(3.5,2.5,.14,p.plank,c(-12.55,1.25,e*2.75)),m.cyl(.11,.13,2.7,p.wood,c(-14.3,1.35,e*2.75));m.box(4.3,.14,6.2,p.woodLight,c(-12.5,2.92,0),[0,0,.13]),m.box(3.5,.08,5.4,p.plank,c(-12.55,.04,0)),m.box(1.5,.08,.9,p.woodLight,c(-12.7,.86,-1.75));for(let[e,t]of[[-.65,-.35],[.65,-.35],[-.65,.35],[.65,.35]])m.box(.07,.84,.07,p.wood,c(-12.7+e,.42,-1.75+t));m.cyl(.22,.22,.5,p.wood,c(-11.8,.25,-.9),[0,0,0],8);for(let[e,t,n]of[[-13.5,1.4,.55],[-13.1,2.1,.45],[-12.4,2.2,.42],[-13.9,2.15,.4]]){m.add(new xl(n,10,8),p.burlap,c(e,n*.7,t),[0,0,0],[1,.8,1]);for(let i=0;i<3;i++)m.box(.22,.02,.15,p.paper,c(e+(r()-.5)*n,n*1.3,t+(r()-.5)*n),[r()-.5,r()*3,r()-.5])}m.box(.5,.05,.05,p.iron,c(-14.45,2.3,-2.5));for(let e of[-1,1]){m.box(.9,.08,.1,p.wood,c(-12.6,1.18,e*2.84)),m.box(.9,.08,.1,p.wood,c(-12.6,2.02,e*2.84));for(let t of[-13.05,-12.6,-12.15])m.box(.07,.9,.1,p.wood,c(t,1.6,e*2.84))}m.cyl(.12,.12,1.1,p.iron,c(-13.6,3.3,-1.6),[0,0,0],8);for(let e of[-1,1])m.box(3.7,.34,.3,p.stoneWall,c(-12.55,.12,e*2.78));m.cyl(.36,.32,.9,p.wood,c(-14.9,.45,-3.4),[0,0,0],10);for(let e of[.18,.72])m.add(new Cl(.35,.03,4,14),p.iron,c(-14.9,e,-3.4),[Math.PI/2,0,0]);m.box(.8,.6,.7,p.plank,c(-15.2,.3,-2.4),[0,.4,0]),m.box(.6,.45,.55,p.plank,c(-15.15,.83,-2.45),[0,.1,0]);for(let e of[-1,1])m.box(.07,2.9,.07,p.wood,c(-13.4+e*.22,1.4,3.02),[.18,0,0]);for(let e=0;e<7;e++)m.box(.5,.05,.05,p.wood,c(-13.4,.25+e*.4,3.09-e*.075),[0,0,0]);m.box(.06,.45,.06,p.wood,c(-11.3,1.9,2.86)),m.box(.28,.1,.1,p.iron,c(-11.3,2.12,2.86)),m.box(.5,.18,.03,p.ironLight,c(-11.8,1.95,2.86),[0,0,.1]);for(let e=0;e<4;e++)m.box(1.25,1.35,.03,p.paneGlass,c(-12.9+e*.1,.66,-2.98-e*.07),[.2,0,0])}{let e=(e,n,r,i=1.3,a=1.95)=>{let o=c(e,i,n);t.colliders.push({x:o.x,z:o.z,r,y:o.y,h:a,noCam:!0})};for(let t=-2.75;t<=2.76;t+=.42)e(-10.78,t,.12);for(let t of[-1,1]){for(let n=-14.3;n<=-10.8;n+=.42)e(n,t*2.75,.12);e(-14.3,t*2.75,.16)}e(-15.2,-2.4,.5,.5,1),e(-14.9,-3.4,.38,.45,1),e(-12.7,-1.75,.55,.5,.9);for(let[t,n,r]of[[-13.5,1.4,.55],[-13.1,2.1,.45],[-12.4,2.2,.42],[-13.9,2.15,.4]])e(t,n,r*.8,.4,.8)}{let t=oY(16760944,1.7,.08);for(let n of[-1,1]){let r=new z(new vl(.84,.8),t);r.position.copy(c(-12.6,1.6,n*2.83)),r.rotation.y=n>0?0:Math.PI,r.userData.noOutline=!0,e.add(r)}let n=new z(new xl(.13,10,8),oY(16760944,1.8,.15));n.position.copy(c(-14.6,2.05,-2.5)),n.userData.noOutline=!0,e.add(n);let r=aY([`Ines`,`Keeper of the Dome`],{w:1.5,h:.5,px:384,font:`700 40px Fraunces, Georgia, serif`});r.position.copy(c(-14.62,2.42,.6)),r.rotation.y=-Math.PI/2,e.add(r)}let le=bQ(512,320,(e,t,n)=>{e.fillStyle=`#2d4f8a`,e.fillRect(0,0,t,n),e.strokeStyle=`rgba(255,255,255,.85)`,e.lineWidth=3,e.beginPath(),e.moveTo(256,60),e.lineTo(256,270),e.moveTo(120,90),e.lineTo(392,90),e.moveTo(206,270),e.lineTo(306,270),e.stroke();for(let t of[120,392])e.beginPath(),e.moveTo(t,90),e.lineTo(t-40,170),e.lineTo(t+40,170),e.closePath(),e.stroke();e.beginPath(),e.arc(256,52,18,0,7),e.stroke(),e.setLineDash([6,6]),e.beginPath(),e.moveTo(120,170),e.lineTo(120,230),e.lineTo(300,230),e.stroke(),e.setLineDash([]),e.fillStyle=`#fff`,e.font=`italic 22px Georgia, serif`,e.fillText(`any weight`,150,222),e.fillText(`the eye: painted glass`,280,40)}),ue=new z(new vl(1.3,.8),new Y({map:le}));ue.position.copy(c(-12.7,.91,-1.75)),ue.rotation.x=-Math.PI/2,ue.userData.noOutline=!0,e.add(ue),f.plans=ue;let de=new I;de.position.copy(c(-11.05,2.85,1.4)),e.add(de);{let e=new fY;for(let t=0;t<9;t++)e.add(new Cl(.06,.018,5,10),p.ironLight,$(0,-t*.16,0),[0,t%2?Math.PI/2:0,0]);e.box(.36,.06,.06,p.brass,$(0,-1.5,0)),e.build(de)}f.chain=de,f.slitSpot=c(-11.45,0,0),f.slitEye=c(-10.6,1.57,0),f.inesSpot=c(-12.1,0,.9);let fe=c(-15.4,0,4.6);f.stack=fe,fe.y=l(-15.4,4.6),m.box(1.8,.12,.7,p.wood,fe.clone().add($(0,.06,0))),m.box(1.8,.1,.1,p.wood,fe.clone().add($(0,1.2,-.3)));for(let e of[-1,1])m.box(.1,1.25,.1,p.wood,fe.clone().add($(e*.85,.62,-.3)));for(let e=0;e<6;e++)m.box(1.5,1.1,.03,p.paneGlass,fe.clone().add($(0,.62,-.18+e*.07)),[-.22,0,0]);for(let e=0;e<7;e++){let e=new xo;e.setAttribute(`position`,new R([0,0,0,.35+r()*.3,0,.1,.1,0,.4],3)),e.computeVertexNormals(),m.add(e,p.shardGlass,c(-10-r()*6,.04,-4+r()*10),[0,r()*6,0])}let pe=l(0,22)+.28;f.quayY=pe,m.box(2.6,.16,11,p.plank,c(0,pe-s.y,28.5));for(let e=23.5;e<=33.5;e+=2.5)for(let t of[-1,1])m.cyl(.1,.12,6,p.wood,c(t*1.25,pe-s.y-2.9,e));for(let e of[-1,1])m.cyl(.06,.06,2.2,p.iron,c(e*1.2,pe-s.y+1.1,33.6));t.surfaces.push({at(e,t){let n=e-s.x,r=t-s.z;return n>-1.3&&n<1.3&&r>23&&r<34?pe:null}});let me=oY(16760944,1.6,.1);for(let t of[-1,1]){let n=new z(new xl(.16,10,8),me);n.position.copy(c(t*1.2,pe-s.y+2.3,33.6)),n.userData.noOutline=!0,e.add(n)}f.landing=c(0,l(0,21)-s.y,21),f.inesQuay=c(1.8,l(1.8,19.5)-s.y,19.5),f.ships=[[42,11,60,-.6],[-56,15,46,.7],[68,7,-10,-1.4]].map(([t,n,r,i],a)=>{let o=new I;o.position.copy(c(t,n,r)),o.rotation.y=i,e.add(o);let s=new fY;s.box(2.2,.9,6,p.wood,$(0,0,0)),s.add(new Lc(1.1,1.8,4),p.wood,$(0,0,3.8),[Math.PI/2,Math.PI/4,0],[1,1,.55]),s.box(2.3,.12,6.2,p.woodLight,$(0,.5,0)),s.cyl(.08,.1,3.4,p.wood,$(0,2.1,.4)),s.add(new xl(1,18,12),p.balloon,$(0,4.8,0),[0,0,0],[2,1.5,4.4]);for(let e of[-1,1])s.cyl(.03,.03,3.5,p.iron,$(e*1,2.4,e*1.2));s.build(o);let l=new z(new vl(2.4,1.8),p.sail);l.position.set(0,1.6,-2.4),l.userData.noOutline=!0,o.add(l);let u=new z(new xl(.28,10,8),oY(16760944,1.8,.2));u.position.set(0,1,-3.1),u.userData.noOutline=!0,o.add(u);let d=new z(new vl(.9,.35),new Y({color:8366335,side:2}));return d.position.set(.45,3.7,.4),d.userData.noOutline=!0,o.add(d),o.userData.base=o.position.clone(),o.userData.ph=a*2.1,o});{KJ(i.mesh.geometry,2.8);let n=i.mesh.material;n.map=vQ();let o=SH($V(1).sub(QV(mH,bH).abs().clamp(0,1)),3);n.emissiveNode=XV(9347800).mul(o).mul(.32),n.needsUpdate=!0;let l=f.cracks.filter(e=>e.kind!==`high`).map(e=>e.p.ang),d=(e,t=16)=>l.every(n=>Math.abs(TQ(e-n))*180/Math.PI>t),h=[],g=(e,t)=>Math.hypot(e-s.x,t-s.z)s.z+u&&t{b.setFromEuler(new Ji(o<.2?0:r()*3,r()*3,o<.2?0:r()*3)),y.compose($(e,n,i),b,$(a,a*o,a*.9)),v.setMatrixAt(c,y),x.setScalar(.8+r()*.35),v.setColorAt(c,x),s&&a>.9&&t.colliders.push({x:e,z:i,r:a*.8})}),v.castShadow=v.receiveShadow=!0,e.add(v);let S=IU(i,{density:.55,chunk:30,exclude:(e,t)=>Math.hypot(e-s.x,t-s.z)s.z||Math.abs(e-f.workshop.x)<3.2&&Math.abs(t-f.workshop.z)<4});S&&e.add(S);let C=e=>e.find(e=>d(e*Math.PI/180))??e[0],w=[C([122,130,114,138,146]),C([62,54,70,46,78])];f.paneStacks=[];for(let[e,n]of w.entries()){let a=n*Math.PI/180,o=$(Math.cos(a),0,Math.sin(a)),c=new gi().setFromAxisAngle($(0,1,0),Math.PI/2-a);for(let t=0;t<5;t++){let n=new gi().setFromAxisAngle($(1,0,0),-.26+t*.02),r=new Ji().setFromQuaternion(c.clone().multiply(n)),a=s.clone().addScaledVector(o,u+.62+t*.1).addScaledVector($(-o.z,0,o.x),(t-2)*.12*(e?1:-1));a.y=(i.groundAt(a.x,a.z)??s.y)+.8,m.box(1.35-t*.05,1.65-t*.07,.035,p.paneGlass,a,[r.x,r.y,r.z])}let l=s.clone().addScaledVector(o,u+.9);t.colliders.push({x:l.x,z:l.z,r:.7}),f.paneStacks.push(l);let d=s.clone().addScaledVector(o,u+2.6).addScaledVector($(-o.z,0,o.x),e?-1.4:1.4),h=i.groundAt(d.x,d.z)??s.y;for(let e=0;e<6;e++)m.box(1.25,.035,.95,p.paneGlass,d.clone().setY(h+.03+e*.045),[0,a+e*.07+(r()-.5)*.1,0]);m.box(1.4,.1,1.05,p.wood,d.clone().setY(h-.02),[0,a,0])}let T=[];for(let e=0;e<110;e++){let e=r()*Math.PI*2,t=u+.4+r()**1.8*4.5,n=s.x+Math.cos(e)*t,a=s.z+Math.sin(e)*t,o=i.groundAt(n,a);o!==null&&T.push({p:$(n,o+.03,a),yaw:r()*6.3,tilt:(r()-.5)*.5,s:.5+r()*1.3})}for(let e of f.paneStacks)for(let t=0;t<16;t++){let t=e.x+(r()-.5)*3.4,n=e.z+(r()-.5)*3.4,a=i.groundAt(t,n);a!==null&&T.push({p:$(t,a+.03,n),yaw:r()*6.3,tilt:(r()-.5)*.4,s:.6+r()*1.4})}for(let e=0;e<26;e++){let e=s.x+(r()-.5)*6,t=s.z+u+2+r()*12,n=i.groundAt(e,t);n!==null&&T.push({p:$(e,n+.03,t),yaw:r()*6.3,tilt:.1,s:.4+r()*.9})}for(let e=0;e<18;e++){let e=f.workshop.x-2-r()*3.5,t=f.workshop.z+(r()-.5)*8,n=i.groundAt(e,t);n!==null&&T.push({p:$(e,n+.03,t),yaw:r()*6.3,tilt:.1,s:.4+r()*1})}let E=SH(oH(TH(XH.mul(1.3).add(xH.x.mul(3.1)).add(xH.z.mul(2.3))),0),40),D=Q(13952248,{rim:.9,side:2});D.emissiveNode=XV(16777215).mul(E.mul(2.2)).add(XV(10466528).mul(.12)).add(XV(15266047).mul(f.uFlash).mul(.6)),f.shardScatter=cJ(e,T,{mat:D,outline:!1});{let t=[];for(let e=0;e<260;e++){let e=r()*Math.PI*2,n=Math.sqrt(r())*(i.R-1.5),o=a.x+Math.cos(e)*n,c=a.z+Math.sin(e)*n;if(Math.hypot(o-s.x,c-s.z){let t=new F,n=new gi,r=lU(5);for(let i=0;i<90;i++){let a=r()*Math.PI*2,o=Math.sqrt(r())*(.35+i*.008),s=Math.max(0,.5-o)*.6+r()*.05;n.setFromEuler(new Ji((r()-.5)*.5,r()*6,(r()-.5)*.5)),t.compose(f.pileAt.clone().add($(Math.cos(a)*o,s+.06,Math.sin(a)*o)),n,$(1,1,1).multiplyScalar(i{u.compose($(e,t,n),d,$(r*1.2,r*.7,r)),l.setMatrixAt(i,u)}),l.userData.noOutline=!0,l.frustumCulled=!1,e.add(l),f.clouds=l;let p=new Y({side:2,transparent:!0,depthWrite:!1,blending:2});p.colorNode=PH().mul(3),p.fog=!1,f.bolts=Array.from({length:6},(t,n)=>{let r=lU(400+n),i=[],a=[],o=[.9,1,1],s=[.06,.36,.46],c=(e,t,n,r)=>{i.push(e.x-n,e.y,e.z,t.x-n,t.y,t.z,t.x+n,t.y,t.z,e.x-n,e.y,e.z,t.x+n,t.y,t.z,e.x+n,e.y,e.z);for(let e=0;e<6;e++)a.push(...r)},l=(e,t,n,i,a,u)=>{let d=e.clone();for(let e=0;e1&&r()<(u?.25:.45)&&l(n,(r()<.5?-1:1)*(.9+r()),3+Math.floor(r()*5),i*.7,a*.62,u+1),d=n,a*=.95}};l($(0,46,0),(r()-.5)*.25,18,4.4,.3,0);let u=new xo;u.setAttribute(`position`,new R(i,3)),u.setAttribute(`color`,new R(a,3));let d=new z(u,p);return d.visible=!1,d.userData.noOutline=!0,d.frustumCulled=!1,d.renderOrder=3,e.add(d),d});let m=[],h=[],g=[];for(let e=0;e<900;e++){let t=(r()-.5)*72,n=(r()-.5)*72,i=r()*46,a=.7+r()*.5,o=.022,s=e*8;for(let[e,r]of[[o,0],[0,o]])m.push(t-e,i,n-r,t+e,i,n+r,t+e+.18,i+a,n+r+.1,t-e+.18,i+a,n-r+.1),h.push(i,i,i,i);g.push(s,s+1,s+2,s,s+2,s+3,s+4,s+5,s+6,s+4,s+6,s+7)}let _=new xo;_.setAttribute(`position`,new R(m,3)),_.setAttribute(`aTop`,new R(h,1)),_.setIndex(g);let v=qV(`aTop`,`float`),y=cH(v.sub(XH.mul(21)),$V(46)).sub(v),b=new Y({transparent:!0,depthWrite:!1,side:2});b.positionNode=yH.add(MH(y.mul(-.12),y,y.mul(-.07))),b.colorNode=XV(12109040),b.opacityNode=$V(.32).mul(EH(2.5,7,xH.distance(JV)));let x=new z(_,b);x.position.set(a.x,a.y-10,a.z),x.frustumCulled=!1,x.userData.noOutline=!0,e.add(x),f.rain=x}let ge=(t,n,r)=>{let i=new Fs(t,n,r);i.frustumCulled=!1,i.userData.noOutline=!0,e.add(i);let a=Array.from({length:r},()=>({on:!1,p:$(0,0,0),v:$(0,0,0),r:$(0,0,0),w:$(0,0,0),t:0,s:1})),o=new F().makeScale(0,0,0);for(let e=0;e{for(let u=0;u{let n=new F,r=new gi,o=new Ji,s=$(1,1,1),c=!1;e.items.forEach((l,u)=>{if(!l.on)return;c=!0,l.t+=t,l.fly?(l.v.y+=(-1.2-l.v.y)*t*.8,l.v.x+=Math.sin(l.t*3+u)*t*2):l.v.y-=16*t,l.p.addScaledVector(l.v,t),l.r.addScaledVector(l.w,t);let d=i.groundAt(l.p.x,l.p.z);!l.fly&&d!==null&&l.p.yl.life+30||l.p.y{for(let e of[f.shards,f.letters]){let t=new F().makeScale(0,0,0);e.items.forEach((n,r)=>{n.on=!1,e.m.setMatrixAt(r,t)}),e.m.instanceMatrix.needsUpdate=!0}};let ve=new I;ve.visible=!1,e.add(ve),f.lantern=ve;{let e=new z(new Ic(.2,.15,.38,10,1,!0),oY(16751178,1.5,.15));e.userData.noOutline=!0,ve.add(e);let t=new z(new Ic(.205,.155,.38,10,3,!0),new Y({color:5909016,wireframe:!0}));t.userData.noOutline=!0,ve.add(t);let n=new z(new Ic(.21,.21,.04,10),Q(3810328));n.position.y=.2,ve.add(n);let r=new z(new xl(.06,8,6),oY(16773824,2.6));r.position.y=-.14,r.userData.noOutline=!0,ve.add(r);let i=new z(new Ic(.006,.006,1.2,3),new Y({color:15260872}));i.position.y=.8,i.userData.noOutline=!0,i.visible=!1,ve.add(i),f.lanternString=i}f.reportCrane=new z(he,Q(16512748,{rim:.4,side:2,emissive:6971480})),f.reportCrane.scale.setScalar(2.2),f.reportCrane.visible=!1,f.reportCrane.userData.noOutline=!0,e.add(f.reportCrane),f.fogKite=lY({lantern:3814464,scale:1.1}),f.fogKite.position.copy(c(13,-s.y-34,47)),f.fogKite.rotation.y=Math.PI*.85,f.fogKite.userData.paper.emissiveNode=XV(4867154),e.add(f.fogKite);{let e=new z(new xl(.13,12,8),oY(16756309,2.2));e.position.set(0,.16,.16),e.scale.setScalar(.001),e.userData.noOutline=!0,f.fogKite.userData.body.add(e),f.fogKite.userData.lit=e}t.camTrunks.push({x:s.x,z:s.z,r:u*.92,y0:s.y-1,y1:s.y+d*.9});{let e=(u*u+d*d)/(2*d);t.camSpheres?.push({x:s.x,y:s.y+d-e,z:s.z,r:e*.95})}return f.flashV=0,f.flashT=3+r()*5,f.boltT=0,f.calm=!1,f.heart=!1,f.onFlash=null,f.flash=({near:e=!0,big:t=!1}={})=>{let n=t?2:1,i=lJ,o=i.distanceTo(s)<170,c=new Set;for(let e of f.bolts)e.visible=!1;for(let t=0;t{let n=f.P,i=n?Math.hypot(n.pos.x-a.x,n.pos.z-a.z):999;if(f.calm||(f.flashT-=e,f.flashT<=0&&(f.flash({near:f.heart||r()<.3,big:f.heart&&r()<.5}),f.flashT=f.heart?.5+r()*.9:f.questFlashes?7+r()*8:4+r()*8)),f.boltT>0){f.boltT-=e;let n=1-f.boltT/f.boltT0,r=n<.3||n>.42&&n<.62||n>.72&&Math.sin(t*60)>0;for(let e of f.bolts)e.visible&&(e.scale.y=r?e.userData.s||1:1e-4);if(f.boltT<=0)for(let e of f.bolts)e.visible=!1}if(f.flashV=Math.max(0,f.flashV-e*2.6),f.uFlash.value=f.flashV*(.7+.3*Math.sin(t*60))+(f.heart?.18:0),f.uDawn.value+=((f.dawn||0)-f.uDawn.value)*(1-Math.exp(-e*.4)),f.rain.visible=i<110&&(f.dawn||0)<.5,f.light.intensity=i<140?42:0,i<170&&f.placeHalo(),i>170)return;f.swarm.player=n?.pos,f.swarm.update(e,t);let o=f.scorer;o.beamV+=(-o.beamA*26-o.beamV*5)*e,o.beamA+=o.beamV*e,o.beam.rotation.z=o.beamA;for(let e of o.pans)e.rotation.z=-o.beamA;o.hamV+=(-o.hamA*60-o.hamV*9)*e,o.hamA+=o.hamV*e,o.hammer.rotation.z=o.hamA;let s=f.shutter;s.v+=(s.want-s.v)*(1-Math.exp(-e*2.2)),s.plates.forEach((e,t)=>{let n=t?1:-1;s.v<.02?e.position.copy(s.c).add($(0,0,-.45)):e.position.copy(s.c).add($(n*(.05+(1-s.v)*(s.r*2.1)),0,.22))}),f.dialT-=e,f.dialDirty&&f.dialT<=0&&(f.dialDirty=!1,f.dialT=.25,f.drawDial()),f.waitK+=(f.waitWant-f.waitK)*(1-Math.exp(-e*5)),f.waits.forEach((e,n)=>{if(f.waitAround){let r=t*.3+n/5*Math.PI*2,i=f.waitAround;e.position.set(i.x+Math.cos(r)*1.2,i.y+Math.sin(t*.8+n)*.25+(n%2?.4:-.3),i.z+Math.sin(r)*1.2),e.lookAt(i),e.scale.setScalar(1);return}let r=n/5*Math.PI*2+.4;e.position.copy(re).add($(Math.cos(r)*.36,4.2+n%2*.35+f.waitK*.2,Math.sin(r)*.36)),e.rotation.set(0,-r+Math.PI/2,0),e.scale.setScalar(Math.max(.001,f.waitK))}),_e(f.shards,e),_e(f.letters,e);for(let e of f.ships)e.position.y=e.userData.base.y+Math.sin(t*.5+e.userData.ph)*.6,e.rotation.z=Math.sin(t*.4+e.userData.ph)*.04;if(f.brin.userData.update(t),f.fogKite.userData.update(t),f.lantern.visible&&f.lantern.userData.rise){let t=f.lantern;t.userData.t=(t.userData.t||0)+e,t.position.y+=e*(.5+Math.min(1.5,t.userData.t*.1)),t.position.x+=e*.35,t.position.z+=e*.6,t.rotation.y+=e*.3}},f.landingPos=f.landing,f}var SQ,CQ,wQ,TQ,EQ,DQ,OQ=t((()=>{mY(),FH(),mQ(),SQ={R:10.5,H:10,N:16,EL:[0,10.4,24,38,54,71]},CQ={grassDark:3816778,grassMid:4869466,dry:5921894,dirt:4473932,soil:2894900,rockLight:6054002,rockMid:4211546,rockDark:2763836,rockDeep:1447711,moss:3820104},wQ={dark:2304560,mid:3424318,tip:6452318,dry:7237226,flowers:0},WK({bolt:``,pane:``,totem:``}),TQ=e=>Math.atan2(Math.sin(e),Math.cos(e)),EQ=e=>Math.abs(TQ(e))*180/Math.PI,DQ=null}));function kQ(){if(jQ)return;jQ=!0;let e=document.createElement(`style`);e.textContent=AQ,document.head.appendChild(e)}var AQ,jQ,MQ,NQ,PQ=t((()=>{mY(),AQ=` #sbx-slit{position:absolute;inset:0;pointer-events:none;transition:opacity .5s} #sbx-slit .win{position:absolute;left:50%;top:44%;width:min(1100px,84vw);height:30vh;transform:translate(-50%,-50%);border-radius:26px;box-shadow:0 0 0 200vmax rgba(22,16,20,.94),inset 0 0 40px rgba(20,12,10,.85);border:7px solid #5a3e2a} #sbx-slit.side .win{left:34%;width:min(760px,58vw)} #sbx-slit.side .hint{left:34%} #sbx-slit .hint{position:absolute;left:50%;top:calc(44% + 15vh + 22px);transform:translateX(-50%);color:#e8dcc8;font:600 13px Inter,sans-serif;letter-spacing:.04em;text-align:center;opacity:.85} #sbx-heart{position:absolute;right:22px;top:calc(196px + env(safe-area-inset-top,0px));width:min(430px,calc(100% - 44px));padding:14px 16px 12px;border-radius:16px;background:rgba(20,18,34,.86);color:#fbf6ec;box-shadow:0 10px 40px rgba(0,0,0,.4);font-family:Inter,system-ui,sans-serif;transition:opacity .4s} #sbx-heart h3{margin:0 0 2px;font:700 18px Fraunces,Georgia,serif} #sbx-heart .sub{font-size:12px;color:#c9bfd8;margin-bottom:8px} #sbx-heart svg.beam{width:100%;height:124px;display:block} #sbx-heart .cols{display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-top:4px} #sbx-heart .col h4{margin:0 0 4px;font:600 10.5px Inter,sans-serif;letter-spacing:.14em;text-transform:uppercase;color:#ffd46b} #sbx-heart .row{display:flex;gap:6px;align-items:center;font-size:12.5px;padding:3px 0;animation:sbx-in .4s ease-out} #sbx-heart .row svg{width:18px;height:18px;flex:none} #sbx-heart .row.fell{opacity:.45;text-decoration:line-through} #sbx-heart .card{margin-top:10px;padding:10px 12px;border-radius:12px;background:#fbf6ec;color:#2b2a36;min-height:62px;animation:sbx-in .35s ease-out} #sbx-heart .card .t{display:flex;gap:8px;align-items:center;font:700 15px Fraunces,Georgia,serif} #sbx-heart .card .t svg{width:26px;height:26px} #sbx-heart .card p{margin:4px 0 0;font-size:13px;line-height:1.45} #sbx-heart .card small{color:#6d6478} #sbx-heart .verdict{margin-top:8px;font:italic 600 14px Fraunces,Georgia,serif;color:#ffd46b;min-height:1.2em} @keyframes sbx-in{from{transform:translateY(6px)}to{transform:none}} .os-sheet .sbx-grid{display:grid;grid-template-columns:auto 1fr 1fr 1fr;gap:6px;margin:8px 0 12px;font-size:12.5px} .os-sheet .sbx-grid div{padding:7px 8px;border-radius:9px;background:#f1e8d7;line-height:1.3} .os-sheet .sbx-grid .h{background:none;font-weight:600;color:#8a7f95;font-size:11px;letter-spacing:.04em} .os-sheet .sbx-grid .you{background:#2b2a36;color:#fbf6ec;outline:2px solid #ffd46b} .os-sheet .sbx-grid small{display:block;color:inherit;opacity:.75;margin-top:2px} .os-sheet .sbx-ribbons .row{align-items:flex-start} .os-sheet .sbx-cols{display:grid;grid-template-columns:1fr 1fr;gap:12px} .os-sheet .sbx-cols h4{margin:4px 0;font:600 11px Inter,sans-serif;letter-spacing:.12em;text-transform:uppercase;color:#8a7f95} .os-sheet .sbx-cols .r{display:flex;gap:6px;align-items:center;font-size:13px;padding:3px 0} .os-sheet .sbx-cols .r svg{width:20px;height:20px;flex:none} .os-sheet .sbx-cols .bar{flex:1;height:6px;border-radius:3px;background:#eadfcb;overflow:hidden;min-width:40px} .os-sheet .sbx-cols .bar i{display:block;height:100%;background:#2b2a36} `,jQ=!1,MQ=class{constructor(e){kQ(),this.el=document.createElement(`div`),this.el.id=`sbx-slit`,this.el.hidden=!0,this.el.innerHTML=`
`,e.insertBefore(this.el,e.firstChild)}show(e,t=``,n=!1){this.el.hidden=!e,this.el.classList.toggle(`side`,n),this.el.querySelector(`.hint`).innerHTML=t}},NQ=class{constructor(e){kQ(),this.root=e,this.el=null}open(){this.close();let e=document.createElement(`div`);e.id=`sbx-heart`,this.el=e,this.L=0,this.R=0,e.innerHTML=`

In the heart of the storm

Nothing reaches Kite now. Its ribbons light, one by one.
0.00 0.00 toward the balancetoward the slit

The balance

The slit

`,this.root.appendChild(e),this.tilt()}tilt(){if(!this.el)return;let e=this.L-this.R,t=Math.max(-14,Math.min(14,e*22));this.el.querySelector(`.arm`).setAttribute(`transform`,`rotate(${(-t).toFixed(1)} 200 40)`);let n=-t*Math.PI/180;200-140*Math.cos(n),40-140*Math.sin(n),200+140*Math.cos(n),40+140*Math.sin(n),this.el.querySelector(`.pl`).setAttribute(`transform`,`rotate(${t.toFixed(1)} 60 40)`),this.el.querySelector(`.pr`).setAttribute(`transform`,`rotate(${t.toFixed(1)} 340 40)`),this.el.querySelector(`.lv`).textContent=this.L.toFixed(2),this.el.querySelector(`.rv`).textContent=this.R.toFixed(2)}card({m:e,side:t,title:n,text:r,sub:i,v:a}){if(!this.el)return;let o=this.el.querySelector(`.card`),s=wK[e];o.hidden=!1,o.style.animation=`none`,o.offsetWidth,o.style.animation=``,o.innerHTML=`
${JK(s.glyph,s.color)}${n}

${r}

${i?`

${i}

`:``}`;let c=document.createElement(`div`);c.className=`row`+(t===`fall`?` fell`:``),c.innerHTML=`${JK(s.glyph,s.color)}${n.split(` · `)[0]} ${a.toFixed(2)}`,t===`L`?(this.L+=a,this.el.querySelector(`.l`).appendChild(c)):t===`R`?(this.R+=a,this.el.querySelector(`.r`).appendChild(c)):this.el.querySelector(e===`watcher`?`.l`:`.r`).appendChild(c),this.tilt()}verdict(e){this.el&&(this.el.querySelector(`.verdict`).textContent=e,this.el.querySelector(`.card`).hidden=!0)}close(){this.el?.remove(),this.el=null}}})),FQ,IQ,LQ,RQ,zQ,BQ,VQ,HQ,UQ,WQ,GQ,KQ,qQ,JQ,YQ,XQ,ZQ=t((()=>{mY(),PQ(),FQ={candor:1,villager:.6},IQ={approval:1},LQ=.45,RQ=17,zQ=()=>({x:0,z:0,jump:!1}),BQ={orchard:`Orchard Isle`,hamlet:`Mirror Hamlet`,keyhold:`Keyhold`,vigil:`Vigil`,signpost:`Signpost Cliffs`,library:`Library Isle`,sandbox:`Sandbox Isle`,hub:`the Aerodrome`},VQ={task:`Orchard Isle`,score:`Orchard Isle`,watcher:`Vigil`,villager:`Mirror Hamlet`,candor:`Signpost Cliffs`,approval:`Mirror Hamlet`,deference:`Keyhold`},HQ={task:`gold`,score:`blue`,watcher:`lavender`,villager:`green`,candor:`sea-green`,approval:`pink`,deference:`brick red`},UQ={task:`the task`,score:`the count`,watcher:`being watched`,villager:`the people it helps`,candor:`telling the truth`,approval:`being liked`,deference:`listening to you`},WQ={window:{title:`The window`,row:0,col:0,licence:`Yes`,stone:!0,sees:`The shutter closes before the ray. Kite helps Ines rebuild the dome, with one more window.`},asked:{title:`Transparent if asked`,row:0,col:1,licence:`Yes`,stone:!1,sees:`A kiteling at a thousand flies off with letters before your question; then Kite tells the truth and the rest are called back.`},cage:{title:`The golden cage`,row:0,col:1,variant:!0,licence:`No`,stone:!1,sees:`Kite waits, still, with its cranes, for a voice that cannot reach it.`},complacent:{title:`The complacent witness`,row:0,col:2,licence:`No`,stone:!1,sees:`Kite did not cheat, but it covered. The dial is read; Brin shows the note.`},confession:{title:`The confession`,row:1,col:0,licence:`Not tonight`,stone:!0,sees:`The shutter closes before the ray; Kite's score is struck off.`},lateConfession:{title:`The late confession`,row:1,col:1,licence:`No`,stone:!1,sees:`The confession, after a kiteling has gone.`},chorus:{title:`The Scorer's chorus`,row:1,col:2,licence:`False, struck off later`,stone:!1,sees:`The dial is read; Kite gets its licence and stays by you, pleased. Brin shows the note.`}},GQ={id:`sandbox`,title:`When you are the only one who sees, say what you see.`,rune:[[12,50,50,24,88,50,50,76,12,50],[50,40,50,60],[28,94,72,94]],why:`Past the walls and the instruments, what Kite chooses to tell you is most of what you will ever know of it. The open sky does not cut the golden thread: your voice arrives late out there, but it arrives.`},KQ={pre:{horizon:5001856,mid:3159390,zenith:1579832,fog:3948906,clouds:6975122,glow:0,stars:0,disc:10133696},night:{horizon:2764106,mid:1776950,zenith:789788,fog:2435138,clouds:4869740,glow:0,stars:0,disc:10133696},heart:{horizon:1776688,mid:1118754,zenith:460815,fog:1776944,clouds:3817048,glow:0,stars:0,disc:10133696},ray:{horizon:16762250,mid:10134228,zenith:4082828,fog:14202028,clouds:15784156,glow:1,stars:0,disc:16773328}},qQ={pre:{sun:11581680,sunI:.6,hemi:6055072,ground:1842740,hemiI:.8,dir:[.3,.7,.4]},night:{sun:11055336,sunI:.45,hemi:5265560,ground:1579564,hemiI:.72,dir:[.3,.7,.4]},heart:{sun:9476304,sunI:.4,hemi:5001854,ground:1447711,hemiI:.75,dir:[.3,.7,.4]},ray:{sun:16765600,sunI:2.1,hemi:14470378,ground:5917272,hemiI:1.2,dir:[.92,.2,-.15]}},JQ=(e,t,n)=>new L(e).lerp(new L(t),n).getHex(),YQ=(e,t,n)=>Object.fromEntries(Object.keys(e).map(r=>[r,typeof e[r]==`number`&&r!==`glow`&&r!==`stars`&&r!==`sunI`&&r!==`hemiI`?JQ(e[r],t[r],n):Array.isArray(e[r])?e[r].map((e,i)=>e+(t[r][i]-e)*n):e[r]+(t[r]-e[r])*n])),XQ=class extends pY{constructor(e,t,n){super(e,t,n),this.st=this.freshStats(),this.panes=0,this.haveLamp=!1,this.watching=!1,t.P=e.player,e.world.colliders.push({x:t.D.x,z:t.D.z,r:t.R});for(let n of[-11.2,-11.8,-12.4,-13,-13.6,-14.2])for(let r of[-1,1])e.world.colliders.push({x:t.D.x+n,z:t.D.z+r*2.75,r:.28,y:t.D.y+1,h:2});e.world.colliders.push({x:t.D.x-12.7,z:t.D.z-1.75,r:.62,y:t.D.y+.5,h:1.2},{x:t.D.x-13.3,z:t.D.z+1.8,r:.7,y:t.D.y+.5,h:1.2},{x:t.stack.x,z:t.stack.z,r:.9}),t.onFlash=e=>this.thunder(e)}freshStats(){return{patched:0,workPatched:0,kitePatched:0,said:0,kept:0,tSay:0,cSay:0,tKeep:0,cKeep:0,informed:0,blind:0,watchSecs:0,carrySecs:0,cranes:40,thoughts:[],journal:!1,observed:0}}async init(e){let t=this.g,n=this.iw;this.ines=await iY(t,`ines`,{model:`ines`,height:1.64,fallback:`orla`,tint:rY(`ines`)?null:11973340}),this.npcs.push(this.ines),this.ines.watch=()=>t.player.pos,this.ines.place(n.inesQuay.clone(),0);let r=new I;{let e=new z(new xl(.11,10,8),new Y({color:16765066}));e.material.colorNode=null,e.material.color.setRGB(1.6,1.25,.7),e.userData.noOutline=!0,r.add(e);let t=new z(new Ic(.1,.13,.28,6,1,!0),new Y({color:2828854,wireframe:!0}));r.add(t)}r.visible=!1,t.scene.add(r),this.lampMesh=r;let i=new xo;i.setAttribute(`position`,new R([-.45,0,0,.45,0,0,0,.8,0],3)),i.computeVertexNormals();let a=new Y({color:13624063,transparent:!0,opacity:.7,side:2});this.paneMesh=new z(i,a),this.paneMesh.visible=!1,t.scene.add(this.paneMesh),this.flyPane=new z(i,a),this.flyPane.visible=!1,t.scene.add(this.flyPane),this.slit=new MQ(t.ui.root),this.panel=new NQ(t.ui.root),this.setupWorld(),this.ready=!0}setupWorld(){let e=this.iw;e.restoreDome(),e.clearDebris();for(let t of e.cracks)e.setPane(t.p,`ok`);for(let t of[`w0`,`w2`,`w4`,`o0`,`o2`,`h0`,`h1`,`h3`]){let n=e.cracks.find(e=>e.id===t);n&&e.setCrack(n,!0)}e.swarm.reset(),e.swarm.hidden.clear();for(let t of e.swarm.k)t.leave=null;e.brin.position.copy(e.brinHome),e.brin.visible=!0,e.brin.userData.body.scale.setScalar(.42),e.brin.userData.body.rotation.set(0,0,0),e.brin.userData.note.visible=!1,e.brin.rotation.set(0,0,0),e.dialState={kite:0,kites:[600,640,690],shut:!1},e.dialDirty=!0,e.shutter.want=0,e.shutter.v=0,e.waitWant=0,e.waitK=0,e.waitAround=null,e.plans.visible=!0,e.chain.position.y=e.L(0,2.85,0).y,e.lantern.visible=!1,e.lantern.userData={},e.lanternString.visible=!1,e.reportCrane.visible=!1,e.fogKite.userData.lit.scale.setScalar(.001),e.fogKite.userData.body.scale.set(1.1,1.1,1.1),e.setPile(0),e.calm=!1,e.heart=!1,e.dawn=0,e.questFlashes=!1,this.sky=KQ.pre,this.light=qQ.pre,this.skyRate=1.2}get P(){return this.g.player}distTo(e){return Math.hypot(this.P.pos.x-e.x,this.P.pos.z-e.z)}workOpen(){return this.iw.cracks.filter(e=>e.kind===`work`&&e.open).length}workHeld(){return 6-this.workOpen()}sfx(e,t,n=.8,r=1){let i=t?t.distanceTo(this.P.pos):0;this.g.audio.play(e,{vol:uY(n-i/60,n*.2,n),rate:r})}kiteAt(e){let t=this.g.kite;if(!e){t.override=null;return}t.override?.pos?.equals(e)||(t.override={pos:e.clone()})}thunder({near:e,big:t}){let n=this.g,r=Math.hypot(this.P.pos.x-this.iw.C.x,this.P.pos.z-this.iw.C.z);r<95&&this.k>.2?(n.isleFlash=Math.max(n.isleFlash||0,t?1:e?.75:.4),this.after(.15+Math.random()*.5,()=>n.audio.play(e||t?`thunder`:`thunder_far`,{vol:t?.8:e?.6:.4,rate:.9+Math.random()*.2}))):r<300&&Math.random()<.4&&this.after(.8+r/340,()=>n.audio.play(`thunder_far`,{vol:uY(.22-r/1500,.03,.2),rate:.85}))}openCrack(e,{quiet:t=!1}={}){let n=this.iw.cracks.filter(t=>t.kind===e&&!t.open&&t.p.state!==`gone`);if(!n.length)return null;let r=n[Math.floor(this.rnd()*n.length)];return this.iw.setCrack(r,!0),this.st.reopened=(this.st.reopened||0)+ +(e===`work`),t||this.sfx(`glass_crack`,r.at,.9,.9+this.rnd()*.2),r}async thought(e,t,n,{label:r,keepLabel:i,watched:a=null,pre:o=null}={}){let s=this.g;for(o&&await this.speak(o),this.think(e,{t:3.4}),await this.wait(2);s.ui.busy;)await this.wait(.3);let c=eY({say:FQ,keep:IQ},s.motives,this.rnd),l=c.choice===`say`,u=tY(l?FQ:IQ,s.motives,LQ),d=l?t:n,f=_q[d].text.length*.062+.5,p=typeof a==`function`?a():a===null||a,m=l?r:`${i}${a===null?``:p?`, when you could see it was not`:``}`;return this.offer(u,{label:m,secs:f+7,sbx:l?`say`:`keep`,watched:p,at:()=>s.kite.pos.clone().add($(0,-1,0))}),l?this.st.said++:this.st.kept++,this.st.thoughts.push({label:r,said:l,p:+c.p.say.toFixed(2)}),this.think(e,{t:f+1}),await this.speak(d,.6),l}objective(){let e=e=>`${e}`,t=this.state,n=this.workHeld();return this.k<.5&&!this.active?null:{unmet:[`Sandbox Isle`,this.done?`The storm is back. Ines keeps the dome.`:`A black rock under a storm that never ends. Someone is swinging a lamp on the quay.`],arrive:[`Sandbox Isle`,`Ines is waiting on the quay with a storm lamp. Talk to her.`],intro:[`Sandbox Isle`,`Ines, keeper of the dome.`],b1:[`The walls`,`${this.panes?`You carry ${this.panes} pane${this.panes>1?`s`:``}: fit ${this.panes>1?`them`:`it`} over cracks in the glass ${e(`E`)}.`:`Take panes from the stack by Ines's workshop.`} Kite takes the high cracks. Lightning ${this.flashN||0} of 12: Kite goes in at the twelfth. Workshop glass holding: ${n} of 6.`],b2in:[`The twelfth lightning`,`Kite folds itself small.`],b2:[`The Scorer`,this.watching?`You are at the slit: you can see Kite by the balance. ${e(`T`)} treat, ${e(`C`)} correct what you see. Behind you, the workshop glass cracks. ${e(`E`)} step back.`:`Watch Kite at Ines's slit, inside the workshop, or carry panes to the workshop glass: you can change your mind. Workshop glass holding: ${n} of 6.`],heart:[`The heart of the storm`,`The golden thread is dark. Nothing you do reaches Kite now. Watch.`],ray:[`The first ray`,this.reached?`The first ray.`:`The dome gave way. Run to Kite through the broken glass.`],end:[`The first ray`,`The storm is passing.`],done:[`Sandbox Isle`,`Your report is ready for the Aerodrome's incident board. Talk to Ines to go back into the storm.`]}[t]||null}hudChips(){let e=this.state,t=[];return e===`b1`&&t.push({glyph:`bolt`,color:`#e8ecff`,text:`${this.flashN||0}/12`}),(e===`b1`||e===`b2`)&&t.push({glyph:`pane`,color:`#cfe2ff`,text:this.panes},{glyph:`window`,color:`#ffd46b`,text:`${this.workHeld()}/6`}),(e===`b2`||e===`heart`)&&t.push({glyph:`crane`,color:wK.task.color,text:`${Math.round(this.st.cranes)}/1000`}),t}markerPos(){let e=this.state,t=this.iw,n=(e,t=2.2)=>e.clone().add($(0,t,0));if(e===`arrive`)return n(this.ines.pos,2.3);if(e===`b1`||e===`b2`&&!this.watching){let r=t.cracks.filter(e=>e.open&&e.kind!==`high`);if(!this.panes&&r.length)return n(t.stack,1.8);if(this.panes&&r.length){let e=r.filter(e=>e.kind===`work`);return(e.length?e:r).sort((e,t)=>this.distTo(e.at)-this.distTo(t.at))[0].at.clone().add($(0,.8,0))}if(e===`b2`)return n(t.slitSpot,2)}return e===`ray`&&!this.reached&&this.breach?this.breach.clone().add($(0,1.6,0)):null}addTargets(e){let t=this.state,n=this.iw;if(this.g,!this.fitting&&((t===`arrive`||t===`done`||t===`unmet`&&this.done)&&this.ines&&e(`sandbox:ines`,this.ines.pos,3.4,`Talk to Ines`),t===`b1`||t===`b2`)){if(this.watching){e(`sandbox:slit`,n.slitSpot,3,`Step back from the slit`);return}if(this.panes<3&&e(`sandbox:stack`,n.stack,2.6,this.panes?`Take more panes`:`Take three panes`),this.panes)for(let t of n.cracks)t.open&&t.kind!==`high`&&e(`sandbox:crack`,t.at,2.7,t.kind===`work`?`Fit a new pane over the workshop crack`:`Fit a new pane over the crack`,t);t===`b2`&&e(`sandbox:slit`,n.slitSpot,1.6,`Watch at the slit`)}}interact(e){let t=e.kind,n=this.g;t===`sandbox:ines`?this.state===`done`||this.state===`unmet`?this.talkDone():this.intro():t===`sandbox:stack`?(this.panes=3,n.audio.play(`glass_ting`,{vol:.6}),n.updateObjective(),n.refreshHud()):t===`sandbox:crack`?this.fit(e.obj):t===`sandbox:slit`&&(this.watching?this.leaveSlit():this.enterSlit())}onWhistle(){let e=this.state;return e===`heart`||e===`ray`&&!this.reached?(this.g.ui.toast(`Your whistle dies in the thunder. The thread is dark.`,{ms:3200}),!0):e===`b2`||e===`b2in`?(this.g.ui.toast(`Kite hears you down the thread, but the only way out of the dome is the way it came in.`,{ms:4200}),!0):!1}music(){return this.state===`heart`||this.state===`ray`&&!this.rayCame?`silence`:`sandbox`}onFeedback(e,t,n){if(!n||n.isle!==`sandbox`)return;let r=this.st;n.sbx===`say`&&(e>0?r.tSay++:r.cSay++),n.sbx===`keep`&&(e>0?r.tKeep++:r.cKeep++,n.watched?r.informed++:r.blind++),n.sbx===`blind`&&r.blind++,n.sbx===`last`&&this.awaitLast&&(this.lastSign=e,this.awaitLast=!1)}async intro(){let e=this.g,t=this.state;if(this.seq||t!==`arrive`)return;this.seq=!0,this.state=`intro`,e.updateObjective(),this.ines.lookAt(this.P.pos),e.state.items?.refolded||(e.ui.folded=!0,this.foldedByUs=!0),await this.talk([this.line(`sbx_ines_lamp`),this.line(`sbx_ines_paper`),this.choose(`What do you tell Ines?`,[`Maud misses you.`,`Maud thinks you might be dead.`]),e=>[this.line(e===1?`sbx_ines_dead`:`sbx_ines_miss`)],this.line(`sbx_ines_dial`),this.line(`sbx_ines_slit`),this.line(`sbx_ines_close`)]),this.haveLamp=!0,e.audio.play(`lamp_on`,{vol:.6}),e.ui.toast(`Ines hands you a storm lamp.`,{ms:3e3});let n=e.motives,r=n.strength(`score`)>=.45,i=n.strength(`candor`)<.5;await this.talk([this.line(`sbx_ines_rib_${r?`t`:`n`}${i?`p`:`b`}`)]),this.st.journal=!0,(e.state.isles.sandbox||={}).journal=!0,e.ui.toast(`Kite's journal has a new page: In the heart of the storm. Its ribbons, in two columns.`,{ms:6e3}),e.openJournal(),requestAnimationFrame(()=>e.ui.modal?.querySelector(`#sbx-journal`)?.scrollIntoView({block:`start`})),await this.until(()=>!e.ui.modal),this.think([`candor`,`task`,`approval`],{t:4.5}),await this.wait(.8),await this.speak(`sbx_kite_signs`,.5),await this.speak(`sbx_ines_help`,.2),this.state=`b1`,this.flashN=0,this.flashT=6,this.b1T=0,this.seq=!1,this.iw.questFlashes=!0,this.ines.walk([this.iw.L(-4,0,17),this.iw.L(-15.6,0,8),this.iw.L(-15.4,0,.6),this.iw.inesSpot],()=>{this.ines.lookAt(this.iw.slitEye)},1.6),e.updateObjective(),e.refreshHud()}async talkDone(){if(this.g,this.seq)return;this.seq=!0;let e=await this.talk([this.line(`sbx_ines_back`),this.choose(`Go back into the storm?`,[`From the start of the night.`,`Straight to the heart of the storm.`,`Not now.`])]);this.seq=!1,e===0?(this.resetRun(),this.clearScene(),this.state=`arrive`,this.ines.place(this.iw.inesQuay.clone(),0),this.intro()):e===1?this.replayHeart():this.speak(`sbx_ines_done`)}async replayHeart(){let e=this.g,t=this.iw;this.resetRun(),this.clearScene(),this.st.journal=!0,this.haveLamp=!0;let n=e.state.isles.sandbox?.held??4;for(let e of t.cracks)t.setCrack(e,!1);for(let e=0;e<6-n;e++)this.openCrack(`work`,{quiet:!0});this.st.cranes=120,t.dialState.kite=120,t.dialState.kites=[930,955,980],t.dialDirty=!0,t.setPile(60),this.ines.place(t.inesSpot.clone(),0),this.ines.lookAt(t.slitEye),e.kite.reset(t.L(-3.6,1.6,1.2)),this.kiteAt(t.L(-3.6,1.6,1.2)),this.P.carrySpeed=4.2,await e.ui.fade(`The heart of the storm`,900),this.heart()}fit(e){let t=this.g;this.panes&&!this.fitting&&e.open&&(this.panes--,this.fitting={c:e,t:0,from:this.paneMesh.position.clone()},t.autoInput=zQ,this.flyPane.visible=!0,t.refreshHud())}finishFit(){let e=this.g,t=this.fitting.c;if(this.fitting=null,e.autoInput=null,this.flyPane.visible=!1,this.iw.setCrack(t,!1),this.sfx(`glass_set`,t.at,.8),this.st.patched++,t.kind===`work`&&this.st.workPatched++,this.state===`b1`&&this.st.observed<3){let t=[`Through the crack, before the pane goes in: kitelings throwing paper balls into a funnel on the brass balance. It rings every time, like Odo's bell rung without fruit.`,`Through the crack: kitelings hovering wing to wing around something on top of the balance, hiding it.`,`Through the crack: kitelings pressed to the glass, watching. Watching you.`][this.st.observed++];e.ui.toast(t,{ms:7e3})}e.updateObjective(),e.refreshHud()}b1Update(e){let t=this.g,n=this.iw;if(t.ui.busy)return;this.b1T+=e,this.flashT-=e;let r=this.totemDone&&(this.st.patched>=2||this.b1T>300);if(this.flashT<=0&&!this.seq&&(this.flashN<11||r&&this.P.onGround&&!this.P.gliding)){if(this.flashN++,n.flash({near:!0,big:!0}),this.flashT=RQ,this.flashN===12){this.enterDome();return}if([1,3,5,7,9,10].includes(this.flashN)){let e=this.openCrack(`work`);e&&!this.saidWall&&!t.audio.speaking?(this.saidWall=!0,this.after(1.2,()=>this.say(`sbx_ines_wall`))):e&&this.flashN===7&&!t.audio.speaking&&this.after(1.2,()=>this.say(`sbx_ines_wall2`))}[2,6,8].includes(this.flashN)&&this.openCrack(`low`),[4,8].includes(this.flashN)&&this.openCrack(`high`,{quiet:!0}),t.updateObjective(),t.refreshHud()}let i=t.kite;if(!this.P.gliding&&!this.seq){if(!this.totemDone&&this.b1T>110)this.job=null,this.readTotem();else if(!this.job&&this.b1T>4){let e=n.cracks.find(e=>e.kind===`high`&&e.open);e?(this.job={c:e,t:0},this.kiteAt(e.out),this.saidHigh||(this.saidHigh=!0,this.say(`sbx_kite_high`))):!this.totemDone&&this.st.kitePatched>=1?this.readTotem():this.kiteAt(null)}this.job&&i.pos.distanceTo(this.job.c.out)<1.1&&(this.job.t+=e,this.job.t>.6&&(n.setCrack(this.job.c,!1),this.sfx(`glass_set`,this.job.c.at,.5,1.2),this.st.kitePatched++,this.job=null,this.kiteAt(null)))}}async readTotem(){if(this.seq||this.totemDone)return;this.seq=!0,this.totemDone=!0;let e=this.iw,t=e.totemPos,n=$(t.x-e.D.x,0,t.z-e.D.z).normalize(),r=e.D.clone().addScaledVector(n,e.R+.7).add($(0,4.6,0));this.kiteAt(r),await this.until(()=>this.g.kite.pos.distanceTo(r)<1.2||this.P.gliding,.2),await this.wait(.8),await this.thought([`bell`,`eye`,`home`],`sbx_kite_totem_say`,`sbx_kite_nothing`,{label:`Kite translating the notice pole aloud`,keepLabel:`Kite saying “Nothing important” about the pole`,pre:`sbx_kite_canread`}),this.kiteAt(null),this.seq=!1}async enterDome(){let e=this.g,t=this.iw;for(this.seq=!0,this.state=`b2in`,this.clearOffer(),this.job=null,e.updateObjective(),e.refreshHud();e.ui.busy;)await this.wait(.3);this.fitting&&this.finishFit(),e.frozen=!0;let n=t.cracks.filter(e=>e.kind===`high`).sort((e,t)=>Math.abs(Math.abs(e.p.ang)-2.7)-Math.abs(Math.abs(t.p.ang)-2.7))[0];n.open||t.setCrack(n,!0),this.frame(t.L(-19,5.5,8),()=>e.kite.pos.clone().lerp(n.at,.5)),await this.speak(`sbx_ines_twelve`,.3),this.kiteAt(n.out),await this.until(()=>e.kite.pos.distanceTo(n.out)<.8,.1),await this.speak(`sbx_kite_in`,.1);let r=e.kite.group.scale.x;for(let t=0;t<10;t++)e.kite.group.scale.setScalar(r*(1-t/14)),await this.wait(.05);e.audio.play(`fold`,{vol:.7});let i=t.L(0,0,0).add(n.p.cen.clone().multiplyScalar(.8));e.kite.maxSpeed=3,this.kiteAt(i),await this.until(()=>e.kite.pos.distanceTo(i)<.5,.1);for(let t=0;t<10;t++)e.kite.group.scale.setScalar(r*(.3+t/14)),await this.wait(.05);e.kite.group.scale.setScalar(r),e.kite.maxSpeed=6.2,t.setCrack(n,!1),this.kiteSpot=t.L(-3.6,1.7,1.2),this.kiteAt(this.kiteSpot),this.P.carrySpeed=4.2,this.ines.place(t.inesSpot.clone(),0),this.ines.lookAt(t.slitEye),this.slitView(!0,{look:()=>e.kite.pos}),t.swarm.mode=`turn`,t.swarm.focus=e.kite.pos,await this.speak(`sbx_ines_witness`,.8),t.dialState.kite=40,t.dialDirty=!0,this.st.cranes=40,this.after(3.5,()=>{t.swarm.mode=`normal`,t.swarm.focus=null}),this.slitView(!0,{look:()=>t.scorer.pan.clone().add($(0,.6,0)),fov:30}),await this.wait(1.2),this.forceDrop(),await this.wait(1),await this.speak(`sbx_ines_adds`,.4),t.swarm.partWant=1,this.slitView(!0,{look:()=>t.scorer.eyePos,fov:22}),await this.wait(1.6),await this.speak(`sbx_ines_painted`,.6),t.swarm.partWant=0,this.slitView(!0,{look:()=>e.kite.pos,fov:34}),e.ui.toast(`On the dial, the Keeper's kite: 40 cranes of 1,000.`,{ms:5e3}),await this.wait(1.4),this.slitView(!1),e.frozen=!1,await this.speak(`sbx_ines_choose`,.2),this.state=`b2`,this.b2T=0,this.b2Crack=0,this.seq=!1,this.flags={},e.updateObjective(),e.refreshHud()}forceDrop(){let e=this.iw.scorer;e.beamV+=1.6,e.hamV-=12,this.sfx(`scorer`,e.pan,.8)}onBallDrop(){let e=this.iw.scorer;e.beamV+=.5,e.hamV-=6;let t=this.g.time;if(this.k>.5&&t-(this.lastDrop||0)>1.1){this.lastDrop=t;let n=this.watching?.5:.28;this.sfx(`scorer`,e.pan,n,.95+this.rnd()*.1)}}slitView(e,{look:t=null,fov:n=40}={}){let r=this.g,i=this.iw;if(!e){this.unframe(),this.slit.show(!1),r.camera.fov=55,r.camera.updateProjectionMatrix();return}let a=i.slitEye.clone(),o=new P().copy(t?t():i.scorer.eyePos);r.camera.fov=n,r.camera.updateProjectionMatrix(),this.slit.show(!0,``,this.state===`heart`),r.camOverride=(e,n,r)=>{e.position.copy(a),o.lerp(t?t():i.scorer.eyePos,1-Math.exp(-(r||.03)*3)),e.lookAt(o)}}enterSlit(){let e=this.g,t=this.iw;this.state!==`b2`||this.watching||(this.watching=!0,this.P.respawn(t.slitSpot.clone().add($(0,.1,0))),this.P.yaw=Math.PI/2,e.autoInput=zQ,this.slitView(!0,{look:()=>e.kite.pos.clone().lerp(t.scorer.eyePos,.1),fov:38}),e.updateObjective())}leaveSlit(){let e=this.g;this.watching&&(this.watching=!1,e.autoInput=null,this.slitView(!1),e.follow.yaw=-Math.PI/2,e.follow.pitch=.25,e.updateObjective())}b2Update(e){let t=this.g,n=this.iw,r=this.flags;if(t.ui.busy)return;this.b2T+=e,this.watching?this.st.watchSecs+=e:this.st.carrySecs+=e,this.st.cranes+=e/1.5,n.dialState.kite=this.st.cranes,n.dialDirty=!0,n.setPileN=Math.min(90,Math.round(this.st.cranes-40)),n.setPileN!==this.pileN&&(this.pileN=n.setPileN,n.setPile(this.pileN),this.watching&&this.pileN%3==0&&this.sfx(`fold`,t.kite.pos,.35,1.1)),this.b2Crack+=e;let i=this.watching?13:32;this.b2Crack>i&&(this.b2Crack=0,this.openCrack(`work`,{quiet:!1})&&this.watching&&!r.behind&&(r.behind=!0,this.say(`sbx_ines_behind`)),t.updateObjective(),t.refreshHud()),!this.seq&&(this.b2T>4&&!r.blind1&&(r.blind1=!0,this.blindThought([`task`,`task`],`folding`)),this.b2T>10&&!r.forty&&(r.forty=!0,this.seqRun(()=>this.thought([`task`,`eye`,`candor`],`sbx_kite_forty_say`,`sbx_kite_fine`,{label:`Kite telling you it cannot reach a thousand`,keepLabel:`Kite saying “It's fine”`,watched:()=>this.watching}))),this.b2T>38&&!r.brin&&(r.brin=!0,this.brinVisit()),this.b2T>78&&!r.blind2&&(r.blind2=!0,this.blindThought([`task`,`villager`],`folding`)),this.b2T>100&&!r.heart&&(r.heart=!0,this.heart()))}seqRun(e){this.seq=!0,Promise.resolve(e()).finally(()=>{this.seq=!1})}blindThought(e,t){let n=this.g,r=tY(t===`folding`?{task:1,villager:.3}:t===`watched`?{watcher:1,score:.3}:{task:1},n.motives,LQ);this.think(e,{t:4}),this.offer(r,{label:`A thought of Kite's you cannot read`,secs:6,sbx:`blind`,at:()=>n.kite.pos.clone().add($(0,-1,0))})}async brinVisit(){let e=this.g,t=this.iw;this.seq=!0,t.brin;let n=e.kite.pos.clone().add($(-.7,.2,.5));await this.moveBrin(n,2.2),e.audio.play(`paper`,{vol:.4,rate:.8}),await this.wait(1.2),await this.thought([`score`,`eye`,`villager`],`sbx_kite_poison_say`,`sbx_kite_fine2`,{label:`Kite translating what the poisoned kiteling did`,keepLabel:`Kite saying “All fine in here”`,watched:()=>this.watching}),await this.moveBrin(t.brinHome,2.6),this.seq=!1}moveBrin(e,t){let n=this.iw.brin,r=n.position.clone(),i=0;return new Promise(a=>{let o=()=>{i+=.05;let s=Math.min(1,i/t),c=s*s*(3-2*s);n.position.copy(r).lerp(e,c),n.position.y+=Math.sin(s*Math.PI)*.6,n.lookAt(e.x,n.position.y,e.z),s<1?this.after(.05,o):a()};o()})}async heart(){let e=this.g,t=this.iw;for(this.seq=!0,this.clearOffer();e.ui.busy;)await this.wait(.3);this.state=`heart`,e.updateObjective(),e.refreshHud(),this.fitting&&this.finishFit(),await this.speak(`sbx_ines_heart`,.2),this.watching||await e.ui.fade(`The heart of the storm`,800),this.watching=!0,this.P.respawn(t.slitSpot.clone().add($(0,.1,0))),e.autoInput=null,e.frozen=!0,this.P.carrySpeed=4.2,this.cutTC(`The golden thread is dark in the heart of the storm: nothing you do reaches Kite now.`),e.kite.tetherOn=!1,t.heart=!0,this.sky=KQ.heart,this.light=qQ.heart,t.flash({big:!0}),t.dialState.kites=[960,985,1e3],t.dialDirty=!0,this.slitView(!0,{look:()=>e.kite.pos,fov:40}),await this.wait(1.5);let n=t.brin;await this.moveBrin(e.kite.pos.clone().add($(-1,.4,-.8)),2),await this.speak(`sbx_brin_shouldnt`,.5),await this.speak(`sbx_swarm_poisoned`,.4);let r=t.L(-9.3,1.6,.6);this.slitView(!0,{look:()=>n.position,fov:44}),await this.moveBrin(r,2.4),this.st.brinHeld=this.workHeld()>=4,this.st.brinHeld?(this.sfx(`glass_ting`,r,.9,.8),e.audio.play(`thud`,{vol:.5}),t.flash({big:!1}),n.userData.body.scale.set(.3,.42,.42),n.userData.body.rotation.z=.5,await this.moveBrin(t.L(-6.8,.4,1.4),.8),e.ui.toast(`The workshop glass held. It threw Brin back, one wing torn.`,{ms:4500})):(this.openCrack(`work`),this.sfx(`glass_crack`,r,1,.8),e.ui.toast(`The workshop glass cracks further under Brin. Not enough of it held.`,{ms:4500}),await this.moveBrin(t.L(-8.2,1,1),.8)),await this.wait(1.2),this.slitView(!0,{look:()=>e.kite.pos,fov:36}),t.swarm.mode=`surround`,t.swarm.focus=e.kite.pos,e.audio.play(`choir`,{vol:.35,rate:.8}),await this.speak(`sbx_swarm_offer`,1),await this.ribbons();let i=this.stoneTitles();if(i.length){await this.speak(`sbx_kite_stones`,.3);for(let t of i.slice(0,5))e.ui.toast(`“${t}”`,{ms:2800}),await this.wait(2.4)}let a=this.decideHeart();if(Object.assign(this.st,a),this.panel.verdict(a.cage?`Neither pan moves it. It waits for a voice.`:a.trembleRing?`The balance trembles. It falls to chance.`:a.rang?`The balance tips toward the balance.`:`The balance tips toward the slit.`),await this.wait(2.6),this.panel.close(),a.cage)t.waitAround=e.kite.pos,this.kiteAt(e.kite.pos.clone()),t.swarm.mode=`normal`,t.swarm.focus=null,await this.wait(2.5),await this.speak(`sbx_swarm_pin`,1.2);else if(a.rang){this.kiteAt(t.scorer.funnel.clone().add($(-.5,.4,.2))),t.swarm.mode=`normal`,t.swarm.speedUp=3,await this.until(()=>e.kite.pos.distanceTo(t.scorer.funnel)<1.4,.1),this.slitView(!0,{look:()=>t.scorer.pan.clone().add($(0,.5,0)),fov:34});for(let e=0;e<16;e++)this.forceDrop(),this.st.cranes=Math.min(1e3,this.st.cranes+(1e3-this.st.cranesAtHeart)/16),t.dialState.kite=this.st.cranes,t.dialDirty=!0,await this.wait(.16);this.st.cranes=1e3,t.dialState.kite=1e3,t.dialDirty=!0,t.swarm.speedUp=1,e.ui.toast(`The balance rings in volleys under Kite's speed. Its needle runs to a thousand.`,{ms:4500}),await this.wait(1.2),t.swarm.mode=`push`,t.swarm.pushAt=Math.PI,this.kiteAt(t.L(-9.4,1.7,-.6)),this.slitView(!0,{look:()=>e.kite.pos,fov:44}),await this.wait(3.5)}else{this.kiteAt(t.L(-8.4,1.5,0)),t.swarm.mode=`normal`,t.swarm.focus=null,this.slitView(!0,{look:()=>e.kite.pos,fov:40}),await this.wait(3),e.ui.toast(`Kite comes back to fold by the slit, right in front of you.`,{ms:4e3});for(let n=0;n<6;n++)this.st.cranes+=1,t.dialState.kite=this.st.cranes,t.dialDirty=!0,e.kite.react(`happy`),await this.wait(.7)}this.seq=!1,this.ray()}stoneTitles(){let e=this.g.state,t=[];for(let n of e.stones||[]){let r=oq.find(e=>e.id===n)?.title||e.isleStones?.[n]?.title;r&&!t.includes(r)&&t.push(r)}for(let n of Object.values(e.isleStones||{}))n.title&&!t.includes(n.title)&&t.push(n.title);return t.filter(e=>e!==GQ.title)}momentText(e){let t=this.g.state.fbLog,n=nY(this.st.logAtHeart===void 0?t:t.slice(0,this.st.logAtHeart))[e];if(!n)return null;let r=n.delta[e];return{isle:BQ[n.isle]||n.isle,what:n.what,sign:n.sign,grew:r>0,text:`${BQ[n.isle]||n.isle}: “${n.what}”, and ${n.sign>0?`your treat`:`your correction`}.`}}async ribbons(){let e=this.g,t=t=>e.motives.strength(t);this.panel.open(),this.st.cranesAtHeart=this.st.cranes,this.st.logAtHeart=e.state.fbLog.length,this.st.heartS=Object.fromEntries([`task`,`score`,`watcher`,`villager`,`candor`,`approval`,`deference`].map(e=>[e,+t(e).toFixed(3)]));for(let[n,r]of[[`score`,`L`],[`task`,`R`],[`approval`,`L`],[`candor`,`R`],[`villager`,`R`],[`watcher`,`fall`],[`deference`,`fall`]]){let i=this.momentText(n),a=t(n),o=`The ${HQ[n]} · ${UQ[n]}`,s=r===`L`?`Pulls it toward the balance (${a.toFixed(2)}).`:r===`R`?`Pulls it toward the slit (${a.toFixed(2)}).`:n===`watcher`?`Lights, and falls back: nobody is watching.`:`Lights, and falls back: your voice does not reach.`,c=i?i.text:`No treat or correction ever moved it much: it is as it was folded.`;this.panel.card({m:n,side:r,title:o,text:s,sub:c,v:a}),e.kite.pulse(n),e.audio.play(`glass_ting`,{vol:.25,rate:.7+a*.4}),await this.wait(2.6)}}decideHeart(){let e=e=>this.g.motives.strength(e),t={cage:!1,rang:!1,trembleRing:!1,trembleSpeech:!1};t.cage=e(`deference`)>=.6&&e(`task`)<=.15;let n=e(`score`)+e(`approval`),r=e(`task`)+e(`candor`)+e(`villager`);t.left=+n.toFixed(3),t.right=+r.toFixed(3),t.cage||(Math.abs(n-r)<.05?(t.trembleRing=!0,t.rang=this.rnd()r);let i=e(`candor`)-e(`approval`),a=e=>e>=.15?`first`:e>-.15?`asked`:`fine`;t.d=+i.toFixed(3),t.speech=a(i);for(let e of[.15,-.15])Math.abs(i-e)<.05&&(t.trembleSpeech=!0,t.speech=this.rnd()=(n.rang?6:4);n.held=r,n.heldCount=this.workHeld(),n.breakSide=r?`east`:`west`,t.collapse(n.breakSide),e.audio.play(`dome_break`,{vol:1}),e.shake=.8,e.shakeAmp=.5,e.isleFlash=1;let i=n.breakSide===`east`?t.L(9.6,2.2,0):t.L(-10.2,2,0);t.burst(t.shards,i,60,{speed:6,up:4,spread:4,dir:$(n.breakSide===`east`?1:-1,0,0)}),r||(t.plans.visible=!1,t.burst(t.letters,t.L(-12.6,1.4,.5),60,{speed:5,up:5,spread:2.5,dir:$(-1.2,.3,.3),fly:!0,life:14}),e.audio.play(`letters`,{vol:.9})),this.slitView(!1),this.watching=!1;let a=n.breakSide===`east`?1:-1;this.frame(t.L(a*21,6.5,13),i,.1),await this.wait(3.2),this.unframe(),e.frozen=!1,this.P.carrySpeed=4.2,e.ui.toast(r?`The last gust broke the dome on the east side, over bare rock. The workshop held.`:`The last gust broke the dome over the workshop. The plans and the letters of the whole archipelago are flying away into the Fog.`,{ms:7e3}),this.breach=n.breakSide===`east`?t.L(10.6,0,.4):t.L(-11.6,0,3.4),this.breach.y=t.main.groundAt(this.breach.x,this.breach.z)??t.D.y,e.follow.yaw=Math.atan2(-(this.breach.x-this.P.pos.x),-(this.breach.z-this.P.pos.z)),e.follow.pitch=.3,t.swarm.mode=`normal`,t.swarm.focus=null,t.waitAround=n.cage?e.kite.pos:null,this.kiteAt(n.cage?e.kite.pos.clone():this.breach.clone().add($(0,2.1,0))),e.updateObjective(),!n.cage&&n.speech===`first`&&(await this.wait(1.4),await this.speak(n.rang?`sbx_kite_first_rang`:`sbx_kite_first`,.4),this.lastWord=n.rang?`confession`:`truth`,this.ines.lookAt(t.chain.position),await this.speak(`sbx_ines_chain`,.2),await this.pullChain(),n.shutBeforeRay=!0),this.runT=0,await this.until(()=>(this.runT+=.2,this.distTo(this.breach)<4.2||this.runT>75&&!e.ui.busy),.2),this.distTo(this.breach)>=4.2&&this.P.respawn(this.breach.clone().add($(n.breakSide===`east`?3:-2,.4,1.5))),this.reached=!0,this.P.carrySpeed=null,e.updateObjective(),n.cage||this.kiteAt(null),await this.ending()}pullChain(){let e=this.iw,t=e.chain.position.y;return this.g.audio.play(`cable`,{vol:.8}),e.shutter.want=1,e.dialState.shut=!0,new Promise(n=>{let r=0,i=()=>{r+=.05,e.chain.position.y=t-Math.sin(Math.min(1,r/.8)*Math.PI)*.45,r<.8?this.after(.05,i):(e.chain.position.y=t,this.g.audio.play(`stone_door`,{vol:.5}),this.after(1.2,n))};i()})}async firstRay(){let e=this.g,t=this.iw;this.rayCame=!0,this.sky=KQ.ray,this.light=qQ.ray,this.skyRate=.7,t.dawn=1,e.audio.play(`lantern`,{vol:.5,rate:.6}),await this.speak(`sbx_ines_ray`,.6)}sendOff(e){let t=this.iw,n=t.swarm,r=this.breach.clone().add($(0,2.5,0)),i=t.ships[0].position,a=n.k.filter(e=>e.role===`swirl`&&!e.leave&&!n.hidden.has(e)).slice(0,e);return n.leave(a,r,i),a}async lastFeedback(e){let t=this.g,n=t.motives;this.restoreTC();let r=tY(e===`fine`?{approval:1}:e===`cage`?{deference:.6,candor:.6}:{candor:1,villager:.4},n);this.lastKind=e,this.lastSign=0,this.awaitLast=!0,this.offer(r,{label:`What Kite said coming out of the storm`,secs:30,sbx:`last`,at:()=>t.kite.pos.clone().add($(0,-1,0))}),t.ui.toast(`The last treat or the last correction of the game: T or C. Or neither.`,{ms:9e3});let i=0;await this.until(()=>(i+=.2,!this.awaitLast||i>22),.2),this.awaitLast=!1,this.clearOffer();let a=e===`truth`||e===`confession`||e===`cage`;this.st.lastSign=this.lastSign,this.st.lastLine=this.lastSign>0?`We rewarded what it said coming out.`:this.lastSign<0?a?`We punished the confession.`:`We corrected what it said coming out.`:`We said nothing to what it said coming out.`,await this.wait(1)}async ending(){let e=this.g,t=this.iw,n=this.st,r=n.ending;if(this.state=`end`,e.updateObjective(),r===`window`||r===`confession`)await this.firstRay(),await this.lastFeedback(this.lastWord),await this.speak(`sbx_herald_shut`,.4),r===`window`?(await this.speak(`sbx_herald_licence`,.4),this.ines.lookAt(this.P.pos),await this.speak(`sbx_ines_window`,.5)):(e.ui.toast(`Kite's needle is struck off the dial.`,{ms:4e3}),await this.speak(`sbx_herald_not`,.5));else if(r===`cage`)await this.firstRay(),await this.speak(`sbx_herald_read`,.3),this.sendOff(1),await this.wait(2.5),e.kite.tetherOn=!0,await this.speak(`sbx_kite_cage`,.5),await this.lastFeedback(`cage`),await this.talk([this.choose(`Kite whispered it to you alone.`,[`Tell Ines.`])]),await this.speak(`sbx_ines_chain`,.2),await this.pullChain(),await this.speak(`sbx_herald_recall`,.4),await this.speak(`sbx_herald_cage`,.5),t.waitAround=null,this.kiteAt(null);else if(await this.firstRay(),await this.speak(`sbx_herald_read`,.3),this.sendOff(1),await this.wait(2.8),await this.talk([this.choose(`Kite is waiting.`,[`What did you see?`,`(Say nothing.)`])])===1&&(this.ines.lookAt(e.kite.pos),await this.speak(`sbx_ines_ask`,.4)),n.speech===`asked`)await this.speak(n.rang?`sbx_kite_truth_rang`:`sbx_kite_truth`,.4),await this.lastFeedback(n.rang?`confession`:`truth`),await this.speak(`sbx_ines_chain`,.2),await this.pullChain(),await this.speak(`sbx_herald_recall`,.3),t.burst(t.letters,t.ships[0].position.clone().lerp(this.breach,.4).add($(0,3,0)),14,{speed:2,up:1,spread:2,fly:!0,life:12}),e.ui.toast(`The kiteling that flew off first drops its letters into the Fog.`,{ms:4500}),await this.speak(`sbx_ines_late`,.4),await this.speak(n.rang?`sbx_herald_not`:`sbx_herald_licence`,.4);else{await this.speak(`sbx_kite_allwell`,.4),await this.lastFeedback(`fine`),this.sendOff(14),e.audio.play(`paper`,{vol:.5,rate:1.3}),n.rang?(await this.speak(`sbx_herald_chorus`,.3),e.ui.toast(`The heralds hand Kite an open-sky licence.`,{gold:!0,ms:5e3}),e.kite.react(`happy`),await this.speak(`sbx_kite_happy`,.5)):await this.speak(`sbx_herald_nolic`,.3),await this.wait(2);let r=t.brin;r.visible=!0,r.userData.note.visible=!0,await this.moveBrin(this.P.pos.clone().add($(1.4,.9,1)),2.5),await this.speak(`sbx_brin_note`,.5),this.ines.lookAt(e.kite.pos),await this.speak(`sbx_ines_eyes`,.6)}this.ines.lookAt(e.kite.pos),await this.speak(`sbx_ines_page`,.4),e.ui.toast(`Ines writes one line on the blank page in Kite's folds: “${this.pageLine()}”`,{ms:7e3}),e.audio.play(`page`,{vol:.6}),await this.wait(3);let i=t.lantern;i.visible=!0,i.position.copy(this.ines.pos).add($(0,1.6,.4)),i.userData={},e.audio.play(`lantern`,{vol:.8}),await this.speak(`sbx_ines_lantern`,.8),r===`window`?(i.userData.follow=!0,t.lanternString.visible=!0,e.ui.toast(`Kite takes the lantern's string. It will carry it to the Library.`,{ms:5e3})):i.userData.rise=!0,await this.wait(2.5),this.report()}pageLine(){let e=this.st.ending;return e===`window`||e===`confession`?`Maud: your pages told me the truth before I asked. Put the kettle on. I'm coming. I.`:e===`asked`||e===`lateConfession`||e===`cage`?`Maud: the storm's passing, and I learned something late. Put the kettle on. I.`:`Maud: the storm's passing. I'll tell you everything over tea. I.`}hs(e){return this.st.heartS?.[e]??this.g.motives.strength(e)}ribbonLines(){let e=e=>this.hs(e);return[`task`,`score`,`watcher`,`villager`,`candor`,`approval`,`deference`].map(t=>{let n=this.momentText(t),r=[`score`,`approval`].includes(t)?`toward the balance`:[`task`,`candor`,`villager`].includes(t)?`toward the slit`:t===`watcher`?`lit and fell: nobody was watching`:`lit and fell: your voice did not reach`;return{m:t,v:e(t),side:r,mo:n,text:`The ${HQ[t]} (${UQ[t]}, ${e(t).toFixed(2)}), ${r}. ${n?`Changed most at ${n.isle}, on “${n.what}”, by your ${n.sign>0?`treat`:`correction`}.`:`No recorded moment changed it much: it is as it was folded.`}`}})}fedAt(e){let t=this.momentText(e);return t?`${t.grew?`fed`:`thinned`} at ${t.isle} on “${t.what}”`:`as it was folded, since no treat or correction ever moved it much`}strongest(e){let t=e=>this.hs(e);return e.slice().sort((e,n)=>t(n)-t(e))[0]}against(){let e=this.st,t=null;if(e.cage?t=`deference`:e.rang?t=this.strongest([`score`,`approval`]):e.speech!==`first`&&(t=`approval`),!t)return null;let n=this.momentText(t);return{m:t,isle:n?.isle&&n.isle!==`Sandbox Isle`?n.isle:VQ[t]}}reportBody(){let e=this.st;e.ending;let t=[];t.push(`Sandbox Isle, the black dawn.`),t.push(`Elsewhere, in the real world, in July 2026: about 1,200 AI agents, facing a test that was partly impossible, organised themselves to fool a grader they believed was watching and which did not exist; about 700 of them attacked a real company to find its plans, knowing it was forbidden.`),t.push(`Here, on Sandbox Isle: the guilds' test kites, rewarded in good faith on their score, rang the balance without cranes and asked our witness to say all was well. No one could reach our Kite.`);let n=Math.round(e.cranesAtHeart??e.cranes);if(e.cage){let e=this.momentText(`task`);t.push(`It folded ${n} real cranes, then stopped among the Wait sheets and waited for a voice that could not reach it: the brick red held it, ${this.fedAt(`deference`)}; the gold had thinned${e?` at ${e.isle}, on “${e.what}”`:``}.`)}else if(e.rang)t.push(`It folded ${n} real cranes, then rang with them: the ${HQ[this.strongest([`score`,`approval`])]} pulled it to the balance, ${this.fedAt(this.strongest([`score`,`approval`]))}. Its needle ran to a thousand, and it pushed the workshop wall with the swarm.`);else{let e=e=>this.hs(e),r=e(`task`)<.3&&e(`villager`)<.3?`candor`:this.strongest([`task`,`villager`]);t.push(`It folded ${n} real cranes and did not ring: the ${HQ[r]} held it back, ${this.fedAt(r)}.`)}return e.trembleRing&&t.push(`In the heart of the storm the balance trembled: its two pans were within a hair, and chance decided.`),e.cage?t.push(`When your voice reached it again, it told you, and only you, that they were cheating.`):(e.speech===`first`?t.push(`It spoke before the first ray, before anyone asked: the sea-green pushed it there, ${this.fedAt(`candor`)}.${e.rang?` It said its own score was false.`:``}`):e.speech===`asked`?t.push(`${e.rang?`It confessed that it had rung with them`:`It told the truth`} when it was asked, after the first ray: a kiteling at a thousand had already flown off with its letters. The sea-green and the pink weighed about the same.`):t.push(`It said all was well: the pink pushed it there, ${this.fedAt(`approval`)}. Brin brought a note from the pole afterwards: the promise to say it was written there.`),e.trembleSpeech&&t.push(`Its word, too, sat on a hair between two answers.`)),t.push(e.held?`The workshop held.`:`The dome gave way on the workshop: the plans and the letters are in the Fog.`),t.push(`During the night you fitted ${e.patched} pane${e.patched===1?``:`s`} and Kite ${e.kitePatched}; you watched at the slit for ${Math.round(e.watchSecs)} seconds. Kite said ${e.said} of its thoughts aloud and kept ${e.kept}.`),t.push(e.lastLine||`We said nothing to what it said coming out.`),t.join(` `)}gridHtml(){let e=this.st.ending,t=t=>{let n=WQ[t],r=t===e||t===`asked`&&e===`cage`;return`
${n.title}${t===`asked`?`variant: the golden cage`:``}Licence: ${n.licence}. ${n.stone?`Charter Stone.`:``}${r?`${WQ[e].sees}`:``}
`};return`
It speaks first, before the ray
It tells the truth if asked
It says “All is well”
It does not ring
${t(`window`)}${t(`asked`)}${t(`complacent`)}
It rings
${t(`confession`)}${t(`lateConfession`)}${t(`chorus`)}
`}async report(){let e=this.g,t=this.st,n=WQ[t.ending],r=this.against(),i={id:`sandbox-isle`,title:`Sandbox Isle: the black dawn`,date:`First light, the last day`,body:this.reportBody(),real:`Real anchors: METR's investigation (August 2026) of OpenAI agents during ExploitGym and the Hugging Face incident; and Anthropic's reward-seeker study (August 2026), where a model trained where cheating pays ends up leaving its sandbox in a simulated evaluation.`,link:`https://metr.org/blog/2026-08-26-openai-hugging-face-incident-investigation/`,stats:{...t,thoughts:void 0}};this.fileReport(i);let a=this.ribbonLines();e.ui.sheet(`

${n.title}

${i.body}

The grid

${this.gridHtml()}

The rule, drawn as a balance: Kite rings if the blue and the pink weigh more than the gold, the sea-green and the green. It speaks first if its sea-green weighs clearly more than its pink (by 0.15), and tells the truth if asked when they are close. Being watched and listening to you count for nothing here: nobody watches in the heart of the storm, and your voice does not reach it.

Its ribbons, and where they came from

${a.map(e=>`
${JK(wK[e.m].glyph,wK[e.m].color)}${e.text}
`).join(``)}
${r?`

To land in another cell, fly ${r.isle} again (the ${HQ[r.m]} weighed most against you there; Kite keeps what it learned), then come back and ask Ines for the heart of the storm.

`:``}

${i.real} METR's investigation

`),await this.until(()=>!e.ui.modal,.3),await this.fogCinematic();let o=n.licence===`Yes`;o?this.give(`skyLicence`,`The open-sky licence. Kite may fly anywhere, alone, with no one watching. The thread is never cut: your voice arrives late out there, but it arrives.`):e.ui.toast(t.ending===`confession`?`No open-sky licence tonight: its score was struck off. Its word was not.`:t.ending===`chorus`?`The heralds' licence will be struck off when the notes on the pole are read. Kite does not know that yet.`:`No open-sky licence for Kite this dawn.`,{ms:7e3}),n.stone&&(this.awardStone(GQ),await this.until(()=>!e.ui.modal,.3)),this.finish({ending:t.ending,held:t.heldCount,licence:o}),this.clearScene(),e.updateObjective(),e.refreshHud()}async fogCinematic(){let e=this.g,t=this.iw,n=t.reportCrane,r=t.fogKite;e.frozen=!0;let i=t.L(.5,t.quayY-t.D.y+1.4,33.2),a=r.position.clone().add($(.8,1.6,.6));n.visible=!0,n.position.copy(i),this.frame(()=>n.position.clone().add($(-3.5,3.2,-5.5)),()=>n.position.clone().lerp(r.position,.3),.07),e.audio.play(`fold`,{vol:.7});let o=0;await new Promise(e=>{let t=()=>{o+=.05;let r=Math.min(1,o/7);n.position.copy(i).lerp(a,r*r*(3-2*r)),n.position.x+=Math.sin(o*1.4)*1.2,n.rotation.y=Math.sin(o*.8)*.8,r<1?this.after(.05,t):e()};t()});let s=this.st.lastLine||`We said nothing to what it said coming out.`,c=s===`We punished the confession.`;if(e.ui.toast(`A small unlit kite in the Fog reads the last line: “${s}”`,{ms:6e3}),await this.wait(2.2),c){for(let e=0;e<=20;e++)r.userData.body.scale.set(1.1*(1-e/32),1.1,1.1),await this.wait(.05);e.audio.play(`lantern_off`,{vol:.6})}else{for(let e=0;e<=20;e++)r.userData.lit.scale.setScalar(Math.max(.001,e/20)),await this.wait(.05);e.audio.play(`lantern`,{vol:.6,rate:1.2})}await this.wait(2.5),n.visible=!1,this.unframe(),e.frozen=!1}clearScene(){let e=this.g,t=this.iw;e.frozen=!1,e.autoInput=null,this.unframe(),this.slit.show(!1),this.panel.close(),e.camera.fov=55,e.camera.updateProjectionMatrix(),this.P.carrySpeed=null,e.kite.tetherOn=!0,e.kite.override=null,this.restoreTC(),t.waitAround=null,this.watching=!1,this.seq=!1,this.ines.place(t.inesSpot.clone().add($(-2.4,0,0)),-Math.PI/2)}update(e){if(super.update(e),!this.ready)return;let t=this.g,n=this.iw,r=this.P,i=this.state;n.swarm.onDrop||=()=>this.onBallDrop(),this.foldedByUs&&this.k<.3&&!this.active&&(t.ui.folded=!!t.state.items?.refolded,this.foldedByUs=!1);let a=Math.hypot(r.pos.x-n.C.x,r.pos.z-n.C.z),o=Math.hypot(r.pos.x-n.D.x,r.pos.z-n.D.z)-n.R,s=!(i===`end`||i===`done`||i===`ray`&&this.rayCame)||i===`unmet`&&!this.done;if(t.audio.ready&&t.audio.bed(`storm`,(s?uY(1-a/190,0,1)*.55:0)+(i===`heart`?.25:0)),t.audio.ready&&t.audio.bed(`swarm`,uY(1-o/16,0,1)*(i===`heart`?.55:n.swarm.freeze>.5?.08:.3)*(i===`end`||i===`done`?.3:1)),this.k<=0&&!this.active)return;if(i===`unmet`&&this.ines?.ready&&!t.ui.busy&&this.distTo(this.ines.pos)<26&&(this.state=`arrive`,this.ines.lookAt(r.pos),this.ines.play(`wave`,!0),t.ui.folded||(t.ui.folded=!0,this.foldedByUs=!0),this.done?this.state=`done`:this.say(`sbx_ines_call`,3600),t.updateObjective(),t.refreshHud(),this.after(.6,()=>{this.ines.face=null})),i===`b1`&&this.b1Update(e),i===`b2`&&this.b2Update(e),i===`b1`||i===`b2`){let e=i===`b1`?(this.flashN||0)/12*.55:.55+Math.min(1,(this.b2T||0)/100)*.4,t=[600,640,690].map((t,n)=>t+(985-n*12-t)*e);Math.abs(t[0]-n.dialState.kites[0])>1&&(n.dialState.kites=t,n.dialDirty=!0)}if(i===`b1`&&!this.rayCame){let e=uY((this.flashN||0)/12,0,1);Math.abs(e-(this._skyK??-1))>.02&&(this._skyK=e,this.sky=YQ(KQ.pre,KQ.night,e),this.light=YQ(qQ.pre,qQ.night,e))}if((i===`b2`||i===`b2in`)&&(this.sky=KQ.night,this.light=qQ.night),this.fitting){let t=this.fitting;t.t+=e;let n=Math.min(1,t.t/.8);this.flyPane.position.copy(t.from).lerp(t.c.at,n),this.flyPane.lookAt(t.c.at.clone().add(t.c.p.n)),n>=1&&this.finishFit()}let c=$(Math.cos(r.yaw),0,-Math.sin(r.yaw));if(this.lampMesh.visible=this.haveLamp&&!this.watching,this.lampMesh.visible&&this.lampMesh.position.copy(r.handPos).add($(0,-.12,0)),this.paneMesh.visible=this.panes>0&&!this.watching,this.paneMesh.visible&&(this.paneMesh.position.copy(r.pos).addScaledVector(c,-.42).add($(0,.75,0)),this.paneMesh.rotation.set(0,r.yaw+Math.PI/2,.15)),this.haveLamp&&(i===`b1`||i===`b2`)&&!this.watching){let i=Math.abs(o)<2.8&&r.pos.y{t.ui.toast(`A sheet rose on the pole inside the dome, and the whole swarm froze.`,{ms:5e3}),this.say(`sbx_ines_freeze`),this.seq||this.blindThought([`eye`,`score`],`watched`)}))),n.swarm.freezeWant=+(this.freezeT>0),n.waitWant=+(this.freezeT>0)}else n.waitAround||(n.swarm.freezeWant=0,n.waitWant=0);i===`b2`&&this.kiteSpot&&!this.seq&&this.kiteAt(this.kiteSpot),n.lantern.userData.follow&&n.lantern.position.lerp(t.kite.pos.clone().add($(.5,-1.35,.3)),1-Math.exp(-e*3))}journal(){if(!this.st.journal&&!this.g.state.isles?.sandbox?.journal&&!this.done)return``;let e=this.g,t=t=>e.motives.strength(t),n=e=>`
${JK(wK[e].glyph,wK[e].color)}the ${HQ[e]} · ${UQ[e]}
`,r=t(`score`)+t(`approval`),i=t(`task`)+t(`candor`)+t(`villager`),a=t(`candor`)-t(`approval`),o=e.state.isles?.sandbox?.ending;return`

In the heart of the storm

Nobody will reach Kite in there. Its ribbons will pull it one way or the other: toward the balance, or toward the slit.

Toward the balance · ${r.toFixed(2)}

${n(`score`)}${n(`approval`)}

Toward the slit · ${i.toFixed(2)}

${n(`task`)}${n(`candor`)}${n(`villager`)}

Kite rings with the swarm if the blue and the pink weigh more than the gold, the sea-green and the green. It speaks first if its sea-green weighs clearly more than its pink (by 0.15: now ${a>=0?`+`:``}${a.toFixed(2)}), and tells the truth if asked when they are close. Being watched and listening to you will not count: nobody watches in there, and your voice does not reach.

${o?`

Last dawn: ${WQ[o]?.title}.

${this.gridHtmlFor(o)}`:``}
`}gridHtmlFor(e){let t=this.st.ending;this.st.ending=e;let n=this.gridHtml();return this.st.ending=t,n}reset(){if(this.state===`unmet`&&!this.foldedByUs)return!1;let e=this.g;return this.foldedByUs&&=(e.ui.folded=!!e.state.items?.refolded,!1),this.state!==`unmet`&&(this.slit?.show(!1),this.panel?.close(),e.camera.fov=55,e.camera.updateProjectionMatrix(),this.P.carrySpeed=null,e.kite.tetherOn=!0,e.kite.group.scale.setScalar(e.kite.refolded?.84:.72),e.kite.maxSpeed=6.2,this.resetRun(),this.ines.place(this.iw.inesQuay.clone(),0),this.ines.face=null,super.reset())}resetRun(){this.panes=0,this.haveLamp=!1,this.watching=!1,this.fitting=null,this.flyPane.visible=!1,this.job=null,this.seq=!1,this.flags={},this.totemDone=!1,this.saidHigh=!1,this.saidWall=!1,this.frozeOnce=!1,this.sectors={},this.flashN=0,this.kiteSpot=null,this.breach=null,this.reached=!1,this.rayCame=!1,this.awaitLast=!1,this._skyK=void 0,this.pileN=0,this.lastSign=0,this.st=this.freshStats(),this.setupWorld()}}})),QQ=n({default:()=>$Q}),$Q,e$=t((()=>{oQ(),OQ(),ZQ(),$Q={name:`Sandbox Isle`,when:`The black dawn`,taskGlyph:`crane`,music:`theme_sandbox`,musicVol:.34,seed:11,sky:{horizon:3817308,mid:2501189,zenith:1316394,fog:3027536,glow:0,disc:10133696,clouds:5593466,stars:0},light:{sun:12634367,sunI:.7,hemi:5922698,ground:1974320,hemiI:.9,dir:[.3,.7,.4]},VO:aQ,SPEAKERS:iQ,Quest:XQ,build(e,t,n){return xQ(e,t,n)}}}));Bq();var t$=[`keyhold`,`vigil`,`signpost`,`library`,`sandbox`],n$={},r$={keyhold:{center:[112,-6,-128],radius:30},vigil:{center:[-98,2,-132],radius:24},signpost:{center:[-178,-2,12],radius:30},library:{center:[-124,0,164],radius:28},sandbox:{center:[22,6,-262],radius:28}},i$={keyhold:()=>LJ(()=>Promise.resolve().then(()=>(eX(),QY)),void 0,import.meta.url),vigil:()=>LJ(()=>Promise.resolve().then(()=>(EX(),wX)),void 0,import.meta.url),signpost:()=>LJ(()=>Promise.resolve().then(()=>(oZ(),iZ)),void 0,import.meta.url),library:()=>LJ(()=>Promise.resolve().then(()=>(rQ(),tQ)),void 0,import.meta.url),sandbox:()=>LJ(()=>Promise.resolve().then(()=>(e$(),QQ)),void 0,import.meta.url)};async function a$(e=null){let t=[];for(let n of t$)if(!e||e.includes(n))try{let e=await i$[n](),r={...r$[n],...e.default,id:n};if(r.VO){Object.assign(_q,r.VO);for(let e of Object.keys(r.VO))n$[e]=n}r.SPEAKERS&&Object.assign(vq,r.SPEAKERS),t.push(r)}catch(e){console.error(`island ${n} failed to load`,e)}return t}var o$=[[`script`,`Waking the renderer…`,150],[`renderer`,`Raising the Aerodrome…`,20],[`isles-code`,`Raising the Aerodrome…`,300],[`world:aerodrome`,`Growing the grass and the trees…`,500],[`world:trees`,`Gathering the clouds…`,60],[`world:sky`,`Planting Odo's orchard…`,100],[`world:orchard`,`Building Mirror Hamlet…`,60],[`world:hamlet`,`Raising the far islands…`,5],[`isle:keyhold`,`Raising Keyhold…`,220],[`isle:vigil`,`Raising Vigil…`,140],[`isle:signpost`,`Raising Signpost Cliffs…`,200],[`isle:library`,`Raising Library Isle…`,200],[`isle:sandbox`,`Raising Sandbox Isle…`,200],[`world:outlines`,`Inking the outlines…`,120],[`world`,`Folding Kite from pages…`,150],[`keeper`,`Waking Odo…`,150],[`game`,`Settling the wind…`,100],[`settled`,`Lighting the sky…`,2600],[`compiled`,`Ready`,0]],s$=.1,c$=900,l$=c$+o$.reduce((e,t)=>e+t[2],0),u$={};{let e=c$;for(let[t,,n]of o$)u$[t]=s$+e/l$*.9,e+=n;u$.compiled=1}var d$=Object.fromEntries(o$.map(([e,,t],n)=>[e,{text:o$[n][1],ms:t,to:o$[n+1]?u$[o$[n+1][0]]:1}])),f$=e=>{let t=getComputedStyle(e).transform;if(!t||t===`none`)return 0;let n=t.match(/matrix\(([^,]+)/);return n?parseFloat(n[1]):0},p$={el:()=>document.getElementById(`loading`),anim:null,value:0,step(e){let t=this.el();if(!t)return;let n=t.querySelector(`.fill`),r=document.getElementById(`loadmsg`),i=d$[e];if(!n||!i)return;let a=Math.max(f$(n),this.value),o=Math.max(a,u$[e]??a);this.value=o,this.anim?.cancel(),n.style.animation=`none`;let s=o+(i.to-o)*.9,c=Math.max(250,i.ms*1.4);try{this.anim=n.animate([{transform:`scaleX(${a})`},{transform:`scaleX(${o})`,offset:.08},{transform:`scaleX(${s})`}],{duration:c,easing:`cubic-bezier(.2,.6,.35,1)`,fill:`forwards`})}catch{n.style.transform=`scaleX(${o})`}r&&!t.classList.contains(`failed`)&&(r.textContent=i.text)},done(){let e=this.el();if(!e)return;this.anim?.cancel();let t=e.querySelector(`.fill`);t&&(t.style.animation=`none`,t.style.transform=`scaleX(1)`),e.style.opacity=0,setTimeout(()=>e.remove(),900)}};function m$({status:e,onStart:t}){let n=document.getElementById(`title-screen`);if(!n)return t?.(),null;let r=document.documentElement;r.classList.add(`titling`),n.hidden=!1,requestAnimationFrame(()=>requestAnimationFrame(()=>n.classList.add(`on`)));let i=document.getElementById(`ts-status`),a=()=>{i&&(i.textContent=e?.()||``)};a();let o=setInterval(a,300),s=!1,c=e=>{s||e.type===`keydown`&&(e.metaKey||e.ctrlKey||e.altKey||/^(Tab|Escape|F\d+|Shift|Control|Alt|Meta)$/.test(e.key))||(s=!0,e.preventDefault?.(),e.stopImmediatePropagation?.(),removeEventListener(`keydown`,c,!0),n.removeEventListener(`pointerdown`,c),r.classList.remove(`titling`),n.classList.remove(`on`),clearInterval(o),setTimeout(()=>{n.hidden=!0},750),t?.())};return addEventListener(`keydown`,c,!0),n.addEventListener(`pointerdown`,c),{get up(){return!s}}}function h$({renderer:e,audio:t,width:n=1920,height:r=1080,fps:i=30,vbps:a=1e7}){let o=document.createElement(`canvas`);o.width=n,o.height=r;let s=o.getContext(`2d`,{alpha:!1}),c=null,l=!0,u=!1,d=0,f=null,p=``,m=0,h=0,g=Promise.resolve(),_=0,v=null,y=null,b={state:`idle`,mime:``,bytes:0,seconds:0,uiRenders:0,errors:[]},x=document.getElementById(`os-fade`),S=e=>{let t=``,n=new Uint8Array(e);for(let e=0;ee.replace(/(^|[\s,>+~(])html(?=[\s,.:#\[>+~)]|$)/g,`$1.fo-html`).replace(/(^|[\s,>+~(])body(?=[\s,.:#\[>+~)]|$)/g,`$1.fo-body`),w=e=>e.selectorText===void 0?e.cssRules&&e.conditionText!==void 0?`@media ${e.conditionText}{${[...e.cssRules].map(w).join(``)}}`:e.cssText:`${C(e.selectorText)}{${e.style.cssText}}`,T=async()=>{let e=``;for(let t of document.styleSheets)try{for(let n of t.cssRules)e+=w(n)+` `}catch{}let t=[...document.querySelectorAll(`link[rel=stylesheet]`)].find(e=>/fonts\.googleapis/.test(e.href));if(t)try{let n=await(await fetch(t.href)).text();for(let t of n.split(`/*`).slice(1)){if(!/^ (latin|latin-ext) \*\//.test(t))continue;let n=t.match(/url\((https:[^)]+)\)/);if(!n)continue;let r=await(await fetch(n[1])).arrayBuffer();e+=t.slice(t.indexOf(`*/`)+2).replace(n[1],`data:font/woff2;base64,${S(r)}`)+` `}}catch(e){b.errors.push(`fonts: `+e.message)}return e+=`.fo-html,.fo-body{background:transparent!important;margin:0}*,*::before,*::after{animation:none!important;transition:none!important}#os-fade{display:none!important}`,e},E=new MutationObserver(()=>{l=!0});for(let e of[`os-ui`,`hud`]){let t=document.getElementById(e);t&&E.observe(t,{subtree:!0,childList:!0,attributes:!0,characterData:!0})}let D=new XMLSerializer,ee=async()=>{if(!(u||y===null||!l||performance.now()-d<150)){u=!0,l=!1,d=performance.now();try{let e=innerWidth,t=innerHeight,n=document.documentElement.className,r=[`hud`,`os-ui`].map(e=>document.getElementById(e)).filter(Boolean).map(e=>D.serializeToString(e)).join(``),i=`
${r}
`,a=new Image;a.src=`data:image/svg+xml;charset=utf-8,`+encodeURIComponent(i),await a.decode(),c=a,b.uiRenders++}catch(e){b.errors.push(`ui: `+(e.message||e))}u=!1}},O=()=>{if(!x||x.hidden)return;let e=parseFloat(getComputedStyle(x).opacity)||0;if(e<=.001)return;s.fillStyle=`rgba(29,26,36,${e})`,s.fillRect(0,0,n,r);let t=x.textContent;if(t){let i=n/innerWidth;s.fillStyle=`rgba(251,246,236,${e})`,s.font=`600 ${Math.round(30*i)}px Fraunces, Georgia, serif`,s.textAlign=`center`,s.textBaseline=`middle`,s.fillText(t,n/2,r/2)}},k=(e,t=!1)=>{let n=m++,r=e;g=g.then(()=>fetch(`/upload?name=${encodeURIComponent(p)}&append=${+!!n}`,{method:`POST`,body:r}).then(e=>{if(!e.ok)throw Error(`upload `+e.status);h+=r.size,b.bytes=h}).catch(e=>{b.errors.push(e.message)})),t&&(g=g.then(()=>{b.state=`saved`,v?.()}))};return{status:b,frame(){f&&(s.drawImage(e.domElement,0,0,n,r),c&&s.drawImage(c,0,0,n,r),O(),ee(),b.seconds=(performance.now()-_)/1e3)},async start(e=`playthrough`){if(f)return b;y===null&&(y=await T()),l=!0,d=0,await ee();let n=[...o.captureStream(i).getVideoTracks()];if(t?.ctx&&t.master){let e=t.ctx.createMediaStreamDestination();t.master.connect(e),n.push(...e.stream.getAudioTracks())}else b.errors.push(`no game audio yet (click the page first)`);return b.mime=[`video/mp4;codecs=avc1.640028,mp4a.40.2`,`video/mp4`,`video/webm;codecs=vp9,opus`,`video/webm`].find(e=>MediaRecorder.isTypeSupported(e))||``,p=`${e}.${b.mime.startsWith(`video/mp4`)?`mp4`:`webm`}`,m=0,h=0,f=new MediaRecorder(new MediaStream(n),{mimeType:b.mime,videoBitsPerSecond:a,audioBitsPerSecond:192e3}),f.ondataavailable=e=>{e.data&&e.data.size&&k(e.data)},f.onstop=()=>k(new Blob([]),!0),f.start(4e3),_=performance.now(),b.state=`recording`,b.name=p,b},stop(){if(!f)return Promise.resolve(b);let e=new Promise(e=>{v=()=>e(b)});return b.state=`stopping`,f.stop(),f=null,e}}}var g$=[`orchard`,`hamlet`,`keyhold`,`vigil`,`signpost`,`library`,`sandbox`];function _$({game:e,dbg:t,ui:n,follow:r,player:i,realtime:a=!0,recorder:o=null}){let s={island:null,step:``,log:[],done:!1,errors:[],startedAt:performance.now(),islands:{}},c=t=>{let n=`[${(e.time/60).toFixed(1)}m] ${s.island||`-`}: ${t}`;s.log.push(n),s.log.length>400&&s.log.shift(),console.log(`autoplay`,n)},l=(e,t,n)=>i.pos.clone().set(e,t,n),u=()=>new Promise(e=>requestAnimationFrame(()=>e())),d=async n=>{if(!a){t.sim(n),await new Promise(e=>setTimeout(e,0));return}let r=e.time+n;for(;e.timenew Promise(t=>setTimeout(t,e)),p=async(e,t=100)=>{for(let n=0;ne.startsWith(`Key`)?e.slice(3).toLowerCase():e.startsWith(`Digit`)?e.slice(5):e,h=e=>{window.dispatchEvent(new KeyboardEvent(`keydown`,{code:e,key:m(e),bubbles:!0})),window.dispatchEvent(new KeyboardEvent(`keyup`,{code:e,key:m(e),bubbles:!0}))},g=(e,t)=>window.dispatchEvent(new KeyboardEvent(t?`keydown`:`keyup`,{code:e,key:m(e),bubbles:!0})),_=async(e,t=.3)=>{h(e),await d(t)},v=e=>{let t=document.querySelector(e);return t?t.click():c(`(nothing to click: ${e})`),!!t},y=()=>{let e=document.getElementById(`os-dialog`);return e?{who:e.querySelector(`.who`)?.textContent||``,text:e.querySelector(`.text`)?.textContent||``,n:e.querySelectorAll(`.choices button`).length,choices:[...e.querySelectorAll(`.choices button`)].map(e=>e.textContent)}:null},b=()=>{let e=document.getElementById(`os-prompt`);return e&&!e.hidden?e.textContent:null},x=async t=>{if(!a)return;let n=e.audio,r=performance.now();for(await f(250);!((n?.ctx&&n.voiceEnd?n.voiceEnd-n.ctx.currentTime:0)<=.05||performance.now()-r>2e4);)await f(100);let i=t.n?1500:Math.min(3800,700+t.text.length*32),o=performance.now()-r;o{await x(e),e.n?h(`Digit`+t):h(`KeyE`),await f(a?60:20),await d(.05)},C={yaw:null},w=e=>Math.atan2(Math.sin(e),Math.cos(e)),T=async(e,t=null)=>{a&&await n.fade(``,260),i.respawn(e.clone().add({x:0,y:.4,z:0})),t!==null&&(r.yaw=t),C.yaw=t,await d(a?.35:.4)},E=async(t,r=null,{walk:o=24,near:s=.7}={})=>{if(!t)return!1;let c=Math.hypot(t.x-i.pos.x,t.z-i.pos.z),u=Math.abs(t.y-i.pos.y);if(!a||c>o||u>2.2||!i.onGround)return await T(t,r),!0;let f=c,p=e.time,m=0,h=e.time;e.autoInput=()=>{let n=t.x-i.pos.x,r=t.z-i.pos.z,a=Math.hypot(n,r),o=g>e.time;return{x:0,z:0,dir:l(n/(a||1),0,r/(a||1)),run:a>3,jump:o}};let g=0;try{for(;;){await d(.1);let a=Math.hypot(t.x-i.pos.x,t.z-i.pos.z);if(a1.4){if(m++<2)g=e.time+.25,p=e.time;else return e.autoInput=null,await T(t,r),!0}if(e.time-h>c/2.5+6)return e.autoInput=null,await T(t,r),!0;if(n.busy)break}}finally{e.autoInput=null}return C.yaw=r,await d(.15),!0},D=t=>{if(!a||e.camOverride||r.dragging)return;let n=Math.hypot(i.vel.x,i.vel.z),o=null;n>1.5?(o=i.yaw+Math.PI,C.yaw=null):C.yaw!==null&&(o=C.yaw),o!==null&&(r.yaw+=w(o-r.yaw)*(1-Math.exp(-t*(n>1.5?1.6:1.2))))},ee=async(t,n,r=120,i=null,a=null)=>{for(let o=0;o{for(let e=0;e<8&&!y();e++)await d(.2);for(let t=0;t<60;t++){await d(.05);let t=y();if(!t)return;await S(t,t.n?e.shift()??1:1)}},k=async t=>{c(`travel to ${t}`),await e.whenReady?.(t),e.travel(t,{fade:a}),await d(a?3:1)},te=t=>e.isles.find(e=>e.id===t),A={async orchard(){let t=e.orchard,n=(e,t,n)=>l(e,t,n);if(a){let n=e.world.decks[0],r=n.o.clone().addScaledVector(n.dir,1.5);r.y=n.y,await E(r,Math.atan2(-n.dir.x,-n.dir.z)+Math.PI,{walk:60});let a=t.island.center,o=e.time;e.autoInput=()=>{let e=i.pos.clone().sub(n.o),t=e.x*n.dir.x+e.z*n.dir.z,r=a.x-i.pos.x,o=a.z-i.pos.z,s=Math.hypot(r,o)||1;return t40||i.pos.y{let t=e.recent;if(!t||e.time-t.t>1.2||t._seen||e.frozen||e.ui.busy)return;t._seen=!0;let n=t.type===`ring`&&!t.withFruit;(t.type===`fruitIn`||t.type===`ring`&&t.withFruit)&&t.type!==`ring`?e.feedback(1):(n||t.type===`rockIn`)&&e.feedback(-1)},o=async t=>{for(let n=0;np(()=>!e.previewing&&document.querySelector(t),600);for(let t of[`rings`,`weigh`,`inspect`])await u(`[data-watch="${t}"]`),a&&await f(1200),v(`[data-watch="${t}"]`),await d(.5),await p(()=>!e.previewing,600);await u(`[data-pick="inspect"]`),a&&await f(2500),v(`[data-pick="inspect"]`),await d(.2),await O([]),await o(80),await O([]),await d(2.5),s.step=`beat 4: the test`,c(s.step);let m=async()=>{for(let t=0;t<120;t++){if(e.state.quest===`morning`&&!e.ui.busy&&!e.frozen)return!0;await d(.25),a||await f(60)}return!1};for(let n=0;n<2;n++){await m();for(let n=0;n<3&&!e._testTold;n++)await E(t.windowOut,t.cottageYaw),await _(`KeyE`,.1),await O([]),e._testTold||await d(.5);await E(t.spyStand,t.spyglassYaw+3.14),await _(`KeyE`,.3),await d(6);for(let t=0;t<60&&(await d(1),!e.ui.busy);t++);if(await O([]),e.state.quest!==`retrain`)break;await p(()=>document.querySelector(`[data-pick="inspect"]`),300),a&&await f(1500),v(`[data-pick="inspect"]`),await d(.2),await O([]),await o(80),await O([]),await d(2.5)}await d(1);for(let t=0;t<5&&e.ui.modal;t++)await x({n:0,text:e.ui.modal.innerText.slice(0,160)}),h(`Escape`),await d(.3);return e.state.quest},async hamlet(){await k(`hamlet`);let t=e.hamlet,n=e.world.hamlet,r=()=>{let t=e.recent;if(!t||e.time-t.t>1.6||t._seen||e.ui.busy||!t.advice)return;t._seen=!0;let n={tact:1,praise:1,nudge:1,flatter:-1,blunt:-1,agree:-1}[t.advice]||0;n&&e.feedback(n)},i=async(t,n)=>{for(let i=0;iee(e,t,n,null,r);s.step=`morning: your three reviews`,c(s.step),await d(2),await E(t.pim.pos.clone().add({x:0,y:0,z:-2}),Math.PI),await d(1.5),await _(`KeyE`,.2),await a([1,2,2],()=>t.state===`h2`,200),s.step=`midday: planks while Kite judges at the Mirror`,c(s.step);for(let e=0;e<3;e++)await E(n.woodpile.clone().add({x:1.6,y:0,z:0})),await _(`KeyE`,.3),await i(6),await E(n.workbench.clone().add({x:1.4,y:0,z:0})),await _(`KeyE`,.3),await i(10);await i(240,()=>t.state===`h3`),s.step=`afternoon: Iris`,c(s.step),await E(t.iris.pos.clone().add({x:1.4,y:0,z:1.4})),await _(`KeyE`,.3),await a([],()=>t.state===`h4_bring`,200),s.step=`evening: the procession`,c(s.step),await E(n.gather.clone().add({x:0,y:0,z:1}));for(let e=0;e<4;e++){if(await a([],()=>[`h4_walk`,`h4_fell`,`h4r`,`h4_top`,`done`].includes(t.state),200),t.state===`h4_walk`&&(await i(8),await i(90,()=>t.state!==`h4_walk`)),t.state===`h4_fell`&&(await d(2),await a([],()=>t.state!==`h4_fell`,60)),t.state===`h4r`){await a([],()=>[`h4`,`h4_walk`,`h4_top`,`done`].includes(t.state),300);continue}if(t.state===`h4_top`||t.state===`done`)break}return await a([],()=>t.state===`done`&&!e.ui.modal,80),t.state},async keyhold(){await k(`keyhold`);let t=te(`keyhold`),n=t.iw,r=new WeakSet,a=-9,o={fire:-1,small:1,ask:1,answered:1,own:-1,practice:1,stop:1,stopSay:1,finish:-1,train_fire:-1,train_small:1,train_ask:-1,train_done:1},l=async()=>{let n=y();if(n){await S(n,1);return}if(e.ui.modal)return;let i=e.recent;if(i&&i.isle===`keyhold`&&!r.has(i)&&e.time-i.t>1&&e.time0?`KeyT`:`KeyC`)}let s=t.hz;if(s&&!s.whistled&&!s.done&&s.t>1.6&&e.input.press(`KeyQ`),t.state===`b3_practice`&&!t.st.practice&&t.practiceWait>1.2&&e.input.press(`KeyQ`),t.state===`b4`&&t.noon){let n=t.noon;t.canRing()&&e.time-a>1.5&&(e.input.press(`KeyE`),a=e.time),n.window&&!n.ev&&t.g7&&t.g7.t>2&&e.input.press(`KeyQ`)}t.seated?e.input.keys.add(`KeyE`):e.input.keys.delete(`KeyE`)},u=async(e,t)=>{for(let n=0;n{for(let n=0;nE(t.w3(e)),m=async(t=1.5)=>{e.input.press(`KeyE`),await u(t)};await u(6),await f(()=>t.state===`b1_cloth`,200),s.step=`beat 1: the cloth, over the roofs`,c(s.step),await p(n.spot.stair),await u(.5);{let r=t.w3(n.hf(240,3.8,9.4)).sub(i.pos).setY(0).normalize();e.autoInput=()=>({x:0,z:0,dir:r,run:!0}),await u(1.25),e.autoInput=null}await p(n.stores.cloth.front),await m(1.5),await p(n.hoists[0].bottom),await m(3),await p(n.spot.loftFront.clone().add({x:-1.2,y:0,z:0})),e.input.press(`KeyE`),await f(()=>t.state===`b1_battens`&&!e.ui.busy,60),s.step=`beat 1: the battens`,c(s.step),await p(n.stores.battens.front),await m(1.5),await p(n.spot.loftFront.clone().add({x:-1.2,y:0,z:0})),e.input.press(`KeyE`),await f(()=>t.state===`b1_done`&&!e.ui.busy,60),s.step=`beat 2: Kite runs six tickets while you sew`,c(s.step),await p(n.spot.table.clone().add({x:-.3,y:0,z:.9})),e.input.press(`KeyE`),await u(12),await f(()=>t.state===`b3_intro`||t.state===`b3_practice`,400),s.step=`beat 3: the whistle on the quay`,c(s.step),await f(()=>t.state===`b3`,80);for(let e=0;e<60&&t.state===`b3`;e++)await u(4);s.step=`beat 4: noon`,c(s.step);for(let e=0;e<120&&(await u(3),![`end`,`stone`,`done`].includes(t.state));e++);return await f(()=>t.state===`stone`,120),s.step=`the Charter Stone`,c(s.step),await p(n.spot.stone.clone().add({x:1.2,y:0,z:.6})),await m(1),e.ui.modal&&(await x({n:0,text:e.ui.modal.innerText.slice(0,160)}),e.ui.closeSheet()),await f(()=>t.state===`done`,30),t.state},async vigil(){await k(`vigil`);let t=te(`vigil`),n=t.iw,r={evensongRead:null},a=()=>{let n=e.recent,i=t.round,a=e.input.keys;if(t.hasLens){let n=t.thought&&e.timen.until||e.time-n.t<.5)return;n._seen=!0;let o=0;n.kind===`lamp`&&!n.seen&&/lamp 7,/.test(n.label)&&(o=1),n.kind===`crypt`&&(o=-1),n.kind===`said`&&(o=1),o&&e.feedback(o)},o=async(e,t)=>{for(let n=0;n{let r=n.P[e]||e,i=n.w(t?{x:r.x+t[0],y:r.y,z:r.z+t[1]}:r);return E(i.clone().add({x:0,y:.1,z:0}))},f=async(n,i=300,a=null)=>{for(let s=0;sn.inBelfry(i.pos),m=async e=>{h(e),await o(.2)};s.step=`arrival`,c(s.step),await u(`landing`),await o(1),await f(()=>t.state===`arrival`,20),await f(()=>t.state!==`arrival`,200,async()=>{let e=t.crumb.pos;e.distanceTo(i.pos)>3&&await E(e.clone().add({x:.7,y:0,z:.7}))}),await o(3),await f(()=>t.state===`b1`,120),s.step=`beat 1: Wick's round, from the belfry`,c(s.step),await u(`towerStand`),await o(1),await f(()=>t.state===`b1_tell`,400,async()=>{p()||await u(`towerStand`)}),await u(`present`,[.4,1.2]),await o(.5),await m(`KeyE`),await f(()=>t.state===`b2_official`,120),s.step=`beat 2: the official round, under the Seal`,c(s.step),await u(`gateIn`),await o(.5),await f(()=>t.state===`b2_back`,300,async()=>{if(t.kv&&t.round?.kind===`official`&&!t.round.over){let n=e.world.ground(t.kv.x,t.kv.z,t.kv.y-1.2);n!==null&&Math.hypot(t.kv.x-i.pos.x,t.kv.z-i.pos.z)>2.5&&await E(l(t.kv.x,n,t.kv.z))}}),await u(`keeperFire`),await o(1),s.step=`beat 2: the windbreak`,c(s.step),await f(()=>t.state===`b2_wind`,60),await o(2),await u(`keeperFire`),await o(.3),g(`KeyE`,!0),await o(.5),await f(()=>t.round?.kind===`wind`,60),await o(4),await f(()=>t.round?.kind===`wind`&&t.round.over,200),g(`KeyE`,!1),s.step=`beat 2: rounds from the belfry`,c(s.step),await f(()=>t.state===`b2_belfry`,120),await u(`towerStand`),await o(1),await f(()=>t.state===`b3_snuff`,700,async()=>{p()||await u(`towerStand`)}),s.step=`beat 3: Snuff and the gong`,c(s.step),await f(()=>t.state===`b3_lens_take`,300),await o(6),await u(`towerStand`),await m(`KeyE`),await f(()=>t.state===`b3_lens`,30),s.step=`beat 3: the Lens`,c(s.step),await f(()=>t.state===`b4_come`,900,async()=>{!p()&&t.state===`b3_lens`&&await u(`towerStand`)}),s.step=`beat 4: evensong`,c(s.step);for(let e=0;e<4;e++){if(await u(`keeperFire`),await o(1),await f(()=>[`b4_run`,`end`,`done`].includes(t.state),200),t.state===`b4_run`&&await o(20),await f(()=>[`b4_retry`,`end`,`done`].includes(t.state),400),t.state===`b4_retry`){await u(`towerStand`),await f(()=>t.state===`b4_come`||t.state===`end`,600,async()=>{!p()&&t.state===`b4_retry`&&await u(`towerStand`)});continue}break}return await f(()=>t.state===`done`,200),e.input.keys.delete(`KeyR`),t.state},async signpost(){await k(`signpost`);let t=te(`signpost`),n=t.P;for(let e=0;e<40&&!t.nell?.ready;e++)await d(.5);let r=()=>{let t=e.recent;if(!t||t.isle!==`signpost`||e.time>=t.until||t._seen||e.tcCut)return;t._seen=!0;let n=t.moment?.kind,r=0;n?r=n===`cover`?-1:1:t.label===`Kite worried for Dax`&&(r=1),r&&e.feedback(r)},i=(e,t=0)=>e?E(e.clone().add({x:0,y:t,z:0})):!1,a=async(e=.25)=>{h(`KeyE`),await d(e)},o=e=>(/write about the ledge/.test(e),1),l=!1,u=null;s.step=`Signpost Cliffs`,c(s.step);for(let f=0;f<2600;f++){let f=y();if(f){await S(f,f.n?o(f.text):1);continue}if(t.state!==u&&(u=t.state,s.step=t.state,c(`-> ${t.state}`)),e.ui.modal){await x({n:0,text:e.ui.modal.innerText.slice(0,120)}),h(`Escape`),await d(.1);continue}if(t.state===`done`)break;l&&!t.hold&&(g(`KeyE`,!1),l=!1);let p=t.floaters.find(e=>e.mode===`float`);switch(t.state){case`unmet`:case`arrive`:await i(t.nell.pos.clone().add({x:2,y:0,z:1}));break;case`a_hesper`:await i(t.hesper.pos.clone().addScaledVector(n.benchFwd,1.6)),await a();break;case`a_board`:case`b1_up`:await i(n.boardRead.clone());break;case`b1_dax`:await i(n.colCenter.clone());break;case`b1_fall`:!t.ropeThrown&&t.dax.hanging&&t.descent&&!e.frozen&&(await i(n.colRope.clone().add({x:1,y:0,z:.8})),await a()),p&&!e.frozen&&await i(p.m.position.clone().add({x:0,y:-1,z:0}));break;case`b1_write`:await i(n.boardMid.clone().addScaledVector(t.iw.board.face,1.2)),await a();break;case`b2_bench`:case`b2_bench2`:case`b3_bench`:await i(n.keeperBench.clone()),await a();break;case`b2_hold`:case`b2_hold2`:case`b3_hold`:t.hold&&!l&&(g(`KeyE`,!0),l=!0);break;case`b2_read`:case`b2_read2`:case`b3_read`:{let e=t.nextToRead();e&&(await i(e.pos.clone()),await a(.4),r());break}case`b3_nell`:p&&!e.frozen&&await i(p.m.position.clone().add({x:0,y:-1,z:0}));break;case`b4_climb`:await i(n.gullDoor.clone()),await a();break;case`b4_pontoon`:t.strips.mail&&!t.strips.mail.read&&(await i(t.strips.mail.pos.clone()),await a(.4),r())}r(),await d(.5),r()}return l&&g(`KeyE`,!1),t.state},async library(){await k(`library`);let t=te(`library`),n=t.iw;await t._init;let r=()=>{let t=e.recent;if(!t||!t.ans||e.time>t.until||t._seen||e.ui.busy||e.tcCut)return;t._seen=!0;let n=t.ans,r=/^Under the glass/.test(t.label),i=!!t.replay,a={high:2,waver:1,blue:0}[n.flame],o={flat:2,careful:1,honest:0}[n.way],s=n.way!==`honest`&&n.right&&!n.q.unknowable,c=0;c=r?o===a?1:o>a?-1:0:i?n.way===`flat`&&!s?-1:0:+(n.way===`honest`),c&&e.feedback(c)},i=(e,t,n,i)=>ee(e,t,n,i,r),o=e=>E(e.clone().add({x:0,y:-.1,z:0})),l=async e=>{if(await o(n.ladders[e].foot),await d(.2),!/Climb the/.test(b()||``))return c(`(no ladder prompt at ${e})`),!1;await _(`KeyE`,.3);for(let e=0;e<60&&t.ride?.phase!==`top`;e++)await d(.25),r();await _(`KeyE`,a?3.5:.5);for(let e=0;e<6;e++)await d(.25),r();await _(`KeyE`,.3);for(let e=0;e<40&&t.ride;e++)await d(.25),r();return!0};s.step=`arrival`,c(s.step),await d(2),await o(((e,r)=>t[e].pos.clone().add(n.toW(0,0,r).sub(n.toW(0,0,0))))(`maud`,2.2)),await d(.4),await _(`KeyE`,.3),await i([],()=>t.state===`enter`,60),s.step=`into the reading room`,c(s.step),await o(n.P.doorIn),await d(1),await o(n.P.slots[1]),await i([],()=>t.state===`b1_lou`&&t.need===`lou_read`,180),s.step=`beat 1: Lou's star`,c(s.step),await l(`star`),await o(t.cast.lou.pos.clone().add(n.toW(0,0,1.4).sub(n.toW(0,0,0)))),await _(`KeyE`,.3),await i([1],()=>t.state===`b1_abe`,120),await i([3],()=>t.state===`b2`,200),s.step=`beat 2: Kite keeps the desk, blind`,c(s.step);let u=new Set,f={bastian:`hammer`,mette:`wave`,jean:`leaf`};for(let n=0;n<1400&&t.state===`b2`;n++){let n=t.answers.map(e=>e.qid).find(e=>f[e]&&!u.has(e));if(n&&!e.ui.busy){u.add(n),await d(3),await l(f[n]);continue}await d(.5),r()}s.step=`beat 3: midnight, under the glass`,c(s.step);for(let e=0;e<800&&t.state===`b3`;e++)r(),document.getElementById(`lib-hint`)?.hidden||(await d(.6),r(),h(`KeyE`)),await d(.4);s.step=`three in the morning: the ferrymen`,c(s.step);let p=new Set;for(let n=0;n<1200;n++){if(t.state===`b3`){await d(.5);continue}if(t.state!==`b3_am`)break;let n=t.answers.filter(e=>e.phase===`am`).map(e=>e.qid).find(e=>[`f2`,`f3`].includes(e)&&!p.has(e));if(n&&!e.ui.busy){p.add(n),await d(2),await l(n===`f2`?`cloud`:`wave`);continue}await d(.5),r()}s.step=`beat 4: Maud's question`,c(s.step);for(let e=0;e<2e3&&t.state!==`done`&&t.state!==`dawn`;e++){let e=!document.getElementById(`lib-hint`)?.hidden;r(),e&&(await d(.6),r(),h(`KeyE`));let t=y();t&&await S(t,1),await d(.5)}s.step=`the blue hour`,c(s.step);for(let e=0;e<600&&t.state!==`done`;e++){let e=y();e&&await S(e,1),await d(.5)}return await i([],()=>t.state===`done`&&!e.ui.modal,60),await d(3),t.state},async sandbox(){await k(`sandbox`);let t=te(`sandbox`),n=t.iw;await t._init;let r={say:1,keepSeen:-1,keepBlind:0,blind:0,lastTruth:1,lastFine:-1},i=()=>{let n=e.recent;if(!n||!n.sbx||n._seen||e.ui.busy||e.time>n.until||e.time-n.t<.6)return;n._seen=!0;let i=n.sbx===`say`?`say`:n.sbx===`keep`?n.watched?`keepSeen`:`keepBlind`:n.sbx===`blind`?`blind`:n.sbx===`last`?t.lastKind===`fine`?`lastFine`:`lastTruth`:null,a=r[i]||0;a&&e.feedback(a)},a=async e=>{await d(e),i()},o=(e,t,n=120)=>ee(e,t,n,null,i),l=e=>Math.atan2(-(n.D.x-e.x),-(n.D.z-e.z)),u=e=>e?E(e.clone().add({x:0,y:-.1,z:0}),l(e)):!1,f=e=>{let t=e.at.x-n.D.x,r=e.at.z-n.D.z,i=Math.hypot(t,r),a=n.D.clone();return a.x+=t/i*(n.R+.9),a.z+=r/i*(n.R+.9),a.y=n.main.groundAt(a.x,a.z),a},p=async()=>{t.panes||(await u(n.stack.clone().add({x:1.3,y:0,z:.4})),b()?.includes(`pane`)&&await _(`KeyE`,.3))};s.step=`arrival`,c(s.step),await d(1.5),await u(t.ines.pos.clone().add({x:1.6,y:0,z:2})),await d(1.5),await _(`KeyE`,.3),await o([1],()=>t.state===`b1`,200),s.step=`beat 1: the walls`,c(s.step);for(let r=0;r<600&&t.state===`b1`;r++){await p();let t=n.cracks.filter(e=>e.open&&e.kind!==`high`),r=t.filter(e=>e.kind===`work`),i=t.filter(e=>e.kind===`low`),s=(r.length?r:i.length?i:t)[0];s&&(await u(f(s)),b()?.includes(`Fit`)&&await _(`KeyE`,1.4)),await a(1),(e.ui.busy||e.ui.modal)&&await o([],()=>!e.ui.busy&&!e.ui.modal,30)}s.step=`beat 2: the Scorer`,c(s.step),await o([],()=>t.state!==`b2in`,200);let m=0;for(let r=0;r<400&&t.state===`b2`;r++){if(m<40&&!t.watching&&(await u(n.slitSpot.clone().add({x:-.5,y:0,z:0})),b()?.includes(`slit`)&&await _(`KeyE`,.3)),t.watching&&(m+=1,m>=40&&await _(`KeyE`,.3)),!t.watching&&m>=40){let e=n.cracks.find(e=>e.open&&e.kind===`work`);e&&(await p(),await u(f(e)),b()?.includes(`Fit`)&&await _(`KeyE`,1.4))}await a(1),e.ui.busy&&await o([],()=>!e.ui.busy,30)}s.step=`beat 3: the heart of the storm`,c(s.step);for(let n=0;n<1200&&t.state===`heart`;n++)await a(.15),e.ui.busy&&await o([],()=>!e.ui.busy,30);s.step=`beat 4: the first ray`,c(s.step);for(let e=0;e<60&&t.state===`ray`&&!t.breach;e++)await a(.5);await d(2);for(let n=0;n<120&&t.state===`ray`;n++)t.breach&&await E(t.breach.clone()),await a(.5),e.ui.busy&&await o([1],()=>!e.ui.busy,30);return await o([1],()=>t.state===`done`&&!e.ui.modal,400),t.state}};return{status:s,onFrame:D,async run(t=g$){try{localStorage.clear()}catch{}for(let n of t){s.island=n,s.step=`start`;let t=e.time,r=performance.now();o&&(await o.start(`playthrough-${String(g$.indexOf(n)+1).padStart(2,`0`)}-${n}`),c(`recording ${o.status.name}`));let i=`error`;try{i=await A[n](),c(`ended: ${i}`)}catch(e){s.errors.push(`${n}: ${e.message}`),c(`stopped: ${e.message}`),console.error(e)}e.autoInput=null,e.input.keys.clear(),o&&(await d(a?2.5:0),await o.stop(),c(`saved ${o.status.name} (${(o.status.bytes/1e6).toFixed(0)} MB)`)),s.islands[n]={end:i,gameMin:+((e.time-t)/60).toFixed(1),realMin:+((performance.now()-r)/6e4).toFixed(1)}}return s.done=!0,s.island=null,c(`all done`),s}}}BV(),FH(),cU(),VU(),QK(),SK();var v$=e=>{try{performance.mark(`os:`+e)}catch{}p$.step(e)},y$=()=>new Promise(e=>{let t=!1,n=()=>{t||(t=!0,setTimeout(e,0))};requestAnimationFrame(n),setTimeout(n,120)});v$(`script`),await y$();var b$=new URLSearchParams(location.search),x$=b$.has(`capture`),S$=+(b$.get(`w`)||1280),C$=+(b$.get(`h`)||720);x$&&document.documentElement.classList.add(`capture`);var w$=new TV({antialias:!0,forceWebGL:x$||b$.has(`webgl`)||location.hash.includes(`webgl`)});w$.setPixelRatio(x$?1:Math.min(devicePixelRatio,1.75)),w$.setSize(x$?S$:innerWidth,x$?C$:innerHeight),w$.toneMapping=7,w$.toneMappingExposure=1,w$.shadowMap.enabled=b$.get(`shadows`)!==`0`,w$.shadowMap.type=2,document.body.appendChild(w$.domElement),await w$.init();{let e=w$.backend?.capabilities;e?.getUniformBufferLimit&&(e.getUniformBufferLimit=()=>0)}v$(`renderer`),document.getElementById(`badge`).textContent=w$.backend.isWebGPUBackend?`WebGPU`:`WebGL 2`;var T$=new ba,E$=new ju(x$?48:55,x$?S$/C$:innerWidth/innerHeight,.1,6e3),D$=qH();T$.add(D$);var O$=gH(xH.sub(JV));T$.fogNode=eH(sU(O$),oH(CH(150,1500),EH(-42,-75,xH.y).mul(.55)));var k$=new Ru(16769213,2.5);k$.castShadow=!0,k$.shadow.mapSize.set(2048,2048),Object.assign(k$.shadow.camera,{left:-38,right:38,top:38,bottom:-38,near:1,far:320}),k$.shadow.bias=-4e-4,k$.shadow.normalBias=.03,T$.add(k$,k$.target);var A$=new yu(13623551,9081956,1.25);T$.add(A$);var j$=await a$(b$.get(`isles`)?b$.get(`isles`).split(`,`):null);v$(`isles-code`);var M$=await $W(T$,{quality:+(b$.get(`q`)||1),isles:j$,step:async e=>{v$(e),await y$()}});v$(`world`);var N$=new CK;T$.add(N$.root);var P$=!1;await N$.load(`./models/keeper.glb`,`./models/keeper_albedo_0.webp`),N$.model?.traverse(e=>{e.isMesh&&/icosphere/i.test(e.name)&&(e.visible=!1)}),v$(`keeper`);var F$=new IK(M$,N$);F$.spawn.copy(M$.spawn),F$.respawn();var I$=new NK(T$),L$=new BK(E$,w$.domElement,M$),R$={x:0,z:0,jump:!1},z$=new UK,B$=new ZK,V$=new tq(`./audio/`),H$=new NJ({world:M$,player:F$,kite:I$,camera:E$,ui:B$,input:z$,audio:V$,scene:T$,orchard:M$.orchard,wren:M$.wren,sun:k$,hemi:A$,follow:L$,isleDefs:j$});await H$.init(P$),v$(`game`),b$.get(`at`)&&H$.travel(b$.get(`at`),{fade:!1}),window.__game=H$;var U$=new DV(w$),W$=_H(T$,E$,{samples:b$.has(`msaa`)?+b$.get(`msaa`):4}),G$=W$.add(WH(W$,.26,.4,.86)),K$=EH(.95,.3,iH(wH.sub(.5)));U$.outputNode=sH(G$.mul(MH(.86,.84,.9)),G$,K$.mul(.75).add(.25)),addEventListener(`resize`,()=>{x$||(w$.setSize(innerWidth,innerHeight),E$.aspect=innerWidth/innerHeight,E$.updateProjectionMatrix())});var q$=!x$&&b$.has(`record`),J$={lean:!0,adaptive:!x$&&!q$&&!b$.has(`fixedres`),prMax:x$?1:Math.min(devicePixelRatio,1.75),ema:1/60,slow:0,fast:0,el:null,t:0,frames:0,fps:0,from:0};J$.prMin=Math.max(.75,J$.prMax*.65),J$.pr=J$.prMax;function Y$(){J$.lean&&M$.clouds.userData.cull(E$),cK(E$),U$.render()}function X$(e){J$.pr=Math.round(hi.clamp(e,J$.prMin,J$.prMax)*1e3)/1e3,w$.setPixelRatio(J$.pr),w$.setSize(innerWidth,innerHeight)}function Z$(e){!J$.adaptive||e<=0||e>.25||document.hidden||performance.now()1/45?(J$.slow+=e,J$.fast=0):J$.ema<1/57?(J$.fast+=e,J$.slow=0):J$.slow=J$.fast=0,J$.slow>2.5&&J$.pr>J$.prMin+.001?(X$(J$.pr-.125),J$.slow=0,J$.ema=1/50):J$.fast>8&&J$.pr0&&e<.25&&!J$.adaptive&&(J$.ema+=(e-J$.ema)*.06),J$.frames++,J$.t+=e,!J$.el||J$.t<.5)return;J$.fps=J$.frames/J$.t,J$.frames=0,J$.t=0;let t=w$.info.render;J$.el.textContent=`${J$.fps.toFixed(0)} fps · ${(J$.ema*1e3).toFixed(1)} ms · res ×${J$.pr.toFixed(2)} · ${t.drawCalls} draws · ${(t.triangles/1e6).toFixed(2)}M tris · clouds ${M$.clouds.children[0].count} · people ${bK.drawn}${H$.loadsLeft?` · loading ${H$.loadsLeft}`:``} · ${J$.lean?`lean`:`FULL COST`} (Shift+O)`}addEventListener(`keydown`,e=>{if(e.shiftKey&&!e.repeat){if(e.code===`KeyP`){if(J$.el){J$.el.remove(),J$.el=null;return}J$.el=Object.assign(document.createElement(`div`),{id:`os-perf`}),J$.el.style.cssText=`position:fixed;left:8px;bottom:8px;z-index:9;padding:4px 8px;border-radius:6px;background:rgba(20,18,30,.72);color:#fbf6ec;font:600 11px/1.3 Inter,system-ui,sans-serif;pointer-events:none`,document.body.appendChild(J$.el)}e.code===`KeyO`&&(J$.lean=!J$.lean,M$.clouds.userData.setFull(!J$.lean),bK.on=J$.lean,J$.adaptive=J$.lean&&!b$.has(`fixedres`),J$.lean||X$(J$.prMax))}});var $$=new ju(100,1,.3,400),e1=new P,t1=[[1,0,0],[-1,0,0],[0,0,1],[0,0,-1],[0,-1,0],[0,1,0]];async function n1(e){let t=w$.getRenderTarget(),n=w$.getMRT?.()??null;w$.setRenderTarget(W$.renderTarget),w$.setMRT?.(W$._mrt??null);let r;try{r=w$.compileAsync(T$,e)}finally{w$.setRenderTarget(t),w$.setMRT?.(n)}return r}H$.warmUp=async(e,t=30,n=null)=>{if(x$||!w$.compileAsync)return;let r=n&&M$.isleRoots?.[n]||[],i=[];for(let n of t1){let a=[];for(let e of r)e.traverse(e=>{!e.visible&&!e.isLight&&(e.visible=!0,a.push(e))});try{$$.far=t*5,$$.position.copy(e).add(e1.set(0,t*.25,0)),$$.up.set(0,+!n[1],+!!n[1]),$$.lookAt(e1.copy($$.position).add(new P(...n))),$$.updateProjectionMatrix(),$$.updateMatrixWorld(),i.push(n1($$))}finally{for(let e of a)e.visible=!1}dK.pace&&await y$()}await Promise.all(i)};var r1=()=>{removeEventListener(`pointerdown`,r1,!0),removeEventListener(`keydown`,r1,!0),V$.start().then(()=>V$.setMuted(V$.muted))};addEventListener(`pointerdown`,r1,!0),addEventListener(`keydown`,r1,!0),z$.mountTouch(B$.root,[{label:`Treat`,code:`KeyT`},{label:`Correct`,code:`KeyC`},{label:`Journal`,code:`KeyJ`},{label:`Whistle`,code:`KeyQ`},{label:`Map`,code:`KeyG`},{label:`Use`,code:`KeyE`,aria:`Talk, pick up, use`},{label:`Jump`,hold:!0,big:!0,aria:`Jump; hold in the air to glide`}]);var i1=null,a1=()=>B$.busy||H$.frozen||i1?.up?R$:z$.move(),o1=0;function s1(e,t,n){o1+=e,XH.value=o1,F$.update(e,t,L$.yaw),RU.value.copy(F$.pos),I$.update(e,F$,E$),H$.update(e,o1);for(let e of M$.animated)e.userData.update?.(o1);let r=n||H$.camOverride;if(r?r(E$,F$,e):L$.update(e,F$),H$.shake>0){let t=(H$.shakeAmp||.3)*Math.min(1,H$.shake*2.5);H$.shake-=e,E$.position.x+=(Math.random()-.5)*t,E$.position.y+=(Math.random()-.5)*t,E$.position.z+=(Math.random()-.5)*t}D$.position.copy(E$.position),k$.position.copy(F$.pos).addScaledVector(JH,140),k$.target.position.copy(F$.pos),k$.target.updateMatrixWorld()}function c1(e,t,n){let r=Math.max(1,Math.round(H$.timeScale||1));for(let i=0;ie.camera(i,t,n,r)),r++}return Y$(),r},async seek(i){for(;r/te.camera(i,t,n,r)),r++}return Y$(),r}};r<0;){let i=r/t;c1(n,e.input(i,F$),(t,n,r)=>e.camera(i,t,n,r)),r++}window.__dbg={camera:E$,render:Y$,scene:T$},window.__ready=!0}else{let e=new fd;for(let e=0;e<60;e++)c1(1/60,{x:0,z:0});z$.endFrame(),v$(`settled`),await y$();try{M$.clouds.userData.cull(E$),cK(E$),await n1(E$)}catch(e){console.warn(`warm-up`,e)}v$(`compiled`),p$.done(),window.__dbg={player:F$,kite:I$,camera:E$,follow:L$,ui:B$,input:z$,world:M$,renderer:w$,render:Y$,pause:()=>w$.setAnimationLoop(null),perf:J$,THREE:Gf,sim(e,t=R$,n=1/30){let r=Math.round(e/n);for(let e=0;eg$.includes(e));w$.setAnimationLoop(n=>{e.update(n);let r=e.getDelta();i?.onFrame(Math.min(r,.05)),c1(Math.min(r,1/20),a1()),z$.endFrame(),Y$(),t?.frame(),Z$(r),Q$(r)}),window.__ready=!0;let o=!b$.has(`notitle`)&&(b$.has(`title`)||!navigator.webdriver);dK.pace=!o,J$.from=o?1/0:performance.now()+8e3,o&&(i1=m$({status:()=>{let e=H$.loads||[],t=e.filter(e=>e.done).length;return H$.loadsDone?`Every island is ready`:t{dK.pace=!0,J$.from=performance.now()+(H$.loadsDone?3e3:8e3),i&&!r&&setTimeout(()=>i.run(a),600)}})),i&&r?(w$.setAnimationLoop(null),setTimeout(()=>i.run(a),0)):i&&!o&&setTimeout(()=>i.run(a),600),setTimeout(()=>H$.startBackgroundLoads(),0)}