@threadcrumbs/threadnauts 1.0.0 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +34 -10
- package/README.md +6 -7
- package/dist/assets/CREDITS.md +1 -1
- package/dist/assets/index-C46d6g6p.js +2464 -0
- package/dist/assets/index-PzTcyxAK.css +1 -0
- package/dist/assets/redspot-DbATwjpD.svg +1 -0
- package/dist/assets/shared-DiTtF988.js +4978 -0
- package/dist/index.html +3 -3
- package/dist/pro-manifest.json +3 -3
- package/package.json +5 -4
- package/server/api.mjs +26 -4
- package/dist/assets/index-C-3KPMaV.css +0 -1
- package/dist/assets/index-xHGM7fhg.js +0 -2381
- package/dist/assets/redspot-CV5z9nSH.svg +0 -1
- package/dist/assets/shared-B_T8JlmU.js +0 -4919
|
@@ -1,2381 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/pro-CzWQdIWB.js","assets/shared-B_T8JlmU.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{M as ke,O as bp,B as qt,F as qe,S as Ye,U as es,V as Se,W as Fs,H as Os,N as vp,T as Tu,C as W,a as F,A as ji,b as dt,R as yp,c as Cp,d as xp,L as Mp,e as kp,f as Tp,g as _u,h as _p,i as Sp,j as $p,k as wc,l as qi,m as bc,n as N,o as xt,p as Ap,q as Su,r as Ep,s as Pp,P as zp,t as Lp,u as Bi,v as Rp,D as Bp,w as Fp,x as Op,y as Ip,z as $u,E as Dp,G as On,I as Vp,J as ai,K as et,Q as Au,X as Np,Y as Eu,Z as Bl,_ as wt,$ as Ut,a0 as Ue,a1 as Dt,a2 as co,a3 as Pt,a4 as De,a5 as Ze,a6 as at,a7 as zt,a8 as tt,a9 as Qt,aa as vt,ab as In,ac as Dn,ad as Ot,ae as Fl,af as Nt,ag as Wp,ah as Ol,ai as Sn,aj as Hr,ak as Fi,al as Hp,am as Up,an as Ao,ao as Pu,ap as zu,aq as vc,ar as Lu,as as Xe,at as gt,au as jp,av as qp,aw as Il,ax as Ur,ay as Ru,az as Vn,aA as yc,aB as ho,aC as Bu,aD as si,aE as _t,aF as Fu,aG as Ou,aH as Iu,aI as Gp,aJ as Cc,aK as Eo,aL as Ya,aM as Zp,aN as Xp,aO as Po,aP as Yp,aQ as xc,aR as Qp,aS as Kp,aT as Jp,aU as Wt,aV as em,aW as tm,aX as sm,aY as im,aZ as zo,a_ as nm,a$ as Mc,b0 as rm,b1 as om,b2 as am,b3 as kc,b4 as lm,b5 as Oi,b6 as cm,b7 as hm,b8 as dm,b9 as um,ba as fm,bb as pm,bc as mm,bd as gm}from"./shared-B_T8JlmU.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const n of document.querySelectorAll('link[rel="modulepreload"]'))i(n);new MutationObserver(n=>{for(const r of n)if(r.type==="childList")for(const o of r.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&i(o)}).observe(document,{childList:!0,subtree:!0});function t(n){const r={};return n.integrity&&(r.integrity=n.integrity),n.referrerPolicy&&(r.referrerPolicy=n.referrerPolicy),n.crossOrigin==="use-credentials"?r.credentials="include":n.crossOrigin==="anonymous"?r.credentials="omit":r.credentials="same-origin",r}function i(n){if(n.ep)return;n.ep=!0;const r=t(n);fetch(n.href,r)}})();const wm="modulepreload",bm=function(s){return"/"+s},Tc={},vm=function(e,t,i){let n=Promise.resolve();if(t&&t.length>0){let l=function(c){return Promise.all(c.map(h=>Promise.resolve(h).then(d=>({status:"fulfilled",value:d}),d=>({status:"rejected",reason:d}))))};document.getElementsByTagName("link");const o=document.querySelector("meta[property=csp-nonce]"),a=o?.nonce||o?.getAttribute("nonce");n=l(t.map(c=>{if(c=bm(c),c in Tc)return;Tc[c]=!0;const h=c.endsWith(".css"),d=h?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${c}"]${d}`))return;const u=document.createElement("link");if(u.rel=h?"stylesheet":wm,h||(u.as="script"),u.crossOrigin="",u.href=c,a&&u.setAttribute("nonce",a),document.head.appendChild(u),h)return new Promise((f,p)=>{u.addEventListener("load",f),u.addEventListener("error",()=>p(new Error(`Unable to preload CSS for ${c}`)))})}))}function r(o){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=o,window.dispatchEvent(a),!a.defaultPrevented)throw o}return n.then(o=>{for(const a of o||[])a.status==="rejected"&&r(a.reason);return e().catch(r)})},Dl="settings.v1",ym="balanced",ps={potato:{label:"Potato",hint:"battery first — flat light, no extras",values:{renderScale:.5,shadows:"off",bloom:!1,antialias:!1,particles:"off",textureQuality:"low",scatterDensity:.15,groundDetail:"low",maxAgents:40,stars:!1,ibl:!1,tiltShift:!1,colorGrade:!1,ambientOcclusion:0,clouds:!1,fauna:"low"}},low:{label:"Low",hint:"for when you are on the go",values:{renderScale:.7,shadows:"off",bloom:!0,antialias:!1,particles:"low",textureQuality:"low",scatterDensity:.35,groundDetail:"low",maxAgents:60,stars:!0,ibl:!1,tiltShift:!1,colorGrade:!0,ambientOcclusion:0,clouds:!0,fauna:"low"}},balanced:{label:"Balanced",hint:"the default — looks good, runs cool",values:{renderScale:1,shadows:"low",bloom:!0,antialias:!1,particles:"low",textureQuality:"medium",scatterDensity:.6,groundDetail:"medium",maxAgents:90,stars:!0,ibl:!0,tiltShift:!0,colorGrade:!0,ambientOcclusion:.25,clouds:!0,fauna:"full"}},high:{label:"High",hint:"sharp shadows and a full sky",values:{renderScale:1,shadows:"high",bloom:!0,antialias:!0,particles:"full",textureQuality:"high",scatterDensity:.85,groundDetail:"high",maxAgents:140,stars:!0,ibl:!0,tiltShift:!0,colorGrade:!0,ambientOcclusion:.25,clouds:!0,fauna:"full"}},ultra:{label:"Ultra",hint:"everything on, plugged in",values:{renderScale:1.5,shadows:"ultra",bloom:!0,antialias:!0,particles:"full",textureQuality:"ultra",scatterDensity:1,groundDetail:"high",maxAgents:200,stars:!0,ibl:!0,tiltShift:!0,colorGrade:!0,ambientOcclusion:.25,clouds:!0,fauna:"full"}}},Du={off:0,low:1024,high:2048,ultra:4096},Cm={low:256,medium:512,high:1024,ultra:1024},xm={off:0,low:900,full:3e3},Mm=Math.max(...Object.values(ps).map(s=>s.values.maxAgents||0)),_c={preset:"balanced",...ps.balanced.values,planet:"moon",skyBodies:"realistic",hideDormant:!0,districts:!0,timeOfDay:.32,autoTime:!1,clockTime:!1,dayLength:240,exposure:1,bloomStrength:.25,tiltShiftStrength:.2,tiltShiftAngle:0,iblIntensity:1,fov:60,worldCurve:.45,saturation:1,vignette:.3,sound:!0,masterVolume:.6,ambienceVolume:.8,effectsVolume:.8,wildlifeVolume:.8,workingVolume:.8,dronesVolume:.8,shipVolume:.8,botVoicesVolume:.8,machineryVolume:.8,autoQuality:!0,autoFrame:!1,leftDrag:"orbit",followSelected:!0,followDefaultOn:!1,showFps:!1,showLabels:!0,reducedMotion:!1,openIn:"app"},km=["wildlifeVolume","workingVolume","dronesVolume","shipVolume","botVoicesVolume","machineryVolume"],Tm=new Set(["planet","groundDetail","scatterDensity","stars"]),_m=new Set(["autoQuality","renderScale","shadows","bloom","antialias","exposure","bloomStrength","tiltShift","tiltShiftStrength","tiltShiftAngle","colorGrade","saturation","vignette","ambientOcclusion"]);class Sm{constructor(){this.saving=!0,this.allow=null,this.held={};const e=$m();this.values={..._c,...e},Object.hasOwn(e,"ambientOcclusion")||(this.values.ambientOcclusion=ps[this.values.preset]?.values.ambientOcclusion??_c.ambientOcclusion),Object.hasOwn(e,"followDefaultOn")||(this.values.followSelected=!0,this.values.followDefaultOn=!0),Sc(e,this.values),this.listeners=new Set,this._saveTimer=0}get(e){return this.values[e]}saved(){return{...this.values,...this.held}}isOverridden(e){const t=ps[this.values.preset];return!!(t&&e in t.values&&t.values[e]!==this.values[e])}set(e,t){if(this.allow&&(t=this.allow(e,t)),this.values[e]===t)return;this.values[e]=t;const i=ps[this.values.preset];i&&e in i.values&&(this.values.preset="custom"),this._emit([e])}applyPreset(e){const t=ps[e];if(!t)return;const i=[];for(const[n,r]of Object.entries(t.values))this.values[n]!==r&&(this.values[n]=r,i.push(n));this.values.preset=e,this._emit(i.length?i:["preset"])}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}_emit(e){const t=new Set(e),i={world:e.some(n=>Tm.has(n)),render:e.some(n=>_m.has(n))};for(const n of this.listeners)n(t,i,this.values);this._scheduleSave()}_scheduleSave(){this.saving&&(clearTimeout(this._saveTimer),this._saveTimer=setTimeout(()=>{try{localStorage.setItem(Dl,JSON.stringify(this.saved()))}catch{}},400))}applyAll(e){const t={...e};ps[t.preset]&&!Object.hasOwn(t,"ambientOcclusion")&&(t.ambientOcclusion=ps[t.preset].values.ambientOcclusion),Sc(t,t);const i=[];for(const[n,r]of Object.entries(t)){const o=this.allow?this.allow(n,r):r;!(n in this.values)||this.values[n]===o||(this.values[n]=o,i.push(n))}return i.length&&this._emit(i),i.length}get shadowSize(){return Du[this.values.shadows]||0}get textureSize(){return Cm[this.values.textureQuality]||512}get particleBudget(){return xm[this.values.particles]??0}}function Sc(s,e){if(typeof s.effectsVolume=="number")for(const t of km)Object.hasOwn(s,t)||(e[t]=s.effectsVolume)}function $m(){try{const s=JSON.parse(localStorage.getItem(Dl)||"{}");return s&&typeof s=="object"?s:{}}catch{return{}}}function Am(){try{return!!localStorage.getItem(Dl)}catch{return!1}}const Er={name:"CopyShader",uniforms:{tDiffuse:{value:null},opacity:{value:1}},vertexShader:`
|
|
3
|
-
|
|
4
|
-
varying vec2 vUv;
|
|
5
|
-
|
|
6
|
-
void main() {
|
|
7
|
-
|
|
8
|
-
vUv = uv;
|
|
9
|
-
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
|
10
|
-
|
|
11
|
-
}`,fragmentShader:`
|
|
12
|
-
|
|
13
|
-
uniform float opacity;
|
|
14
|
-
|
|
15
|
-
uniform sampler2D tDiffuse;
|
|
16
|
-
|
|
17
|
-
varying vec2 vUv;
|
|
18
|
-
|
|
19
|
-
void main() {
|
|
20
|
-
|
|
21
|
-
vec4 texel = texture2D( tDiffuse, vUv );
|
|
22
|
-
gl_FragColor = opacity * texel;
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
}`};class ys{constructor(){this.isPass=!0,this.enabled=!0,this.needsSwap=!0,this.clear=!1,this.renderToScreen=!1}setSize(){}render(){console.error("THREE.Pass: .render() must be implemented in derived pass.")}dispose(){}}const Em=new bp(-1,1,1,-1,0,1);class Pm extends qt{constructor(){super(),this.setAttribute("position",new qe([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new qe([0,2,0,0,2,0],2))}}const zm=new Pm;class Nn{constructor(e){this._mesh=new ke(zm,e)}dispose(){this._mesh.geometry.dispose()}render(e){e.render(this._mesh,Em)}get material(){return this._mesh.material}set material(e){this._mesh.material=e}}class jr extends ys{constructor(e,t="tDiffuse"){super(),this.textureID=t,this.uniforms=null,this.material=null,e instanceof Ye?(this.uniforms=e.uniforms,this.material=e):e&&(this.uniforms=es.clone(e.uniforms),this.material=new Ye({name:e.name!==void 0?e.name:"unspecified",defines:Object.assign({},e.defines),uniforms:this.uniforms,vertexShader:e.vertexShader,fragmentShader:e.fragmentShader})),this._fsQuad=new Nn(this.material)}render(e,t,i){this.uniforms[this.textureID]&&(this.uniforms[this.textureID].value=i.texture),this._fsQuad.material=this.material,this.renderToScreen?(e.setRenderTarget(null),this._fsQuad.render(e)):(e.setRenderTarget(t),this.clear&&e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil),this._fsQuad.render(e))}dispose(){this.material.dispose(),this._fsQuad.dispose()}}class $c extends ys{constructor(e,t){super(),this.scene=e,this.camera=t,this.clear=!0,this.needsSwap=!1,this.inverse=!1}render(e,t,i){const n=e.getContext(),r=e.state;r.buffers.color.setMask(!1),r.buffers.depth.setMask(!1),r.buffers.color.setLocked(!0),r.buffers.depth.setLocked(!0);let o,a;this.inverse?(o=0,a=1):(o=1,a=0),r.buffers.stencil.setTest(!0),r.buffers.stencil.setOp(n.REPLACE,n.REPLACE,n.REPLACE),r.buffers.stencil.setFunc(n.ALWAYS,o,4294967295),r.buffers.stencil.setClear(a),r.buffers.stencil.setLocked(!0),e.setRenderTarget(i),this.clear&&e.clear(),e.render(this.scene,this.camera),e.setRenderTarget(t),this.clear&&e.clear(),e.render(this.scene,this.camera),r.buffers.color.setLocked(!1),r.buffers.depth.setLocked(!1),r.buffers.color.setMask(!0),r.buffers.depth.setMask(!0),r.buffers.stencil.setLocked(!1),r.buffers.stencil.setFunc(n.EQUAL,1,4294967295),r.buffers.stencil.setOp(n.KEEP,n.KEEP,n.KEEP),r.buffers.stencil.setLocked(!0)}}class Lm extends ys{constructor(){super(),this.needsSwap=!1}render(e){e.state.buffers.stencil.setLocked(!1),e.state.buffers.stencil.setTest(!1)}}class Rm{constructor(e,t){if(this.renderer=e,this._pixelRatio=e.getPixelRatio(),t===void 0){const i=e.getSize(new Se);this._width=i.width,this._height=i.height,t=new Fs(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:Os}),t.texture.name="EffectComposer.rt1"}else this._width=t.width,this._height=t.height;this.renderTarget1=t,this.renderTarget2=t.clone(),this.renderTarget2.texture.name="EffectComposer.rt2",this.writeBuffer=this.renderTarget1,this.readBuffer=this.renderTarget2,this.renderToScreen=!0,this.passes=[],this.copyPass=new jr(Er),this.copyPass.material.blending=vp,this.timer=new Tu}swapBuffers(){const e=this.readBuffer;this.readBuffer=this.writeBuffer,this.writeBuffer=e}addPass(e){this.passes.push(e),e.setSize(this._width*this._pixelRatio,this._height*this._pixelRatio)}insertPass(e,t){this.passes.splice(t,0,e),e.setSize(this._width*this._pixelRatio,this._height*this._pixelRatio)}removePass(e){const t=this.passes.indexOf(e);t!==-1&&this.passes.splice(t,1)}isLastEnabledPass(e){for(let t=e+1;t<this.passes.length;t++)if(this.passes[t].enabled)return!1;return!0}render(e){this.timer.update(),e===void 0&&(e=this.timer.getDelta());const t=this.renderer.getRenderTarget();let i=!1;for(let n=0,r=this.passes.length;n<r;n++){const o=this.passes[n];if(o.enabled!==!1){if(o.renderToScreen=this.renderToScreen&&this.isLastEnabledPass(n),o.render(this.renderer,this.writeBuffer,this.readBuffer,e,i),o.needsSwap){if(i){const a=this.renderer.getContext(),l=this.renderer.state.buffers.stencil;l.setFunc(a.NOTEQUAL,1,4294967295),this.copyPass.render(this.renderer,this.writeBuffer,this.readBuffer,e),l.setFunc(a.EQUAL,1,4294967295)}this.swapBuffers()}$c!==void 0&&(o instanceof $c?i=!0:o instanceof Lm&&(i=!1))}}this.renderer.setRenderTarget(t)}reset(e){if(e===void 0){const t=this.renderer.getSize(new Se);this._pixelRatio=this.renderer.getPixelRatio(),this._width=t.width,this._height=t.height,e=this.renderTarget1.clone(),e.setSize(this._width*this._pixelRatio,this._height*this._pixelRatio)}this.renderTarget1.dispose(),this.renderTarget2.dispose(),this.renderTarget1=e,this.renderTarget2=e.clone(),this.writeBuffer=this.renderTarget1,this.readBuffer=this.renderTarget2}setSize(e,t){this._width=e,this._height=t;const i=this._width*this._pixelRatio,n=this._height*this._pixelRatio;this.renderTarget1.setSize(i,n),this.renderTarget2.setSize(i,n);for(let r=0;r<this.passes.length;r++)this.passes[r].setSize(i,n)}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget1.dispose(),this.renderTarget2.dispose(),this.copyPass.dispose()}}class Bm extends ys{constructor(e,t,i=null,n=null,r=null){super(),this.scene=e,this.camera=t,this.overrideMaterial=i,this.clearColor=n,this.clearAlpha=r,this.clear=!0,this.clearDepth=!1,this.needsSwap=!1,this.isRenderPass=!0,this._oldClearColor=new W}render(e,t,i){const n=e.autoClear;e.autoClear=!1;let r,o;this.overrideMaterial!==null&&(o=this.scene.overrideMaterial,this.scene.overrideMaterial=this.overrideMaterial),this.clearColor!==null&&(e.getClearColor(this._oldClearColor),e.setClearColor(this.clearColor,e.getClearAlpha())),this.clearAlpha!==null&&(r=e.getClearAlpha(),e.setClearAlpha(this.clearAlpha)),this.clearDepth==!0&&e.clearDepth(),e.setRenderTarget(this.renderToScreen?null:i),this.clear===!0&&e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil),e.render(this.scene,this.camera),this.clearColor!==null&&e.setClearColor(this._oldClearColor),this.clearAlpha!==null&&e.setClearAlpha(r),this.overrideMaterial!==null&&(this.scene.overrideMaterial=o),e.autoClear=n}}const Fm={uniforms:{tDiffuse:{value:null},luminosityThreshold:{value:1},smoothWidth:{value:1},defaultColor:{value:new W(0)},defaultOpacity:{value:0}},vertexShader:`
|
|
26
|
-
|
|
27
|
-
varying vec2 vUv;
|
|
28
|
-
|
|
29
|
-
void main() {
|
|
30
|
-
|
|
31
|
-
vUv = uv;
|
|
32
|
-
|
|
33
|
-
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
|
34
|
-
|
|
35
|
-
}`,fragmentShader:`
|
|
36
|
-
|
|
37
|
-
uniform sampler2D tDiffuse;
|
|
38
|
-
uniform vec3 defaultColor;
|
|
39
|
-
uniform float defaultOpacity;
|
|
40
|
-
uniform float luminosityThreshold;
|
|
41
|
-
uniform float smoothWidth;
|
|
42
|
-
|
|
43
|
-
varying vec2 vUv;
|
|
44
|
-
|
|
45
|
-
void main() {
|
|
46
|
-
|
|
47
|
-
vec4 texel = texture2D( tDiffuse, vUv );
|
|
48
|
-
|
|
49
|
-
float v = luminance( texel.xyz );
|
|
50
|
-
|
|
51
|
-
vec4 outputColor = vec4( defaultColor.rgb, defaultOpacity );
|
|
52
|
-
|
|
53
|
-
float alpha = smoothstep( luminosityThreshold, luminosityThreshold + smoothWidth, v );
|
|
54
|
-
|
|
55
|
-
gl_FragColor = mix( outputColor, texel, alpha );
|
|
56
|
-
|
|
57
|
-
}`};class Ii extends ys{constructor(e,t=1,i,n){super(),this.strength=t,this.radius=i,this.threshold=n,this.resolution=e!==void 0?new Se(e.x,e.y):new Se(256,256),this.clearColor=new W(0,0,0),this.needsSwap=!1,this.renderTargetsHorizontal=[],this.renderTargetsVertical=[],this.nMips=5;let r=Math.round(this.resolution.x/2),o=Math.round(this.resolution.y/2);this.renderTargetBright=new Fs(r,o,{type:Os}),this.renderTargetBright.texture.name="UnrealBloomPass.bright",this.renderTargetBright.texture.generateMipmaps=!1;for(let h=0;h<this.nMips;h++){const d=new Fs(r,o,{type:Os});d.texture.name="UnrealBloomPass.h"+h,d.texture.generateMipmaps=!1,this.renderTargetsHorizontal.push(d);const u=new Fs(r,o,{type:Os});u.texture.name="UnrealBloomPass.v"+h,u.texture.generateMipmaps=!1,this.renderTargetsVertical.push(u),r=Math.round(r/2),o=Math.round(o/2)}const a=Fm;this.highPassUniforms=es.clone(a.uniforms),this.highPassUniforms.luminosityThreshold.value=n,this.highPassUniforms.smoothWidth.value=.01,this.materialHighPassFilter=new Ye({uniforms:this.highPassUniforms,vertexShader:a.vertexShader,fragmentShader:a.fragmentShader}),this.separableBlurMaterials=[];const l=[6,10,14,18,22];r=Math.round(this.resolution.x/2),o=Math.round(this.resolution.y/2);for(let h=0;h<this.nMips;h++)this.separableBlurMaterials.push(this._getSeparableBlurMaterial(l[h])),this.separableBlurMaterials[h].uniforms.invSize.value=new Se(1/r,1/o),r=Math.round(r/2),o=Math.round(o/2);this.compositeMaterial=this._getCompositeMaterial(this.nMips),this.compositeMaterial.uniforms.blurTexture1.value=this.renderTargetsVertical[0].texture,this.compositeMaterial.uniforms.blurTexture2.value=this.renderTargetsVertical[1].texture,this.compositeMaterial.uniforms.blurTexture3.value=this.renderTargetsVertical[2].texture,this.compositeMaterial.uniforms.blurTexture4.value=this.renderTargetsVertical[3].texture,this.compositeMaterial.uniforms.blurTexture5.value=this.renderTargetsVertical[4].texture,this.compositeMaterial.uniforms.bloomStrength.value=t,this.compositeMaterial.uniforms.bloomRadius.value=.1;const c=[1,.8,.6,.4,.2];this.compositeMaterial.uniforms.bloomFactors.value=c,this.bloomTintColors=[new F(1,1,1),new F(1,1,1),new F(1,1,1),new F(1,1,1),new F(1,1,1)],this.compositeMaterial.uniforms.bloomTintColors.value=this.bloomTintColors,this.copyUniforms=es.clone(Er.uniforms),this.blendMaterial=new Ye({uniforms:this.copyUniforms,vertexShader:Er.vertexShader,fragmentShader:Er.fragmentShader,premultipliedAlpha:!0,blending:ji,depthTest:!1,depthWrite:!1,transparent:!0}),this._oldClearColor=new W,this._oldClearAlpha=1,this._basic=new dt,this._fsQuad=new Nn(null)}dispose(){for(let e=0;e<this.renderTargetsHorizontal.length;e++)this.renderTargetsHorizontal[e].dispose();for(let e=0;e<this.renderTargetsVertical.length;e++)this.renderTargetsVertical[e].dispose();this.renderTargetBright.dispose();for(let e=0;e<this.separableBlurMaterials.length;e++)this.separableBlurMaterials[e].dispose();this.compositeMaterial.dispose(),this.blendMaterial.dispose(),this._basic.dispose(),this._fsQuad.dispose()}setSize(e,t){let i=Math.round(e/2),n=Math.round(t/2);this.renderTargetBright.setSize(i,n);for(let r=0;r<this.nMips;r++)this.renderTargetsHorizontal[r].setSize(i,n),this.renderTargetsVertical[r].setSize(i,n),this.separableBlurMaterials[r].uniforms.invSize.value=new Se(1/i,1/n),i=Math.round(i/2),n=Math.round(n/2)}render(e,t,i,n,r){e.getClearColor(this._oldClearColor),this._oldClearAlpha=e.getClearAlpha();const o=e.autoClear;e.autoClear=!1,e.setClearColor(this.clearColor,0),r&&e.state.buffers.stencil.setTest(!1),this.renderToScreen&&(this._fsQuad.material=this._basic,this._basic.map=i.texture,e.setRenderTarget(null),e.clear(),this._fsQuad.render(e)),this.highPassUniforms.tDiffuse.value=i.texture,this.highPassUniforms.luminosityThreshold.value=this.threshold,this._fsQuad.material=this.materialHighPassFilter,e.setRenderTarget(this.renderTargetBright),e.clear(),this._fsQuad.render(e);let a=this.renderTargetBright;for(let l=0;l<this.nMips;l++)this._fsQuad.material=this.separableBlurMaterials[l],this.separableBlurMaterials[l].uniforms.colorTexture.value=a.texture,this.separableBlurMaterials[l].uniforms.direction.value=Ii.BlurDirectionX,e.setRenderTarget(this.renderTargetsHorizontal[l]),e.clear(),this._fsQuad.render(e),this.separableBlurMaterials[l].uniforms.colorTexture.value=this.renderTargetsHorizontal[l].texture,this.separableBlurMaterials[l].uniforms.direction.value=Ii.BlurDirectionY,e.setRenderTarget(this.renderTargetsVertical[l]),e.clear(),this._fsQuad.render(e),a=this.renderTargetsVertical[l];this._fsQuad.material=this.compositeMaterial,this.compositeMaterial.uniforms.bloomStrength.value=this.strength,this.compositeMaterial.uniforms.bloomRadius.value=this.radius,this.compositeMaterial.uniforms.bloomTintColors.value=this.bloomTintColors,e.setRenderTarget(this.renderTargetsHorizontal[0]),e.clear(),this._fsQuad.render(e),this._fsQuad.material=this.blendMaterial,this.copyUniforms.tDiffuse.value=this.renderTargetsHorizontal[0].texture,r&&e.state.buffers.stencil.setTest(!0),this.renderToScreen?(e.setRenderTarget(null),this._fsQuad.render(e)):(e.setRenderTarget(i),this._fsQuad.render(e)),e.setClearColor(this._oldClearColor,this._oldClearAlpha),e.autoClear=o}_getSeparableBlurMaterial(e){const t=[],i=e/3;for(let n=0;n<e;n++)t.push(.39894*Math.exp(-.5*n*n/(i*i))/i);return new Ye({defines:{KERNEL_RADIUS:e},uniforms:{colorTexture:{value:null},invSize:{value:new Se(.5,.5)},direction:{value:new Se(.5,.5)},gaussianCoefficients:{value:t}},vertexShader:`
|
|
58
|
-
|
|
59
|
-
varying vec2 vUv;
|
|
60
|
-
|
|
61
|
-
void main() {
|
|
62
|
-
|
|
63
|
-
vUv = uv;
|
|
64
|
-
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
|
65
|
-
|
|
66
|
-
}`,fragmentShader:`
|
|
67
|
-
|
|
68
|
-
#include <common>
|
|
69
|
-
|
|
70
|
-
varying vec2 vUv;
|
|
71
|
-
|
|
72
|
-
uniform sampler2D colorTexture;
|
|
73
|
-
uniform vec2 invSize;
|
|
74
|
-
uniform vec2 direction;
|
|
75
|
-
uniform float gaussianCoefficients[KERNEL_RADIUS];
|
|
76
|
-
|
|
77
|
-
void main() {
|
|
78
|
-
|
|
79
|
-
float weightSum = gaussianCoefficients[0];
|
|
80
|
-
vec3 diffuseSum = texture2D( colorTexture, vUv ).rgb * weightSum;
|
|
81
|
-
|
|
82
|
-
for ( int i = 1; i < KERNEL_RADIUS; i ++ ) {
|
|
83
|
-
|
|
84
|
-
float x = float( i );
|
|
85
|
-
float w = gaussianCoefficients[i];
|
|
86
|
-
vec2 uvOffset = direction * invSize * x;
|
|
87
|
-
vec3 sample1 = texture2D( colorTexture, vUv + uvOffset ).rgb;
|
|
88
|
-
vec3 sample2 = texture2D( colorTexture, vUv - uvOffset ).rgb;
|
|
89
|
-
diffuseSum += ( sample1 + sample2 ) * w;
|
|
90
|
-
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
gl_FragColor = vec4( diffuseSum, 1.0 );
|
|
94
|
-
|
|
95
|
-
}`})}_getCompositeMaterial(e){return new Ye({defines:{NUM_MIPS:e},uniforms:{blurTexture1:{value:null},blurTexture2:{value:null},blurTexture3:{value:null},blurTexture4:{value:null},blurTexture5:{value:null},bloomStrength:{value:1},bloomFactors:{value:null},bloomTintColors:{value:null},bloomRadius:{value:0}},vertexShader:`
|
|
96
|
-
|
|
97
|
-
varying vec2 vUv;
|
|
98
|
-
|
|
99
|
-
void main() {
|
|
100
|
-
|
|
101
|
-
vUv = uv;
|
|
102
|
-
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
|
103
|
-
|
|
104
|
-
}`,fragmentShader:`
|
|
105
|
-
|
|
106
|
-
varying vec2 vUv;
|
|
107
|
-
|
|
108
|
-
uniform sampler2D blurTexture1;
|
|
109
|
-
uniform sampler2D blurTexture2;
|
|
110
|
-
uniform sampler2D blurTexture3;
|
|
111
|
-
uniform sampler2D blurTexture4;
|
|
112
|
-
uniform sampler2D blurTexture5;
|
|
113
|
-
uniform float bloomStrength;
|
|
114
|
-
uniform float bloomRadius;
|
|
115
|
-
uniform float bloomFactors[NUM_MIPS];
|
|
116
|
-
uniform vec3 bloomTintColors[NUM_MIPS];
|
|
117
|
-
|
|
118
|
-
float lerpBloomFactor( const in float factor ) {
|
|
119
|
-
|
|
120
|
-
float mirrorFactor = 1.2 - factor;
|
|
121
|
-
return mix( factor, mirrorFactor, bloomRadius );
|
|
122
|
-
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
void main() {
|
|
126
|
-
|
|
127
|
-
// 3.0 for backwards compatibility with previous alpha-based intensity
|
|
128
|
-
vec3 bloom = 3.0 * bloomStrength * (
|
|
129
|
-
lerpBloomFactor( bloomFactors[ 0 ] ) * bloomTintColors[ 0 ] * texture2D( blurTexture1, vUv ).rgb +
|
|
130
|
-
lerpBloomFactor( bloomFactors[ 1 ] ) * bloomTintColors[ 1 ] * texture2D( blurTexture2, vUv ).rgb +
|
|
131
|
-
lerpBloomFactor( bloomFactors[ 2 ] ) * bloomTintColors[ 2 ] * texture2D( blurTexture3, vUv ).rgb +
|
|
132
|
-
lerpBloomFactor( bloomFactors[ 3 ] ) * bloomTintColors[ 3 ] * texture2D( blurTexture4, vUv ).rgb +
|
|
133
|
-
lerpBloomFactor( bloomFactors[ 4 ] ) * bloomTintColors[ 4 ] * texture2D( blurTexture5, vUv ).rgb
|
|
134
|
-
);
|
|
135
|
-
|
|
136
|
-
float bloomAlpha = max( bloom.r, max( bloom.g, bloom.b ) );
|
|
137
|
-
gl_FragColor = vec4( bloom, bloomAlpha );
|
|
138
|
-
|
|
139
|
-
}`})}}Ii.BlurDirectionX=new Se(1,0);Ii.BlurDirectionY=new Se(0,1);const Kn={name:"OutputShader",uniforms:{tDiffuse:{value:null},toneMappingExposure:{value:1}},vertexShader:`
|
|
140
|
-
precision highp float;
|
|
141
|
-
|
|
142
|
-
uniform mat4 modelViewMatrix;
|
|
143
|
-
uniform mat4 projectionMatrix;
|
|
144
|
-
|
|
145
|
-
attribute vec3 position;
|
|
146
|
-
attribute vec2 uv;
|
|
147
|
-
|
|
148
|
-
varying vec2 vUv;
|
|
149
|
-
|
|
150
|
-
void main() {
|
|
151
|
-
|
|
152
|
-
vUv = uv;
|
|
153
|
-
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
|
154
|
-
|
|
155
|
-
}`,fragmentShader:`
|
|
156
|
-
|
|
157
|
-
precision highp float;
|
|
158
|
-
|
|
159
|
-
uniform sampler2D tDiffuse;
|
|
160
|
-
|
|
161
|
-
#include <tonemapping_pars_fragment>
|
|
162
|
-
#include <colorspace_pars_fragment>
|
|
163
|
-
|
|
164
|
-
varying vec2 vUv;
|
|
165
|
-
|
|
166
|
-
void main() {
|
|
167
|
-
|
|
168
|
-
gl_FragColor = texture2D( tDiffuse, vUv );
|
|
169
|
-
|
|
170
|
-
// tone mapping
|
|
171
|
-
|
|
172
|
-
#ifdef LINEAR_TONE_MAPPING
|
|
173
|
-
|
|
174
|
-
gl_FragColor.rgb = LinearToneMapping( gl_FragColor.rgb );
|
|
175
|
-
|
|
176
|
-
#elif defined( REINHARD_TONE_MAPPING )
|
|
177
|
-
|
|
178
|
-
gl_FragColor.rgb = ReinhardToneMapping( gl_FragColor.rgb );
|
|
179
|
-
|
|
180
|
-
#elif defined( CINEON_TONE_MAPPING )
|
|
181
|
-
|
|
182
|
-
gl_FragColor.rgb = CineonToneMapping( gl_FragColor.rgb );
|
|
183
|
-
|
|
184
|
-
#elif defined( ACES_FILMIC_TONE_MAPPING )
|
|
185
|
-
|
|
186
|
-
gl_FragColor.rgb = ACESFilmicToneMapping( gl_FragColor.rgb );
|
|
187
|
-
|
|
188
|
-
#elif defined( AGX_TONE_MAPPING )
|
|
189
|
-
|
|
190
|
-
gl_FragColor.rgb = AgXToneMapping( gl_FragColor.rgb );
|
|
191
|
-
|
|
192
|
-
#elif defined( NEUTRAL_TONE_MAPPING )
|
|
193
|
-
|
|
194
|
-
gl_FragColor.rgb = NeutralToneMapping( gl_FragColor.rgb );
|
|
195
|
-
|
|
196
|
-
#elif defined( CUSTOM_TONE_MAPPING )
|
|
197
|
-
|
|
198
|
-
gl_FragColor.rgb = CustomToneMapping( gl_FragColor.rgb );
|
|
199
|
-
|
|
200
|
-
#endif
|
|
201
|
-
|
|
202
|
-
// color space
|
|
203
|
-
|
|
204
|
-
#ifdef SRGB_TRANSFER
|
|
205
|
-
|
|
206
|
-
gl_FragColor = sRGBTransferOETF( gl_FragColor );
|
|
207
|
-
|
|
208
|
-
#endif
|
|
209
|
-
|
|
210
|
-
}`};class Om extends ys{constructor(){super(),this.isOutputPass=!0,this.uniforms=es.clone(Kn.uniforms),this.material=new yp({name:Kn.name,uniforms:this.uniforms,vertexShader:Kn.vertexShader,fragmentShader:Kn.fragmentShader}),this._fsQuad=new Nn(this.material),this._outputColorSpace=null,this._toneMapping=null}render(e,t,i){this.uniforms.tDiffuse.value=i.texture,this.uniforms.toneMappingExposure.value=e.toneMappingExposure,(this._outputColorSpace!==e.outputColorSpace||this._toneMapping!==e.toneMapping)&&(this._outputColorSpace=e.outputColorSpace,this._toneMapping=e.toneMapping,this.material.defines={},Cp.getTransfer(this._outputColorSpace)===xp&&(this.material.defines.SRGB_TRANSFER=""),this._toneMapping===Mp?this.material.defines.LINEAR_TONE_MAPPING="":this._toneMapping===kp?this.material.defines.REINHARD_TONE_MAPPING="":this._toneMapping===Tp?this.material.defines.CINEON_TONE_MAPPING="":this._toneMapping===_u?this.material.defines.ACES_FILMIC_TONE_MAPPING="":this._toneMapping===_p?this.material.defines.AGX_TONE_MAPPING="":this._toneMapping===Sp?this.material.defines.NEUTRAL_TONE_MAPPING="":this._toneMapping===$p&&(this.material.defines.CUSTOM_TONE_MAPPING=""),this.material.needsUpdate=!0),this.renderToScreen===!0?(e.setRenderTarget(null),this._fsQuad.render(e)):(e.setRenderTarget(t),this.clear&&e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil),this._fsQuad.render(e))}dispose(){this.material.dispose(),this._fsQuad.dispose()}}const Jn={defines:{SMAA_THRESHOLD:"0.1"},uniforms:{tDiffuse:{value:null},resolution:{value:new Se(1/1024,1/512)}},vertexShader:`
|
|
211
|
-
|
|
212
|
-
uniform vec2 resolution;
|
|
213
|
-
|
|
214
|
-
varying vec2 vUv;
|
|
215
|
-
varying vec4 vOffset[ 3 ];
|
|
216
|
-
|
|
217
|
-
void SMAAEdgeDetectionVS( vec2 texcoord ) {
|
|
218
|
-
vOffset[ 0 ] = texcoord.xyxy + resolution.xyxy * vec4( -1.0, 0.0, 0.0, 1.0 ); // WebGL port note: Changed sign in W component
|
|
219
|
-
vOffset[ 1 ] = texcoord.xyxy + resolution.xyxy * vec4( 1.0, 0.0, 0.0, -1.0 ); // WebGL port note: Changed sign in W component
|
|
220
|
-
vOffset[ 2 ] = texcoord.xyxy + resolution.xyxy * vec4( -2.0, 0.0, 0.0, 2.0 ); // WebGL port note: Changed sign in W component
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
void main() {
|
|
224
|
-
|
|
225
|
-
vUv = uv;
|
|
226
|
-
|
|
227
|
-
SMAAEdgeDetectionVS( vUv );
|
|
228
|
-
|
|
229
|
-
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
|
230
|
-
|
|
231
|
-
}`,fragmentShader:`
|
|
232
|
-
|
|
233
|
-
uniform sampler2D tDiffuse;
|
|
234
|
-
|
|
235
|
-
varying vec2 vUv;
|
|
236
|
-
varying vec4 vOffset[ 3 ];
|
|
237
|
-
|
|
238
|
-
vec4 SMAAColorEdgeDetectionPS( vec2 texcoord, vec4 offset[3], sampler2D colorTex ) {
|
|
239
|
-
vec2 threshold = vec2( SMAA_THRESHOLD, SMAA_THRESHOLD );
|
|
240
|
-
|
|
241
|
-
// Calculate color deltas:
|
|
242
|
-
vec4 delta;
|
|
243
|
-
vec3 C = texture2D( colorTex, texcoord ).rgb;
|
|
244
|
-
|
|
245
|
-
vec3 Cleft = texture2D( colorTex, offset[0].xy ).rgb;
|
|
246
|
-
vec3 t = abs( C - Cleft );
|
|
247
|
-
delta.x = max( max( t.r, t.g ), t.b );
|
|
248
|
-
|
|
249
|
-
vec3 Ctop = texture2D( colorTex, offset[0].zw ).rgb;
|
|
250
|
-
t = abs( C - Ctop );
|
|
251
|
-
delta.y = max( max( t.r, t.g ), t.b );
|
|
252
|
-
|
|
253
|
-
// We do the usual threshold:
|
|
254
|
-
vec2 edges = step( threshold, delta.xy );
|
|
255
|
-
|
|
256
|
-
// Then discard if there is no edge:
|
|
257
|
-
if ( dot( edges, vec2( 1.0, 1.0 ) ) == 0.0 )
|
|
258
|
-
discard;
|
|
259
|
-
|
|
260
|
-
// Calculate right and bottom deltas:
|
|
261
|
-
vec3 Cright = texture2D( colorTex, offset[1].xy ).rgb;
|
|
262
|
-
t = abs( C - Cright );
|
|
263
|
-
delta.z = max( max( t.r, t.g ), t.b );
|
|
264
|
-
|
|
265
|
-
vec3 Cbottom = texture2D( colorTex, offset[1].zw ).rgb;
|
|
266
|
-
t = abs( C - Cbottom );
|
|
267
|
-
delta.w = max( max( t.r, t.g ), t.b );
|
|
268
|
-
|
|
269
|
-
// Calculate the maximum delta in the direct neighborhood:
|
|
270
|
-
float maxDelta = max( max( max( delta.x, delta.y ), delta.z ), delta.w );
|
|
271
|
-
|
|
272
|
-
// Calculate left-left and top-top deltas:
|
|
273
|
-
vec3 Cleftleft = texture2D( colorTex, offset[2].xy ).rgb;
|
|
274
|
-
t = abs( C - Cleftleft );
|
|
275
|
-
delta.z = max( max( t.r, t.g ), t.b );
|
|
276
|
-
|
|
277
|
-
vec3 Ctoptop = texture2D( colorTex, offset[2].zw ).rgb;
|
|
278
|
-
t = abs( C - Ctoptop );
|
|
279
|
-
delta.w = max( max( t.r, t.g ), t.b );
|
|
280
|
-
|
|
281
|
-
// Calculate the final maximum delta:
|
|
282
|
-
maxDelta = max( max( maxDelta, delta.z ), delta.w );
|
|
283
|
-
|
|
284
|
-
// Local contrast adaptation in action:
|
|
285
|
-
edges.xy *= step( 0.5 * maxDelta, delta.xy );
|
|
286
|
-
|
|
287
|
-
return vec4( edges, 0.0, 0.0 );
|
|
288
|
-
}
|
|
289
|
-
|
|
290
|
-
void main() {
|
|
291
|
-
|
|
292
|
-
gl_FragColor = SMAAColorEdgeDetectionPS( vUv, vOffset, tDiffuse );
|
|
293
|
-
|
|
294
|
-
}`},er={defines:{SMAA_MAX_SEARCH_STEPS:"8",SMAA_AREATEX_MAX_DISTANCE:"16",SMAA_AREATEX_PIXEL_SIZE:"( 1.0 / vec2( 160.0, 560.0 ) )",SMAA_AREATEX_SUBTEX_SIZE:"( 1.0 / 7.0 )"},uniforms:{tDiffuse:{value:null},tArea:{value:null},tSearch:{value:null},resolution:{value:new Se(1/1024,1/512)}},vertexShader:`
|
|
295
|
-
|
|
296
|
-
uniform vec2 resolution;
|
|
297
|
-
|
|
298
|
-
varying vec2 vUv;
|
|
299
|
-
varying vec4 vOffset[ 3 ];
|
|
300
|
-
varying vec2 vPixcoord;
|
|
301
|
-
|
|
302
|
-
void SMAABlendingWeightCalculationVS( vec2 texcoord ) {
|
|
303
|
-
vPixcoord = texcoord / resolution;
|
|
304
|
-
|
|
305
|
-
// We will use these offsets for the searches later on (see @PSEUDO_GATHER4):
|
|
306
|
-
vOffset[ 0 ] = texcoord.xyxy + resolution.xyxy * vec4( -0.25, 0.125, 1.25, 0.125 ); // WebGL port note: Changed sign in Y and W components
|
|
307
|
-
vOffset[ 1 ] = texcoord.xyxy + resolution.xyxy * vec4( -0.125, 0.25, -0.125, -1.25 ); // WebGL port note: Changed sign in Y and W components
|
|
308
|
-
|
|
309
|
-
// And these for the searches, they indicate the ends of the loops:
|
|
310
|
-
vOffset[ 2 ] = vec4( vOffset[ 0 ].xz, vOffset[ 1 ].yw ) + vec4( -2.0, 2.0, -2.0, 2.0 ) * resolution.xxyy * float( SMAA_MAX_SEARCH_STEPS );
|
|
311
|
-
|
|
312
|
-
}
|
|
313
|
-
|
|
314
|
-
void main() {
|
|
315
|
-
|
|
316
|
-
vUv = uv;
|
|
317
|
-
|
|
318
|
-
SMAABlendingWeightCalculationVS( vUv );
|
|
319
|
-
|
|
320
|
-
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
|
321
|
-
|
|
322
|
-
}`,fragmentShader:`
|
|
323
|
-
|
|
324
|
-
#define SMAASampleLevelZeroOffset( tex, coord, offset ) texture2D( tex, coord + float( offset ) * resolution, 0.0 )
|
|
325
|
-
|
|
326
|
-
uniform sampler2D tDiffuse;
|
|
327
|
-
uniform sampler2D tArea;
|
|
328
|
-
uniform sampler2D tSearch;
|
|
329
|
-
uniform vec2 resolution;
|
|
330
|
-
|
|
331
|
-
varying vec2 vUv;
|
|
332
|
-
varying vec4 vOffset[3];
|
|
333
|
-
varying vec2 vPixcoord;
|
|
334
|
-
|
|
335
|
-
#if __VERSION__ == 100
|
|
336
|
-
vec2 round( vec2 x ) {
|
|
337
|
-
return sign( x ) * floor( abs( x ) + 0.5 );
|
|
338
|
-
}
|
|
339
|
-
#endif
|
|
340
|
-
|
|
341
|
-
float SMAASearchLength( sampler2D searchTex, vec2 e, float bias, float scale ) {
|
|
342
|
-
// Not required if searchTex accesses are set to point:
|
|
343
|
-
// float2 SEARCH_TEX_PIXEL_SIZE = 1.0 / float2(66.0, 33.0);
|
|
344
|
-
// e = float2(bias, 0.0) + 0.5 * SEARCH_TEX_PIXEL_SIZE +
|
|
345
|
-
// e * float2(scale, 1.0) * float2(64.0, 32.0) * SEARCH_TEX_PIXEL_SIZE;
|
|
346
|
-
e.r = bias + e.r * scale;
|
|
347
|
-
return 255.0 * texture2D( searchTex, e, 0.0 ).r;
|
|
348
|
-
}
|
|
349
|
-
|
|
350
|
-
float SMAASearchXLeft( sampler2D edgesTex, sampler2D searchTex, vec2 texcoord, float end ) {
|
|
351
|
-
/**
|
|
352
|
-
* @PSEUDO_GATHER4
|
|
353
|
-
* This texcoord has been offset by (-0.25, -0.125) in the vertex shader to
|
|
354
|
-
* sample between edge, thus fetching four edges in a row.
|
|
355
|
-
* Sampling with different offsets in each direction allows to disambiguate
|
|
356
|
-
* which edges are active from the four fetched ones.
|
|
357
|
-
*/
|
|
358
|
-
vec2 e = vec2( 0.0, 1.0 );
|
|
359
|
-
|
|
360
|
-
for ( int i = 0; i < SMAA_MAX_SEARCH_STEPS; i ++ ) { // WebGL port note: Changed while to for
|
|
361
|
-
e = texture2D( edgesTex, texcoord, 0.0 ).rg;
|
|
362
|
-
texcoord -= vec2( 2.0, 0.0 ) * resolution;
|
|
363
|
-
if ( ! ( texcoord.x > end && e.g > 0.8281 && e.r == 0.0 ) ) break;
|
|
364
|
-
}
|
|
365
|
-
|
|
366
|
-
// We correct the previous (-0.25, -0.125) offset we applied:
|
|
367
|
-
texcoord.x += 0.25 * resolution.x;
|
|
368
|
-
|
|
369
|
-
// The searches are bias by 1, so adjust the coords accordingly:
|
|
370
|
-
texcoord.x += resolution.x;
|
|
371
|
-
|
|
372
|
-
// Disambiguate the length added by the last step:
|
|
373
|
-
texcoord.x += 2.0 * resolution.x; // Undo last step
|
|
374
|
-
texcoord.x -= resolution.x * SMAASearchLength(searchTex, e, 0.0, 0.5);
|
|
375
|
-
|
|
376
|
-
return texcoord.x;
|
|
377
|
-
}
|
|
378
|
-
|
|
379
|
-
float SMAASearchXRight( sampler2D edgesTex, sampler2D searchTex, vec2 texcoord, float end ) {
|
|
380
|
-
vec2 e = vec2( 0.0, 1.0 );
|
|
381
|
-
|
|
382
|
-
for ( int i = 0; i < SMAA_MAX_SEARCH_STEPS; i ++ ) { // WebGL port note: Changed while to for
|
|
383
|
-
e = texture2D( edgesTex, texcoord, 0.0 ).rg;
|
|
384
|
-
texcoord += vec2( 2.0, 0.0 ) * resolution;
|
|
385
|
-
if ( ! ( texcoord.x < end && e.g > 0.8281 && e.r == 0.0 ) ) break;
|
|
386
|
-
}
|
|
387
|
-
|
|
388
|
-
texcoord.x -= 0.25 * resolution.x;
|
|
389
|
-
texcoord.x -= resolution.x;
|
|
390
|
-
texcoord.x -= 2.0 * resolution.x;
|
|
391
|
-
texcoord.x += resolution.x * SMAASearchLength( searchTex, e, 0.5, 0.5 );
|
|
392
|
-
|
|
393
|
-
return texcoord.x;
|
|
394
|
-
}
|
|
395
|
-
|
|
396
|
-
float SMAASearchYUp( sampler2D edgesTex, sampler2D searchTex, vec2 texcoord, float end ) {
|
|
397
|
-
vec2 e = vec2( 1.0, 0.0 );
|
|
398
|
-
|
|
399
|
-
for ( int i = 0; i < SMAA_MAX_SEARCH_STEPS; i ++ ) { // WebGL port note: Changed while to for
|
|
400
|
-
e = texture2D( edgesTex, texcoord, 0.0 ).rg;
|
|
401
|
-
texcoord += vec2( 0.0, 2.0 ) * resolution; // WebGL port note: Changed sign
|
|
402
|
-
if ( ! ( texcoord.y > end && e.r > 0.8281 && e.g == 0.0 ) ) break;
|
|
403
|
-
}
|
|
404
|
-
|
|
405
|
-
texcoord.y -= 0.25 * resolution.y; // WebGL port note: Changed sign
|
|
406
|
-
texcoord.y -= resolution.y; // WebGL port note: Changed sign
|
|
407
|
-
texcoord.y -= 2.0 * resolution.y; // WebGL port note: Changed sign
|
|
408
|
-
texcoord.y += resolution.y * SMAASearchLength( searchTex, e.gr, 0.0, 0.5 ); // WebGL port note: Changed sign
|
|
409
|
-
|
|
410
|
-
return texcoord.y;
|
|
411
|
-
}
|
|
412
|
-
|
|
413
|
-
float SMAASearchYDown( sampler2D edgesTex, sampler2D searchTex, vec2 texcoord, float end ) {
|
|
414
|
-
vec2 e = vec2( 1.0, 0.0 );
|
|
415
|
-
|
|
416
|
-
for ( int i = 0; i < SMAA_MAX_SEARCH_STEPS; i ++ ) { // WebGL port note: Changed while to for
|
|
417
|
-
e = texture2D( edgesTex, texcoord, 0.0 ).rg;
|
|
418
|
-
texcoord -= vec2( 0.0, 2.0 ) * resolution; // WebGL port note: Changed sign
|
|
419
|
-
if ( ! ( texcoord.y < end && e.r > 0.8281 && e.g == 0.0 ) ) break;
|
|
420
|
-
}
|
|
421
|
-
|
|
422
|
-
texcoord.y += 0.25 * resolution.y; // WebGL port note: Changed sign
|
|
423
|
-
texcoord.y += resolution.y; // WebGL port note: Changed sign
|
|
424
|
-
texcoord.y += 2.0 * resolution.y; // WebGL port note: Changed sign
|
|
425
|
-
texcoord.y -= resolution.y * SMAASearchLength( searchTex, e.gr, 0.5, 0.5 ); // WebGL port note: Changed sign
|
|
426
|
-
|
|
427
|
-
return texcoord.y;
|
|
428
|
-
}
|
|
429
|
-
|
|
430
|
-
vec2 SMAAArea( sampler2D areaTex, vec2 dist, float e1, float e2, float offset ) {
|
|
431
|
-
// Rounding prevents precision errors of bilinear filtering:
|
|
432
|
-
vec2 texcoord = float( SMAA_AREATEX_MAX_DISTANCE ) * round( 4.0 * vec2( e1, e2 ) ) + dist;
|
|
433
|
-
|
|
434
|
-
// We do a scale and bias for mapping to texel space:
|
|
435
|
-
texcoord = SMAA_AREATEX_PIXEL_SIZE * texcoord + ( 0.5 * SMAA_AREATEX_PIXEL_SIZE );
|
|
436
|
-
|
|
437
|
-
// Move to proper place, according to the subpixel offset:
|
|
438
|
-
texcoord.y += SMAA_AREATEX_SUBTEX_SIZE * offset;
|
|
439
|
-
|
|
440
|
-
return texture2D( areaTex, texcoord, 0.0 ).rg;
|
|
441
|
-
}
|
|
442
|
-
|
|
443
|
-
vec4 SMAABlendingWeightCalculationPS( vec2 texcoord, vec2 pixcoord, vec4 offset[ 3 ], sampler2D edgesTex, sampler2D areaTex, sampler2D searchTex, ivec4 subsampleIndices ) {
|
|
444
|
-
vec4 weights = vec4( 0.0, 0.0, 0.0, 0.0 );
|
|
445
|
-
|
|
446
|
-
vec2 e = texture2D( edgesTex, texcoord ).rg;
|
|
447
|
-
|
|
448
|
-
if ( e.g > 0.0 ) { // Edge at north
|
|
449
|
-
vec2 d;
|
|
450
|
-
|
|
451
|
-
// Find the distance to the left:
|
|
452
|
-
vec2 coords;
|
|
453
|
-
coords.x = SMAASearchXLeft( edgesTex, searchTex, offset[ 0 ].xy, offset[ 2 ].x );
|
|
454
|
-
coords.y = offset[ 1 ].y; // offset[1].y = texcoord.y - 0.25 * resolution.y (@CROSSING_OFFSET)
|
|
455
|
-
d.x = coords.x;
|
|
456
|
-
|
|
457
|
-
// Now fetch the left crossing edges, two at a time using bilinear
|
|
458
|
-
// filtering. Sampling at -0.25 (see @CROSSING_OFFSET) enables to
|
|
459
|
-
// discern what value each edge has:
|
|
460
|
-
float e1 = texture2D( edgesTex, coords, 0.0 ).r;
|
|
461
|
-
|
|
462
|
-
// Find the distance to the right:
|
|
463
|
-
coords.x = SMAASearchXRight( edgesTex, searchTex, offset[ 0 ].zw, offset[ 2 ].y );
|
|
464
|
-
d.y = coords.x;
|
|
465
|
-
|
|
466
|
-
// We want the distances to be in pixel units (doing this here allow to
|
|
467
|
-
// better interleave arithmetic and memory accesses):
|
|
468
|
-
d = d / resolution.x - pixcoord.x;
|
|
469
|
-
|
|
470
|
-
// SMAAArea below needs a sqrt, as the areas texture is compressed
|
|
471
|
-
// quadratically:
|
|
472
|
-
vec2 sqrt_d = sqrt( abs( d ) );
|
|
473
|
-
|
|
474
|
-
// Fetch the right crossing edges:
|
|
475
|
-
coords.y -= 1.0 * resolution.y; // WebGL port note: Added
|
|
476
|
-
float e2 = SMAASampleLevelZeroOffset( edgesTex, coords, ivec2( 1, 0 ) ).r;
|
|
477
|
-
|
|
478
|
-
// Ok, we know how this pattern looks like, now it is time for getting
|
|
479
|
-
// the actual area:
|
|
480
|
-
weights.rg = SMAAArea( areaTex, sqrt_d, e1, e2, float( subsampleIndices.y ) );
|
|
481
|
-
}
|
|
482
|
-
|
|
483
|
-
if ( e.r > 0.0 ) { // Edge at west
|
|
484
|
-
vec2 d;
|
|
485
|
-
|
|
486
|
-
// Find the distance to the top:
|
|
487
|
-
vec2 coords;
|
|
488
|
-
|
|
489
|
-
coords.y = SMAASearchYUp( edgesTex, searchTex, offset[ 1 ].xy, offset[ 2 ].z );
|
|
490
|
-
coords.x = offset[ 0 ].x; // offset[1].x = texcoord.x - 0.25 * resolution.x;
|
|
491
|
-
d.x = coords.y;
|
|
492
|
-
|
|
493
|
-
// Fetch the top crossing edges:
|
|
494
|
-
float e1 = texture2D( edgesTex, coords, 0.0 ).g;
|
|
495
|
-
|
|
496
|
-
// Find the distance to the bottom:
|
|
497
|
-
coords.y = SMAASearchYDown( edgesTex, searchTex, offset[ 1 ].zw, offset[ 2 ].w );
|
|
498
|
-
d.y = coords.y;
|
|
499
|
-
|
|
500
|
-
// We want the distances to be in pixel units:
|
|
501
|
-
d = d / resolution.y - pixcoord.y;
|
|
502
|
-
|
|
503
|
-
// SMAAArea below needs a sqrt, as the areas texture is compressed
|
|
504
|
-
// quadratically:
|
|
505
|
-
vec2 sqrt_d = sqrt( abs( d ) );
|
|
506
|
-
|
|
507
|
-
// Fetch the bottom crossing edges:
|
|
508
|
-
coords.y -= 1.0 * resolution.y; // WebGL port note: Added
|
|
509
|
-
float e2 = SMAASampleLevelZeroOffset( edgesTex, coords, ivec2( 0, 1 ) ).g;
|
|
510
|
-
|
|
511
|
-
// Get the area for this direction:
|
|
512
|
-
weights.ba = SMAAArea( areaTex, sqrt_d, e1, e2, float( subsampleIndices.x ) );
|
|
513
|
-
}
|
|
514
|
-
|
|
515
|
-
return weights;
|
|
516
|
-
}
|
|
517
|
-
|
|
518
|
-
void main() {
|
|
519
|
-
|
|
520
|
-
gl_FragColor = SMAABlendingWeightCalculationPS( vUv, vPixcoord, vOffset, tDiffuse, tArea, tSearch, ivec4( 0.0 ) );
|
|
521
|
-
|
|
522
|
-
}`},Lo={uniforms:{tDiffuse:{value:null},tColor:{value:null},resolution:{value:new Se(1/1024,1/512)}},vertexShader:`
|
|
523
|
-
|
|
524
|
-
uniform vec2 resolution;
|
|
525
|
-
|
|
526
|
-
varying vec2 vUv;
|
|
527
|
-
varying vec4 vOffset[ 2 ];
|
|
528
|
-
|
|
529
|
-
void SMAANeighborhoodBlendingVS( vec2 texcoord ) {
|
|
530
|
-
vOffset[ 0 ] = texcoord.xyxy + resolution.xyxy * vec4( -1.0, 0.0, 0.0, 1.0 ); // WebGL port note: Changed sign in W component
|
|
531
|
-
vOffset[ 1 ] = texcoord.xyxy + resolution.xyxy * vec4( 1.0, 0.0, 0.0, -1.0 ); // WebGL port note: Changed sign in W component
|
|
532
|
-
}
|
|
533
|
-
|
|
534
|
-
void main() {
|
|
535
|
-
|
|
536
|
-
vUv = uv;
|
|
537
|
-
|
|
538
|
-
SMAANeighborhoodBlendingVS( vUv );
|
|
539
|
-
|
|
540
|
-
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
|
541
|
-
|
|
542
|
-
}`,fragmentShader:`
|
|
543
|
-
|
|
544
|
-
uniform sampler2D tDiffuse;
|
|
545
|
-
uniform sampler2D tColor;
|
|
546
|
-
uniform vec2 resolution;
|
|
547
|
-
|
|
548
|
-
varying vec2 vUv;
|
|
549
|
-
varying vec4 vOffset[ 2 ];
|
|
550
|
-
|
|
551
|
-
vec4 SMAANeighborhoodBlendingPS( vec2 texcoord, vec4 offset[ 2 ], sampler2D colorTex, sampler2D blendTex ) {
|
|
552
|
-
// Fetch the blending weights for current pixel:
|
|
553
|
-
vec4 a;
|
|
554
|
-
a.xz = texture2D( blendTex, texcoord ).xz;
|
|
555
|
-
a.y = texture2D( blendTex, offset[ 1 ].zw ).g;
|
|
556
|
-
a.w = texture2D( blendTex, offset[ 1 ].xy ).a;
|
|
557
|
-
|
|
558
|
-
// Is there any blending weight with a value greater than 0.0?
|
|
559
|
-
if ( dot(a, vec4( 1.0, 1.0, 1.0, 1.0 )) < 1e-5 ) {
|
|
560
|
-
return texture2D( colorTex, texcoord, 0.0 );
|
|
561
|
-
} else {
|
|
562
|
-
// Up to 4 lines can be crossing a pixel (one through each edge). We
|
|
563
|
-
// favor blending by choosing the line with the maximum weight for each
|
|
564
|
-
// direction:
|
|
565
|
-
vec2 offset;
|
|
566
|
-
offset.x = a.a > a.b ? a.a : -a.b; // left vs. right
|
|
567
|
-
offset.y = a.g > a.r ? -a.g : a.r; // top vs. bottom // WebGL port note: Changed signs
|
|
568
|
-
|
|
569
|
-
// Then we go in the direction that has the maximum weight:
|
|
570
|
-
if ( abs( offset.x ) > abs( offset.y )) { // horizontal vs. vertical
|
|
571
|
-
offset.y = 0.0;
|
|
572
|
-
} else {
|
|
573
|
-
offset.x = 0.0;
|
|
574
|
-
}
|
|
575
|
-
|
|
576
|
-
// Fetch the opposite color and lerp by hand:
|
|
577
|
-
vec4 C = texture2D( colorTex, texcoord, 0.0 );
|
|
578
|
-
texcoord += sign( offset ) * resolution;
|
|
579
|
-
vec4 Cop = texture2D( colorTex, texcoord, 0.0 );
|
|
580
|
-
float s = abs( offset.x ) > abs( offset.y ) ? abs( offset.x ) : abs( offset.y );
|
|
581
|
-
|
|
582
|
-
// WebGL port note: Added gamma correction
|
|
583
|
-
C.xyz = pow(C.xyz, vec3(2.2));
|
|
584
|
-
Cop.xyz = pow(Cop.xyz, vec3(2.2));
|
|
585
|
-
vec4 mixed = mix(C, Cop, s);
|
|
586
|
-
mixed.xyz = pow(mixed.xyz, vec3(1.0 / 2.2));
|
|
587
|
-
|
|
588
|
-
return mixed;
|
|
589
|
-
}
|
|
590
|
-
}
|
|
591
|
-
|
|
592
|
-
void main() {
|
|
593
|
-
|
|
594
|
-
gl_FragColor = SMAANeighborhoodBlendingPS( vUv, vOffset, tColor, tDiffuse );
|
|
595
|
-
|
|
596
|
-
}`};class Im extends ys{constructor(){super(),this._edgesRT=new Fs(1,1,{depthBuffer:!1,type:Os}),this._edgesRT.texture.name="SMAAPass.edges",this._weightsRT=new Fs(1,1,{depthBuffer:!1,type:Os}),this._weightsRT.texture.name="SMAAPass.weights";const e=this,t=new Image;t.src=this._getAreaTexture(),t.onload=function(){e._areaTexture.needsUpdate=!0},this._areaTexture=new wc,this._areaTexture.name="SMAAPass.area",this._areaTexture.image=t,this._areaTexture.minFilter=qi,this._areaTexture.generateMipmaps=!1,this._areaTexture.flipY=!1;const i=new Image;i.src=this._getSearchTexture(),i.onload=function(){e._searchTexture.needsUpdate=!0},this._searchTexture=new wc,this._searchTexture.name="SMAAPass.search",this._searchTexture.image=i,this._searchTexture.magFilter=bc,this._searchTexture.minFilter=bc,this._searchTexture.generateMipmaps=!1,this._searchTexture.flipY=!1,this._uniformsEdges=es.clone(Jn.uniforms),this._materialEdges=new Ye({defines:Object.assign({},Jn.defines),uniforms:this._uniformsEdges,vertexShader:Jn.vertexShader,fragmentShader:Jn.fragmentShader}),this._uniformsWeights=es.clone(er.uniforms),this._uniformsWeights.tDiffuse.value=this._edgesRT.texture,this._uniformsWeights.tArea.value=this._areaTexture,this._uniformsWeights.tSearch.value=this._searchTexture,this._materialWeights=new Ye({defines:Object.assign({},er.defines),uniforms:this._uniformsWeights,vertexShader:er.vertexShader,fragmentShader:er.fragmentShader}),this._uniformsBlend=es.clone(Lo.uniforms),this._uniformsBlend.tDiffuse.value=this._weightsRT.texture,this._materialBlend=new Ye({uniforms:this._uniformsBlend,vertexShader:Lo.vertexShader,fragmentShader:Lo.fragmentShader}),this._fsQuad=new Nn(null)}render(e,t,i){this._uniformsEdges.tDiffuse.value=i.texture,this._fsQuad.material=this._materialEdges,e.setRenderTarget(this._edgesRT),this.clear&&e.clear(),this._fsQuad.render(e),this._fsQuad.material=this._materialWeights,e.setRenderTarget(this._weightsRT),this.clear&&e.clear(),this._fsQuad.render(e),this._uniformsBlend.tColor.value=i.texture,this._fsQuad.material=this._materialBlend,this.renderToScreen?(e.setRenderTarget(null),this._fsQuad.render(e)):(e.setRenderTarget(t),this.clear&&e.clear(),this._fsQuad.render(e))}setSize(e,t){this._edgesRT.setSize(e,t),this._weightsRT.setSize(e,t),this._materialEdges.uniforms.resolution.value.set(1/e,1/t),this._materialWeights.uniforms.resolution.value.set(1/e,1/t),this._materialBlend.uniforms.resolution.value.set(1/e,1/t)}dispose(){this._edgesRT.dispose(),this._weightsRT.dispose(),this._areaTexture.dispose(),this._searchTexture.dispose(),this._materialEdges.dispose(),this._materialWeights.dispose(),this._materialBlend.dispose(),this._fsQuad.dispose()}_getAreaTexture(){return"data:image/png;base64,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"}_getSearchTexture(){return"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEIAAAAhCAAAAABIXyLAAAAAOElEQVRIx2NgGAWjYBSMglEwEICREYRgFBZBqDCSLA2MGPUIVQETE9iNUAqLR5gIeoQKRgwXjwAAGn4AtaFeYLEAAAAASUVORK5CYII="}}const Dm=.02,Ac={uniforms:{tDiffuse:{value:null},tDepth:{value:null},uTexel:{value:new Se(1/1024,1/1024)},uAxis:{value:new Se(1,0)},uMaxRadius:{value:8},uFocusDistance:{value:30},uFocusRange:{value:20},uTilt:{value:0},uNear:{value:.1},uFar:{value:500},uTanHalfFov:{value:Math.tan(N.degToRad(38)/2)},uAspect:{value:1},uProjectionOffset:{value:new Se}},vertexShader:`
|
|
597
|
-
varying vec2 vUv;
|
|
598
|
-
void main() {
|
|
599
|
-
vUv = uv;
|
|
600
|
-
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
|
601
|
-
}
|
|
602
|
-
`,fragmentShader:`
|
|
603
|
-
uniform sampler2D tDiffuse;
|
|
604
|
-
uniform vec2 uTexel;
|
|
605
|
-
uniform vec2 uAxis;
|
|
606
|
-
uniform float uMaxRadius;
|
|
607
|
-
varying vec2 vUv;
|
|
608
|
-
|
|
609
|
-
#ifdef COC_FROM_DEPTH
|
|
610
|
-
uniform sampler2D tDepth;
|
|
611
|
-
uniform float uFocusDistance;
|
|
612
|
-
uniform float uFocusRange;
|
|
613
|
-
uniform float uTilt;
|
|
614
|
-
uniform float uNear;
|
|
615
|
-
uniform float uFar;
|
|
616
|
-
uniform float uTanHalfFov;
|
|
617
|
-
uniform float uAspect;
|
|
618
|
-
uniform vec2 uProjectionOffset;
|
|
619
|
-
|
|
620
|
-
/** Window depth back to view space. Negative in front of the camera. */
|
|
621
|
-
float viewZOf( float depth ) {
|
|
622
|
-
float ndc = depth * 2.0 - 1.0;
|
|
623
|
-
return -( 2.0 * uNear * uFar ) / ( uFar + uNear - ndc * ( uFar - uNear ) );
|
|
624
|
-
}
|
|
625
|
-
|
|
626
|
-
float circleOfConfusion() {
|
|
627
|
-
float depth = texture2D( tDepth, vUv ).x;
|
|
628
|
-
|
|
629
|
-
// An unbound depth texture samples as 0, which is the near plane — a distance
|
|
630
|
-
// nothing is ever drawn at. Treating that as "no depth available, leave it sharp"
|
|
631
|
-
// means a half-wired frame shows the scene rather than a full-screen smear.
|
|
632
|
-
if ( depth <= 0.0 ) return 0.0;
|
|
633
|
-
|
|
634
|
-
// The sky is at the far plane and has no business anchoring focus — it is simply the
|
|
635
|
-
// furthest thing there is, so it takes the maximum blur and stays there.
|
|
636
|
-
if ( depth >= 0.9999 ) return 1.0;
|
|
637
|
-
|
|
638
|
-
float dist = -viewZOf( depth );
|
|
639
|
-
|
|
640
|
-
// Rebuild the view-space point. A tilted plane is only meaningful against a real
|
|
641
|
-
// position; measuring along the view axis alone would ignore the tilt entirely.
|
|
642
|
-
vec2 ndc = vUv * 2.0 - 1.0 + uProjectionOffset;
|
|
643
|
-
vec3 viewPos = vec3( ndc.x * uTanHalfFov * uAspect, ndc.y * uTanHalfFov, -1.0 ) * dist;
|
|
644
|
-
|
|
645
|
-
// Signed distance to the plane of focus, tilted about the horizontal axis.
|
|
646
|
-
vec3 planeNormal = vec3( 0.0, sin( uTilt ), cos( uTilt ) );
|
|
647
|
-
float signedDist = dot( viewPos - vec3( 0.0, 0.0, -uFocusDistance ), planeNormal );
|
|
648
|
-
|
|
649
|
-
return clamp( abs( signedDist ) / max( uFocusRange, 0.0001 ), 0.0, 1.0 );
|
|
650
|
-
}
|
|
651
|
-
#endif
|
|
652
|
-
|
|
653
|
-
/**
|
|
654
|
-
* Taps per side. Spacing is the radius over this, so the kernel stays properly sampled
|
|
655
|
-
* at every radius rather than the taps drifting apart as the blur widens — which is what
|
|
656
|
-
* turns a blur into visible copies of the picture.
|
|
657
|
-
*/
|
|
658
|
-
const int STEPS = 8;
|
|
659
|
-
|
|
660
|
-
void main() {
|
|
661
|
-
#ifdef COC_FROM_DEPTH
|
|
662
|
-
float coc = circleOfConfusion();
|
|
663
|
-
#else
|
|
664
|
-
float coc = texture2D( tDiffuse, vUv ).a;
|
|
665
|
-
#endif
|
|
666
|
-
|
|
667
|
-
float radius = uMaxRadius * coc;
|
|
668
|
-
|
|
669
|
-
// Under about a third of a pixel there is nothing to gather that the centre tap does
|
|
670
|
-
// not already have, and the whole in-focus band takes this branch.
|
|
671
|
-
if ( radius < 0.35 ) {
|
|
672
|
-
gl_FragColor = vec4( texture2D( tDiffuse, vUv ).rgb, COC_OUT );
|
|
673
|
-
return;
|
|
674
|
-
}
|
|
675
|
-
|
|
676
|
-
vec2 unit = uAxis * uTexel;
|
|
677
|
-
vec4 sum = texture2D( tDiffuse, vUv );
|
|
678
|
-
float weight = 1.0;
|
|
679
|
-
|
|
680
|
-
for ( int i = 1; i <= STEPS; i++ ) {
|
|
681
|
-
float fraction = float( i ) / float( STEPS );
|
|
682
|
-
float offset = fraction * radius;
|
|
683
|
-
// Sigma is radius/3: the radius cancels out of the Gaussian exponent. These
|
|
684
|
-
// weights are constant, so the compiler can fold them instead of doing eight
|
|
685
|
-
// exponentials per blurred pixel in each pass.
|
|
686
|
-
float w = exp( -4.5 * fraction * fraction );
|
|
687
|
-
sum += texture2D( tDiffuse, vUv + unit * offset ) * w;
|
|
688
|
-
sum += texture2D( tDiffuse, vUv - unit * offset ) * w;
|
|
689
|
-
weight += 2.0 * w;
|
|
690
|
-
}
|
|
691
|
-
|
|
692
|
-
gl_FragColor = vec4( ( sum / weight ).rgb, COC_OUT );
|
|
693
|
-
}
|
|
694
|
-
`};function Vm(){const s=new jr({...Ac,defines:{COC_FROM_DEPTH:"",COC_OUT:"coc"}}),e=new jr({...Ac,defines:{COC_OUT:"1.0"}});s.uniforms.uAxis.value.set(1,0),e.uniforms.uAxis.value.set(0,1);const t=[s,e],i=(l,c)=>{for(const h of t)h.uniforms[l].value=c};let n=.4,r=1080,o=30;const a=()=>{i("uMaxRadius",n*Dm*r),i("uFocusDistance",o),i("uFocusRange",o*(.8+(.08-.8)*n))};return{passes:t,set enabled(l){for(const c of t)c.enabled=l},get enabled(){return s.enabled},setDepthTexture(l){s.uniforms.tDepth.value=l},setStrength(l){n=Math.max(0,Math.min(1,l)),a()},setAngle(l){i("uTilt",l*Math.PI/180)},setFocusDistance(l){o=Math.max(.1,l),a()},setCamera(l){i("uNear",l.near),i("uFar",l.far),i("uAspect",l.aspect),i("uTanHalfFov",Math.tan(N.degToRad(l.fov)/2));const c=l.projectionMatrix.elements;for(const h of t)h.uniforms.uProjectionOffset.value.set(c[8],c[9])},setSize(l,c){r=Math.max(1,c);for(const h of t)h.uniforms.uTexel.value.set(1/Math.max(1,l),1/r);a()}}}const Ec=`
|
|
695
|
-
varying vec2 vUv;
|
|
696
|
-
void main() {
|
|
697
|
-
vUv = uv;
|
|
698
|
-
gl_Position = vec4(position.xy, 0.0, 1.0);
|
|
699
|
-
}
|
|
700
|
-
`;class Nm extends ys{constructor(e){super(),this.camera=e,this.needsSwap=!1,this.target=null,this.width=1,this.height=1,this.material=new Ye({name:"ContactOcclusion",vertexShader:Ec,depthTest:!1,depthWrite:!1,uniforms:{tDepth:{value:null},uTexel:{value:new Se(1,1)},uProjectionInverse:{value:new xt},uProjectionScale:{value:new Se},uStrength:{value:0}},fragmentShader:`
|
|
701
|
-
uniform sampler2D tDepth;
|
|
702
|
-
uniform vec2 uTexel;
|
|
703
|
-
uniform mat4 uProjectionInverse;
|
|
704
|
-
uniform vec2 uProjectionScale;
|
|
705
|
-
uniform float uStrength;
|
|
706
|
-
varying vec2 vUv;
|
|
707
|
-
|
|
708
|
-
vec3 viewPosition(vec2 uv, float depth) {
|
|
709
|
-
vec4 p = uProjectionInverse * vec4(uv * 2.0 - 1.0, depth * 2.0 - 1.0, 1.0);
|
|
710
|
-
return p.xyz / max(p.w, 0.000001);
|
|
711
|
-
}
|
|
712
|
-
vec3 positionAt(vec2 uv) {
|
|
713
|
-
return viewPosition(uv, texture2D(tDepth, uv).r);
|
|
714
|
-
}
|
|
715
|
-
|
|
716
|
-
void main() {
|
|
717
|
-
float depth = texture2D(tDepth, vUv).r;
|
|
718
|
-
// Sky, and the outermost texel where normal reconstruction has no neighbours.
|
|
719
|
-
if (depth >= 0.999999 || any(lessThan(vUv, uTexel)) || any(greaterThan(vUv, 1.0 - uTexel))) {
|
|
720
|
-
gl_FragColor = vec4(1.0); return;
|
|
721
|
-
}
|
|
722
|
-
vec3 p = viewPosition(vUv, depth);
|
|
723
|
-
vec3 l = positionAt(vUv - vec2(uTexel.x, 0.0));
|
|
724
|
-
vec3 r = positionAt(vUv + vec2(uTexel.x, 0.0));
|
|
725
|
-
vec3 b = positionAt(vUv - vec2(0.0, uTexel.y));
|
|
726
|
-
vec3 t = positionAt(vUv + vec2(0.0, uTexel.y));
|
|
727
|
-
// Choose the neighbour on the same surface at silhouettes. A cross-edge normal
|
|
728
|
-
// would invent dark outlines around every roof and antenna against the sky.
|
|
729
|
-
vec3 dx = abs(l.z - p.z) < abs(r.z - p.z) ? p - l : r - p;
|
|
730
|
-
vec3 dy = abs(b.z - p.z) < abs(t.z - p.z) ? p - b : t - p;
|
|
731
|
-
vec3 n = cross(dx, dy);
|
|
732
|
-
float n2 = dot(n, n);
|
|
733
|
-
if (n2 < 1e-18) { gl_FragColor = vec4(1.0); return; }
|
|
734
|
-
n *= inversesqrt(max(n2, 1e-18));
|
|
735
|
-
if (dot(n, -p) < 0.0) n = -n;
|
|
736
|
-
|
|
737
|
-
const float RADIUS = 0.32;
|
|
738
|
-
vec2 uvRadius = uProjectionScale * RADIUS / max(-p.z, 0.01);
|
|
739
|
-
// Smoothly vanish below a pixel, rather than resolve into moving black specks
|
|
740
|
-
// when the user zooms out. Bound the close-up footprint as well.
|
|
741
|
-
float radiusPixels = uvRadius.y / uTexel.y;
|
|
742
|
-
float visibility = smoothstep(0.75, 2.5, radiusPixels);
|
|
743
|
-
uvRadius *= min(1.0, 40.0 / max(radiusPixels, 0.001));
|
|
744
|
-
float occlusion = 0.0;
|
|
745
|
-
// A fixed spiral, with no random rotation, temporal noise or accumulated history.
|
|
746
|
-
// The same camera and geometry always produce exactly the same shading.
|
|
747
|
-
for (int i = 0; i < 16; i++) {
|
|
748
|
-
float f = (float(i) + 0.5) / 16.0;
|
|
749
|
-
float angle = float(i) * 2.39996323;
|
|
750
|
-
vec2 uv = vUv + vec2(cos(angle), sin(angle)) * sqrt(f) * uvRadius;
|
|
751
|
-
if (any(lessThan(uv, uTexel)) || any(greaterThan(uv, 1.0 - uTexel))) continue;
|
|
752
|
-
float sampleDepth = texture2D(tDepth, uv).r;
|
|
753
|
-
if (sampleDepth >= 0.999999) continue;
|
|
754
|
-
vec3 delta = viewPosition(uv, sampleDepth) - p;
|
|
755
|
-
float distance2 = dot(delta, delta);
|
|
756
|
-
float distance = sqrt(max(distance2, 1e-10));
|
|
757
|
-
// Only nearby geometry above the surface can occlude it. Distant buildings
|
|
758
|
-
// behind a silhouette, and flat/convex parts of the suit, contribute nothing.
|
|
759
|
-
float horizon = max(0.0, dot(n, delta) / distance - 0.12);
|
|
760
|
-
float falloff = 1.0 - smoothstep(RADIUS * 0.2, RADIUS, distance);
|
|
761
|
-
occlusion += horizon * falloff;
|
|
762
|
-
}
|
|
763
|
-
float shade = 1.0 - uStrength * visibility * min(0.70, occlusion * (3.0 / 16.0));
|
|
764
|
-
gl_FragColor = vec4(vec3(shade), 1.0);
|
|
765
|
-
}
|
|
766
|
-
`}),this.multiply=new Ye({name:"ApplyContactOcclusion",vertexShader:Ec,depthTest:!1,depthWrite:!1,blending:Ap,premultipliedAlpha:!0,transparent:!0,toneMapped:!1,uniforms:{tOcclusion:{value:null},uTexel:{value:new Se(1,1)}},fragmentShader:`
|
|
767
|
-
uniform sampler2D tOcclusion;
|
|
768
|
-
uniform vec2 uTexel;
|
|
769
|
-
varying vec2 vUv;
|
|
770
|
-
void main() {
|
|
771
|
-
// A compact, fixed Gaussian softens sample footprints at high strength without
|
|
772
|
-
// any temporal noise, extra scene draws, or a large halo around silhouettes.
|
|
773
|
-
float shade = 0.0;
|
|
774
|
-
for (int y = -1; y <= 1; y++) for (int x = -1; x <= 1; x++) {
|
|
775
|
-
float weight = (x == 0 ? 2.0 : 1.0) * (y == 0 ? 2.0 : 1.0);
|
|
776
|
-
shade += texture2D(tOcclusion, vUv + vec2(float(x), float(y)) * uTexel * 1.5).r * weight;
|
|
777
|
-
}
|
|
778
|
-
gl_FragColor = vec4(vec3(shade / 16.0), 1.0);
|
|
779
|
-
}
|
|
780
|
-
`}),this.quad=new Nn(this.material),this.setStrength(0)}setStrength(e){const t=Number.isFinite(e)?N.clamp(e,0,1):0;this.material.uniforms.uStrength.value=t,this.enabled=t>0,!this.enabled&&this.target&&(this.target.dispose(),this.target=null,this.multiply.uniforms.tOcclusion.value=null)}setSize(e,t){this.width=Math.max(1,Math.round(e)),this.height=Math.max(1,Math.round(t)),this.target?.setSize(this.width,this.height),this.material.uniforms.uTexel.value.set(1/this.width,1/this.height),this.multiply.uniforms.uTexel.value.copy(this.material.uniforms.uTexel.value)}render(e,t,i){if(!this.enabled||!i.depthTexture)return;this.target||(this.target=new Fs(this.width,this.height,{format:Ep,type:Su,depthBuffer:!1,stencilBuffer:!1}),this.multiply.uniforms.tOcclusion.value=this.target.texture);const n=this.material.uniforms;n.tDepth.value=i.depthTexture,n.uProjectionInverse.value.copy(this.camera.projectionMatrixInverse);const r=this.camera.projectionMatrix.elements;n.uProjectionScale.value.set(r[0]*.5,r[5]*.5);const o=e.autoClear;try{e.autoClear=!1,this.quad.material=this.material,e.setRenderTarget(this.target),this.quad.render(e),this.quad.material=this.multiply,e.setRenderTarget(i),this.quad.render(e)}finally{e.autoClear=o}}dispose(){this.target?.dispose(),this.target=null,this.material.dispose(),this.multiply.dispose(),this.quad.dispose()}}const Vl=1,Wm=typeof navigator<"u"&&/apple/i.test(navigator.vendor||"")&&!/chrome|chromium|edg\//i.test(navigator.userAgent||"");class Hm{constructor(e){this.settings=e,this.timer=new Tu,this.timer.connect(document),this.elapsed=0,this.updaters=[],this.drawHooks=new Set,this.running=!1,this.scene=new Pp,this.camera=new zp(e.get("fov"),1,.5,900),this.renderer=new Lp({antialias:!1,powerPreference:"high-performance",stencil:!1,depth:!0,preserveDrawingBuffer:Wm}),this.renderer.setPixelRatio(1),this.renderer.outputColorSpace=Bi,this.renderer.toneMapping=_u,this.renderer.toneMappingExposure=e.get("exposure"),this.renderer.shadowMap.type=Rp,this.renderer.info.autoReset=!1,this.canvas=this.renderer.domElement,this.canvas.classList.add("world-canvas"),this.composer=null,this.bloomPass=null,this.occlusionPass=null,this.smaaPass=null,this.tiltShift=null,this.gradePass=null,this._planetGrade={saturation:1,warmth:0},this._focusDistance=30,this.perf=new qm,this._boundLoop=this._loop.bind(this),this._onResize=()=>this.resize(),this.applySettings()}mount(e){return e.appendChild(this.canvas),window.addEventListener("resize",this._onResize),this._dprQuery=matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`),this._dprQuery.addEventListener?.("change",this._onResize),this._observer=new ResizeObserver(this._onResize),this._observer.observe(e),this._onWake=()=>{document.hidden||!this.running||(this.resize(),this.renderFrame())},document.addEventListener("visibilitychange",this._onWake),window.addEventListener("focus",this._onWake),window.addEventListener("pageshow",this._onWake),this.resize(),this}add(e){return this.updaters.push(e),e}applySettings(){const e=this.settings,t=this.renderer,i=Du[e.get("shadows")]||0;t.shadowMap.enabled=i>0,this._shadowSize!==i&&(this._shadowSize=i,this.scene.traverse(r=>{r.isLight&&r.shadow?.map&&(r.shadow.map.dispose(),r.shadow.map=null,i&&r.shadow.mapSize.setScalar(i))}),t.shadowMap.needsUpdate=!0),t.toneMappingExposure=e.get("exposure"),this.camera.fov=e.get("fov"),this.camera.updateProjectionMatrix(),this._wantsPost()?this._ensureComposer():this._disposeComposer(),this.composer&&(this.occlusionPass?.setStrength(e.get("ambientOcclusion")),this.bloomPass&&(this.bloomPass.enabled=e.get("bloom"),this.bloomPass.strength=e.get("bloomStrength")),this.smaaPass&&(this.smaaPass.enabled=e.get("antialias")),this.gradePass&&(this.gradePass.enabled=e.get("colorGrade"),this._syncGrade()),this.tiltShift&&(this.tiltShift.enabled=e.get("tiltShift"),this.tiltShift.setStrength(e.get("tiltShiftStrength")),this.tiltShift.setAngle(e.get("tiltShiftAngle")),this.tiltShift.setCamera(this.camera))),this.resize()}_ensureComposer(){if(this.composer)return;const e=new Bp(1,1);e.type=Fp;const t=new Fs(1,1,{type:Os,colorSpace:Op,samples:0,depthBuffer:!0,stencilBuffer:!1,depthTexture:e}),i=new Rm(this.renderer,t);i.addPass(new Bm(this.scene,this.camera)),this.occlusionPass=new Nm(this.camera),this.occlusionPass.setStrength(this.settings.get("ambientOcclusion")),i.addPass(this.occlusionPass),this.bloomPass=new Ii(new Se(1,1),this.settings.get("bloomStrength"),.55,.92),i.addPass(this.bloomPass),this.tiltShift=Vm();for(const n of this.tiltShift.passes)i.addPass(n);this.tiltShift.enabled=this.settings.get("tiltShift"),this.tiltShift.setStrength(this.settings.get("tiltShiftStrength")),this.tiltShift.setAngle(this.settings.get("tiltShiftAngle")),this.tiltShift.setCamera(this.camera),this.tiltShift.setFocusDistance(this._focusDistance),i.addPass(new Um(this.scene,this.camera)),i.addPass(new Om),this.gradePass=new jr(jm),this.gradePass.enabled=this.settings.get("colorGrade"),i.addPass(this.gradePass),this._syncGrade(),this.smaaPass=new Im(1,1),i.addPass(this.smaaPass),this.composer=i}_disposeComposer(){if(this.composer){for(const e of this.composer.passes)e.dispose?.();this.composer.dispose(),this.composer=null,this.bloomPass=null,this.occlusionPass=null,this.smaaPass=null,this.tiltShift=null,this.gradePass=null}}sceneTarget(){return this.composer?.readBuffer??null}_wantsPost(){const e=this.settings;return!!(e.get("bloom")||e.get("antialias")||e.get("tiltShift")||e.get("colorGrade")||e.get("ambientOcclusion")>0)}setPlanetGrade(e){this._planetGrade={saturation:e?.saturation??1,warmth:e?.warmth??0},this._syncGrade()}_syncGrade(){if(!this.gradePass)return;const e=this.gradePass.uniforms;e.uSaturation.value=this.settings.get("saturation")*this._planetGrade.saturation,e.uWarmth.value=this._planetGrade.warmth,e.uVignette.value=this.settings.get("vignette")}resize(){const e=this.canvas.parentElement;if(!e)return;const t=Math.max(1,e.clientWidth),i=Math.max(1,e.clientHeight);this.camera.aspect=t/i,this.camera.updateProjectionMatrix();const n=this._targetScale(),r=this.settings.get("autoQuality")&&this._scaleCeiling===n?Math.min(this.viewport?.scale??n,n):n;this._scaleCeiling=n;const o=Math.max(1,Math.round(t*r)),a=Math.max(1,Math.round(i*r));this.viewport={w:t,h:i,bw:o,bh:a,scale:r},this.autoScaled=r<n-.01,this._resizePending=!0}_resizeBuffers(){if(!this._resizePending||!this.viewport)return;this._resizePending=!1;const{bw:e,bh:t}=this.viewport;(this.canvas.width!==e||this.canvas.height!==t)&&this.renderer.setSize(e,t,!1),this.composer&&(this.composer.renderTarget1.width!==e||this.composer.renderTarget1.height!==t)&&this.composer.setSize(e,t),this.tiltShift?.setSize(e,t),this.tiltShift?.setCamera(this.camera)}_syncDepthTexture(){this.tiltShift&&this.composer&&this.tiltShift.setDepthTexture(this.composer.readBuffer.depthTexture)}setFocusDistance(e){this._focusDistance=e,this.tiltShift?.setFocusDistance(e)}_targetScale(){return this.settings.get("renderScale")*(window.devicePixelRatio||1)}start(){this.running||(this.running=!0,this.timer.reset(),this.renderer.setAnimationLoop(this._boundLoop))}stop(){this.running=!1,this.renderer.setAnimationLoop(null)}_loop(){this.timer.update();const e=Math.min(this.timer.getDelta(),.1);this.elapsed+=e;for(const t of this.updaters)t.update?.(e,this.elapsed);this.settings.get("autoQuality")&&this._governQuality(),this.renderer.info.reset(),this._draw(e);for(const t of this.drawHooks)t();this.perf.sample(e,this.renderer.info)}renderFrame(){this.renderer.info.reset(),this._draw(0)}_draw(e){this._resizeBuffers(),this.composer&&this._wantsPost()?(this.camera.layers.set(0),this._syncDepthTexture(),this.composer.render(e)):(this.camera.layers.enableAll(),this.renderer.render(this.scene,this.camera))}_governQuality(){const e=performance.now();if(e-(this._lastGovern||0)<1e3)return;this._lastGovern=e;const t=this.perf.fps;if(t<=0)return;const i=this._targetScale(),n=this.viewport?.scale??i,r=Math.min(i,.35*(window.devicePixelRatio||1));this._slow=t<45?(this._slow||0)+1:0,this._fast=t>58?(this._fast||0)+1:0;const o=window.devicePixelRatio||1;let a=n;if(this._slow>=3?(a=Math.max(r,n-.15*o),this._slow=0,this._climbAt=e+3e4):this._fast>=8&&n<i&&e>=(this._climbAt||0)&&(a=Math.min(i,n+.1*o),this._fast=0),Math.abs(a-n)>.01){const l=this.canvas.parentElement;if(!l)return;const c=Math.max(1,Math.round(l.clientWidth*a)),h=Math.max(1,Math.round(l.clientHeight*a));this.viewport={...this.viewport,bw:c,bh:h,scale:a},this._resizePending=!0,this.autoScaled=a<i-.01}}dispose(){this.stop(),this.timer.dispose(),window.removeEventListener("resize",this._onResize),this._dprQuery?.removeEventListener?.("change",this._onResize),this._observer?.disconnect(),document.removeEventListener("visibilitychange",this._onWake),window.removeEventListener("focus",this._onWake),window.removeEventListener("pageshow",this._onWake),this._disposeComposer(),this.renderer.dispose()}}class Um extends ys{constructor(e,t){super(),this.scene=e,this.camera=t,this.needsSwap=!1,this.clear=!1}render(e,t,i){const n=e.autoClear;e.autoClear=!1,this.camera.layers.set(Vl),e.setRenderTarget(this.renderToScreen?null:i),e.render(this.scene,this.camera),this.camera.layers.set(0),e.autoClear=n}}const jm={uniforms:{tDiffuse:{value:null},uSaturation:{value:1},uWarmth:{value:0},uVignette:{value:.3}},vertexShader:`
|
|
781
|
-
varying vec2 vUv;
|
|
782
|
-
void main() {
|
|
783
|
-
vUv = uv;
|
|
784
|
-
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
|
785
|
-
}
|
|
786
|
-
`,fragmentShader:`
|
|
787
|
-
uniform sampler2D tDiffuse;
|
|
788
|
-
uniform float uSaturation;
|
|
789
|
-
uniform float uWarmth;
|
|
790
|
-
uniform float uVignette;
|
|
791
|
-
varying vec2 vUv;
|
|
792
|
-
void main() {
|
|
793
|
-
vec4 c = texture2D( tDiffuse, vUv );
|
|
794
|
-
vec3 col = c.rgb;
|
|
795
|
-
// Lifted, tinted blacks.
|
|
796
|
-
col += ( 1.0 - col ) * vec3( 0.035, 0.045, 0.075 ) * ( 1.0 - smoothstep( 0.0, 0.5, dot( col, vec3( 0.333 ) ) ) );
|
|
797
|
-
float l = dot( col, vec3( 0.2126, 0.7152, 0.0722 ) );
|
|
798
|
-
col = mix( vec3( l ), col, uSaturation );
|
|
799
|
-
col *= vec3( 1.0 + uWarmth * 0.9, 1.0 + uWarmth * 0.25, 1.0 - uWarmth * 0.9 );
|
|
800
|
-
col = mix( col, col * col * ( 3.0 - 2.0 * col ), 0.16 );
|
|
801
|
-
vec2 d = vUv - 0.5;
|
|
802
|
-
col *= 1.0 - dot( d, d ) * uVignette * 1.15;
|
|
803
|
-
gl_FragColor = vec4( clamp( mix( c.rgb, col, clamp( c.a, 0.0, 1.0 ) ), 0.0, 1.0 ), 1.0 );
|
|
804
|
-
}
|
|
805
|
-
`};class qm{constructor(){this.fps=0,this.frameMs=0,this.drawCalls=0,this.triangles=0,this._frames=0}sample(e,t){const i=e*1e3,n=this._frames<10?.3:.06;this.frameMs+=(i-this.frameMs)*n,this.fps=this.frameMs>0?1e3/this.frameMs:0,this._frames++,this._frames%10===0&&(this.drawCalls=t.render.calls,this.triangles=t.render.triangles)}}const tr=N.degToRad(56),Gm=N.degToRad(6),Zm=N.degToRad(84),Xm=3,wn=4,Vu=.65,sr=150,Ro=62,Ym=.92,Bo=82,Qm=.055,Pc=2,Km=3.5,Jm=1.1,Fo=[0,1,2,3].map(s=>s*Math.PI/2+Math.PI/4),Rt=(s,e,t,i)=>N.damp(s,e,t,i),zc=(s,e)=>s.width===e.width&&s.height===e.height&&s.right===e.right&&s.bottom===e.bottom&&s.left===e.left&&s.top===e.top;class e1{constructor(e,t,i){this.camera=e,this.dom=t,this.settings=i,this.target=new F(0,0,0),this.desiredTarget=this.target.clone(),this.azimuth=Fo[0],this.desiredAzimuth=this.azimuth,this.polar=tr,this.desiredPolar=tr,this.distance=Ro,this.desiredDistance=Ro,this.idleFor=0,this.interacting=!1,this.enabled=!0,this.orbiting=!1,this.orbitBlend=0,this.suppressed=!1,this._pointers=new Map,this._mode=null,this._last=new Se,this._pinch=0,this._moved=0,this._panAnchor=new F,this._hasAnchor=!1,this._zoom=null,this._plane=new Ip(new F(0,1,0),0),this._ray=new $u,this._ndc=new Se,this._hit=new F,this._hit2=new F,this._shake=0,this._followAgent=null,this._followPosition=new F,this._followDelta=new F,this._offset=new Se,this._offsetGoal=new Se,this._bind(),this._sync()}_bind(){const e=this.dom;e.style.touchAction="none",this._onDown=t=>this._pointerDown(t),this._onMove=t=>this._pointerMove(t),this._onUp=t=>this._pointerUp(t),this._onWheel=t=>this._wheel(t),this._onMenu=t=>t.preventDefault(),e.addEventListener("pointerdown",this._onDown),window.addEventListener("pointermove",this._onMove,{passive:!1}),window.addEventListener("pointerup",this._onUp),window.addEventListener("pointercancel",this._onUp),e.addEventListener("wheel",this._onWheel,{passive:!1}),e.addEventListener("contextmenu",this._onMenu)}dispose(){const e=this.dom;e.removeEventListener("pointerdown",this._onDown),window.removeEventListener("pointermove",this._onMove),window.removeEventListener("pointerup",this._onUp),window.removeEventListener("pointercancel",this._onUp),e.removeEventListener("wheel",this._onWheel),e.removeEventListener("contextmenu",this._onMenu)}_pointerDown(e){if(!this.enabled)return;if(this._pointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this._moved=0,this._zoom=null,this._pointers.size===2){this._mode="pinch",this._moved=6,this._pinch=this._pinchDistance(),this._grab(...this._pinchCentre());return}const t=this._dragsToOrbit(e);this._mode=t?"orbit":"pan",this._last.set(e.clientX,e.clientY),this.interacting=!0,this.idleFor=0,t||this._grab(e.clientX,e.clientY)}_dragsToOrbit(e){if(e.pointerType==="touch")return!1;const t=e.button===2||e.button===1||e.ctrlKey||e.shiftKey||e.altKey,i=this.settings.get("leftDrag")!=="pan";return t?!i:i}_grab(e,t){this._hasAnchor=!!this.groundPoint(e,t,this._panAnchor)}_pointerMove(e){if(!this._mode)return;const t=this._pointers.get(e.pointerId);if(t&&(t.x=e.clientX,t.y=e.clientY),this.idleFor=0,this._mode==="pinch"){e.preventDefault();const r=this._pinchDistance(),[o,a]=this._pinchCentre();this._pinch>0&&r>0&&(this.desiredDistance=N.clamp(this.desiredDistance*(this._pinch/r),wn,sr),this.distance=this.desiredDistance,this._sync()),this._pinch=r,this._dragGround(o,a);return}const i=e.clientX-this._last.x,n=e.clientY-this._last.y;if(this._last.set(e.clientX,e.clientY),this._moved+=Math.abs(i)+Math.abs(n),!this.suppressed){if(this._mode==="orbit"){e.preventDefault(),this.desiredAzimuth-=i*.006,this.desiredPolar=N.clamp(this.desiredPolar-n*.005,Gm,Zm);return}e.preventDefault(),this._dragGround(e.clientX,e.clientY)}}_dragGround(e,t){if(!this._hasAnchor||!this.groundPoint(e,t,this._hit))return;const i=this._panAnchor.x-this._hit.x,n=this._panAnchor.z-this._hit.z;!Number.isFinite(i)||!Number.isFinite(n)||Math.hypot(i,n)>this.distance*2||(this.desiredTarget.x+=i,this.desiredTarget.z+=n,this._clampTarget(),this.target.copy(this.desiredTarget),this._sync())}_pointerUp(e){if(this._pointers.delete(e.pointerId),this._pointers.size===0)this._mode=null,this.interacting=!1,this.suppressed=!1,this._hasAnchor=!1;else if(this._pointers.size===1){this._mode="pan";const[t]=this._pointers.values();this._last.set(t.x,t.y),this._grab(t.x,t.y)}}_wheel(e){if(!this.enabled)return;e.preventDefault();const t=e.deltaMode===1?16:e.deltaMode===2?100:1,i=e.deltaY*t/100,n=Math.sign(i)*Math.min(Math.abs(i),2.5)*(e.ctrlKey?1.6:1);this.desiredDistance=N.clamp(this.desiredDistance*(1+n*.16),wn,sr),this.groundPoint(e.clientX,e.clientY,this._hit2)&&(this._zoom={world:this._hit2.clone(),sx:e.clientX,sy:e.clientY}),this.idleFor=0}_pinchDistance(){const[e,t]=[...this._pointers.values()];return Math.hypot(e.x-t.x,e.y-t.y)}_pinchCentre(){const[e,t]=[...this._pointers.values()];return[(e.x+t.x)/2,(e.y+t.y)/2]}_clampTarget(){const e=this.desiredTarget,t=Math.hypot(e.x,e.z);t>Bo&&(e.x=e.x/t*Bo,e.z=e.z/t*Bo)}get wasClick(){return this._moved<6}focus(e,{distance:t,keepHeight:i=!1}={}){this.desiredTarget.copy(e),i||(this.desiredTarget.y=0),this._clampTarget(),t&&(this.desiredDistance=N.clamp(t,wn,sr)),this._zoom=null,this.idleFor=99}setFollow(e){e=e||null,e!==this._followAgent&&(this._followAgent=e,this._zoom=null,e?(this._followPosition.copy(e.pos),this.desiredTarget.copy(e.pos),this.desiredTarget.y+=Vu,this._clampTarget()):this.desiredTarget.copy(this.target))}get following(){return!!this._followAgent}setViewportInsets(e,t,{right:i=0,bottom:n=0,left:r=0,top:o=0}={},{visible:a=!0}={}){e=Math.max(1,e),t=Math.max(1,t),i=N.clamp(i,0,e*.9),n=N.clamp(n,0,t*.9),r=N.clamp(r,0,(e-i)*.4),o=N.clamp(o,0,(t-n)*.4);const l={width:e,height:t,right:i,bottom:n,left:r,top:o},c=!!this._panels&&this._panelsShown!==a&&zc(this._panels,l);this._panels=l,this._panelsShown=a,this._resetFrame=a?l:{width:e,height:t,right:0,bottom:0,left:0,top:0},c||this._frame(this._resetFrame)}_frame(e,t=!1){this._framing&&zc(this._framing,e)||(this._framing={...e},this.camera.aspect=e.width/e.height,this._offsetGoal.set((e.right-e.left)/2,(e.bottom-e.top)/2),t||this._offset.copy(this._offsetGoal),this._applyOffset())}_applyOffset(){const{width:e,height:t}=this._framing;this._offset.x||this._offset.y?this.camera.setViewOffset(e,t,this._offset.x,this._offset.y,e,t):this.camera.clearViewOffset(),this._refreshInputAnchors()}_trackFollow(){if(!this._followAgent)return;const e=this._followDelta.subVectors(this._followAgent.pos,this._followPosition);this._followPosition.copy(this._followAgent.pos),e.lengthSq()!==0&&(this.target.add(e),this.desiredTarget.add(e),this._sync(),this._refreshInputAnchors())}_refreshInputAnchors(){if(this._hasAnchor){const[e,t]=this._mode==="pinch"?this._pinchCentre():[this._last.x,this._last.y];this._hasAnchor=!!this.groundPoint(e,t,this._panAnchor)}this._zoom&&!this.groundPoint(this._zoom.sx,this._zoom.sy,this._zoom.world)&&(this._zoom=null)}resetView(e,t=[]){this._resetFrame&&this._frame(this._resetFrame,!0),this.orbiting=!1,this.desiredTarget.set(e?.x??0,0,e?.z??0),this._clampTarget(),this.desiredPolar=tr,this.desiredAzimuth=this._nearestIso(),this.desiredDistance=N.clamp(this._fitDistance(t)||Ro,wn,sr),this._zoom=null,this.idleFor=99}_fitDistance(e){const t=this._framing||{width:1,height:1,right:0,bottom:0,left:0,top:0},i=Math.tan(N.degToRad(this.camera.fov)/2)*Ym,n=i*(1-(t.bottom+t.top)/t.height),r=i*this.camera.aspect*(1-(t.right+t.left)/t.width),o=Math.sin(this.desiredPolar),a=new F(o*Math.sin(this.desiredAzimuth),Math.cos(this.desiredPolar),o*Math.cos(this.desiredAzimuth)),l=new F(0,1,0).cross(a).normalize(),c=a.clone().cross(l),h=new F;let d=0;for(const u of e){h.subVectors(u,this.desiredTarget);const f=h.dot(a);d=Math.max(d,Math.abs(h.dot(l))/r+f,Math.abs(h.dot(c))/n+f)}return d}inView(e){this.camera.updateMatrixWorld();const t=new F;for(const i of e)if(t.copy(i).applyMatrix4(this.camera.matrixWorldInverse),t.z>-this.camera.near||(t.applyMatrix4(this.camera.projectionMatrix),Math.abs(t.x)>1||Math.abs(t.y)>1))return!1;return!0}settle(){this.target.copy(this.desiredTarget),this.distance=this.desiredDistance,this.polar=this.desiredPolar,this.azimuth=this.desiredAzimuth,this._sync()}setOrbit(e){return this.orbiting=e,e&&(this.idleFor=Pc),this.orbiting}toggleOrbit(){return this.setOrbit(!this.orbiting)}shake(e=.5){this.settings.get("reducedMotion")||(this._shake=Math.min(1.4,this._shake+e))}_nearestIso(){let e=Fo[0],t=1/0;for(const i of Fo){const n=i+Math.round((this.desiredAzimuth-i)/(Math.PI*2))*Math.PI*2,r=Math.abs(n-this.desiredAzimuth);r<t&&(t=r,e=n)}return e}update(e){if(this._trackFollow(),this.interacting||(this.idleFor+=e),this.orbiting){const i=!this.interacting&&this.idleFor>=Pc?1:0;this.orbitBlend=Rt(this.orbitBlend,i,i?Jm:Km,e);const n=Qm*this.orbitBlend;this.desiredAzimuth+=n*e,this.azimuth+=n*e}else this.orbitBlend=0;if(!this.following&&!this.orbiting&&this.settings.get("autoFrame")&&this.idleFor>2.2&&!this.interacting){const i=Math.min(1.4,(this.idleFor-2.2)*.7);this.desiredAzimuth=Rt(this.desiredAzimuth,this._nearestIso(),i,e),this.desiredPolar=Rt(this.desiredPolar,tr,i,e)}const t=this.settings.get("reducedMotion")?40:9;if(this.azimuth=Rt(this.azimuth,this.desiredAzimuth,t,e),this.polar=Rt(this.polar,this.desiredPolar,t,e),this.distance=Rt(this.distance,this.desiredDistance,12,e),this.interacting||(this.target.x=Rt(this.target.x,this.desiredTarget.x,t,e),this.target.y=Rt(this.target.y,this.desiredTarget.y,t,e),this.target.z=Rt(this.target.z,this.desiredTarget.z,t,e)),this._framing&&!this._offset.equals(this._offsetGoal)&&(this._offset.x=Rt(this._offset.x,this._offsetGoal.x,t,e),this._offset.y=Rt(this._offset.y,this._offsetGoal.y,t,e),this._offset.distanceTo(this._offsetGoal)<.5&&this._offset.copy(this._offsetGoal),this._applyOffset()),this._sync(),this._holdZoomAnchor(),this._shake>.001){this._shake=Rt(this._shake,0,3.2,e);const i=performance.now()*.001,n=this._shake*.35;this.camera.position.x+=Math.sin(i*41)*n,this.camera.position.y+=Math.sin(i*57)*n,this.camera.position.z+=Math.cos(i*47)*n,this.camera.lookAt(this.target),this.camera.updateMatrixWorld()}}_holdZoomAnchor(){if(!this._zoom)return;if(Math.abs(this.distance-this.desiredDistance)<.02){this._zoom=null;return}if(!this.groundPoint(this._zoom.sx,this._zoom.sy,this._hit)){this._zoom=null;return}const e=this._zoom.world.x-this._hit.x,t=this._zoom.world.z-this._hit.z;if(Math.hypot(e,t)>this.distance*2){this._zoom=null;return}this.desiredTarget.x+=e,this.desiredTarget.z+=t,this._clampTarget(),this.target.x=this.desiredTarget.x,this.target.z=this.desiredTarget.z,this._sync()}_sync(){const e=Math.sin(this.polar);this.camera.position.set(this.target.x+this.distance*e*Math.sin(this.azimuth),this.target.y+this.distance*Math.cos(this.polar),this.target.z+this.distance*e*Math.cos(this.azimuth));const t=this.groundAt?.(this.camera.position.x,this.camera.position.z);t!==void 0&&(this.camera.position.y=Math.max(this.camera.position.y,t+Xm)),this.camera.lookAt(this.target),this.camera.updateMatrixWorld()}pointerRay(e,t){const i=this.dom.getBoundingClientRect();return!i.width||!i.height?null:(this._ndc.set((e-i.left)/i.width*2-1,-((t-i.top)/i.height)*2+1),this._ray.setFromCamera(this._ndc,this.camera),this._ray.ray)}groundPoint(e,t,i=new F){const n=this.pointerRay(e,t);return n&&n.intersectPlane(this._plane,i)?i:null}}function t1(){return{uReflectionA:{value:null},uReflectionB:{value:null},uReflectionPosA:{value:new F},uReflectionPosB:{value:new F},uReflectionMix:{value:1},uReflectionReady:{value:0}}}function s1(s,e){Object.assign(s.uniforms,e),s.vertexShader=`varying vec3 vReflectionPosition;
|
|
806
|
-
${s.vertexShader}`.replace("#include <project_vertex>",`#include <project_vertex>
|
|
807
|
-
vec4 reflectionPosition = vec4( transformed, 1.0 );
|
|
808
|
-
#ifdef USE_INSTANCING
|
|
809
|
-
reflectionPosition = instanceMatrix * reflectionPosition;
|
|
810
|
-
#endif
|
|
811
|
-
vReflectionPosition = ( modelMatrix * reflectionPosition ).xyz;`),s.fragmentShader=`
|
|
812
|
-
uniform samplerCube uReflectionA;
|
|
813
|
-
uniform samplerCube uReflectionB;
|
|
814
|
-
uniform vec3 uReflectionPosA;
|
|
815
|
-
uniform vec3 uReflectionPosB;
|
|
816
|
-
uniform float uReflectionMix;
|
|
817
|
-
uniform float uReflectionReady;
|
|
818
|
-
varying vec3 vReflectionPosition;
|
|
819
|
-
vec3 localGlassReflection( vec3 sky, vec3 direction, float roughness ) {
|
|
820
|
-
if ( uReflectionReady <= 0.0 ) return sky;
|
|
821
|
-
float reachA = 1.0 - smoothstep( 3.0, 10.0, distance( vReflectionPosition, uReflectionPosA ) );
|
|
822
|
-
float reachB = 1.0 - smoothstep( 3.0, 10.0, distance( vReflectionPosition, uReflectionPosB ) );
|
|
823
|
-
// A 128px cube has seven mip levels; soften subpixel edges as the visor shrinks.
|
|
824
|
-
float footprint = max( length( dFdx( direction ) ), length( dFdy( direction ) ) );
|
|
825
|
-
float lod = clamp( max( roughness * 7.0, log2( max( 1.0, footprint * 128.0 ) ) ), 0.0, 7.0 );
|
|
826
|
-
vec3 a = textureLod( uReflectionA, direction, lod ).rgb;
|
|
827
|
-
vec3 b = textureLod( uReflectionB, direction, lod ).rgb;
|
|
828
|
-
return mix( sky, mix( mix( sky, a, reachA ), mix( sky, b, reachB ), uReflectionMix ), uReflectionReady );
|
|
829
|
-
}
|
|
830
|
-
|
|
831
|
-
${s.fragmentShader}`.replace("#include <envmap_physical_pars_fragment>",Au.envmap_physical_pars_fragment.replace("return envMapColor.rgb * envMapIntensity;","return localGlassReflection( envMapColor.rgb, reflectVec, roughness ) * envMapIntensity;"))}class i1{constructor({scene:e,renderer:t,settings:i,sky:n,astronauts:r,excluded:o=()=>[]}){Object.assign(this,{scene:e,renderer:t,settings:i,sky:n,astronauts:r,excluded:o}),this.uniforms=r.reflectionUniforms,this.targets=null,this.face=-1,this.published=-1,this.lastCapture=-1/0,this.clock=0,this.blend=1,this.anchor=new F,this.position=new F,this._point=new F,this._projected=new F,this._matrix=new xt,this.stats={captures:0,faces:0,lastFaceCalls:0}}invalidate(){this.face=-1,this.published=-1,this.lastCapture=-1/0,this.uniforms.uReflectionReady.value=0,this.uniforms.uReflectionMix.value=1,this.blend=1}_allocate(){this.targets=[0,1].map(()=>new Dp(128,{type:Os,generateMipmaps:!1,minFilter:On,magFilter:qi})),this.cube=new Vp(.06,500,this.targets[0]),this.cube.coordinateSystem=this.renderer.coordinateSystem,this.cube.updateCoordinateSystem()}_chooseAnchor(e,t){let i=1/0,n=null;t.updateMatrixWorld();for(const r of this.astronauts._drawnAgents){if(r.scale<.8)continue;this.astronauts.parts.visor.getMatrixAt(r.index,this._matrix),this._point.setFromMatrixPosition(this._matrix);const o=ai(this._projected.copy(this._point));if(o.distanceToSquared(t.position)>1225||(o.project(t),Math.abs(o.x)>1.15||Math.abs(o.y)>1.15||o.z>1||o.z<-1))continue;const a=this._point.distanceToSquared(e),l=r===this.astronauts.selected?-1:a;l<i&&(i=l,n=r,this.anchor.copy(this._point))}return n}update(e,t,i){if(!this.renderer)return;if(this.clock+=Math.min(Math.max(e,0),.1),!this.settings.get("ibl")){this.targets&&this._release();return}if(this.renderer.shadowMap.enabled&&this.sky.sun?.castShadow&&!this.sky.sun.shadow.map)return;const n=this.uniforms;if(this.blend=Math.min(1,this.blend+Math.max(e,0)/.4),n.uReflectionMix.value=N.smoothstep(this.blend,0,1),n.uReflectionReady.value=this.published<0?0:Math.min(1,n.uReflectionReady.value+Math.max(e,0)/.4),this.face<0){if(this.blend<1||!this.scene.environment||!this._chooseAnchor(t,i))return;const r=this.clock-this.lastCapture;if(r<.7||r<2.5&&this.anchor.distanceToSquared(this.position)<.75**2)return;this.targets||this._allocate(),this.writing=this.published===0?1:0,this.published>=0&&(n.uReflectionA.value=n.uReflectionB.value,n.uReflectionPosA.value.copy(n.uReflectionPosB.value)),this.position.copy(this.anchor),this.cube.position.copy(ai(this.anchor.clone())),this.cube.updateMatrixWorld(!0),this.captureCurve={amount:et.uCurveAmount.value,focus:et.uCurveFocus.value.clone(),forward:et.uCurveForward.value.clone()},this.face=0}if(this._captureFace(),++this.face===6){const r=this.targets[this.writing].texture;this.published<0&&(n.uReflectionA.value=r,n.uReflectionPosA.value.copy(this.position)),n.uReflectionB.value=r,n.uReflectionPosB.value.copy(this.position),this.published=this.writing,this.face=-1,this.blend=0,n.uReflectionMix.value=0,this.lastCapture=this.clock,this.stats.captures++}}_captureFace(){const e=this.renderer,t=this.targets[this.writing],i={target:e.getRenderTarget(),face:e.getActiveCubeFace(),mip:e.getActiveMipmapLevel(),autoClear:e.autoClear,shadowAuto:e.shadowMap.autoUpdate,shadowNeeds:e.shadowMap.needsUpdate,xr:e.xr.enabled,dome:this.sky.dome.position.clone(),curve:et.uCurveAmount.value,focus:et.uCurveFocus.value.clone(),forward:et.uCurveForward.value.clone()},n=[this.astronauts.group,this.sky.stars,this.sky.companion,...this.excluded()].filter(Boolean).map(r=>[r,r.visible]);try{for(const[o]of n)o.visible=!1;this.sky.dome.position.copy(this.cube.position),et.uCurveAmount.value=this.captureCurve.amount,et.uCurveFocus.value.copy(this.captureCurve.focus),et.uCurveForward.value.copy(this.captureCurve.forward),e.xr.enabled=!1,e.autoClear=!0,e.shadowMap.autoUpdate=!1,e.shadowMap.needsUpdate=!1,t.texture.generateMipmaps=this.face===5,e.setRenderTarget(t,this.face);const r=e.info.render.calls;e.render(this.scene,this.cube.children[this.face]),this.stats.lastFaceCalls=e.info.autoReset?e.info.render.calls:e.info.render.calls-r,this.stats.faces++}finally{for(const[r,o]of n)r.visible=o;this.sky.dome.position.copy(i.dome),et.uCurveAmount.value=i.curve,et.uCurveFocus.value.copy(i.focus),et.uCurveForward.value.copy(i.forward),e.xr.enabled=i.xr,e.autoClear=i.autoClear,e.shadowMap.autoUpdate=i.shadowAuto,e.shadowMap.needsUpdate=i.shadowNeeds,e.setRenderTarget(i.target,i.face,i.mip)}}_release(){this.invalidate(),this.uniforms.uReflectionA.value=null,this.uniforms.uReflectionB.value=null;for(const e of this.targets||[])e.dispose();this.targets=null,this.cube=null}dispose(){this._release()}}const Lc=[{dir:[.82,.57],amp:.42,len:11,speed:1.35},{dir:[-.44,.9],amp:.28,len:6.4,speed:1.05},{dir:[.97,-.24],amp:.18,len:3.7,speed:.85},{dir:[-.62,-.78],amp:.12,len:2.1,speed:.65}],n1=.4,r1=.12,Qa=16,Nu=2.5,o1=2.2,ir={low:96,medium:160,high:220},a1={level:-1.2,shallow:6283480,deep:1728424,foam:16055295,opacity:.92,waveHeight:.12,waveScale:1,speed:1,sparkle:1,ripples:1,glow:0},l1=Math.PI*2,Wu=Lc.map(s=>{const e=i=>Number(i.toFixed(6)),t=e(l1/s.len);return{dx:e(s.dir[0]),dz:e(s.dir[1]),amp:e(s.amp),k:t,omega:e(t*s.speed),lean:e(n1/(t*Lc.length))}});function c1(){const s=t=>t.toFixed(6);return`
|
|
832
|
-
uniform float uWaveHeight;
|
|
833
|
-
uniform float uWaveScale;
|
|
834
|
-
void bcWaves( vec2 p, float t, out float h, out vec2 off, out vec3 n ) {
|
|
835
|
-
h = 0.0;
|
|
836
|
-
off = vec2( 0.0 );
|
|
837
|
-
vec2 slope = vec2( 0.0 );
|
|
838
|
-
float k, ph, s, c;${Wu.map((t,i)=>`
|
|
839
|
-
// wave ${i}
|
|
840
|
-
k = ${s(t.k)} / uWaveScale;
|
|
841
|
-
ph = k * dot( vec2( ${s(t.dx)}, ${s(t.dz)} ), p ) - ${s(t.omega)} * t;
|
|
842
|
-
s = sin( ph );
|
|
843
|
-
c = cos( ph );
|
|
844
|
-
h += ${s(t.amp)} * s;
|
|
845
|
-
off += vec2( ${s(t.dx)}, ${s(t.dz)} ) * ( ${s(t.lean)} * c );
|
|
846
|
-
slope += vec2( ${s(t.dx)}, ${s(t.dz)} ) * ( ${s(t.amp)} * k * c );`).join("")}
|
|
847
|
-
h *= uWaveHeight;
|
|
848
|
-
slope *= uWaveHeight;
|
|
849
|
-
// The lean scales with the height around its tuning point, so a flat calm has no lean
|
|
850
|
-
// and a heavier swell leans harder, and stays proportionate at any wave scale.
|
|
851
|
-
off *= uWaveScale * ( uWaveHeight / ${s(r1)} );
|
|
852
|
-
n = normalize( vec3( -slope.x, 1.0, -slope.y ) );
|
|
853
|
-
}
|
|
854
|
-
`}function h1(s,e,t,i,n){let r=0;for(const o of Wu){const a=o.k/n;r+=o.amp*Math.sin(a*(o.dx*s+o.dz*e)-o.omega*t)}return r*i}const d1=`
|
|
855
|
-
float bcHash( vec2 p ) {
|
|
856
|
-
vec3 p3 = fract( vec3( p.xyx ) * 0.1031 );
|
|
857
|
-
p3 += dot( p3, p3.yzx + 33.33 );
|
|
858
|
-
return fract( ( p3.x + p3.y ) * p3.z );
|
|
859
|
-
}
|
|
860
|
-
float bcNoise( vec2 p ) {
|
|
861
|
-
vec2 i = floor( p );
|
|
862
|
-
vec2 f = fract( p );
|
|
863
|
-
vec2 u = f * f * ( 3.0 - 2.0 * f );
|
|
864
|
-
return mix(
|
|
865
|
-
mix( bcHash( i ), bcHash( i + vec2( 1.0, 0.0 ) ), u.x ),
|
|
866
|
-
mix( bcHash( i + vec2( 0.0, 1.0 ) ), bcHash( i + vec2( 1.0, 1.0 ) ), u.x ),
|
|
867
|
-
u.y );
|
|
868
|
-
}
|
|
869
|
-
float bcFbm( vec2 p ) {
|
|
870
|
-
float sum = 0.0;
|
|
871
|
-
float amp = 0.5;
|
|
872
|
-
for ( int i = 0; i < 3; i++ ) {
|
|
873
|
-
sum += bcNoise( p ) * amp;
|
|
874
|
-
p = p * 2.07 + vec2( 17.3, 9.1 );
|
|
875
|
-
amp *= 0.5;
|
|
876
|
-
}
|
|
877
|
-
return sum;
|
|
878
|
-
}
|
|
879
|
-
`,u1=`
|
|
880
|
-
attribute float aDepth;
|
|
881
|
-
uniform float uTime;
|
|
882
|
-
varying vec2 vWaterXZ;
|
|
883
|
-
varying float vWaterDepth;
|
|
884
|
-
${c1()}
|
|
885
|
-
`,f1=`
|
|
886
|
-
#define BC_MAX_RIPPLES ${Qa}
|
|
887
|
-
#define BC_RIPPLE_LIFE ${Nu.toFixed(3)}
|
|
888
|
-
#define BC_RIPPLE_SPEED ${o1.toFixed(3)}
|
|
889
|
-
varying vec2 vWaterXZ;
|
|
890
|
-
varying float vWaterDepth;
|
|
891
|
-
uniform float uTime;
|
|
892
|
-
uniform float uElapsed;
|
|
893
|
-
uniform float uNight;
|
|
894
|
-
uniform vec3 uSunDir;
|
|
895
|
-
uniform vec3 uShallow;
|
|
896
|
-
uniform vec3 uDeep;
|
|
897
|
-
uniform vec3 uFoam;
|
|
898
|
-
uniform vec2 uOpacity;
|
|
899
|
-
uniform float uSparkle;
|
|
900
|
-
uniform float uGlow;
|
|
901
|
-
uniform float uRippleStrength;
|
|
902
|
-
uniform vec4 uRipples[ BC_MAX_RIPPLES ];
|
|
903
|
-
uniform vec3 uIce;
|
|
904
|
-
${d1}
|
|
905
|
-
float bcCellEdge( vec2 p ) {
|
|
906
|
-
vec2 i = floor( p );
|
|
907
|
-
vec2 f = fract( p );
|
|
908
|
-
float d1 = 8.0;
|
|
909
|
-
float d2 = 8.0;
|
|
910
|
-
for ( int y = -1; y <= 1; y++ ) {
|
|
911
|
-
for ( int x = -1; x <= 1; x++ ) {
|
|
912
|
-
vec2 g = vec2( float( x ), float( y ) );
|
|
913
|
-
vec2 o = vec2( bcHash( i + g ), bcHash( i + g + 17.17 ) );
|
|
914
|
-
float d = length( g + o - f );
|
|
915
|
-
if ( d < d1 ) {
|
|
916
|
-
d2 = d1;
|
|
917
|
-
d1 = d;
|
|
918
|
-
} else if ( d < d2 ) {
|
|
919
|
-
d2 = d;
|
|
920
|
-
}
|
|
921
|
-
}
|
|
922
|
-
}
|
|
923
|
-
return d2 - d1;
|
|
924
|
-
}
|
|
925
|
-
`,p1=`
|
|
926
|
-
#include <color_fragment>
|
|
927
|
-
float bcFoam = 0.0;
|
|
928
|
-
float bcIceMatte = 0.0;
|
|
929
|
-
vec2 bcRippleTilt = vec2( 0.0 );
|
|
930
|
-
{
|
|
931
|
-
float depth = vWaterDepth;
|
|
932
|
-
// Depth-driven ramp. The pow keeps the turquoise wide: with a plain smoothstep the
|
|
933
|
-
// shallows are a thin fringe and the water reads as blue, which is not the look.
|
|
934
|
-
float deepT = pow( smoothstep( 0.0, 3.2, depth ), 0.7 );
|
|
935
|
-
vec3 water = mix( uShallow, uDeep, deepT );
|
|
936
|
-
float alpha = mix( uOpacity.x, uOpacity.y, smoothstep( 0.0, 2.4, depth ) );
|
|
937
|
-
|
|
938
|
-
// Foam cannot reach depth 1 even at maximum wobble/breathing. Most of an ocean is
|
|
939
|
-
// deeper, so skip the six shoreline noise octaves there. Gameplay ripples still run.
|
|
940
|
-
if ( depth < 1.0 ) {
|
|
941
|
-
// Shoreline foam. The wobble is on the depth, not the band edges, so all three bands
|
|
942
|
-
// wander together and keep their spacing.
|
|
943
|
-
float wobble = ( bcFbm( vWaterXZ * 0.55 + vec2( uTime * 0.11, -uTime * 0.07 ) ) - 0.5 ) * 0.34;
|
|
944
|
-
float breathe = sin( uTime * 0.55 + vWaterXZ.x * 0.05 + vWaterXZ.y * 0.04 ) * 0.045;
|
|
945
|
-
float d = depth + wobble + breathe;
|
|
946
|
-
// Lace along the very edge, a wide band just off it, and a thinner one further out.
|
|
947
|
-
float line = 1.0 - smoothstep( 0.0, 0.05, d );
|
|
948
|
-
float band1 = smoothstep( 0.11, 0.16, d ) * ( 1.0 - smoothstep( 0.27, 0.34, d ) );
|
|
949
|
-
float band2 = smoothstep( 0.46, 0.51, d ) * ( 1.0 - smoothstep( 0.58, 0.66, d ) );
|
|
950
|
-
// A second, finer noise eats holes in the bands so they are lace rather than stripes.
|
|
951
|
-
float holes = smoothstep( 0.32, 0.6, bcFbm( vWaterXZ * 1.9 + vec2( -uTime * 0.2, uTime * 0.13 ) ) );
|
|
952
|
-
bcFoam = clamp( line + band1 * holes + band2 * holes * 0.8, 0.0, 1.0 );
|
|
953
|
-
// Nothing above the waterline: negative depth is under the terrain and is only ever seen
|
|
954
|
-
// for a frame where a crest lifts the surface through a sliver of beach.
|
|
955
|
-
bcFoam *= step( -0.02, depth );
|
|
956
|
-
}
|
|
957
|
-
|
|
958
|
-
// Ripple rings, from whatever gameplay has dropped on the surface lately.
|
|
959
|
-
float rippleFoam = 0.0;
|
|
960
|
-
for ( int i = 0; i < BC_MAX_RIPPLES; i++ ) {
|
|
961
|
-
vec4 rp = uRipples[ i ];
|
|
962
|
-
if ( rp.w <= 0.0 ) continue;
|
|
963
|
-
float age = uElapsed - rp.z;
|
|
964
|
-
if ( age < 0.0 || age > BC_RIPPLE_LIFE ) continue;
|
|
965
|
-
vec2 toP = vWaterXZ - rp.xy;
|
|
966
|
-
float r = length( toP );
|
|
967
|
-
float ringR = age * BC_RIPPLE_SPEED;
|
|
968
|
-
float dr = r - ringR;
|
|
969
|
-
float band = exp( -( dr * dr ) / 0.06 ) * rp.w * ( 1.0 - age / BC_RIPPLE_LIFE );
|
|
970
|
-
rippleFoam += band;
|
|
971
|
-
// The ring is a small hump: its slope leans the normal outward on the leading edge and
|
|
972
|
-
// inward on the trailing one, which is what lets the light pick the ring out.
|
|
973
|
-
bcRippleTilt += ( toP / max( r, 0.001 ) ) * ( dr * band );
|
|
974
|
-
}
|
|
975
|
-
rippleFoam *= uRippleStrength;
|
|
976
|
-
bcRippleTilt *= uRippleStrength * 2.4;
|
|
977
|
-
bcFoam = clamp( bcFoam + rippleFoam * 0.8, 0.0, 1.0 );
|
|
978
|
-
|
|
979
|
-
// Night takes the saturation out rather than only the brightness: the lights are already
|
|
980
|
-
// low after dark, and a fully saturated turquoise under a dim sun looks lit from within.
|
|
981
|
-
water = mix( water, water * vec3( 0.55, 0.62, 0.78 ), uNight );
|
|
982
|
-
|
|
983
|
-
diffuseColor.rgb = mix( water, uFoam, bcFoam );
|
|
984
|
-
diffuseColor.a = mix( alpha, 1.0, bcFoam );
|
|
985
|
-
#ifdef BC_ICE
|
|
986
|
-
vec2 warped = vWaterXZ + vec2( bcFbm( vWaterXZ * 0.04 ), bcFbm( vWaterXZ * 0.04 + 7.3 ) ) * 18.0;
|
|
987
|
-
float cracks = ( 1.0 - smoothstep( 0.0, 0.035, bcCellEdge( warped * uIce.x ) ) ) * smoothstep( 0.38, 0.55, bcFbm( vWaterXZ * 0.025 + 21.0 ) );
|
|
988
|
-
float hairline = ( 1.0 - smoothstep( 0.0, 0.03, bcCellEdge( warped * uIce.x * 2.7 + 11.0 ) ) ) * smoothstep( 0.5, 0.66, bcFbm( vWaterXZ * 0.05 - 4.0 ) );
|
|
989
|
-
float frost = smoothstep( 0.5, 0.8, bcFbm( vWaterXZ * 0.08 + 5.0 ) ) * uIce.y;
|
|
990
|
-
float drift = smoothstep( 0.6, 0.76, bcFbm( vWaterXZ * 0.035 - 9.0 ) ) * uIce.z;
|
|
991
|
-
vec3 ice = diffuseColor.rgb;
|
|
992
|
-
ice = mix( ice, uFoam, frost * 0.55 );
|
|
993
|
-
ice = mix( ice, uFoam, cracks * 0.75 + hairline * 0.3 );
|
|
994
|
-
ice = mix( ice, uFoam, drift );
|
|
995
|
-
diffuseColor.rgb = ice;
|
|
996
|
-
diffuseColor.a = clamp( diffuseColor.a + frost * 0.3 + cracks * 0.35 + hairline * 0.12 + drift, 0.0, 1.0 );
|
|
997
|
-
bcIceMatte = clamp( frost + drift + cracks * 0.5, 0.0, 1.0 );
|
|
998
|
-
#endif
|
|
999
|
-
}
|
|
1000
|
-
`,m1=`
|
|
1001
|
-
#include <roughnessmap_fragment>
|
|
1002
|
-
roughnessFactor = mix( roughnessFactor, 0.75, max( bcFoam, bcIceMatte ) );
|
|
1003
|
-
`,g1=`
|
|
1004
|
-
#include <normal_fragment_begin>
|
|
1005
|
-
{
|
|
1006
|
-
vec3 tilt = ( viewMatrix * vec4( bcRippleTilt.x, 0.0, bcRippleTilt.y, 0.0 ) ).xyz;
|
|
1007
|
-
normal = normalize( normal + tilt );
|
|
1008
|
-
nonPerturbedNormal = normal;
|
|
1009
|
-
// Roundoff can put a dot of unit vectors just above 1. Keep pow's base nonnegative.
|
|
1010
|
-
float facing = clamp( dot( normal, normalize( vViewPosition ) ), 0.0, 1.0 );
|
|
1011
|
-
float fresnel = pow( 1.0 - facing, 3.0 );
|
|
1012
|
-
diffuseColor.a = mix( diffuseColor.a, 0.98, fresnel * 0.7 );
|
|
1013
|
-
}
|
|
1014
|
-
`,w1=`
|
|
1015
|
-
#include <emissivemap_fragment>
|
|
1016
|
-
{
|
|
1017
|
-
vec3 V = normalize( vViewPosition );
|
|
1018
|
-
vec3 L = normalize( ( viewMatrix * vec4( uSunDir, 0.0 ) ).xyz );
|
|
1019
|
-
vec3 H = normalize( L + V );
|
|
1020
|
-
float glint = pow( max( dot( normal, H ), 0.0 ), 48.0 );
|
|
1021
|
-
float day = 1.0 - uNight;
|
|
1022
|
-
|
|
1023
|
-
vec2 sp = vWaterXZ * 5.5;
|
|
1024
|
-
float n1 = bcNoise( sp + vec2( uTime * 0.9, -uTime * 0.6 ) );
|
|
1025
|
-
float n2 = bcNoise( sp * 1.37 + vec2( -uTime * 0.7, uTime * 0.8 ) + 41.7 );
|
|
1026
|
-
float sparkle = smoothstep( 0.74, 0.92, n1 ) * smoothstep( 0.74, 0.92, n2 );
|
|
1027
|
-
// Only above the horizon, and only where the sun is actually high enough to glint.
|
|
1028
|
-
sparkle *= glint * day * smoothstep( 0.05, 0.3, uSunDir.y ) * uSparkle * ( 1.0 - bcFoam );
|
|
1029
|
-
totalEmissiveRadiance += vec3( 1.0, 0.98, 0.92 ) * sparkle * 2.6;
|
|
1030
|
-
|
|
1031
|
-
// Foam is lit from within a little so it pops against the shallows, and the moon lays a
|
|
1032
|
-
// cool sheen along the swell after dark — kept under the bloom threshold, so it stays a
|
|
1033
|
-
// sheen rather than a glow.
|
|
1034
|
-
totalEmissiveRadiance += uFoam * bcFoam * 0.18;
|
|
1035
|
-
// Lava: the surface is its own light, brightest in the shallows where the crust is thin,
|
|
1036
|
-
// and pulsing slowly so it reads as molten rather than painted.
|
|
1037
|
-
totalEmissiveRadiance += diffuseColor.rgb * uGlow * ( 0.75 + 0.25 * bcNoise( vWaterXZ * 0.35 + uTime * 0.05 ) );
|
|
1038
|
-
totalEmissiveRadiance += vec3( 0.42, 0.52, 0.72 ) * glint * uNight * 0.28;
|
|
1039
|
-
}
|
|
1040
|
-
`;function b1({planet:s,heightAt:e,size:t=340,segments:i,quality:n="medium"}={}){if(!s?.water)return null;const r={...a1,...s.water};let o=i||ir[n]||ir.medium;const a={uTime:{value:0},uElapsed:{value:0},uNight:{value:0},uSunDir:{value:new F(0,1,0)},uShallow:{value:new W(r.shallow)},uDeep:{value:new W(r.deep)},uFoam:{value:new W(r.foam)},uOpacity:{value:new Se(r.opacity*.6,r.opacity)},uWaveHeight:{value:r.waveHeight},uWaveScale:{value:r.waveScale},uSparkle:{value:r.sparkle},uGlow:{value:r.glow},uRippleStrength:{value:r.ripples},uRipples:{value:Array.from({length:Qa},()=>new Np(0,0,0,0))},uIce:{value:new F(r.ice?.cracks??.07,r.ice?.frost??.5,r.ice?.snow??.3)}},l=new Eu({color:16777215,roughness:.14,metalness:0,ior:1.33,envMapIntensity:1,transparent:!0,depthWrite:!0,side:Bl,fog:!0});l.name="water",r.ice&&(l.defines={BC_ICE:""}),l.onBeforeCompile=f=>{wt(f),Object.assign(f.uniforms,a),f.vertexShader=f.vertexShader.replace("#include <common>",`#include <common>
|
|
1041
|
-
${u1}`).replace("#include <beginnormal_vertex>",`#include <beginnormal_vertex>
|
|
1042
|
-
float bcLift;
|
|
1043
|
-
vec2 bcSlide;
|
|
1044
|
-
bcWaves( position.xz, uTime, bcLift, bcSlide, objectNormal );`).replace("#include <begin_vertex>",`#include <begin_vertex>
|
|
1045
|
-
transformed.y += bcLift;
|
|
1046
|
-
transformed.xz += bcSlide;
|
|
1047
|
-
// The pre-slide xz, so ripple centres and foam noise are anchored to the world and do not
|
|
1048
|
-
// swim sideways with the swell. The lift is folded into the depth so the foam breathes as
|
|
1049
|
-
// each crest passes over the beach.
|
|
1050
|
-
vWaterXZ = position.xz;
|
|
1051
|
-
vWaterDepth = aDepth + bcLift;`),f.fragmentShader=f.fragmentShader.replace("#include <common>",`#include <common>
|
|
1052
|
-
${f1}`).replace("#include <color_fragment>",p1).replace("#include <roughnessmap_fragment>",m1).replace("#include <normal_fragment_begin>",g1).replace("#include <emissivemap_fragment>",w1)},l.customProgramCacheKey=()=>r.ice?"bc-water-ice":"bc-water";const c=new ke(Rc(t,o,r.level,e),l);c.name="water",c.position.y=r.level,c.receiveShadow=!0,c.castShadow=!1,c.renderOrder=-10;const h=r.open?new ke(v1(t,r.farDepth??30),l):null;h&&(h.name="far-sea",h.renderOrder=-11,h.receiveShadow=!0,c.add(h));let d=0,u=0;return{mesh:c,uniforms:a,update(f,p,m,g=0,w=null){d=p,a.uTime.value=p*r.speed,a.uElapsed.value=p,a.uNight.value=g,w&&a.uSunDir.value.copy(w);for(const b of a.uRipples.value)b.w>0&&p-b.z>Nu&&(b.w=0)},ripple(f,p,m=1){a.uRipples.value[u].set(f,p,d,m),u=(u+1)%Qa},heightAt(f,p,m=d){return r.level+h1(f,p,m*r.speed,a.uWaveHeight.value,a.uWaveScale.value)},setQuality(f){const p=ir[f]||ir.medium;p!==o&&(o=p,c.geometry.dispose(),c.geometry=Rc(t,o,r.level,e))},dispose(){c.geometry.dispose(),h?.geometry.dispose(),l.dispose(),c.parent?.remove(c)}}}function v1(s,e){const t=s/2,i=[t];for(let d=t,u=12;d<1400;u*=1.35)i.push(d+=u);const n=[];for(let d=0;d<=34;d++)n.push(-t+s*d/34);const r=[...i.slice(1).reverse().map(d=>-d),...n,...i.slice(1)],o=r.length,a=[],l=[];for(const d of r)for(const u of r)a.push(u,0,d),l.push(e);const c=[];for(let d=0;d<o-1;d++)for(let u=0;u<o-1;u++){const f=(r[u]+r[u+1])/2,p=(r[d]+r[d+1])/2;if(Math.abs(f)<t&&Math.abs(p)<t)continue;const m=d*o+u;c.push(m,m+o,m+1,m+1,m+o,m+o+1)}const h=new qt;return h.setAttribute("position",new qe(a,3)),h.setAttribute("normal",new qe(a.map((d,u)=>u%3===1?1:0),3)),h.setAttribute("aDepth",new qe(l,1)),h.setIndex(c),h}function Rc(s,e,t,i){const n=new Ut(s,s,e,e);n.rotateX(-Math.PI/2);const r=n.attributes.position,o=new Float32Array(r.count);for(let a=0;a<r.count;a++)o[a]=t-i(r.getX(a),r.getZ(a));return n.setAttribute("aDepth",new Ue(o,1)),n}const Xi=new F;function Bt(s,e,t,i,n,r){const o=2*Math.PI*n/4,a=Math.max(r-2*n,0),l=Math.PI/4;Xi.copy(e),Xi[i]=0,Xi.normalize();const c=.5*o/(o+a),h=1-Xi.angleTo(s)/l;return Math.sign(Xi[t])===1?h*c:a/(o+a)+c+c*(1-h)}class Nl extends Dt{constructor(e=1,t=1,i=1,n=2,r=.1){const o=n*2+1;if(r=Math.min(e/2,t/2,i/2,r),super(1,1,1,o,o,o),this.type="RoundedBoxGeometry",this.parameters={width:e,height:t,depth:i,segments:n,radius:r},o===1)return;const a=this.toNonIndexed();this.index=null,this.attributes.position=a.attributes.position,this.attributes.normal=a.attributes.normal,this.attributes.uv=a.attributes.uv;const l=new F,c=new F,h=new F(e,t,i).divideScalar(2).subScalar(r),d=this.attributes.position.array,u=this.attributes.normal.array,f=this.attributes.uv.array,p=d.length/6,m=new F,g=.5/o;for(let w=0,b=0;w<d.length;w+=3,b+=2)switch(l.fromArray(d,w),c.copy(l),c.x-=Math.sign(c.x)*g,c.y-=Math.sign(c.y)*g,c.z-=Math.sign(c.z)*g,c.normalize(),d[w+0]=h.x*Math.sign(l.x)+c.x*r,d[w+1]=h.y*Math.sign(l.y)+c.y*r,d[w+2]=h.z*Math.sign(l.z)+c.z*r,u[w+0]=c.x,u[w+1]=c.y,u[w+2]=c.z,Math.floor(w/p)){case 0:m.set(1,0,0),f[b+0]=Bt(m,c,"z","y",r,i),f[b+1]=1-Bt(m,c,"y","z",r,t);break;case 1:m.set(-1,0,0),f[b+0]=1-Bt(m,c,"z","y",r,i),f[b+1]=1-Bt(m,c,"y","z",r,t);break;case 2:m.set(0,1,0),f[b+0]=1-Bt(m,c,"x","z",r,e),f[b+1]=Bt(m,c,"z","x",r,i);break;case 3:m.set(0,-1,0),f[b+0]=1-Bt(m,c,"x","z",r,e),f[b+1]=1-Bt(m,c,"z","x",r,i);break;case 4:m.set(0,0,1),f[b+0]=1-Bt(m,c,"x","y",r,e),f[b+1]=1-Bt(m,c,"y","x",r,t);break;case 5:m.set(0,0,-1),f[b+0]=Bt(m,c,"x","y",r,e),f[b+1]=1-Bt(m,c,"y","x",r,t);break}}static fromJSON(e){return new Nl(e.width,e.height,e.depth,e.segments,e.radius)}}function nr(s,{nx:e=0,ny:t=1,nz:i=0}){const n=Math.cos(s.tilt),r=Math.sin(s.tilt),o=Math.cos(s.yaw),a=Math.sin(s.yaw);return .15*(Math.abs(e*o+t*r*a-i*n*a)+Math.abs(t*n+i*r)+Math.abs(e*a-t*r*o+i*n*o))/Math.max(.1,t)}function y1(s,e,t){let n=!1;const r=Math.max(1,Math.ceil(e/(1/60))),o=e/r;for(let a=0;a<r;a++){const l=t(s.x,s.z);if(s.bounces>=3&&s.vx===0&&s.vy===0&&s.vz===0){if(Math.abs(s.y-nr(s,l)-l.height)<.25){s.y=l.height+nr(s,l);continue}s.bounces=0}const c=s.x,h=s.z;s.vy-=9.8*o,s.x+=s.vx*o,s.y+=s.vy*o,s.z+=s.vz*o,s.yaw+=s.spin*o,s.tilt+=s.spin*.6*o;let d=t(s.x,s.z);d.height>l.height+.2&&d.height>s.y+.15&&(s.x=c,s.z=h,s.vx*=-.38,s.vz*=-.38,d=l);const u=nr(s,d);if(s.y-u>d.height||s.vy>=0)continue;s.y=d.height+u;const{nx:f=0,ny:p=1,nz:m=0}=d,g=s.vx*f+s.vy*p+s.vz*m;s.vx=(s.vx-g*f)*.55-g*f*.38,s.vy=(s.vy-g*p)*.55-g*p*.38,s.vz=(s.vz-g*m)*.55-g*m*.38,s.spin*=.4,s.bounces++,s.landed||(n=!0),s.landed=!0,p>.65&&(s.bounces>=3||Math.hypot(s.vx,s.vy,s.vz)<.4)&&(s.bounces=3,s.vx=s.vy=s.vz=s.spin=s.tilt=0,s.y=d.height+nr(s,d))}return n}const Li={uTime:{value:0},uMotion:{value:1}},Bc={off:0,low:.6,full:1},C1=.45,x1=`
|
|
1053
|
-
#include <common>
|
|
1054
|
-
// bc:fauna-vert
|
|
1055
|
-
// Four per-vertex flags share one slot: a drone carries position, normal, its instance
|
|
1056
|
-
// matrix (four slots), its colour and five of its own, and the WebGL limit on a Mac is
|
|
1057
|
-
// sixteen — one attribute per float is the difference between a drone and a link error.
|
|
1058
|
-
attribute vec4 aPart; // wing, spin, emissive, crate
|
|
1059
|
-
#define aWing aPart.x
|
|
1060
|
-
#define aSpin aPart.y
|
|
1061
|
-
#define aEmissive aPart.z
|
|
1062
|
-
#define aCrate aPart.w
|
|
1063
|
-
attribute vec3 aPivot;
|
|
1064
|
-
attribute float aAccent;
|
|
1065
|
-
attribute float aPhase;
|
|
1066
|
-
#ifdef BC_DRONE
|
|
1067
|
-
attribute float aCarry;
|
|
1068
|
-
attribute float aRotor;
|
|
1069
|
-
#endif
|
|
1070
|
-
varying float vEmissive;
|
|
1071
|
-
varying float vAccent;
|
|
1072
|
-
varying float vPhase;
|
|
1073
|
-
uniform float uTime;
|
|
1074
|
-
uniform float uMotion;
|
|
1075
|
-
|
|
1076
|
-
vec3 bcSpinY( vec3 p, vec3 hub, float a ) {
|
|
1077
|
-
vec3 r = p - hub;
|
|
1078
|
-
float s = sin( a );
|
|
1079
|
-
float c = cos( a );
|
|
1080
|
-
return hub + vec3( r.x * c + r.z * s, r.y, -r.x * s + r.z * c );
|
|
1081
|
-
}
|
|
1082
|
-
vec3 bcSpinZ( vec3 p, vec3 hub, float a ) {
|
|
1083
|
-
vec3 r = p - hub;
|
|
1084
|
-
float s = sin( a );
|
|
1085
|
-
float c = cos( a );
|
|
1086
|
-
return hub + vec3( r.x * c - r.y * s, r.x * s + r.y * c, r.z );
|
|
1087
|
-
}
|
|
1088
|
-
// A wing hinges on the body's long axis (Z) — that is what lifts a tip up and down. A tail
|
|
1089
|
-
// fin swings about the vertical (Y).
|
|
1090
|
-
#if BC_WING_AXIS == 1
|
|
1091
|
-
#define bcWingSpin bcSpinY
|
|
1092
|
-
#else
|
|
1093
|
-
#define bcWingSpin bcSpinZ
|
|
1094
|
-
#endif
|
|
1095
|
-
|
|
1096
|
-
float bcFlap() {
|
|
1097
|
-
float t = uTime * uMotion;
|
|
1098
|
-
float amp = BC_FLAP_AMP;
|
|
1099
|
-
#ifdef BC_GLIDE
|
|
1100
|
-
// Flap in bursts and glide between them: a slow second sine, offset per instance, gates
|
|
1101
|
-
// the amplitude. Below its threshold the wings simply hold.
|
|
1102
|
-
amp *= smoothstep( -0.15, 0.45, sin( t * 0.4 + aPhase * 2.3 ) );
|
|
1103
|
-
#endif
|
|
1104
|
-
return sin( t * BC_FLAP_RATE + aPhase ) * amp;
|
|
1105
|
-
}
|
|
1106
|
-
`,M1=`
|
|
1107
|
-
#include <beginnormal_vertex>
|
|
1108
|
-
if ( aWing != 0.0 ) objectNormal = bcWingSpin( objectNormal, vec3( 0.0 ), bcFlap() * aWing );
|
|
1109
|
-
#ifdef BC_DRONE
|
|
1110
|
-
if ( aSpin != 0.0 ) objectNormal = bcSpinY( objectNormal, vec3( 0.0 ), aRotor * aSpin );
|
|
1111
|
-
#endif
|
|
1112
|
-
`,k1=`
|
|
1113
|
-
#include <begin_vertex>
|
|
1114
|
-
vEmissive = aEmissive;
|
|
1115
|
-
vAccent = aAccent;
|
|
1116
|
-
vPhase = aPhase;
|
|
1117
|
-
if ( aWing != 0.0 ) transformed = bcWingSpin( transformed, aPivot, bcFlap() * aWing );
|
|
1118
|
-
#ifdef BC_DRONE
|
|
1119
|
-
if ( aSpin != 0.0 ) transformed = bcSpinY( transformed, aPivot, aRotor * aSpin );
|
|
1120
|
-
// An empty drone's crate and cable collapse to a point inside the hull rather than being
|
|
1121
|
-
// culled — degenerate triangles cost nothing and keep the geometry one piece.
|
|
1122
|
-
if ( aCrate > 0.5 ) transformed = mix( aPivot, transformed, aCarry );
|
|
1123
|
-
#endif
|
|
1124
|
-
`,T1=`
|
|
1125
|
-
#include <common>
|
|
1126
|
-
// bc:fauna-frag
|
|
1127
|
-
varying float vEmissive;
|
|
1128
|
-
varying float vAccent;
|
|
1129
|
-
varying float vPhase;
|
|
1130
|
-
uniform float uTime;
|
|
1131
|
-
uniform vec3 uAccentA;
|
|
1132
|
-
uniform vec3 uAccentB;
|
|
1133
|
-
`,_1=`
|
|
1134
|
-
#include <color_fragment>
|
|
1135
|
-
if ( vAccent > 1.5 ) diffuseColor.rgb = uAccentB;
|
|
1136
|
-
else if ( vAccent > 0.5 ) diffuseColor.rgb = uAccentA;
|
|
1137
|
-
`,S1=`
|
|
1138
|
-
#include <emissivemap_fragment>
|
|
1139
|
-
#ifdef BC_DRONE
|
|
1140
|
-
// A short strobe rather than a pulse, like an aircraft's, and well above 1.0 so bloom
|
|
1141
|
-
// picks it out. Phase-offset so a parked row does not blink as one.
|
|
1142
|
-
float bcBlink = step( 0.82, fract( uTime * 0.9 + vPhase * 0.16 ) );
|
|
1143
|
-
totalEmissiveRadiance += vec3( 2.5, 0.2, 0.16 ) * vEmissive * ( 0.12 + 0.88 * bcBlink );
|
|
1144
|
-
#endif
|
|
1145
|
-
`;function Fc(s,e,t,i){return s.defines={...e},s.customProgramCacheKey=()=>i,s.onBeforeCompile=n=>{wt(n),Object.assign(n.uniforms,t),n.vertexShader=n.vertexShader.replace("#include <common>",x1).replace("#include <beginnormal_vertex>",M1).replace("#include <begin_vertex>",k1),n.fragmentShader=n.fragmentShader.replace("#include <common>",T1).replace("#include <color_fragment>",_1).replace("#include <emissivemap_fragment>",S1)},s}const Oc=s=>Number(s).toFixed(4);function Wn(s){const e={uTime:Li.uTime,uMotion:Li.uMotion,uAccentA:{value:new W(s.accentA??0)},uAccentB:{value:new W(s.accentB??0)}},t={BC_WING_AXIS:s.axis==="y"?1:0,BC_FLAP_RATE:Oc((s.rate||0)*Math.PI*2),BC_FLAP_AMP:Oc(s.amp||0)};s.glide&&(t.BC_GLIDE=""),s.drone&&(t.BC_DRONE="");const i=`bc-fauna:${s.name}:${JSON.stringify(t)}`,n=Fc(new tt({roughness:.7,metalness:0,side:s.side??vt}),t,e,i),r=s.shadow?Fc(new In({depthPacking:Dn}),t,e,`${i}:depth`):null;return{material:n,depth:r}}const $1=["aWing","aSpin","aEmissive","aCrate"];function Ne(s,e={}){const t=s.attributes.position.count,i=new Float32Array(t*4);for(let r=0;r<t;r++)for(let o=0;o<4;o++)i[r*4+o]=e[$1[o]]||0;s.setAttribute("aPart",new Ue(i,4)),s.setAttribute("aAccent",new Ue(new Float32Array(t).fill(e.aAccent||0),1));const n=new Float32Array(t*3);if(e.pivot)for(let r=0;r<t;r++)n[r*3]=e.pivot[0],n[r*3+1]=e.pivot[1],n[r*3+2]=e.pivot[2];return s.setAttribute("aPivot",new Ue(n,3)),s}function uo(s){const e=s.map(i=>i.index?i.toNonIndexed():i),t=Nt(e,!1);for(const i of s)i.dispose();for(const i of e)s.includes(i)||i.dispose();return t}function A1(s,e){if(e===1)return s;s.scale(e,e,e);const t=s.getAttribute("aPivot");for(let i=0;i<t.array.length;i++)t.array[i]*=e;return t.needsUpdate=!0,s}function Di(s,e,t,i,n){const r=new qt,o=n*s;return r.setAttribute("position",new qe([0,0,e/2,0,0,-e/2,o,0,t/2-i,o,0,-t/2-i],3)),r.setAttribute("normal",new qe([0,1,0,0,1,0,0,1,0,0,1,0],3)),r.setAttribute("uv",new qe([0,1,0,0,1,1,1,0],2)),r.setIndex(n>0?[0,2,1,1,2,3]:[0,1,2,1,3,2]),r}function E1(s,e){const t=new Fl(s,e,6);return t.rotateX(Math.PI/2),t}const Ic={gull:{span:.62,root:.13,tip:.035,sweep:.16,body:[.55,.45,1.5],tail:.08,rate:2.6,amp:.5,glide:!0,speed:6,turn:1.1,wander:.9,dip:!0,diurnal:!0,beak:15769648,colors:[16052974,15263456,14210767]},parrot:{span:.46,root:.14,tip:.05,sweep:.1,body:[.6,.5,1.4],tail:.18,rate:5.5,amp:.75,glide:!1,speed:5.5,turn:1.6,wander:1.4,dip:!1,diurnal:!0,beak:3813936,colors:[15223354,4175178,3833824,15777840]},crow:{span:.52,root:.14,tip:.06,sweep:.1,body:[.6,.5,1.5],tail:.14,rate:3.6,amp:.6,glide:!1,speed:5.5,turn:1.4,wander:1.1,dip:!1,diurnal:!1,beak:1842210,colors:[1973798,2500142,2894388]},swallow:{span:.42,root:.1,tip:.025,sweep:.2,body:[.5,.4,1.2],tail:.16,rate:6.5,amp:.65,glide:!0,speed:8.5,turn:2.6,wander:2.4,dip:!1,diurnal:!0,beak:2763312,colors:[2768010,2241390,3820186]}};function P1(s){const e=.11*s.body[2],t=new Qt(.11,8,6);t.scale(s.body[0],s.body[1],s.body[2]);const i=new Qt(.06,6,5);i.translate(0,.04,e+.01);const n=E1(.02,.07);n.translate(0,.035,e+.08);const r=Di(s.span,s.root,s.tip,s.sweep,1);r.translate(.04,.02,0);const o=Di(s.span,s.root,s.tip,s.sweep,-1);o.translate(-.04,.02,0);const a=new Ut(.16,s.tail);return a.rotateX(-Math.PI/2),a.translate(0,.02,-e-s.tail/2+.05),uo([Ne(t),Ne(i),Ne(n,{aAccent:1}),Ne(r,{aWing:1,pivot:[.1,.05,0]}),Ne(o,{aWing:-1,pivot:[-.1,.05,0]}),Ne(a)])}function z1(){const s=new Qt(.018,6,4);s.scale(1,1,3.4);const e=Di(.065,.09,.055,.008,1);e.translate(.006,.004,0);const t=Di(.065,.09,.055,.008,-1);return t.translate(-.006,.004,0),uo([Ne(s,{aAccent:1}),Ne(e,{aWing:1,pivot:[0,.004,0]}),Ne(t,{aWing:-1,pivot:[0,.004,0]})])}function Hu(){const s=new Qt(.1,9,7);s.scale(.8,1,2.2);const e=Di(.14,.06,.17,0,1);e.rotateY(Math.PI/2),e.rotateZ(Math.PI/2),e.translate(0,0,-.2);const t=Di(.07,.1,.03,.03,1);return t.rotateZ(Math.PI/2),t.translate(0,.08,.02),uo([Ne(s),Ne(e,{aWing:1,pivot:[0,0,-.18],aAccent:1}),Ne(t,{aAccent:1})])}const L1=[1,-1.04,1.08,-.96];function R1(){const s=[],e=new Nl(.5,.2,.5,3,.07);s.push(Ne(e));const t=new Qt(.12,8,6);t.scale(1,.6,1),t.translate(0,.1,.02),s.push(Ne(t,{aAccent:1}));for(let a=0;a<4;a++){const l=a&1?1:-1,c=a&2?1:-1,h=new Dt(.42,.035,.05);h.rotateY(Math.atan2(-c,l)),h.translate(l*.24,.06,c*.24),s.push(Ne(h,{aAccent:1}));const d=l*.36,u=c*.36,f=new Ot(.03,.03,.05,8);f.translate(d,.09,u),s.push(Ne(f,{aAccent:1}));const p=L1[a],m=new Ot(.15,.15,.008,6);m.translate(d,.115,u),s.push(Ne(m,{aSpin:p,pivot:[d,.115,u],aAccent:2}));const g=new Dt(.3,.01,.045);g.translate(d,.125,u),s.push(Ne(g,{aSpin:p,pivot:[d,.125,u],aAccent:1}));const w=new Dt(.045,.01,.3);w.translate(d,.125,u),s.push(Ne(w,{aSpin:p,pivot:[d,.125,u],aAccent:1}))}for(const a of[-1,1]){const l=new Dt(.03,.12,.34);l.translate(a*.16,-.15,0),s.push(Ne(l,{aAccent:1}))}const i=new Qt(.028,6,4);i.translate(0,.02,.27),s.push(Ne(i,{aEmissive:1}));const n=[0,-.05,0],r=new Dt(.012,.36,.012);r.translate(0,-.28,0),s.push(Ne(r,{aCrate:1,pivot:n,aAccent:1}));const o=new Dt(.3,.3,.3);return o.translate(0,-.61,0),s.push(Ne(o,{aCrate:1,pivot:n,aAccent:2})),uo(s)}const be=new co,Ds=new F,Dc={x:0,z:0},Oo=new W,Ps=new xt().makeScale(0,0,0);function B1(s){let e=2166136261;for(let t=0;t<s.length;t++)e=Math.imul(e^s.charCodeAt(t),16777619);return e>>>0}function Uu(s){for(;s>Math.PI;)s-=Math.PI*2;for(;s<-Math.PI;)s+=Math.PI*2;return s}function Hn(s,e,t,i,n){const r=new zt(s,e.material,t);return r.name=i,r.frustumCulled=!1,r.castShadow=n,r.receiveShadow=!1,e.depth&&(r.customDepthMaterial=e.depth),r.instanceMatrix.setUsage(at),r}function Un(s,e,t){const i=new Float32Array(e);for(let n=0;n<e;n++)i[n]=t()*Math.PI*2;s.setAttribute("aPhase",new Ze(i,1))}function jn(s,e,t,i,n=.06){for(let r=0;r<e;r++)Oo.set(t[r%t.length]),Oo.offsetHSL((i()-.5)*.02,(i()-.5)*n,(i()-.5)*n),s.setColorAt(r,Oo);s.instanceColor.needsUpdate=!0}const Io=60;class F1{constructor(e,t,i,n,r){this.kind=Ic[t.kind]||Ic.gull,this.env=i,this.rand=De(n),this.count=Math.max(0,Math.round(t.count??14)),this.altitude=t.altitude||[14,22],this.size=t.size??1;const o=A1(P1(this.kind),this.size);Un(o,this.count,this.rand),this.mats=Wn({name:`bird-${t.kind}`,rate:this.kind.rate,amp:this.kind.amp,glide:this.kind.glide,accentA:this.kind.beak,shadow:!0}),this.mesh=Hn(o,this.mats,this.count,"birds",!0),jn(this.mesh,this.count,t.colors?.length?t.colors:this.kind.colors,this.rand),e.add(this.mesh),this.tx=0,this.tz=0,this.groundY=0,this.retarget=0,this._pickTarget();const[a,l]=this.altitude;this.birds=[],this.info=[];for(let c=0;c<this.count;c++){const h=this.rand()*Math.PI*2,d=this.rand()*14,u=a+this.rand()*(l-a),f=this.rand()*Math.PI*2;this.birds.push({x:this.tx+Math.cos(h)*d,y:this.groundY+u,z:this.tz+Math.sin(h)*d,vx:Math.sin(f)*this.kind.speed,vy:0,vz:Math.cos(f)*this.kind.speed,fx:Math.sin(f)*this.kind.speed,fy:0,fz:Math.cos(f)*this.kind.speed,alt:u,heading:f,wander:this.rand()*Math.PI*2,roll:0,dip:0,dipWait:6+this.rand()*20,rippled:!1}),this.info.push({x:0,y:0,z:0})}this.callTimer=4+this.rand()*8,this.setTier(r)}setTier(e){this.active=this.count?Math.max(1,Math.round(this.count*e)):0,this.mesh.count=this.active,this.info.length=this.active;for(let t=0;t<this.active;t++)this.info[t]||(this.info[t]={x:0,y:0,z:0})}_pickTarget(){const e=this.rand()*Math.PI*2,t=Math.sqrt(this.rand())*Io;this.tx=Math.cos(e)*t,this.tz=Math.sin(e)*t;const i=this.env.heightAt(this.tx,this.tz);this.groundY=this.env.waterLevel!=null?Math.max(i,this.env.waterLevel):i,this.retarget=25}update(e,t,i,n){const r=this.active;if(!r)return;const o=this.birds,a=this.kind,l=this.env,c=l.waterLevel;let h=0,d=0;for(let y=0;y<r;y++)h+=o[y].x,d+=o[y].z;h/=r,d/=r,this.retarget-=e;const u=this.tx-h,f=this.tz-d;(this.retarget<=0||u*u+f*f<100)&&this._pickTarget();const p=a.speed*n,m=a.speed*a.turn*n,g=9,w=g*g,b=2.4*2.4;for(let y=0;y<r;y++){const C=o[y];let _=0,x=0,T=0,M=0,k=0,A=0,P=0,$=0,H=0,q=0;for(let it=0;it<r;it++){if(it===y)continue;const Ct=o[it],gi=Ct.x-C.x,wi=Ct.y-C.y,Zi=Ct.z-C.z,qs=gi*gi+wi*wi+Zi*Zi;if(!(qs>w)&&(_+=Ct.x,x+=Ct.y,T+=Ct.z,k+=Ct.vx,A+=Ct.vy,P+=Ct.vz,M++,qs<b&&qs>1e-4)){const Gs=1/qs;$-=gi*Gs,H-=wi*Gs,q-=Zi*Gs}}let Y=0,G=0,ee=0;M&&(_=_/M-C.x,x=x/M-C.y,T=T/M-C.z,Y+=_*.06,G+=x*.06,ee+=T*.06,k=k/M-C.vx,A=A/M-C.vy,P=P/M-C.vz,Y+=k*.35,G+=A*.35,ee+=P*.35),Y+=$*2.2,G+=H*2.2,ee+=q*2.2,C.wander+=(this.rand()-.5)*3*e,Y+=Math.sin(C.wander)*a.wander*.5,ee+=Math.cos(C.wander)*a.wander*.5,Y+=(this.tx-C.x)*.02,ee+=(this.tz-C.z)*.02,C.x*C.x+C.z*C.z>Io*Io&&(Y-=C.x*.05,ee-=C.z*.05),a.dip&&c!=null&&(C.dip>0?(C.dip-=e,!C.rippled&&C.y<c+.8&&i?.ripple&&(i.ripple(C.x,C.z,.5),C.rippled=!0)):(C.dipWait-=e,C.dipWait<=0&&(l.heightAt(C.x,C.z)<c-.3?(C.dip=3,C.rippled=!1,C.dipWait=10+this.rand()*20):C.dipWait=3)));const xe=C.dip>0?c+.5:this.groundY+C.alt;G+=(xe-C.y)*.6-C.vy*.9;const we=Y*Y+G*G+ee*ee;if(we>m*m){const it=m/Math.sqrt(we);Y*=it,G*=it,ee*=it}C.vx+=Y*e,C.vy+=G*e,C.vz+=ee*e;const U=Math.sqrt(C.vx*C.vx+C.vy*C.vy+C.vz*C.vz)||1,Q=1+(p*(C.dip>0?1.15:1)/U-1)*Math.min(1,2.5*e);C.vx*=Q,C.vy*=Q,C.vz*=Q,C.x+=C.vx*e,C.y+=C.vy*e,C.z+=C.vz*e;const he=Math.min(1,6*e);C.fx+=(C.vx-C.fx)*he,C.fy+=(C.vy-C.fy)*he,C.fz+=(C.vz-C.fz)*he;const Ae=Math.atan2(C.fx,C.fz),Ve=-Math.cos(Ae)*Y+Math.sin(Ae)*ee,lt=N.clamp(-Ve/(m||1)*.9,-.8,.8);C.roll+=(lt-C.roll)*Math.min(1,3*e),be.position.set(C.x,C.y,C.z),Ds.set(C.x+C.fx,C.y+C.fy,C.z+C.fz),be.lookAt(Ds),be.rotateZ(C.roll),be.scale.set(1,1,1),be.updateMatrix(),this.mesh.setMatrixAt(y,be.matrix);const ut=this.info[y];ut.x=C.x,ut.y=C.y,ut.z=C.z}if(this.mesh.instanceMatrix.needsUpdate=!0,this.callTimer-=e,this.callTimer<=0&&(this.callTimer=6+this.rand()*9,i?.sound&&!(a.diurnal&&t>.5))){const y=o[Math.floor(this.rand()*r)];i.sound("bird-call",y.x,y.y,y.z)}}dispose(){this.mesh.removeFromParent(),this.mesh.geometry.dispose(),this.mats.material.dispose(),this.mats.depth?.dispose()}}const O1=[15903035,7128304,15751802,16180074,10977e3,16052454];class I1{constructor(e,t,i,n,r){this.env=i,this.rand=De(n),this.count=Math.max(0,Math.round(t.count??40));const o=z1();Un(o,this.count,this.rand),this.mats=Wn({name:"butterfly",rate:14,amp:1.1,accentA:2761760,shadow:!1}),this.mesh=Hn(o,this.mats,this.count,"butterflies",!1),jn(this.mesh,this.count,t.colors?.length?t.colors:O1,this.rand,.1),e.add(this.mesh),this.flies=[];for(let a=0;a<this.count;a++){const l={ax:0,az:0,gy:0,x:0,y:0,z:0,vx:0,vy:0,vz:0,tx:0,ty:0,tz:0,heading:this.rand()*Math.PI*2,retarget:0,hop:12+this.rand()*25};this._hop(l),l.x=l.tx,l.y=l.ty,l.z=l.tz,this.flies.push(l),this._write(a,l)}this.mesh.instanceMatrix.needsUpdate=!0,this.setTier(r)}setTier(e){this.active=this.count?Math.max(1,Math.round(this.count*e)):0,this.mesh.count=this.active}_hop(e){const t=this.rand()*Math.PI*2,i=6+Math.sqrt(this.rand())*44;e.ax=Math.cos(t)*i,e.az=Math.sin(t)*i,e.hop=12+this.rand()*25,this._retarget(e)}_retarget(e){const t=this.rand()*Math.PI*2,i=this.rand()*2.5;e.tx=e.ax+Math.cos(t)*i,e.tz=e.az+Math.sin(t)*i,e.gy=this.env.heightAt(e.tx,e.tz),this.env.waterLevel!=null&&(e.gy=Math.max(e.gy,this.env.waterLevel)),e.ty=e.gy+.4+this.rand()*1.2,e.retarget=.7+this.rand()*1.8}_write(e,t){be.position.set(t.x,t.y,t.z),be.rotation.set(N.clamp(-t.vy*.3,-.5,.5),t.heading,0),be.scale.set(1,1,1),be.updateMatrix(),this.mesh.setMatrixAt(e,be.matrix)}update(e,t,i){const n=this.active;if(!n)return;const r=t.position,o=1.3*i;for(let a=0;a<n;a++){const l=this.flies[a],c=l.x-r.x,h=l.z-r.z;if(c*c+h*h>22500)continue;l.retarget-=e,l.hop-=e,l.hop<=0?this._hop(l):l.retarget<=0&&this._retarget(l);const d=(l.tx-l.x)*1.8+(this.rand()-.5)*6,u=(l.ty-l.y)*3+(this.rand()-.5)*3,f=(l.tz-l.z)*1.8+(this.rand()-.5)*6,p=Math.max(0,1-1.4*e);l.vx=(l.vx+d*e)*p,l.vy=(l.vy+u*e)*p,l.vz=(l.vz+f*e)*p;const m=l.vx*l.vx+l.vy*l.vy+l.vz*l.vz;if(m>o*o){const g=o/Math.sqrt(m);l.vx*=g,l.vy*=g,l.vz*=g}l.x+=l.vx*e,l.y+=l.vy*e,l.z+=l.vz*e,l.y<l.gy+.25&&(l.y=l.gy+.25),m>.01&&(l.heading+=Uu(Math.atan2(l.vx,l.vz)-l.heading)*Math.min(1,6*e)),this._write(a,l)}this.mesh.instanceMatrix.needsUpdate=!0}dispose(){this.mesh.removeFromParent(),this.mesh.geometry.dispose(),this.mats.material.dispose()}}const ju=[10471392,15766106,12572840,15257712],D1=-7.5;class V1{constructor(e,t,i,n,r){this.env=i,this.rand=De(n),this.count=Math.max(0,Math.round(t.count??10));const o=Hu();Un(o,this.count,this.rand),this.mats=Wn({name:"fish",axis:"y",rate:8,amp:.45,accentA:6982304,shadow:!1}),this.mesh=Hn(o,this.mats,this.count,"fish",!1),jn(this.mesh,this.count,ju,this.rand),e.add(this.mesh),this.fish=[];for(let a=0;a<this.count;a++)this.fish.push({x:0,y:0,z:0,vx:0,vy:0,vz:0,live:!1}),this.mesh.setMatrixAt(a,Ps);this.mesh.instanceMatrix.needsUpdate=!0,this.launchTimer=1+this.rand()*2,this.setTier(r)}setTier(e){this.active=this.count?Math.max(1,Math.round(this.count*e)):0,this.mesh.count=this.active}_surface(e,t,i){return this.env.waterHeightAt?this.env.waterHeightAt(e,t,i):this.env.waterLevel}_launch(e,t){let i=-1;for(let n=0;n<this.active;n++)if(!this.fish[n].live){i=n;break}if(!(i<0))for(let n=0;n<8;n++){const r=this.rand()*Math.PI*2,o=20+this.rand()*70,a=Math.cos(r)*o,l=Math.sin(r)*o;if(this.env.heightAt(a,l)>=this.env.waterLevel-.4)continue;const c=this.fish[i],h=this.rand()*Math.PI*2,d=.6+this.rand()*1.2;c.x=a,c.z=l,c.y=this._surface(a,l,e)-.25,c.vx=Math.cos(h)*d,c.vz=Math.sin(h)*d,c.vy=3+this.rand()*2,c.live=!0,t?.ripple?.(a,l,.5);return}}update(e,t,i,n){if(this.active){this.launchTimer-=e,this.launchTimer<=0&&(this.launchTimer=2.5+this.rand()*4,this._launch(t,i));for(let r=0;r<this.active;r++){const o=this.fish[r];if(!o.live)continue;o.vy+=D1*e*n,o.x+=o.vx*e*n,o.y+=o.vy*e*n,o.z+=o.vz*e*n;const a=this._surface(o.x,o.z,t);if(o.vy<0&&o.y<a-.1){o.live=!1,this.mesh.setMatrixAt(r,Ps),i?.ripple?.(o.x,o.z,1.4),i?.sound?.("fish-splash",o.x,a,o.z);continue}be.position.set(o.x,o.y,o.z),Ds.set(o.x+o.vx,o.y+o.vy,o.z+o.vz),be.lookAt(Ds),be.scale.set(1,1,1),be.updateMatrix(),this.mesh.setMatrixAt(r,be.matrix)}this.mesh.instanceMatrix.needsUpdate=!0}}dispose(){this.mesh.removeFromParent(),this.mesh.geometry.dispose(),this.mats.material.dispose()}}class N1{constructor(e,t,i,n,r){this.env=i,this.rand=De(n),this.above=t.above??null,this.bed=t.bed??[3.2,1/0],this.band=t.band??[30,140],this.depth=t.depth??[1,1.8],this.count=Math.max(0,Math.round(t.count??24));const o=Hu();Un(o,this.count,this.rand),this.mats=Wn({name:"swimmers",axis:"y",rate:2.2,amp:.4,accentA:1712672,shadow:!1}),this.mesh=Hn(o,this.mats,this.count,"swimmers",!1),jn(this.mesh,this.count,t.colors??ju,this.rand),e.add(this.mesh);const[a,l]=t.size??[2,3];this.fish=[];let c=null,h=0;for(let d=0;d<this.count;d++){if(h<=0&&(c=this._school(),h=2+Math.floor(this.rand()*5)),h--,!c){this.mesh.setMatrixAt(d,Ps);continue}this.fish.push({slot:d,school:c,angle:c.angle-this.rand()*.5,lane:.85+this.rand()*.3,depth:c.depth+(this.rand()-.5)*.5,size:a+this.rand()*(l-a),bob:this.rand()*Math.PI*2})}this.mesh.instanceMatrix.needsUpdate=!0,this.setTier(r)}_school(){if(this.above){const i=this.rand()*Math.PI*2,n=40+this.rand()*90,[r,o]=this.above;return{x:Math.cos(i)*n,z:Math.sin(i)*n,rx:10+this.rand()*12,rz:7+this.rand()*8,tilt:this.rand()*Math.PI,speed:(.05+this.rand()*.06)*(this.rand()<.5?-1:1),angle:this.rand()*Math.PI*2,depth:r+this.rand()*(o-r)}}const e=this.env.waterLevel,t=(i,n,r,o=1/0)=>{const a=e-this.env.heightAt(i,n);return a>r&&a<o};for(let i=0;i<40;i++){const n=this.rand()*Math.PI*2,r=this.band[0]+this.rand()*(this.band[1]-this.band[0]),o=Math.cos(n)*r,a=Math.sin(n)*r;if(t(o,a,this.bed[0],this.bed[1])){for(let l=22;l>=7;l-=3)if(Array.from({length:10},(h,d)=>d/10*Math.PI*2).every(h=>t(o+Math.cos(h)*l,a+Math.sin(h)*l*.7,this.bed[0]*.75,this.bed[1]*1.2)))return{x:o,z:a,rx:l,rz:l*.7,tilt:this.rand()*Math.PI,speed:(.08+this.rand()*.1)*(this.rand()<.5?-1:1),angle:this.rand()*Math.PI*2,depth:this.depth[0]+this.rand()*(this.depth[1]-this.depth[0])}}}return null}setTier(e){this.active=this.fish.length?Math.max(1,Math.round(this.fish.length*e)):0;for(let t=this.active;t<this.fish.length;t++)this.mesh.setMatrixAt(this.fish[t].slot,Ps);this.mesh.instanceMatrix.needsUpdate=!0}update(e,t,i){if(!this.active)return;const n=this.env.waterLevel;for(let r=0;r<this.active;r++){const o=this.fish[r],a=o.school;o.angle+=a.speed*e*i*2.4/o.lane;const l=1+.12*Math.sin(t*.13+o.bob),c=Math.cos(o.angle),h=Math.sin(o.angle),d=c*a.rx*o.lane*l,u=h*a.rz*o.lane*l,f=Math.cos(a.tilt),p=Math.sin(a.tilt),m=a.x+d*f-u*p,g=a.z+d*p+u*f,w=Math.sign(a.speed),b=-h*a.rx*w,y=c*a.rz*w;be.position.set(m,(this.above?this.env.heightAt(m,g)+o.depth:n-o.depth)+Math.sin(t*.6+o.bob)*.12,g),Ds.set(m+b*f-y*p,be.position.y,g+b*p+y*f),be.lookAt(Ds),be.scale.setScalar(o.size),be.updateMatrix(),this.mesh.setMatrixAt(o.slot,be.matrix)}this.mesh.instanceMatrix.needsUpdate=!0}dispose(){this.mesh.removeFromParent(),this.mesh.geometry.dispose(),this.mats.material.dispose()}}const W1={angler:0,clawfish:1},H1=`
|
|
1146
|
-
#include <common>
|
|
1147
|
-
attribute vec4 aMonster;
|
|
1148
|
-
varying vec2 vLocal;
|
|
1149
|
-
varying vec4 vMonster;
|
|
1150
|
-
void main() {
|
|
1151
|
-
vLocal = vec2( uv.x - 0.5, 0.5 - uv.y );
|
|
1152
|
-
vMonster = aMonster;
|
|
1153
|
-
vec4 world = modelMatrix * instanceMatrix * vec4( position, 1.0 );
|
|
1154
|
-
world.xyz = bcBend( world.xyz );
|
|
1155
|
-
gl_Position = projectionMatrix * viewMatrix * world;
|
|
1156
|
-
}
|
|
1157
|
-
`,U1=`
|
|
1158
|
-
#include <common>
|
|
1159
|
-
uniform float uTime;
|
|
1160
|
-
uniform vec3 uShadow;
|
|
1161
|
-
uniform vec3 uLure;
|
|
1162
|
-
varying vec2 vLocal;
|
|
1163
|
-
varying vec4 vMonster;
|
|
1164
|
-
float ellipse( vec2 p, vec2 center, vec2 radius ) {
|
|
1165
|
-
return ( length( ( p - center ) / radius ) - 1.0 ) * min( radius.x, radius.y );
|
|
1166
|
-
}
|
|
1167
|
-
float limb( vec2 p, vec2 a, vec2 b, float ra, float rb ) {
|
|
1168
|
-
vec2 pa = p - a;
|
|
1169
|
-
vec2 ba = b - a;
|
|
1170
|
-
float h = clamp( dot( pa, ba ) / dot( ba, ba ), 0.0, 1.0 );
|
|
1171
|
-
return length( pa - ba * h ) - mix( ra, rb, h );
|
|
1172
|
-
}
|
|
1173
|
-
float angler( vec2 p, float t ) {
|
|
1174
|
-
p.x -= sin( p.y * 9.0 - t * 2.2 ) * 0.035 * smoothstep( 0.05, -0.5, p.y );
|
|
1175
|
-
float d = ellipse( p, vec2( 0.0, 0.3 ), vec2( 0.17, 0.13 ) );
|
|
1176
|
-
d = min( d, ellipse( p, vec2( 0.0, 0.08 ), vec2( 0.13, 0.22 ) ) );
|
|
1177
|
-
d = min( d, limb( p, vec2( 0.0, -0.08 ), vec2( 0.0, -0.4 ), 0.07, 0.02 ) );
|
|
1178
|
-
d = min( d, ellipse( p, vec2( 0.0, -0.44 ), vec2( 0.13, 0.045 ) ) );
|
|
1179
|
-
for ( int k = 0; k < 3; k++ ) {
|
|
1180
|
-
float y = 0.16 - float( k ) * 0.1;
|
|
1181
|
-
float step = sin( t * 2.6 + float( k ) * 1.7 ) * 0.03;
|
|
1182
|
-
vec2 hip = vec2( 0.1, y );
|
|
1183
|
-
vec2 foot = vec2( 0.27, y - 0.09 + step );
|
|
1184
|
-
d = min( d, limb( vec2( abs( p.x ), p.y ), hip, foot, 0.025, 0.012 ) );
|
|
1185
|
-
}
|
|
1186
|
-
d = min( d, limb( p, vec2( 0.0, 0.42 ), vec2( 0.02 * sin( t ), 0.5 ), 0.008, 0.006 ) );
|
|
1187
|
-
return d;
|
|
1188
|
-
}
|
|
1189
|
-
float clawfish( vec2 p, float t ) {
|
|
1190
|
-
float sway = sin( p.y * 11.0 - t * 2.8 ) * 0.05 * ( 0.4 + 0.6 * smoothstep( 0.3, -0.5, p.y ) );
|
|
1191
|
-
vec2 q = vec2( p.x - sway, p.y );
|
|
1192
|
-
float d = limb( q, vec2( 0.0, 0.42 ), vec2( 0.0, -0.48 ), 0.045, 0.008 );
|
|
1193
|
-
d = min( d, ellipse( q, vec2( 0.0, 0.42 ), vec2( 0.06, 0.07 ) ) );
|
|
1194
|
-
float reach = 0.02 * sin( t * 1.9 );
|
|
1195
|
-
d = min( d, limb( vec2( abs( q.x ), q.y ), vec2( 0.04, 0.34 ), vec2( 0.13, 0.44 + reach ), 0.022, 0.012 ) );
|
|
1196
|
-
d = min( d, limb( vec2( abs( q.x ), q.y ), vec2( 0.13, 0.44 + reach ), vec2( 0.09, 0.5 + reach ), 0.014, 0.006 ) );
|
|
1197
|
-
return d;
|
|
1198
|
-
}
|
|
1199
|
-
void main() {
|
|
1200
|
-
float kind = vMonster.x;
|
|
1201
|
-
float depth = vMonster.y;
|
|
1202
|
-
float t = uTime + vMonster.z * 10.0;
|
|
1203
|
-
float shown = vMonster.w;
|
|
1204
|
-
vec2 p = vLocal + vec2( sin( vLocal.y * 14.0 + uTime * 1.3 ), cos( vLocal.x * 12.0 + uTime * 1.1 ) ) * 0.006 * ( 0.4 + depth );
|
|
1205
|
-
float d = kind < 0.5 ? angler( p, t ) : clawfish( p, t );
|
|
1206
|
-
float blur = mix( 0.008, 0.07, depth );
|
|
1207
|
-
float body = 1.0 - smoothstep( -blur, blur, d );
|
|
1208
|
-
float dark = body * mix( 0.72, 0.0, pow( depth, 0.8 ) ) * shown;
|
|
1209
|
-
float glow = 0.0;
|
|
1210
|
-
if ( kind < 0.5 ) {
|
|
1211
|
-
vec2 lure = vec2( 0.02 * sin( t ), 0.5 );
|
|
1212
|
-
glow = exp( -dot( vLocal - lure, vLocal - lure ) / mix( 0.0004, 0.004, depth ) ) * ( 0.75 + 0.25 * sin( uTime * 3.0 + vMonster.z * 6.0 ) );
|
|
1213
|
-
} else {
|
|
1214
|
-
float along = fract( vLocal.y * 9.0 + vMonster.z );
|
|
1215
|
-
glow = body * smoothstep( 0.4, 0.5, along ) * ( 1.0 - smoothstep( 0.5, 0.6, along ) ) * 0.5 * ( 1.0 - depth );
|
|
1216
|
-
}
|
|
1217
|
-
glow *= shown * mix( 1.0, 0.45, depth );
|
|
1218
|
-
float alpha = clamp( dark + glow, 0.0, 1.0 );
|
|
1219
|
-
if ( alpha < 0.002 ) discard;
|
|
1220
|
-
vec3 color = ( uShadow * dark + uLure * glow * 1.6 ) / max( alpha, 1e-3 );
|
|
1221
|
-
gl_FragColor = vec4( color, alpha );
|
|
1222
|
-
#include <tonemapping_fragment>
|
|
1223
|
-
#include <colorspace_fragment>
|
|
1224
|
-
}
|
|
1225
|
-
`;class j1{constructor(e,t,i,n,r){this.env=i,this.rand=De(n),this.count=Math.max(0,Math.round(t.count??3));const o=t.kinds??["angler","clawfish"],a=new Ut(1,1,16,16);a.rotateX(-Math.PI/2),this.monster=new Ze(new Float32Array(this.count*4),4),this.monster.setUsage(at),a.setAttribute("aMonster",this.monster),this.material=new Ye({uniforms:{...et,uTime:Li.uTime,uShadow:{value:new W(t.shadow??266264)},uLure:{value:new W(t.lure??8060888)}},vertexShader:H1,fragmentShader:U1,transparent:!0,depthWrite:!1}),this.mesh=new zt(a,this.material,this.count),this.mesh.name="sea-monsters",this.mesh.frustumCulled=!1,this.mesh.renderOrder=-5,this.mesh.instanceMatrix.setUsage(at),e.add(this.mesh);const[l,c]=t.size??[24,36];this.monsters=Array.from({length:this.count},(h,d)=>{const u=o[d%o.length];return this.mesh.setMatrixAt(d,Ps),{slot:d,kind:W1[u]??0,size:(l+this.rand()*(c-l))*(u==="clawfish"?1.3:1),seed:this.rand(),phase:"resting",until:4+d*18+this.rand()*8,lane:null}}),this.mesh.instanceMatrix.needsUpdate=!0,this.setTier(r)}_lane(e){const t=this.env.waterLevel,i=(r,o)=>this.env.heightAt(r,o)<t-1.5,n=e.size*.6;for(let r=0;r<60;r++){const o=this.rand()*Math.PI*2,a=70+this.rand()*110,l=Math.cos(o)*a,c=Math.sin(o)*a;if(i(l,c)){for(let h=40;h>=18;h-=6)if(Array.from({length:16},(u,f)=>f/16*Math.PI*2).every(u=>i(l+Math.cos(u)*(h+n),c+Math.sin(u)*(h+n))&&i(l+Math.cos(u)*Math.max(0,h-n),c+Math.sin(u)*Math.max(0,h-n))))return{x:l,z:c,radius:h,angle:this.rand()*Math.PI*2,turn:this.rand()<.5?-1:1,rise:8+this.rand()*3,cruise:14+this.rand()*12,dive:8+this.rand()*3}}}return null}setTier(e){this.active=this.count?Math.max(1,Math.round(this.count*Math.min(1,e))):0;for(let t=this.active;t<this.count;t++)this.mesh.setMatrixAt(t,Ps);this.mesh.instanceMatrix.needsUpdate=!0}update(e,t,i){if(!this.active)return;const n=this.env.waterLevel;for(let r=0;r<this.active;r++){const o=this.monsters[r];if(o.phase==="resting"){if(this.mesh.setMatrixAt(o.slot,Ps),t<o.until)continue;if(o.lane=this._lane(o),!o.lane){o.until=t+20;continue}o.phase="swimming",o.start=t}const a=o.lane,l=t-o.start,c=a.rise+a.cruise+a.dive;if(l>c){o.phase="resting",o.until=t+18+this.rand()*34,this.mesh.setMatrixAt(o.slot,Ps);continue}const h=N.smootherstep(l,0,a.rise),d=N.smootherstep(l,a.rise+a.cruise,c),u=N.clamp(1-(h-d)*.85+Math.sin(l*.5+o.seed*6)*.04,0,1),f=a.angle+a.turn*l*(2.6*i/a.radius),p=f+a.turn*.1,m=a.x+Math.cos(f)*a.radius,g=a.z+Math.sin(f)*a.radius;be.position.set(m,n+.12,g),Ds.set(a.x+Math.cos(p)*a.radius,n+.12,a.z+Math.sin(p)*a.radius),be.lookAt(Ds),be.scale.setScalar(o.size*(1+u*.15)),be.updateMatrix(),this.mesh.setMatrixAt(o.slot,be.matrix),this.monster.setXYZW(o.slot,o.kind,u,o.seed,N.smoothstep(l,0,1.5)*(1-N.smoothstep(l,c-1.5,c)))}this.mesh.instanceMatrix.needsUpdate=!0,this.monster.needsUpdate=!0}dispose(){this.mesh.removeFromParent(),this.mesh.geometry.dispose(),this.material.dispose()}}const q1=[15921128,15769690,7324888],G1=5,Z1=6,Vc=24,X1=7,Do=.85,Nc=4.2,Y1=42,Wc=.3;class Q1{constructor(e,t,i,n,r){this.env=i,this.rand=De(n),this.count=Math.max(0,Math.round(t.count??3));const o=R1();Un(o,this.count,this.rand),this.carry=new Ze(new Float32Array(this.count).fill(1),1),this.carry.setUsage(at),this.rotor=new Ze(new Float32Array(this.count),1),this.rotor.setUsage(at),o.setAttribute("aCarry",this.carry),o.setAttribute("aRotor",this.rotor),this.mats=Wn({name:"drone",drone:!0,accentA:3816772,accentB:13214314,side:Bl,shadow:!0}),this.mesh=Hn(o,this.mats,this.count,"drones",!0),jn(this.mesh,this.count,q1,this.rand,.04),e.add(this.mesh),this.parcels=[],this.parcelMesh=new zt(new Dt(.3,.3,.3),new tt({color:13214314,roughness:.8,metalness:.05}),Vc),this.parcelMesh.count=0,this.parcelMesh.castShadow=!0,this.parcelMesh.frustumCulled=!1,this.parcelMesh.instanceMatrix.setUsage(at),e.add(this.parcelMesh),this.pad={x:0,y:0,z:0},this.door={x:0,y:0,z:0},this.sites=[],this.drones=[],this.pool=[];for(let a=0;a<this.count;a++)this.drones.push({state:"parked",x:0,y:0,z:0,vx:0,vy:0,vz:0,homeX:0,homeZ:0,tx:0,ty:0,tz:0,heading:0,roll:0,pitch:0,throttle:Wc,angle:this.rand()*Math.PI*2,timer:6+this.rand()*19,carry:1,dropped:!1,rippleTimer:0}),this.pool.push({x:0,y:0,z:0,busy:!1});this.info=[],this._placed=!1,this.setTier(r)}setTier(e){this.active=this.count?Math.max(1,Math.round(this.count*e)):0,this.mesh.count=this.active,this.info.length=0;for(let t=0;t<this.active;t++)this.info.push(this.pool[t])}setSites(e,t,i){this.pad.x=e.x,this.pad.y=e.y,this.pad.z=e.z,this.door.x=t.x,this.door.y=t.y,this.door.z=t.z,this.sites=i;const n=Math.atan2(t.x-e.x,t.z-e.z);for(let r=0;r<this.count;r++){const o=this.drones[r],a=n+(r+.5)/this.count*Math.PI*2;o.homeX=e.x+Math.sin(a)*Nc,o.homeZ=e.z+Math.cos(a)*Nc,(o.state==="parked"||o.state==="land")&&(o.x=o.homeX,o.z=o.homeZ,o.y=e.y+Do,o.heading=a+Math.PI,o.state="parked")}this._placed=!0}_release(e){this.parcels.length>=Vc&&this.parcels.shift(),this.parcels.push({x:e.x+(this.rand()-.5)*.2,y:e.y-.75,z:e.z+(this.rand()-.5)*.2,vx:(this.rand()-.5)*.4,vy:0,vz:(this.rand()-.5)*.4,spin:(this.rand()-.5)*6,yaw:this.rand()*Math.PI*2,tilt:0,bounces:0,life:0,landed:!1})}_updateParcels(e,t){const i=this.parcels;let n=0;for(let r=i.length-1;r>=0;r--){const o=i[r];o.life+=e;const a=this.env.parcelSurfaceAt||((c,h)=>({height:this.env.heightAt(c,h)}));y1(o,e,a)&&t?.sound?.("drone-drop",o.x,o.y,o.z);const l=N.clamp((X1-o.life)/1.2,0,1);if(l<=0){i.splice(r,1);continue}be.position.set(o.x,o.y,o.z),be.rotation.set(o.tilt,o.yaw,0),be.scale.setScalar(l),be.updateMatrix(),this.parcelMesh.setMatrixAt(n++,be.matrix)}this.parcelMesh.count=n,this.parcelMesh.instanceMatrix.needsUpdate=!0}_cruiseY(e,t){return Math.max(this.env.heightAt(e,t),C1)+Z1}_pickSite(e){const t=this.sites;if(!t.length)return null;const i=o=>{for(let a=0;a<this.active;a++){const l=this.drones[a];if(l!==e&&l.state!=="parked"&&l.state!=="land"&&l.site===o)return!0}return!1},n=o=>o.length?o[Math.floor(this.rand()*o.length)]:null,r=t.filter(o=>o.active);return n(r.filter(o=>!i(o)))||n(t.filter(o=>!i(o)))||n(r)||n(t)}_dropSpot(e,t){const i=this.rand()*Math.PI*2,n=.4+this.rand()*Math.max(.4,(t.radius||1.4)*.55);e.site=t,e.tx=t.x+Math.cos(i)*n,e.ty=t.y,e.tz=t.z+Math.sin(i)*n}_separate(e,t){t.x=0,t.z=0;for(let i=0;i<this.active;i++){const n=this.drones[i];if(n===e||n.state==="parked")continue;const r=e.x-n.x,o=e.z-n.z,a=r*r+o*o;if(a>6.25||a<1e-4)continue;const l=Math.sqrt(a),c=(1-l/2.5)*2.2;t.x+=r/l*c,t.z+=o/l*c}return t}update(e,t,i,n){const r=this.active;if(!r||!this._placed)return;const o=G1*n,a=this.env.waterLevel;for(let l=0;l<r;l++){const c=this.drones[l];let h=c.y,d=1,u=0,f=0;switch(c.state){case"parked":{if(h=this.pad.y+Do,d=Wc,c.timer-=e,c.timer<=0){const $=this._pickSite(c);$?(this._dropSpot(c,$),c.carry=1,c.dropped=!1,c.state="takeoff"):c.timer=4+this.rand()*6}break}case"takeoff":{h=this._cruiseY(c.x,c.z),c.y>h-.3&&(c.state="cruise");break}case"cruise":case"return":{const $=c.state==="cruise"?c.tx:c.homeX,H=c.state==="cruise"?c.tz:c.homeZ,q=$-c.x,Y=H-c.z,G=Math.hypot(q,Y);if(h=this._cruiseY(c.x,c.z),G<.4)c.state==="cruise"?(c.state="hover",c.timer=3+this.rand()*3,c.hoverT=c.timer):c.state="land";else{const se=Math.min(o,1+G*1.6);u=q/G*se,f=Y/G*se}const ee=this._separate(c,Dc);u+=ee.x,f+=ee.z;break}case"hover":{c.timer-=e;const $=1-c.timer/c.hoverT;h=this._cruiseY(c.x,c.z)-1-Math.sin($*Math.PI)*.6+l%3*.45;const H=this._separate(c,Dc);u=H.x,f=H.z,!c.dropped&&$>.55&&(c.dropped=!0,c.carry=0,this._release(c)),c.timer<=0&&(c.state="return");break}case"land":{h=this.pad.y+Do,c.y<h+.1&&(c.state="parked",c.timer=6+this.rand()*19,c.carry=1);break}}const p=(u-c.vx)*Math.min(1,2.5*e),m=(f-c.vz)*Math.min(1,2.5*e);c.vx+=p,c.vz+=m;const g=c.state==="takeoff"?2.6:c.state==="land"?1.6:2.2,w=N.clamp((h-c.y)*2,-g*n,g*n);c.vy+=(w-c.vy)*Math.min(1,4*e),c.x+=c.vx*e,c.y+=c.vy*e,c.z+=c.vz*e,c.vx*c.vx+c.vz*c.vz>.04&&(c.heading+=Uu(Math.atan2(c.vx,c.vz)-c.heading)*Math.min(1,3*e));const y=Math.sin(c.heading),C=Math.cos(c.heading),_=c.vx*y+c.vz*C,x=e>0?(p*y+m*C)/e:0,T=c.vx*C-c.vz*y,M=e>0?(p*C-m*y)/e:0,k=N.clamp(_*.045+x*.03,-.35,.35),A=N.clamp(T*.045+M*.03,-.35,.35);c.pitch+=(k-c.pitch)*Math.min(1,4*e),c.roll+=(A-c.roll)*Math.min(1,4*e),c.throttle+=(d-c.throttle)*Math.min(1,1.5*e),c.angle+=Y1*c.throttle*n*e,c.angle>1e4&&(c.angle-=1e4),this.rotor.array[l]=c.angle,this.carry.array[l]=c.carry,a!=null&&i?.ripple&&(c.rippleTimer-=e,c.rippleTimer<=0&&c.y-a<2.5&&this.env.heightAt(c.x,c.z)<a&&(c.rippleTimer=.15,i.ripple(c.x,c.z,.35))),be.position.set(c.x,c.y,c.z),be.rotation.set(0,c.heading,0),be.rotateX(c.pitch),be.rotateZ(c.roll),be.scale.set(1,1,1),be.updateMatrix(),this.mesh.setMatrixAt(l,be.matrix);const P=this.pool[l];P.x=c.x,P.y=c.y,P.z=c.z,P.busy=c.state!=="parked"}this.mesh.instanceMatrix.needsUpdate=!0,this.rotor.needsUpdate=!0,this.carry.needsUpdate=!0,this._updateParcels(e,i)}dispose(){this.parcelMesh.removeFromParent(),this.parcelMesh.geometry.dispose(),this.parcelMesh.material.dispose(),this.mesh.removeFromParent(),this.mesh.geometry.dispose(),this.mats.material.dispose(),this.mats.depth?.dispose()}}const Hc=[];class K1{constructor(e,t){this.scene=e,this.settings=t,this.group=new Pt,this.group.name="fauna",e.add(this.group),this.env=null,this.planet=null,this.flock=null,this.meadow=null,this.shoal=null,this.swimmers=null,this.seaMonsters=null,this.fleet=null,this._sites={pad:{x:0,y:0,z:0},door:{x:0,y:0,z:0},sites:[]},this._tier=Bc[t.get("fauna")]??1,this.motion=t.get("reducedMotion")?.5:1,Li.uMotion.value=this.motion}setPlanet(e,t){this._clear(),this.planet=e,this.env=t;const i=e?.fauna;if(!i||!t)return;const n=B1(e.id||e.name||"planet");i.birds&&i.birds.kind!=="none"&&(i.birds.count??14)>0&&(this.flock=new F1(this.group,i.birds,t,n^6941,this._tier)),i.butterflies&&(i.butterflies.count??40)>0&&(this.meadow=new I1(this.group,i.butterflies,t,n^11310,this._tier)),i.fish&&t.waterLevel!=null&&(i.fish.count??10)>0&&(this.shoal=new V1(this.group,i.fish,t,n^15679,this._tier)),i.swimmers&&(t.waterLevel!=null||i.swimmers.above)&&(i.swimmers.count??24)>0&&(this.swimmers=new N1(this.group,i.swimmers,t,n^23132,this._tier)),i.seaMonsters&&t.waterLevel!=null&&(i.seaMonsters.count??3)>0&&(this.seaMonsters=new j1(this.group,i.seaMonsters,t,n^27501,this._tier)),i.drones&&(i.drones.count??3)>0&&(this.fleet=new Q1(this.group,i.drones,t,n^20032,this._tier),this.fleet.setSites(this._sites.pad,this._sites.door,this._sites.sites))}setSites({ship:e,pad:t,sites:i}){const n=this._sites;t&&(n.pad.x=t.x,n.pad.y=t.y,n.pad.z=t.z),e?(n.door.x=e.x,n.door.y=e.y,n.door.z=e.z):t&&(n.door.x=t.x,n.door.y=t.y,n.door.z=t.z+1),n.sites=i||[],this.fleet?.setSites(n.pad,n.door,n.sites)}update(e,t,i,n,r){e=Math.min(e,.1),Li.uTime.value=t;const o=this.motion;this.flock?.update(e,n,r,o),this.meadow&&(this.meadow.mesh.visible=n<.6,this.meadow.mesh.visible&&this.meadow.update(e,i,o)),this.shoal?.update(e,t,r,o),this.swimmers?.update(e,t,o),this.seaMonsters?.update(e,t,o),this.fleet?.update(e,t,r,o)}get drones(){return this.fleet?this.fleet.info:Hc}get birds(){return this.flock?this.flock.info:Hc}onSettingsChanged(e){e.has("fauna")&&(this._tier=Bc[this.settings.get("fauna")]??1,this.flock?.setTier(this._tier),this.meadow?.setTier(this._tier),this.shoal?.setTier(this._tier),this.swimmers?.setTier(this._tier),this.seaMonsters?.setTier(this._tier),this.fleet?.setTier(this._tier)),e.has("reducedMotion")&&(this.motion=this.settings.get("reducedMotion")?.5:1,Li.uMotion.value=this.motion)}_clear(){this.flock?.dispose(),this.meadow?.dispose(),this.shoal?.dispose(),this.swimmers?.dispose(),this.seaMonsters?.dispose(),this.fleet?.dispose(),this.flock=this.meadow=this.shoal=this.swimmers=this.seaMonsters=this.fleet=null}dispose(){this._clear(),this.group.removeFromParent()}}class J1{constructor(e,t){this.buildings=e,this.groundAt=t,this.ray=new $u,this.normal=new F,this.normalMatrix=new Wp,this.hits=[]}at(e,t){const i={height:this.groundAt(e,t),nx:0,ny:1,nz:0};for(const{mesh:n}of this.buildings.values()){const r=n.geometry.boundingBox;if(!r)continue;const o=Math.hypot(Math.max(Math.abs(r.min.x),Math.abs(r.max.x)),Math.max(Math.abs(r.min.z),Math.abs(r.max.z)));if(Math.hypot(e-n.position.x,t-n.position.z)>o+.2)continue;const l=(1-(n.userData.uniforms?.uProgress.value??1))*(r.max.y-r.min.y);n.updateWorldMatrix(!0,!1),this.ray.ray.origin.set(e,n.position.y+r.max.y+1,t),this.ray.ray.direction.set(0,-1,0),this.hits.length=0,this.ray.intersectObject(n,!1,this.hits),this.normalMatrix.getNormalMatrix(n.matrixWorld);for(const c of this.hits){if(n.geometry.getAttribute("aSpin")?.getX(c.face.a)>0)continue;const h=c.point.y-l;h<=i.height||(this.normal.copy(c.face.normal).applyNormalMatrix(this.normalMatrix),!(this.normal.y<.1)&&(i.height=h,i.nx=this.normal.x,i.ny=this.normal.y,i.nz=this.normal.z))}}return i}}const Uc={low:24e3,medium:5e4,high:9e4},jc=6,rr=70,qc=125,e2=.8,Gc=5,t2=9,s2=.26,i2=.9,n2=.5,Vo=s=>Number(s).toFixed(4),r2=`
|
|
1226
|
-
#include <common>
|
|
1227
|
-
// bc:grass-vert
|
|
1228
|
-
attribute float aPhase;
|
|
1229
|
-
attribute float aTint;
|
|
1230
|
-
varying float vHeight;
|
|
1231
|
-
varying float vTint;
|
|
1232
|
-
varying float vFade;
|
|
1233
|
-
uniform float uTime;
|
|
1234
|
-
uniform float uSway;
|
|
1235
|
-
uniform vec2 uWindDir;
|
|
1236
|
-
|
|
1237
|
-
float bcGrassHash( vec2 p ) {
|
|
1238
|
-
return fract( sin( dot( p, vec2( 127.1, 311.7 ) ) ) * 43758.5453 );
|
|
1239
|
-
}
|
|
1240
|
-
// Value noise, -1..1. The slow gust field that rides on top of the travelling wave.
|
|
1241
|
-
float bcGrassNoise( vec2 p ) {
|
|
1242
|
-
vec2 i = floor( p );
|
|
1243
|
-
vec2 f = fract( p );
|
|
1244
|
-
vec2 u = f * f * ( 3.0 - 2.0 * f );
|
|
1245
|
-
float a = bcGrassHash( i );
|
|
1246
|
-
float b = bcGrassHash( i + vec2( 1.0, 0.0 ) );
|
|
1247
|
-
float c = bcGrassHash( i + vec2( 0.0, 1.0 ) );
|
|
1248
|
-
float d = bcGrassHash( i + vec2( 1.0, 1.0 ) );
|
|
1249
|
-
return mix( mix( a, b, u.x ), mix( c, d, u.x ), u.y ) * 2.0 - 1.0;
|
|
1250
|
-
}
|
|
1251
|
-
`,o2=`
|
|
1252
|
-
#include <beginnormal_vertex>
|
|
1253
|
-
// bc:grass-normal
|
|
1254
|
-
// A flat card under a directional light is a hard two-tone. Pulled most of the way to
|
|
1255
|
-
// straight up, every blade takes roughly the light the ground under it takes, and the
|
|
1256
|
-
// field reads as a soft carpet with a little sheen on the tips rather than as slats.
|
|
1257
|
-
objectNormal = normalize( mix( objectNormal, vec3( 0.0, 1.0, 0.0 ), 0.6 ) );
|
|
1258
|
-
`,a2=`
|
|
1259
|
-
#include <begin_vertex>
|
|
1260
|
-
// bc:grass-move
|
|
1261
|
-
{
|
|
1262
|
-
vHeight = uv.y;
|
|
1263
|
-
vTint = aTint;
|
|
1264
|
-
// Where this blade stands, in the world — the wave and the gusts are functions of place.
|
|
1265
|
-
vec3 base = ( modelMatrix * vec4( instanceMatrix[ 3 ].xyz, 1.0 ) ).xyz;
|
|
1266
|
-
vFade = smoothstep( ${Vo(Ol*.8)}, ${Vo(Sn*.36)}, length( base.xz ) );
|
|
1267
|
-
|
|
1268
|
-
float h = length( instanceMatrix[ 1 ].xyz );
|
|
1269
|
-
// Squared so the root stays planted and the bend is a curve rather than a hinge.
|
|
1270
|
-
float bend = uv.y * uv.y;
|
|
1271
|
-
vec2 dir = uWindDir;
|
|
1272
|
-
vec2 perp = vec2( -dir.y, dir.x );
|
|
1273
|
-
// A wave rolling downwind, about twenty-five metres crest to crest, with a slow-drifting
|
|
1274
|
-
// noise field over it so the field gusts in patches instead of pulsing as one.
|
|
1275
|
-
float wave = sin( dot( base.xz, dir ) * 0.25 - uTime * 1.6 + aPhase * 0.7 ) * 0.6
|
|
1276
|
-
+ bcGrassNoise( base.xz * 0.08 + uTime * 0.15 );
|
|
1277
|
-
float gust = 0.55 + 0.45 * wave;
|
|
1278
|
-
// A quicker side-to-side flutter, out of step per blade and along the blade's length.
|
|
1279
|
-
float flutter = sin( uTime * 4.5 + aPhase * 6.2832 + uv.y * 2.0 ) * 0.12;
|
|
1280
|
-
vec2 lean = ( dir * gust + perp * flutter ) * uSway * ${Vo(n2)} * h * bend;
|
|
1281
|
-
|
|
1282
|
-
vec3 d = vec3( lean.x, 0.0, lean.y );
|
|
1283
|
-
vec3 ax = normalize( instanceMatrix[ 0 ].xyz );
|
|
1284
|
-
vec3 az = normalize( instanceMatrix[ 2 ].xyz );
|
|
1285
|
-
transformed.xz += vec2( dot( d, ax ), dot( d, az ) );
|
|
1286
|
-
// A blade that leans is an arc, not a shear: the tip dips by about lean² over twice the
|
|
1287
|
-
// height it leaned from, in the blade's own units. Clamped so an extreme gust flattens
|
|
1288
|
-
// the blade rather than pushing it through the ground.
|
|
1289
|
-
float dip = dot( lean, lean ) * 0.5 / ( max( uv.y, 0.05 ) * h * h );
|
|
1290
|
-
transformed.y -= min( dip, uv.y * 0.5 );
|
|
1291
|
-
}
|
|
1292
|
-
`,l2=`
|
|
1293
|
-
#include <common>
|
|
1294
|
-
// bc:grass-frag
|
|
1295
|
-
varying float vHeight;
|
|
1296
|
-
varying float vTint;
|
|
1297
|
-
varying float vFade;
|
|
1298
|
-
uniform vec3 uRoot;
|
|
1299
|
-
uniform vec3 uTip;
|
|
1300
|
-
uniform vec3 uGlow;
|
|
1301
|
-
`,c2=`
|
|
1302
|
-
#include <color_fragment>
|
|
1303
|
-
// bc:grass-color
|
|
1304
|
-
{
|
|
1305
|
-
// Root to tip, biased toward the root so the bright tip colour is a highlight rather
|
|
1306
|
-
// than half the blade; ±12% brightness per blade; darker still right at the ground so
|
|
1307
|
-
// the base of the field sinks into the terrain instead of floating on it.
|
|
1308
|
-
// Perspective interpolation can put the root a fraction below zero on a grazing
|
|
1309
|
-
// blade. pow(negative, fractional) is NaN, which bloom spreads into black blocks.
|
|
1310
|
-
diffuseColor.rgb = mix( uRoot, uTip, pow( clamp( vHeight, 0.0, 1.0 ), 1.2 ) );
|
|
1311
|
-
diffuseColor.rgb *= 0.88 + 0.24 * vTint;
|
|
1312
|
-
diffuseColor.rgb *= 0.72 + 0.28 * smoothstep( 0.0, 0.3, vHeight );
|
|
1313
|
-
// The terrain darkens toward the horizon so the eye settles on the colony; grass that
|
|
1314
|
-
// stayed bright out there would float above its own ground.
|
|
1315
|
-
diffuseColor.rgb *= 1.0 - vFade * 0.55;
|
|
1316
|
-
totalEmissiveRadiance += uGlow * pow( clamp( vHeight, 0.0, 1.0 ), 3.0 );
|
|
1317
|
-
}
|
|
1318
|
-
`,h2=`
|
|
1319
|
-
#include <normal_fragment_begin>
|
|
1320
|
-
// bc:grass-facing
|
|
1321
|
-
// Three flips a double-sided normal on the back face, which would turn every blade seen
|
|
1322
|
-
// from behind black. A blade has no back: it is lit from above whichever side we see.
|
|
1323
|
-
#ifdef DOUBLE_SIDED
|
|
1324
|
-
normal *= faceDirection;
|
|
1325
|
-
#endif
|
|
1326
|
-
`;function bi(s,e,t){if(!s.includes(e))throw new Error(`grass: shader has no ${e} to patch`);return s.replace(e,t)}function Zc(s,e,t){return s.customProgramCacheKey=()=>t,s.onBeforeCompile=i=>{wt(i),Object.assign(i.uniforms,e),i.vertexShader=bi(i.vertexShader,"#include <common>",r2),i.vertexShader=bi(i.vertexShader,"#include <beginnormal_vertex>",o2),i.vertexShader=bi(i.vertexShader,"#include <begin_vertex>",a2),s.isMeshDepthMaterial||(i.fragmentShader=bi(i.fragmentShader,"#include <common>",l2),i.fragmentShader=bi(i.fragmentShader,"#include <color_fragment>",c2),i.fragmentShader=bi(i.fragmentShader,"#include <normal_fragment_begin>",h2))},s}const Xc=[1,.92,.72,.42];function d2(s){const e=Xc.length,t=[],i=[],n=[];for(let a=0;a<e;a++){const l=a/e,c=s*Xc[a]/2,h=.12*l*l;t.push(-c,l,h,c,l,h),i.push(0,l,1,l)}t.push(0,1,.12),i.push(.5,1);const r=e*2;for(let a=0;a<e-1;a++){const l=a*2;n.push(l,l+1,l+2,l+1,l+3,l+2)}n.push((e-1)*2,(e-1)*2+1,r);const o=new qt;return o.setAttribute("position",new qe(t,3)),o.setAttribute("uv",new qe(i,2)),o.setIndex(n),o.computeVertexNormals(),o}function u2(s){const e=s.grass,t=s.ground||{},i=new W(e.root??t.low??3103284),n=new W(e.tip??t.high??7182922);e.root===void 0&&i.offsetHSL(0,.04,-.05),e.tip===void 0&&n.offsetHSL(0,.04,-.01);const r=Array.isArray(e.height)&&e.height.length===2?e.height:[.25,.55];return{root:i,tip:n,height:r,width:e.width??.085,sway:N.clamp(e.sway??.6,0,1),glow:new W(e.glow??0),patchy:e.patchy??0}}function f2({planet:s,heightAt:e,blocked:t,density:i=1,seed:n=777,quality:r="medium"}){if(!s?.grass)return null;const o=u2(s),a=Math.round((Uc[r]??Uc.medium)*N.clamp(i,0,1));if(a<=0)return null;const l=De(n),c=d2(o.width),h=new Float32Array(a),d=new Float32Array(a),u=new Float32Array(a*16),f=t||(()=>!1),p=s.water?.level,m=p!==void 0?p+(s.shore?.band??0)*.7+.05:-1/0,g=new co,[w,b]=o.height;let y=0;const C=a*3;for(let A=0;A<C&&y<a;A++){const P=l()*Math.PI*2;let $;l()<e2?$=Math.sqrt(N.lerp(jc*jc,rr*rr,l())):$=rr+(qc-rr)*Math.pow(l(),1.6);const H=Math.cos(P)*$,q=Math.sin(P)*$;if(o.patchy&&.5+.25*(Math.sin(H*.21+Math.sin(q*.17)*1.7)+Math.sin(q*.19+Math.sin(H*.13)*1.9))<o.patchy||e(H,q)<m)continue;const G=e(H+.5,q)-e(H-.5,q),ee=e(H,q+.5)-e(H,q-.5);if(Math.hypot(G,ee)>i2)continue;const se=N.smoothstep($,Ol,qc),xe=l(),we=Gc+Math.floor(l()*(t2-Gc+1));for(let U=0;U<we&&y<a;U++){const re=l()*Math.PI*2,Q=Math.sqrt(l())*s2,he=H+Math.cos(re)*Q,Ae=q+Math.sin(re)*Q;if(f(he,Ae))continue;const Ve=e(he,Ae);if(Ve<m)continue;const lt=(w+l()*(b-w))*(1+se*.8),ut=.85+l()*.3;g.position.set(he,Ve-.02,Ae),g.rotation.set(0,l()*Math.PI*2,0),g.scale.set(ut,lt,ut),g.updateMatrix(),g.matrix.toArray(u,y*16),h[y]=l()*Math.PI*2,d[y]=xe*.75+l()*.25,y++}}c.setAttribute("aPhase",new Ze(h,1)),c.setAttribute("aTint",new Ze(d,1));const _={uTime:{value:0},uSway:{value:o.sway*.6},uWindDir:{value:new Se(1,.35).normalize()},uRoot:{value:o.root},uTip:{value:o.tip},uGlow:{value:new W}},x=Zc(new tt({color:16777215,roughness:.85,metalness:0,side:vt,vertexColors:!1}),_,"bc-grass"),T=Zc(new In({depthPacking:Dn}),_,"bc-grass:depth"),M=new zt(c,x,a);M.name="grass",M.instanceMatrix.array.set(u),M.instanceMatrix.needsUpdate=!0,M.count=y,M.customDepthMaterial=T,M.castShadow=!1,M.receiveShadow=!0,M.frustumCulled=!1;let k=0;return{mesh:M,uniforms:_,count:y,update(A,P,$=0){k=P!==void 0?P:k+(A||0),_.uTime.value=k,_.uGlow.value.copy(o.glow).multiplyScalar($)},setWind(A,P,$){_.uSway.value=N.clamp(A??0,0,1)*o.sway,P!==void 0&&$!==void 0&&(P!==0||$!==0)&&_.uWindDir.value.set(P,$).normalize()},dispose(){M.removeFromParent(),c.dispose(),x.dispose(),T.dispose()}}}const Yc={low:{segments:36,rings:[7,4],vines:140,puffs:16,sea:16},medium:{segments:48,rings:[10,6],vines:260,puffs:24,sea:24},high:{segments:64,rings:[13,8],vines:400,puffs:32,sea:32}},qu=2,Gu=8,Zu=2,Xu=50,Qc=400;function p2(s){const e=De(s),t=256,i=new Float32Array(t*t);for(let r=0;r<i.length;r++)i[r]=e()*2-1;const n=(r,o)=>i[(r%t+t)%t*t+(o%t+t)%t];return function(o,a){const l=Math.floor(o),c=Math.floor(a),h=o-l,d=a-c,u=h*h*(3-2*h),f=d*d*(3-2*d);return n(l,c)*(1-u)*(1-f)+n(l+1,c)*u*(1-f)+n(l,c+1)*(1-u)*f+n(l+1,c+1)*u*f}}const Ai=N.smoothstep,qr=N.clamp;function or(s,e,t){if(!s.includes(e))throw new Error(`skyisland: shader anchor ${e} not found`);return s.replace(e,t)}function m2({heightAt:s,rimRadius:e,depth:t,cloudLevel:i,segments:n,rings:r,noise:o,rand:a,palette:l}){const[c,h]=r,d=n,u=i+Xu,f=-t,p=e+qu,m=e+Gu,g=1+c+(h-1),w=g*d+1,b=new Float32Array(w*3),y=new Float32Array(w*3),C=l.rock,_=l.soil.clone().lerp(l.groundLow,.35),x=l.vine.clone().lerp(l.groundLow,.3),T=new W;function M(U,re,Q,he,Ae,Ve,lt){const ut=Math.cos(re),it=Math.sin(re),Ct=Ao(o,ut*2.6+he*.07,it*2.6+he*.13,3),gi=Ao(o,ut*6+31+he*.2,it*6+17-he*.15,2),wi=Math.sin(he*.8+Ct*3),Zi=Math.pow(Math.max(0,wi),6),qs=Math.max(.5,Q+(Ct*2.4+Zi*1.8)*Ve),Gs=he+gi*.6*Ve;b[U*3]=ut*qs,b[U*3+1]=Gs,b[U*3+2]=it*qs;const $o=qr((Ae-Gs)/(Ae+t),0,1);if(lt)T.copy(_);else{T.copy(C).multiplyScalar(.92+(.5+.5*wi)*.16+gi*.1);const mp=1-Ai($o,.06+Ct*.05,.17+Ct*.05);T.lerp(_,mp),T.multiplyScalar(1-$o*.45);const gp=Ao(o,ut*7+50,it*7+Gs*.09+50,2),wp=Ai(gp,.12,.4)*(1-Ai($o,.3,.7))*.75;T.lerp(x,wp)}y[U*3]=T.r,y[U*3+1]=T.g,y[U*3+2]=T.b}for(let U=0;U<d;U++){const re=U/d*Math.PI*2,Q=s(Math.cos(re)*e,Math.sin(re)*e),he=Q-Zu,Ae=e-1.5;M(U,re,Ae,s(Math.cos(re)*Ae,Math.sin(re)*Ae)-.5,Q,0,!0);for(let Ve=0;Ve<c;Ve++){const lt=Ve/(c-1),ut=he+(u-he)*lt,it=p+(m-p)*Math.pow(lt,.55);M((1+Ve)*d+U,re,it,ut,Q,Ai(lt,0,.22))}for(let Ve=1;Ve<h;Ve++){const lt=Ve/h,ut=u+(f-u)*lt,it=m*Math.pow(1-lt*lt,.7);M((1+c+Ve-1)*d+U,re,it,ut,Q,1-lt)}}const k=g*d;b[k*3]=(a()-.5)*2,b[k*3+1]=f,b[k*3+2]=(a()-.5)*2,T.copy(C).multiplyScalar(.5),y[k*3]=T.r,y[k*3+1]=T.g,y[k*3+2]=T.b;const A=[],P=new F,$=new F,H=new F,q=new F,Y=new F,G=new F,ee=(U,re,Q)=>{P.fromArray(b,U*3),$.fromArray(b,re*3),H.fromArray(b,Q*3),q.subVectors($,P),Y.subVectors(H,P),q.cross(Y),G.set(P.x+$.x+H.x,0,P.z+$.z+H.z),G.lengthSq()>.01&&G.normalize(),(P.y+$.y+H.y)/3<u&&(G.y=-1),q.dot(G)<0?A.push(U,Q,re):A.push(U,re,Q)};for(let U=0;U<g-1;U++)for(let re=0;re<d;re++){const Q=(re+1)%d,he=U*d+re,Ae=U*d+Q,Ve=(U+1)*d+re,lt=(U+1)*d+Q;ee(he,Ae,Ve),ee(Ae,lt,Ve)}for(let U=0;U<d;U++)ee((g-1)*d+U,(g-1)*d+(U+1)%d,k);const se=new qt;se.setAttribute("position",new Ue(b,3)),se.setAttribute("color",new Ue(y,3)),se.setIndex(A);const xe=se.toNonIndexed();se.dispose();const we=xe.attributes.color;for(let U=0;U<we.count;U+=3){const re=1+(a()-.5)*.14;for(let Q=0;Q<3;Q++){const he=(we.getComponent(U,Q)+we.getComponent(U+1,Q)+we.getComponent(U+2,Q))/3,Ae=qr(he*re,0,1);we.setComponent(U,Q,Ae),we.setComponent(U+1,Q,Ae),we.setComponent(U+2,Q,Ae)}}return xe.computeVertexNormals(),xe.computeBoundingSphere(),xe}const No=5,Kc=[.72,.84,.96];function g2(){const s=[],e=[],t=[],i=[],n=o=>.16*Math.sin(o*2.6);for(let o=0;o<=No;o++){const a=o/No,l=(.22*(1-.7*a)+.03)/2;if(s.push(-l,-a,n(a),l,-a,n(a)),e.push(a,a),t.push(0,0),o<No){const c=o*2;i.push(c,c+1,c+2,c+1,c+3,c+2)}}for(let o=0;o<Kc.length;o++){const a=Kc[o],l=o*2.1+.4,c=Math.cos(l)*.36,h=Math.sin(l)*.36+n(a),d=-.14,u=-Math.sin(l)*.11,f=Math.cos(l)*.11,p=s.length/3;s.push(0,-a,n(a)),s.push(c*.5+u,-a+d*.5,h*.5+f),s.push(c,-a+d,h),s.push(c*.5-u,-a+d*.5,h*.5-f),e.push(a,a,a,a),t.push(1,1,1,1),i.push(p,p+1,p+2,p,p+2,p+3)}const r=new qt;return r.setAttribute("position",new qe(s,3)),r.setAttribute("aT",new qe(e,1)),r.setAttribute("aLeaf",new qe(t,1)),r.setIndex(i),r.computeVertexNormals(),r}const w2=`
|
|
1327
|
-
#include <common>
|
|
1328
|
-
attribute float aT;
|
|
1329
|
-
attribute float aLeaf;
|
|
1330
|
-
attribute float aPhase;
|
|
1331
|
-
attribute vec3 aShape; // length, thickness, has a leaf tuft
|
|
1332
|
-
uniform float uTime;
|
|
1333
|
-
varying float vT;
|
|
1334
|
-
varying float vLeaf;`,b2=`
|
|
1335
|
-
#include <begin_vertex>
|
|
1336
|
-
vT = aT;
|
|
1337
|
-
vLeaf = aLeaf;
|
|
1338
|
-
// A tuft this instance was not dealt collapses to its anchor and draws nothing.
|
|
1339
|
-
if ( aLeaf > 0.5 && aShape.z < 0.5 ) transformed = vec3( 0.0 );
|
|
1340
|
-
// Length and thickness are per instance but not part of the instance matrix, so the leaves
|
|
1341
|
-
// and the strand's width keep their real size on a long vine and a short one alike.
|
|
1342
|
-
transformed.y -= aT * ( aShape.x - 1.0 );
|
|
1343
|
-
transformed.x *= mix( aShape.y, 1.0, aLeaf );
|
|
1344
|
-
// Sway grows with the square of the distance down the strand: the root stays put, the tip
|
|
1345
|
-
// wanders. Scaled a little by length, or a stub of a root would thrash like a long one.
|
|
1346
|
-
float sway = aT * aT * min( 1.0, aShape.x * 0.18 );
|
|
1347
|
-
transformed.x += sin( uTime * 0.8 + aPhase ) * sway * 0.35;
|
|
1348
|
-
transformed.z += cos( uTime * 0.55 + aPhase * 1.7 ) * sway * 0.16;`,v2=`
|
|
1349
|
-
#include <common>
|
|
1350
|
-
uniform vec3 uLeaf;
|
|
1351
|
-
varying float vT;
|
|
1352
|
-
varying float vLeaf;`,y2=`
|
|
1353
|
-
#include <color_fragment>
|
|
1354
|
-
// Darker where it leaves the rock, its own colour by the tip; leaves in the leaf colour.
|
|
1355
|
-
diffuseColor.rgb *= 0.78 + 0.22 * vT;
|
|
1356
|
-
diffuseColor.rgb = mix( diffuseColor.rgb, uLeaf, vLeaf * 0.85 );`;function Jc(s,e,t,i){return s.customProgramCacheKey=()=>t,s.onBeforeCompile=n=>{wt(n),Object.assign(n.uniforms,e),n.vertexShader=or(or(n.vertexShader,"#include <common>",w2),"#include <begin_vertex>",b2),i&&(n.fragmentShader=or(or(n.fragmentShader,"#include <common>",v2),"#include <color_fragment>",y2))},s}function C2({mesh:s,count:e,rimRadius:t,cloudLevel:i,heightAt:n,rand:r,palette:o}){const a=i+Xu,l=t+qu,c=t+Gu,h=new Float32Array(e),d=new Float32Array(e*3),u=new Float32Array(e*3),f=new xt,p=new F,m=new Fi,g=new Fi,w=new F(1,1,1),b=new F(1,0,0),y=new F(0,1,0),C=new W,_=o.soil.clone().lerp(o.rock,.4);for(let x=0;x<e;x++){const T=r()*Math.PI*2,k=n(Math.cos(T)*t,Math.sin(T)*t)-Zu,A=r()<.4,P=A?.02+r()*.13:.55+r()*.45,$=l+(c-l)*Math.pow(P,.55)-1.5;p.set(Math.cos(T)*$,k+(a-k)*P,Math.sin(T)*$);const H=A?.35+r()*.4:r()*.2;m.setFromAxisAngle(y,Math.PI/2-T),m.multiply(g.setFromAxisAngle(b,-H)),m.multiply(g.setFromAxisAngle(y,(r()-.5)*1.2)),f.compose(p,m,w),s.setMatrixAt(x,f),h[x]=r()*Math.PI*2;const q=4+Math.pow(r(),1.3)*14;d[x*3]=q,d[x*3+1]=.7+r()*.8,d[x*3+2]=!A&&r()<.45?1:0,A||r()<.25?C.copy(_):C.copy(o.vine),C.offsetHSL((r()-.5)*.04,(r()-.5)*.15,(r()-.5)*.14),u[x*3]=C.r,u[x*3+1]=C.g,u[x*3+2]=C.b}s.geometry.setAttribute("aPhase",new Ze(h,1)),s.geometry.setAttribute("aShape",new Ze(d,3)),s.instanceColor=new Ze(u,3),s.instanceMatrix.needsUpdate=!0}const x2=`
|
|
1357
|
-
float cloudHash( vec2 p ) {
|
|
1358
|
-
return fract( sin( dot( p, vec2( 127.1, 311.7 ) ) ) * 43758.5453 );
|
|
1359
|
-
}
|
|
1360
|
-
float cloudNoise( vec2 p ) {
|
|
1361
|
-
vec2 i = floor( p );
|
|
1362
|
-
vec2 f = fract( p );
|
|
1363
|
-
f = f * f * ( 3.0 - 2.0 * f );
|
|
1364
|
-
return mix(
|
|
1365
|
-
mix( cloudHash( i ), cloudHash( i + vec2( 1.0, 0.0 ) ), f.x ),
|
|
1366
|
-
mix( cloudHash( i + vec2( 0.0, 1.0 ) ), cloudHash( i + vec2( 1.0, 1.0 ) ), f.x ),
|
|
1367
|
-
f.y );
|
|
1368
|
-
}
|
|
1369
|
-
float cloudFbm( vec2 p ) {
|
|
1370
|
-
float s = 0.0;
|
|
1371
|
-
float a = 0.5;
|
|
1372
|
-
for ( int i = 0; i < 5; i++ ) {
|
|
1373
|
-
s += cloudNoise( p ) * a;
|
|
1374
|
-
p = p * 2.03 + vec2( 17.0, 9.0 );
|
|
1375
|
-
a *= 0.5;
|
|
1376
|
-
}
|
|
1377
|
-
return s;
|
|
1378
|
-
}`,M2=`
|
|
1379
|
-
#include <common>
|
|
1380
|
-
#include <fog_pars_vertex>
|
|
1381
|
-
varying vec2 vUv;
|
|
1382
|
-
varying vec3 vWorld;
|
|
1383
|
-
void main() {
|
|
1384
|
-
vUv = uv;
|
|
1385
|
-
vec4 world = modelMatrix * vec4( position, 1.0 );
|
|
1386
|
-
vWorld = world.xyz;
|
|
1387
|
-
// The sea projects by hand, so it bends by hand: world position, bent, then the view.
|
|
1388
|
-
vec4 mvPosition = viewMatrix * vec4( bcBend( world.xyz ), 1.0 );
|
|
1389
|
-
gl_Position = projectionMatrix * mvPosition;
|
|
1390
|
-
#include <fog_vertex>
|
|
1391
|
-
}`,k2=`
|
|
1392
|
-
#include <common>
|
|
1393
|
-
#include <fog_pars_fragment>
|
|
1394
|
-
uniform float uTime;
|
|
1395
|
-
uniform vec3 uColor;
|
|
1396
|
-
uniform vec3 uShade;
|
|
1397
|
-
uniform float uLight;
|
|
1398
|
-
uniform float uCore; // radius inside which the sea is solid, in world units
|
|
1399
|
-
uniform float uFade; // radius the sea has fully faded out at
|
|
1400
|
-
varying vec2 vUv;
|
|
1401
|
-
varying vec3 vWorld;
|
|
1402
|
-
${x2}
|
|
1403
|
-
void main() {
|
|
1404
|
-
// Two sheets of noise sliding different ways: a broad slow swell and a finer, quicker
|
|
1405
|
-
// grain over it, so the cover churns rather than scrolling past as one sheet.
|
|
1406
|
-
vec2 p1 = vWorld.xz * 0.016 + uTime * vec2( 0.010, 0.004 );
|
|
1407
|
-
vec2 p2 = vWorld.xz * 0.045 - uTime * vec2( 0.006, 0.009 );
|
|
1408
|
-
float n = cloudFbm( p1 ) * 0.7 + cloudFbm( p2 ) * 0.3;
|
|
1409
|
-
float cover = smoothstep( 0.36, 0.64, n );
|
|
1410
|
-
// Lit from one side: the noise sampled a step toward the light, differenced against
|
|
1411
|
-
// itself, is a cheap slope — bright on the face toward the sun, shaded in the troughs.
|
|
1412
|
-
float lit = clamp( ( cloudFbm( p1 + vec2( 0.06, 0.05 ) ) - cloudFbm( p1 ) ) * 6.0 + 0.62, 0.0, 1.0 );
|
|
1413
|
-
vec3 col = mix( uShade, uColor, lit ) * mix( 0.86, 1.0, cover ) * uLight;
|
|
1414
|
-
// Solid over the island, thinning toward open air — and gone well before the edge.
|
|
1415
|
-
float d = length( vWorld.xz );
|
|
1416
|
-
float open = smoothstep( uCore, uFade, d );
|
|
1417
|
-
float thin = smoothstep( 0.6, 0.8, cloudFbm( vWorld.xz * 0.006 + uTime * 0.002 ) );
|
|
1418
|
-
float alpha = mix( 0.82, 1.0, cover );
|
|
1419
|
-
alpha *= 1.0 - open * thin * 0.75;
|
|
1420
|
-
alpha *= 1.0 - smoothstep( 0.55, 0.98, length( vUv - 0.5 ) * 2.0 );
|
|
1421
|
-
gl_FragColor = vec4( col, alpha );
|
|
1422
|
-
#include <fog_fragment>
|
|
1423
|
-
#include <tonemapping_fragment>
|
|
1424
|
-
#include <colorspace_fragment>
|
|
1425
|
-
}`;function T2(){const t=new Uint8Array(131072),i=[[.5,.5,.4],[.3,.46,.3],[.7,.48,.31],[.42,.66,.25],[.62,.62,.22]];for(let r=0;r<128;r++){const o=(r+.5)/128;for(let a=0;a<256;a++){const l=(a+.5)/256;let c=1;for(const[u,f,p]of i){const m=Math.hypot((l-u)*2,(o-f)*1.9)/(p*2),g=Math.pow(Math.max(0,1-m),1.7);c*=1-g}let h=1-c;h*=Ai(o,.04,.3),h*=1-Ai(Math.hypot((l-.5)*2,(o-.5)*2.2),.72,1);const d=(r*256+a)*4;t[d]=255,t[d+1]=255,t[d+2]=255,t[d+3]=Math.round(qr(h,0,1)*255)}}const n=new Hp(t,256,128,Up,Su);return n.magFilter=qi,n.minFilter=On,n.generateMipmaps=!0,n.needsUpdate=!0,n}const _2=`
|
|
1426
|
-
#include <common>
|
|
1427
|
-
#include <fog_pars_vertex>
|
|
1428
|
-
attribute float aSpin;
|
|
1429
|
-
varying vec2 vUv;
|
|
1430
|
-
varying float vNear;
|
|
1431
|
-
void main() {
|
|
1432
|
-
vUv = uv;
|
|
1433
|
-
// The instance matrix carries where the puff is and how big it is, and nothing else. The
|
|
1434
|
-
// anchor is bent like the ground under it; the quad is then built flat in view space,
|
|
1435
|
-
// turned a little per instance so the same sprite reads as several.
|
|
1436
|
-
mat4 im = modelMatrix * instanceMatrix;
|
|
1437
|
-
vec3 anchor = im[ 3 ].xyz;
|
|
1438
|
-
float size = length( im[ 0 ].xyz );
|
|
1439
|
-
vec4 mvPosition = viewMatrix * vec4( bcBend( anchor ), 1.0 );
|
|
1440
|
-
float c = cos( aSpin );
|
|
1441
|
-
float s = sin( aSpin );
|
|
1442
|
-
mvPosition.xy += vec2( position.x * c - position.y * s, position.x * s + position.y * c ) * size;
|
|
1443
|
-
// A puff the camera flies through fades out rather than clipping into a hard edge.
|
|
1444
|
-
vNear = smoothstep( 6.0, 16.0, -mvPosition.z );
|
|
1445
|
-
gl_Position = projectionMatrix * mvPosition;
|
|
1446
|
-
#include <fog_vertex>
|
|
1447
|
-
}`,S2=`
|
|
1448
|
-
#include <common>
|
|
1449
|
-
#include <fog_pars_fragment>
|
|
1450
|
-
uniform sampler2D uMap;
|
|
1451
|
-
uniform vec3 uColor;
|
|
1452
|
-
uniform vec3 uShade;
|
|
1453
|
-
uniform float uLight;
|
|
1454
|
-
uniform float uOpacity;
|
|
1455
|
-
varying vec2 vUv;
|
|
1456
|
-
varying float vNear;
|
|
1457
|
-
void main() {
|
|
1458
|
-
float a = texture2D( uMap, vUv ).a;
|
|
1459
|
-
// Lit from above: the crown in the cloud colour, the flat underside in the shade.
|
|
1460
|
-
float lit = smoothstep( 0.12, 0.8, vUv.y );
|
|
1461
|
-
vec3 col = mix( uShade, uColor, lit ) * uLight;
|
|
1462
|
-
gl_FragColor = vec4( col, a * vNear * uOpacity );
|
|
1463
|
-
#include <fog_fragment>
|
|
1464
|
-
#include <tonemapping_fragment>
|
|
1465
|
-
#include <colorspace_fragment>
|
|
1466
|
-
}`;function $2({planet:s,heightAt:e,rimRadius:t=58,seed:i=4321,quality:n="medium"}){const r=Yc[n]||Yc.medium,o=s.skyIsland||{},a=o.cloudLevel??-28,l=o.depth??42,c={rock:new W(o.rock??s.rock??7035984),soil:new W(o.soil??5916210),vine:new W(o.vine??5208634),cloud:new W(o.cloud??s.clouds?.color??16777215),groundLow:new W(s.ground?.low??4868690)},h=c.cloud.clone().multiplyScalar(.78).lerp(new W(9413568),.25),d=new Pt;d.name="sky-island";const u=m2({heightAt:e,rimRadius:t,depth:l,cloudLevel:a,segments:r.segments,rings:r.rings,noise:p2(i),rand:De(i^23063),palette:c}),f=new tt({vertexColors:!0,roughness:.95,metalness:0,flatShading:!0,envMapIntensity:.3}),p=new ke(u,f);p.name="sky-island-underside",p.castShadow=!0,p.receiveShadow=!0,d.add(p);const m={uTime:{value:0},uLeaf:{value:c.vine.clone().offsetHSL(.02,.1,.12)}},g=Jc(new tt({color:16777215,roughness:.85,metalness:0,side:vt}),m,"bc-skyisland-vine",!0),w=Jc(new In({depthPacking:Dn,side:vt}),m,"bc-skyisland-vine:depth",!1),b=new zt(g2(),g,r.vines);b.name="sky-island-vines",b.customDepthMaterial=w,b.castShadow=n!=="low",b.receiveShadow=!0,b.frustumCulled=!1,C2({mesh:b,count:r.vines,rimRadius:t,cloudLevel:a,heightAt:e,rand:De(i^29134),palette:c}),d.add(b);const y={...es.merge([Hr.fog]),...et,uTime:{value:0},uColor:{value:c.cloud.clone()},uShade:{value:h.clone()},uLight:{value:1},uCore:{value:t+28},uFade:{value:t+110}},C=new Ye({uniforms:y,vertexShader:M2,fragmentShader:k2,transparent:!0,depthWrite:!1,fog:!0,side:vt}),_=new Ut(Qc,Qc,r.sea,r.sea);_.rotateX(-Math.PI/2);const x=new ke(_,C);x.name="sky-island-cloud-sea",x.position.y=a,x.renderOrder=-20,x.frustumCulled=!1,d.add(x);const T=T2(),M={...es.merge([Hr.fog]),...et,uMap:{value:T},uColor:{value:c.cloud.clone()},uShade:{value:h.clone()},uLight:{value:1},uOpacity:{value:.92}},k=new Ye({uniforms:M,vertexShader:_2,fragmentShader:S2,transparent:!0,depthWrite:!1,fog:!0}),A=r.puffs,P=new zt(new Ut(1,.5),k,A);P.name="sky-island-puffs",P.instanceMatrix.setUsage(at),P.renderOrder=-15,P.frustumCulled=!1;const $=new Float32Array(A),H=new Float32Array(A),q=new Float32Array(A),Y=new Float32Array(A),G=new Float32Array(A),ee=new Float32Array(A),se=new Float32Array(A);{const U=De(i^49421),re=-4,Q=a+4;for(let he=0;he<A;he++){$[he]=U()*Math.PI*2;const Ae=U();H[he]=t+12+Ae*70,q[he]=Q+(re-Q)*Math.pow(U(),.8),Y[he]=6+U()*4+Ae*8,G[he]=(.003+U()*.005)*(U()<.5?1:-1),ee[he]=U()*Math.PI*2,se[he]=(U()-.5)*.5}P.geometry.setAttribute("aSpin",new Ze(se,1))}const xe=new xt,we=U=>{const re=xe.elements;for(let Q=0;Q<A;Q++){const he=$[Q],Ae=H[Q]+Math.sin(U*.11+ee[Q]*1.3)*1.5,Ve=Y[Q];xe.makeTranslation(Math.cos(he)*Ae,q[Q]+Math.sin(U*.25+ee[Q])*.8,Math.sin(he)*Ae),re[0]=Ve,re[5]=Ve,P.setMatrixAt(Q,xe)}P.instanceMatrix.needsUpdate=!0};return we(0),d.add(P),{group:d,meshes:{underside:p,vines:b,sea:x,puffs:P},uniforms:{vines:m,sea:y,puffs:M},setDaylight(U){const re=.18+.82*qr(U,0,1);y.uLight.value=re,M.uLight.value=re},update(U,re){m.uTime.value=re,y.uTime.value=re;for(let Q=0;Q<A;Q++)$[Q]+=G[Q]*U;we(re)},dispose(){d.parent?.remove(d),u.dispose(),f.dispose(),b.geometry.dispose(),g.dispose(),w.dispose(),b.dispose(),_.dispose(),C.dispose(),P.geometry.dispose(),k.dispose(),P.dispose(),T.dispose()}}}const A2=Math.PI/6,Wo={min:9,max:17},eh=[{t:0,r:1.04,lip:1.15},{t:.07,r:1,lip:.95},{t:.18,r:.9,lip:.5},{t:.34,r:.74,lip:.12},{t:.54,r:.52,lip:0},{t:.76,r:.3,lip:0},{t:.93,r:.13,lip:0}],ft=12,Ho=6;function E2({cells:s,cellRadius:e,margin:t=3,seed:i=1717,palette:n={},quality:r="medium"}){const o=new Pt;o.name="hex-island";const a=De(i),l=new W(n.soil??7031346),c=new W(n.rock??8023650),h=new W(n.rock??8023650).multiplyScalar(.55),d=new W(n.moss??5214010),u=n.seam===void 0?null:new W(n.seam),f=n.rough??1,p=n.spikes??1,m=s.reduce((x,T)=>({x:x.x+T.x/s.length,z:x.z+T.z/s.length}),{x:0,z:0}),g=Math.max(1,...s.map(x=>Math.hypot(x.x-m.x,x.z-m.z))),w=[],b=[];for(const x of s){const T=1-Math.hypot(x.x-m.x,x.z-m.z)/(g+e),M=Wo.min+(Wo.max-Wo.min)*(.4+.6*T)*(.85+a()*.3),k=(a()-.5)*.5,A={x:(a()-.5)*.25,z:(a()-.5)*.25};w.push(P2(x,e,t,M,k,A,a,l,c,h,d,u,f));const P=Math.round((1+Math.floor(a()*3)+(T>.55?1:0))*p);for(let $=0;$<P;$++){const H=a()*Math.PI*2,q=a()*e*.5,Y=T*T;w.push(z2(x.x+Math.cos(H)*q,x.z+Math.sin(H)*q,-1-a()*2,-M-2-a()*8-Y*(6+a()*14),(.5+a()*.8)*(1+Y*2.2),a,c,h))}for(let $=0;$<6;$++){const H=Math.PI/3*$+Math.PI/6,q=x.x+Math.cos(H)*e*Math.sqrt(3),Y=x.z+Math.sin(H)*e*Math.sqrt(3);if(!!s.some(se=>Math.hypot(se.x-q,se.z-Y)<e*.6))continue;const ee=2+Math.floor(a()*3);for(let se=0;se<ee;se++){const xe=(a()-.5)*.8,we=x.x+Math.cos(H)*e*.86+Math.cos(H+Math.PI/2)*xe*e,U=x.z+Math.sin(H)*e*.86+Math.sin(H+Math.PI/2)*xe*e;b.push({x:we,z:U,y:-.6-a()*1.4,len:3+Math.pow(a(),1.3)*10,yaw:H})}}}const y=Nt(w,!1);for(const x of w)x.dispose();y.computeVertexNormals();const C=new ke(y,new tt({vertexColors:!0,roughness:.96,metalness:0,flatShading:!0}));C.castShadow=!0,C.receiveShadow=!0,C.name="island-rock",o.add(C);const _=n.vines===!1?null:L2(b,a,n.vine??5214010,r);return _&&o.add(_.mesh),{group:o,update(x,T){_&&(_.uniforms.uTime.value=T)},dispose(){o.removeFromParent(),C.geometry.dispose(),C.material.dispose(),_?.mesh.geometry.dispose(),_?.mesh.material.dispose(),_?.mesh.customDepthMaterial?.dispose()}}}function P2(s,e,t,i,n,r,o,a,l,c,h,d,u){const f=eh.length,p=[],m=[],g=new W;for(let x=0;x<f;x++){const{t:T,r:M,lip:k}=eh[x],A=-.3-i*T,P=x===0?.15:i*.06*u;for(let $=0;$<ft;$++){const H=$/ft*Math.PI*2+A2+n*T,q=$%2===0?1:.9,Y=(e*M+t*k)*q*(1+(o()*.28-.14)*u);p.push(s.x+Math.cos(H)*Y+r.x*i*T,A-o()*P,s.z+Math.sin(H)*Y+r.z*i*T),T<.2?g.copy(a).offsetHSL(0,0,-T*.4):g.copy(l).lerp(c,Math.min(1,(T-.18)*1.3)),T>.05&&T<.4&&o()<.22&&g.lerp(h,.55),d&&T>.1&&T<.32&&g.lerp(d,.7),g.offsetHSL(0,0,(o()-.5)*.08),m.push(g.r,g.g,g.b)}}const w=-.3-i-1.2;p.push(s.x+r.x*i,w,s.z+r.z*i),g.copy(c),m.push(g.r,g.g,g.b);const b=f*ft;p.push(s.x,-.2,s.z),g.copy(a),m.push(g.r,g.g,g.b);const y=b+1,C=[];for(let x=0;x<f-1;x++)for(let T=0;T<ft;T++){const M=x*ft+T,k=x*ft+(T+1)%ft,A=(x+1)*ft+T,P=(x+1)*ft+(T+1)%ft;C.push(M,k,A,k,P,A)}for(let x=0;x<ft;x++){const T=(f-1)*ft+x,M=(f-1)*ft+(x+1)%ft;C.push(T,M,b),C.push(y,(x+1)%ft,x)}const _=new qt;return _.setAttribute("position",new qe(p,3)),_.setAttribute("color",new qe(m,3)),_.setIndex(C),_.toNonIndexed()}function z2(s,e,t,i,n,r,o,a){const l=new Fl(n,t-i,5,3);l.rotateX(Math.PI);const c=l.attributes.position,h=new Float32Array(c.count*3),d=new W,u=t-i,f=(r()-.5)*.25,p=(r()-.5)*.25;for(let m=0;m<c.count;m++){const g=c.getY(m),w=(u/2-g)/u;c.setXYZ(m,c.getX(m)*(1+(r()-.5)*.3)+f*w*u,g,c.getZ(m)*(1+(r()-.5)*.3)+p*w*u),d.copy(o).lerp(a,.3+w*.7),h[m*3]=d.r,h[m*3+1]=d.g,h[m*3+2]=d.b}return l.setAttribute("color",new Ue(h,3)),l.translate(s,(t+i)/2,e),l.deleteAttribute("normal"),l.deleteAttribute("uv"),l.index?l.toNonIndexed():l}function L2(s,e,t,i){const r=[],o=[],a=[];for(let b=0;b<=Ho;b++){const y=b/Ho,C=(.16*(1-.7*y)+.03)/2;if(r.push(-C,-y,0,C,-y,0),o.push(0,y,1,y),b<Ho){const _=b*2;a.push(_,_+2,_+1,_+1,_+2,_+3)}}const l=new qt;l.setAttribute("position",new qe(r,3)),l.setAttribute("uv",new qe(o,2)),l.setAttribute("normal",new qe(new Array(r.length).fill(0).map((b,y)=>y%3===2?1:0),3)),l.setIndex(a);const c=Math.max(1,Math.round(s.length*(i==="low"?.5:1))),h=new Float32Array(c),d={uTime:{value:0}},u=b=>{wt(b),Object.assign(b.uniforms,d),b.vertexShader=b.vertexShader.replace("#include <common>",`#include <common>
|
|
1467
|
-
attribute float aPhase;
|
|
1468
|
-
uniform float uTime;`).replace("#include <begin_vertex>",`#include <begin_vertex>
|
|
1469
|
-
// The top stays tied to the rock; the free end swings, more the further it hangs.
|
|
1470
|
-
float bcT = uv.y;
|
|
1471
|
-
transformed.x += sin( uTime * 0.7 + aPhase ) * bcT * bcT * 0.5;
|
|
1472
|
-
transformed.z += cos( uTime * 0.5 + aPhase * 1.6 ) * bcT * bcT * 0.25;`)},f=new tt({color:t,roughness:.9,metalness:0,side:vt});f.onBeforeCompile=u,f.customProgramCacheKey=()=>"bc-hex-vine";const p=new In({depthPacking:Dn});p.onBeforeCompile=u,p.customProgramCacheKey=()=>"bc-hex-vine:depth";const m=new zt(l,f,c);m.customDepthMaterial=p,m.castShadow=i!=="low",m.frustumCulled=!1,m.name="island-vines";const g=new co,w=new W;for(let b=0;b<c;b++){const y=s[b%s.length];g.position.set(y.x,y.y,y.z),g.rotation.set(0,y.yaw+(e()-.5)*.8,0),g.scale.set(1,y.len,1),g.updateMatrix(),m.setMatrixAt(b,g.matrix),w.set(t).offsetHSL((e()-.5)*.04,(e()-.5)*.15,(e()-.5)*.18),m.setColorAt(b,w),h[b]=e()*Math.PI*2}return l.setAttribute("aPhase",new Ze(h,1)),m.instanceMatrix.needsUpdate=!0,m.instanceColor&&(m.instanceColor.needsUpdate=!0),{mesh:m,uniforms:d}}const R2=`
|
|
1473
|
-
#include <common>
|
|
1474
|
-
#include <fog_pars_vertex>
|
|
1475
|
-
varying vec3 vWorld;
|
|
1476
|
-
void main() {
|
|
1477
|
-
vec4 world = modelMatrix * vec4( position, 1.0 );
|
|
1478
|
-
vWorld = world.xyz;
|
|
1479
|
-
vec4 mvPosition = viewMatrix * vec4( bcBend( world.xyz ), 1.0 );
|
|
1480
|
-
gl_Position = projectionMatrix * mvPosition;
|
|
1481
|
-
#include <fog_vertex>
|
|
1482
|
-
}
|
|
1483
|
-
`,B2=`
|
|
1484
|
-
#include <common>
|
|
1485
|
-
#include <fog_pars_fragment>
|
|
1486
|
-
varying vec3 vWorld;
|
|
1487
|
-
uniform vec3 uColor;
|
|
1488
|
-
uniform float uAmount;
|
|
1489
|
-
uniform float uLight;
|
|
1490
|
-
uniform float uTime;
|
|
1491
|
-
uniform float uOffset;
|
|
1492
|
-
uniform float uClear;
|
|
1493
|
-
uniform float uCentre;
|
|
1494
|
-
|
|
1495
|
-
float mistHash( vec2 p ) { return fract( sin( dot( p, vec2( 127.1, 311.7 ) ) ) * 43758.5453 ); }
|
|
1496
|
-
float mistNoise( vec2 p ) {
|
|
1497
|
-
vec2 i = floor( p ); vec2 f = fract( p ); f = f * f * ( 3.0 - 2.0 * f );
|
|
1498
|
-
return mix( mix( mistHash( i ), mistHash( i + vec2( 1.0, 0.0 ) ), f.x ), mix( mistHash( i + vec2( 0.0, 1.0 ) ), mistHash( i + vec2( 1.0, 1.0 ) ), f.x ), f.y );
|
|
1499
|
-
}
|
|
1500
|
-
float mistFbm( vec2 p ) {
|
|
1501
|
-
float s = 0.0; float a = 0.5;
|
|
1502
|
-
for ( int i = 0; i < 4; i++ ) { s += mistNoise( p ) * a; p = p * 2.07 + 13.0; a *= 0.5; }
|
|
1503
|
-
return s;
|
|
1504
|
-
}
|
|
1505
|
-
|
|
1506
|
-
void main() {
|
|
1507
|
-
vec2 p = vWorld.xz * 0.035 + uOffset;
|
|
1508
|
-
float n = mistFbm( p + uTime * vec2( 0.018, 0.007 ) ) * 0.7 + mistFbm( p * 2.6 - uTime * vec2( 0.011, 0.024 ) ) * 0.3;
|
|
1509
|
-
float a = smoothstep( 0.3, 0.72, n ) * uAmount;
|
|
1510
|
-
a *= mix( uCentre, 1.0, smoothstep( uClear * 0.55, uClear * 1.25, length( vWorld.xz ) ) );
|
|
1511
|
-
a *= smoothstep( 5.0, 22.0, distance( vWorld, cameraPosition ) );
|
|
1512
|
-
a *= 1.0 - smoothstep( ${(Sn*.42).toFixed(1)}, ${(Sn*.5).toFixed(1)}, max( abs( vWorld.x ), abs( vWorld.z ) ) );
|
|
1513
|
-
gl_FragColor = vec4( uColor * uLight, a );
|
|
1514
|
-
#include <fog_fragment>
|
|
1515
|
-
}
|
|
1516
|
-
`;function F2({planet:s,quality:e="medium"}){const t=s.mist;if(!t)return null;const i=e==="low"?2:3,n=new Pt;n.name="mist";const r=new W(t.color),o=new Ut(Sn,Sn,1,1).rotateX(-Math.PI/2),a=[];for(let l=0;l<i;l++){const c=new Ye({uniforms:{...es.merge([Hr.fog]),...et,uColor:{value:r},uAmount:{value:(t.amount??.5)*(1-l*.22)},uLight:{value:1},uTime:{value:0},uOffset:{value:l*7.3},uClear:{value:Ol*(t.clear??.6)},uCentre:{value:t.centre??.35}},vertexShader:R2,fragmentShader:B2,transparent:!0,depthWrite:!1,fog:!0,side:vt});a.push(c);const h=new ke(o,c);h.position.y=(t.base??0)+(l+.5)/i*(t.height??1.6),h.renderOrder=4,h.frustumCulled=!1,n.add(h)}return{mesh:n,update(l,c){const h=N.lerp(t.night??.22,1,c);for(const d of a)d.uniforms.uTime.value=l*(t.speed??1),d.uniforms.uLight.value=h},dispose(){o.dispose();for(const l of a)l.dispose()}}}const O2=560,Uo=260,Yi=18,I2=3,D2=`
|
|
1517
|
-
attribute vec3 aCurtain;
|
|
1518
|
-
uniform float uTime;
|
|
1519
|
-
uniform float uCenter;
|
|
1520
|
-
uniform float uSpan;
|
|
1521
|
-
uniform float uDistance;
|
|
1522
|
-
varying vec2 vCurtain;
|
|
1523
|
-
varying float vRibbon;
|
|
1524
|
-
varying vec3 vNormalWorld;
|
|
1525
|
-
varying vec3 vToEye;
|
|
1526
|
-
vec3 curtainPoint( float s, float v, float ribbon ) {
|
|
1527
|
-
float t = uTime;
|
|
1528
|
-
float phase = ribbon * 2.3;
|
|
1529
|
-
float angle = uCenter + ( s - 0.5 ) * uSpan * ( 1.0 - ribbon * 0.12 );
|
|
1530
|
-
float fold = sin( s * 9.0 + t * 0.11 + phase ) * 0.6 + sin( s * 23.0 - t * 0.17 + phase * 1.7 ) * 0.28 + sin( s * 51.0 + t * 0.29 ) * 0.1;
|
|
1531
|
-
float radial = uDistance * ( 1.0 + ribbon * 0.09 ) + fold * 120.0;
|
|
1532
|
-
float bottom = -0.24 + ribbon * 0.07 + 0.06 * sin( s * 13.0 + t * 0.07 + phase ) + 0.025 * sin( s * 37.0 - t * 0.13 );
|
|
1533
|
-
float top = 0.5 + ribbon * 0.08 + 0.12 * sin( s * 7.0 - t * 0.05 + phase );
|
|
1534
|
-
float lift = mix( bottom, top, v ) * uDistance;
|
|
1535
|
-
return vec3( cos( angle ) * radial, lift, sin( angle ) * radial );
|
|
1536
|
-
}
|
|
1537
|
-
void main() {
|
|
1538
|
-
vec3 here = curtainPoint( aCurtain.x, aCurtain.y, aCurtain.z );
|
|
1539
|
-
vec3 along = curtainPoint( aCurtain.x + 0.002, aCurtain.y, aCurtain.z ) - here;
|
|
1540
|
-
vNormalWorld = normalize( cross( along, vec3( 0.0, 1.0, 0.0 ) ) );
|
|
1541
|
-
vec4 world = modelMatrix * vec4( here, 1.0 );
|
|
1542
|
-
vToEye = cameraPosition - world.xyz;
|
|
1543
|
-
vCurtain = aCurtain.xy;
|
|
1544
|
-
vRibbon = aCurtain.z;
|
|
1545
|
-
gl_Position = projectionMatrix * viewMatrix * world;
|
|
1546
|
-
}
|
|
1547
|
-
`,V2=`
|
|
1548
|
-
#include <common>
|
|
1549
|
-
uniform float uTime;
|
|
1550
|
-
uniform float uFade;
|
|
1551
|
-
varying vec2 vCurtain;
|
|
1552
|
-
varying float vRibbon;
|
|
1553
|
-
varying vec3 vNormalWorld;
|
|
1554
|
-
varying vec3 vToEye;
|
|
1555
|
-
float curtainHash( float n ) { return fract( sin( n * 127.1 ) * 43758.5453 ); }
|
|
1556
|
-
float curtainNoise( float x ) {
|
|
1557
|
-
float i = floor( x );
|
|
1558
|
-
float f = fract( x );
|
|
1559
|
-
return mix( curtainHash( i ), curtainHash( i + 1.0 ), f * f * ( 3.0 - 2.0 * f ) );
|
|
1560
|
-
}
|
|
1561
|
-
void main() {
|
|
1562
|
-
float s = vCurtain.x;
|
|
1563
|
-
float v = vCurtain.y;
|
|
1564
|
-
float t = uTime;
|
|
1565
|
-
float rays = 0.12 + 0.88 * pow( curtainNoise( s * 420.0 + vRibbon * 31.0 + t * 0.35 ), 2.6 );
|
|
1566
|
-
rays *= 0.35 + 0.65 * smoothstep( 0.25, 0.75, curtainNoise( s * 61.0 - t * 0.21 + vRibbon * 7.0 ) );
|
|
1567
|
-
float edge = smoothstep( 0.0, 0.03, v ) * exp( -v * 3.4 );
|
|
1568
|
-
float rim = exp( -pow( ( v - 0.025 ) / 0.03, 2.0 ) ) * 1.4;
|
|
1569
|
-
float ends = smoothstep( 0.0, 0.16, s ) * smoothstep( 1.0, 0.84, s );
|
|
1570
|
-
float pulse = 0.75 + 0.25 * sin( t * 0.6 + s * 18.0 + vRibbon * 2.0 );
|
|
1571
|
-
float edgeOn = 0.55 + 2.4 * pow( 1.0 - abs( dot( normalize( vNormalWorld ), normalize( vToEye ) ) ), 2.5 );
|
|
1572
|
-
vec3 green = vec3( 0.12, 1.0, 0.42 );
|
|
1573
|
-
vec3 violet = vec3( 0.72, 0.22, 0.95 );
|
|
1574
|
-
vec3 color = mix( green, violet, smoothstep( 0.32, 0.75, v ) );
|
|
1575
|
-
float glow = ( edge + rim ) * rays * ends * pulse * edgeOn * ( 1.0 - vRibbon * 0.25 );
|
|
1576
|
-
gl_FragColor = vec4( color * glow * uFade * 0.8, 1.0 );
|
|
1577
|
-
#include <tonemapping_fragment>
|
|
1578
|
-
#include <colorspace_fragment>
|
|
1579
|
-
}
|
|
1580
|
-
`;function N2({sky:s,amount:e=1}){const t=De(9133),i=[],n=[];for(let u=0;u<I2;u++){const f=i.length/3;for(let p=0;p<=Uo;p++)for(let m=0;m<=Yi;m++)i.push(p/Uo,Math.pow(m/Yi,1.6),u);for(let p=0;p<Uo;p++)for(let m=0;m<Yi;m++){const g=f+p*(Yi+1)+m,w=g+Yi+1;n.push(g,w,g+1,g+1,w,w+1)}}const r=new qt;r.setAttribute("aCurtain",new qe(i,3)),r.setAttribute("position",new qe(new Array(i.length).fill(0),3)),r.setIndex(n);const o={uTime:{value:0},uCenter:{value:0},uSpan:{value:N.degToRad(130)},uDistance:{value:O2},uFade:{value:0}},a=new Ye({uniforms:o,vertexShader:D2,fragmentShader:V2,transparent:!0,depthWrite:!1,blending:ji,side:vt,fog:!1}),l=new ke(r,a);l.name="aurora-curtains",l.frustumCulled=!1,l.renderOrder=-800,l.visible=!1;const c=new F,h={from:0,to:0,start:-1/0,length:80};let d=null;return{mesh:l,update(u,f){const p=Math.pow(1-s.domeUniforms.uDay.value,1.5);if(d===null&&(d=u+8),u-h.start>h.length&&u>d&&p>.55&&f){f.getWorldDirection(c);const b=Math.atan2(c.z,c.x),y=t()<.5?-1:1;h.from=b-y*N.degToRad(95),h.to=b+y*N.degToRad(95),h.start=u,h.length=70+t()*30,d=u+h.length+80+t()*120}const g=N.clamp((u-h.start)/h.length,0,1),w=N.smoothstep(g,0,.14)*(1-N.smoothstep(g,.82,1));o.uFade.value=w*p*e,o.uTime.value=u,o.uCenter.value=N.lerp(h.from,h.to,N.smootherstep(g,0,1)),l.visible=o.uFade.value>.002,f&&l.position.copy(f.position)},dispose(){r.dispose(),a.dispose()}}}const W2=`
|
|
1581
|
-
#include <common>
|
|
1582
|
-
attribute vec4 aJet;
|
|
1583
|
-
attribute vec3 aSpan;
|
|
1584
|
-
varying vec2 vUv;
|
|
1585
|
-
varying float vSeed;
|
|
1586
|
-
varying float vFacing;
|
|
1587
|
-
uniform vec3 uSunDir;
|
|
1588
|
-
uniform float uBend;
|
|
1589
|
-
uniform float uLean;
|
|
1590
|
-
void main() {
|
|
1591
|
-
vec3 base = aJet.xyz;
|
|
1592
|
-
vec3 toEye = cameraPosition - base;
|
|
1593
|
-
vec3 side = normalize( vec3( -toEye.z, 0.0, toEye.x ) );
|
|
1594
|
-
vec3 axis = vec3( 0.0, 1.0, 0.0 );
|
|
1595
|
-
if ( uLean > 0.0 ) {
|
|
1596
|
-
vec3 away = -normalize( uSunDir );
|
|
1597
|
-
vec2 drift = normalize( away.xz + vec2( 1e-4 ) );
|
|
1598
|
-
float lift = mix( 0.45, 2.2, smoothstep( -0.3, 0.7, away.y ) );
|
|
1599
|
-
axis = normalize( mix( axis, normalize( vec3( drift.x, lift, drift.y ) ), uLean ) );
|
|
1600
|
-
side = normalize( cross( axis, toEye ) );
|
|
1601
|
-
}
|
|
1602
|
-
float reach = mix( aSpan.y, aSpan.z, pow( position.y, 0.7 ) );
|
|
1603
|
-
vec3 world = base + side * position.x * reach + axis * position.y * aSpan.x;
|
|
1604
|
-
vec3 view = normalize( world - cameraPosition );
|
|
1605
|
-
vFacing = max( dot( view, normalize( uSunDir ) ), 0.0 );
|
|
1606
|
-
vUv = vec2( position.x, position.y );
|
|
1607
|
-
vSeed = aJet.w;
|
|
1608
|
-
gl_Position = projectionMatrix * viewMatrix * vec4( mix( world, bcBend( world ), uBend ), 1.0 );
|
|
1609
|
-
}
|
|
1610
|
-
`,H2=`
|
|
1611
|
-
uniform float uTime;
|
|
1612
|
-
uniform float uSpeed;
|
|
1613
|
-
uniform float uCanopy;
|
|
1614
|
-
uniform vec3 uColor;
|
|
1615
|
-
uniform vec3 uCore;
|
|
1616
|
-
uniform float uDay;
|
|
1617
|
-
uniform float uBright;
|
|
1618
|
-
uniform float uFall;
|
|
1619
|
-
varying vec2 vUv;
|
|
1620
|
-
varying float vSeed;
|
|
1621
|
-
varying float vFacing;
|
|
1622
|
-
float jetHash( vec2 p ) {
|
|
1623
|
-
return fract( sin( dot( p, vec2( 127.1, 311.7 ) ) ) * 43758.5453 );
|
|
1624
|
-
}
|
|
1625
|
-
float jetNoise( vec2 p ) {
|
|
1626
|
-
vec2 i = floor( p );
|
|
1627
|
-
vec2 f = fract( p );
|
|
1628
|
-
f = f * f * ( 3.0 - 2.0 * f );
|
|
1629
|
-
return mix( mix( jetHash( i ), jetHash( i + vec2( 1.0, 0.0 ) ), f.x ), mix( jetHash( i + vec2( 0.0, 1.0 ) ), jetHash( i + vec2( 1.0, 1.0 ) ), f.x ), f.y );
|
|
1630
|
-
}
|
|
1631
|
-
float jetFbm( vec2 p ) {
|
|
1632
|
-
float s = 0.0;
|
|
1633
|
-
float a = 0.5;
|
|
1634
|
-
for ( int i = 0; i < 4; i++ ) {
|
|
1635
|
-
s += jetNoise( p ) * a;
|
|
1636
|
-
p = p * 2.03 + vec2( 17.0, 9.0 );
|
|
1637
|
-
a *= 0.5;
|
|
1638
|
-
}
|
|
1639
|
-
return s;
|
|
1640
|
-
}
|
|
1641
|
-
void main() {
|
|
1642
|
-
float v = vUv.y;
|
|
1643
|
-
float u = vUv.x;
|
|
1644
|
-
float n = jetFbm( vec2( u * 3.0 + vSeed * 13.0, v * 7.0 - uTime * uSpeed + vSeed * 5.0 ) );
|
|
1645
|
-
float span = abs( u ) * mix( 1.0, 2.6, uCanopy * smoothstep( 0.2, 0.75, v ) );
|
|
1646
|
-
float column = 1.0 - smoothstep( 0.15, 0.95, span + ( n - 0.5 ) * 0.5 );
|
|
1647
|
-
float core = 1.0 - smoothstep( 0.0, 0.35, span + ( n - 0.5 ) * 0.25 );
|
|
1648
|
-
float canopy = 0.0;
|
|
1649
|
-
if ( uCanopy > 0.0 ) {
|
|
1650
|
-
vec2 c = vec2( u / 0.78, ( v - 0.8 ) / 0.16 );
|
|
1651
|
-
float shell = length( c ) + ( n - 0.5 ) * 0.35;
|
|
1652
|
-
canopy = smoothstep( 1.0, 0.74, shell ) * smoothstep( 0.3, 0.72, shell ) * smoothstep( -1.25, 0.1, c.y );
|
|
1653
|
-
column *= 1.0 - smoothstep( 0.6, 0.8, v ) * 0.8;
|
|
1654
|
-
}
|
|
1655
|
-
float rise = smoothstep( 0.0, 0.04, v ) * ( 1.0 - smoothstep( mix( mix( 0.55, 0.75, uCanopy ), 0.97, uFall ), mix( 0.97, 0.995, uFall ), v ) );
|
|
1656
|
-
float rim = ( 1.0 - smoothstep( 0.82, 0.98, abs( u ) ) ) * ( 1.0 - smoothstep( 0.93, 0.995, v ) );
|
|
1657
|
-
float alpha = clamp( ( column * ( 0.35 + 0.9 * n ) + core * 0.5 * ( 1.0 - v ) ) * rise + canopy * uCanopy * ( 0.5 + 0.7 * n ), 0.0, 1.0 ) * rim;
|
|
1658
|
-
if ( alpha < 0.01 ) discard;
|
|
1659
|
-
vec3 col = mix( uColor, uCore, core * ( 1.0 - v ) );
|
|
1660
|
-
col *= ( 0.25 + 0.75 * uDay ) * ( 1.0 + vFacing * vFacing * 1.6 ) * uBright;
|
|
1661
|
-
gl_FragColor = vec4( col, alpha * 0.85 );
|
|
1662
|
-
#include <tonemapping_fragment>
|
|
1663
|
-
#include <colorspace_fragment>
|
|
1664
|
-
}
|
|
1665
|
-
`;function ar(s,e,t){if(!e.length)return null;const i=De(3301),n=new Pt,r=[];for(const o of s){const a=e.filter((f,p)=>p%o.every===(o.offset??0));if(!a.length)continue;const l=new Float32Array(a.length*4),c=new Float32Array(a.length*3);a.forEach((f,p)=>{const m=.7+i()*.6;l.set([f.x,f.y-.5,f.z,i()*10],p*4);const g=o.fixed||f.height===void 0;c.set([g?o.height*m:f.height,o.base,o.top*(g?m:1)],p*3)});const h=new Pu().copy(new Ut(2,1,1,16).translate(0,.5,0));h.instanceCount=a.length,h.setAttribute("aJet",new Ze(l,4)),h.setAttribute("aSpan",new Ze(c,3));const d=new Ye({uniforms:{...et,uTime:{value:0},uSpeed:{value:o.speed??.6},uCanopy:{value:o.canopy??0},uColor:{value:new W(o.color)},uCore:{value:new W(o.core??o.color)},uBright:{value:o.bright??1},uBend:{value:o.flat?0:1},uLean:{value:o.lean??0},uFall:{value:o.fall?1:0},uSunDir:t.domeUniforms.uSunDir,uDay:o.glow?{value:1}:t.domeUniforms.uDay},vertexShader:W2,fragmentShader:H2,transparent:!0,depthWrite:!1,side:vt,blending:o.glow?ji:zu,fog:!1}),u=new ke(h,d);u.frustumCulled=!1,u.renderOrder=4,n.add(u),r.push({geometry:h,material:d})}return{mesh:n,update(o){for(const a of r)a.material.uniforms.uTime.value=o},dispose(){for(const o of r)o.geometry.dispose(),o.material.dispose()}}}const Pr=720,xs=[-260,-60,-15,.25,.55,.8,.94,1],U2=`
|
|
1666
|
-
uniform float uTime;
|
|
1667
|
-
uniform float uSwell;
|
|
1668
|
-
varying vec3 vWorld;
|
|
1669
|
-
varying vec3 vColor;
|
|
1670
|
-
void main() {
|
|
1671
|
-
vec4 world = modelMatrix * vec4( position, 1.0 );
|
|
1672
|
-
if ( uSwell > 0.0 && world.y > 0.0 ) {
|
|
1673
|
-
float phase = atan( world.z, world.x ) * 2.0 - uTime * 0.05;
|
|
1674
|
-
float crest = pow( max( 0.0, sin( phase + 0.55 * sin( phase ) ) ), 3.0 );
|
|
1675
|
-
world.y *= 0.05 + 0.95 * crest;
|
|
1676
|
-
}
|
|
1677
|
-
vWorld = world.xyz;
|
|
1678
|
-
vColor = color;
|
|
1679
|
-
gl_Position = projectionMatrix * viewMatrix * world;
|
|
1680
|
-
}
|
|
1681
|
-
`,j2=`
|
|
1682
|
-
attribute vec4 aSpin;
|
|
1683
|
-
uniform float uTime;
|
|
1684
|
-
uniform float uDrift;
|
|
1685
|
-
varying vec3 vWorld;
|
|
1686
|
-
varying vec3 vColor;
|
|
1687
|
-
vec3 turn( vec3 p, vec3 axis, float a ) {
|
|
1688
|
-
return p * cos( a ) + cross( axis, p ) * sin( a ) + axis * dot( axis, p ) * ( 1.0 - cos( a ) );
|
|
1689
|
-
}
|
|
1690
|
-
void main() {
|
|
1691
|
-
vec3 p = turn( position, normalize( aSpin.xyz ), uTime * aSpin.w );
|
|
1692
|
-
vec4 world = modelMatrix * instanceMatrix * vec4( p, 1.0 );
|
|
1693
|
-
float a = uTime * uDrift;
|
|
1694
|
-
world.xz = mat2( cos( a ), -sin( a ), sin( a ), cos( a ) ) * world.xz;
|
|
1695
|
-
vWorld = world.xyz;
|
|
1696
|
-
vColor = color;
|
|
1697
|
-
gl_Position = projectionMatrix * viewMatrix * world;
|
|
1698
|
-
}
|
|
1699
|
-
`,q2=`
|
|
1700
|
-
attribute float aSize;
|
|
1701
|
-
attribute float aShade;
|
|
1702
|
-
uniform float uTime;
|
|
1703
|
-
uniform vec3 uAxis;
|
|
1704
|
-
varying float vShade;
|
|
1705
|
-
varying float vSeed;
|
|
1706
|
-
vec3 turn( vec3 p, vec3 axis, float a ) {
|
|
1707
|
-
return p * cos( a ) + cross( axis, p ) * sin( a ) + axis * dot( axis, p ) * ( 1.0 - cos( a ) );
|
|
1708
|
-
}
|
|
1709
|
-
void main() {
|
|
1710
|
-
vShade = aShade;
|
|
1711
|
-
vSeed = fract( dot( position, vec3( 0.013, 0.027, 0.019 ) ) * 91.0 );
|
|
1712
|
-
vec4 mv = modelViewMatrix * vec4( turn( position, uAxis, uTime * 0.0015 ), 1.0 );
|
|
1713
|
-
gl_PointSize = aSize;
|
|
1714
|
-
gl_Position = projectionMatrix * mv;
|
|
1715
|
-
}
|
|
1716
|
-
`,G2=`
|
|
1717
|
-
uniform vec3 uColor;
|
|
1718
|
-
uniform vec3 uSunDir;
|
|
1719
|
-
uniform vec3 uSunColor;
|
|
1720
|
-
varying float vShade;
|
|
1721
|
-
varying float vSeed;
|
|
1722
|
-
void main() {
|
|
1723
|
-
vec2 d = gl_PointCoord * 2.0 - 1.0;
|
|
1724
|
-
d.y = -d.y;
|
|
1725
|
-
float a = atan( d.y, d.x );
|
|
1726
|
-
float lump = 0.8 + 0.2 * sin( a * 3.0 + vSeed * 40.0 ) * sin( a * 5.0 + vSeed * 17.0 );
|
|
1727
|
-
float r = length( d ) / lump;
|
|
1728
|
-
if ( r > 1.0 ) discard;
|
|
1729
|
-
vec3 n = vec3( d / lump, sqrt( max( 0.0, 1.0 - r * r ) ) );
|
|
1730
|
-
vec3 sun = normalize( ( viewMatrix * vec4( uSunDir, 0.0 ) ).xyz );
|
|
1731
|
-
vec3 col = uColor * vShade * ( 0.22 + uSunColor * max( dot( n, sun ), 0.0 ) * 1.6 );
|
|
1732
|
-
gl_FragColor = vec4( col, 1.0 );
|
|
1733
|
-
#include <tonemapping_fragment>
|
|
1734
|
-
#include <colorspace_fragment>
|
|
1735
|
-
}
|
|
1736
|
-
`,Z2=`
|
|
1737
|
-
attribute vec4 aMist;
|
|
1738
|
-
attribute vec3 aTint;
|
|
1739
|
-
attribute float aPhase;
|
|
1740
|
-
uniform float uTime;
|
|
1741
|
-
uniform float uDrift;
|
|
1742
|
-
varying vec2 vUv;
|
|
1743
|
-
varying vec3 vTint;
|
|
1744
|
-
varying float vSeed;
|
|
1745
|
-
varying float vDepth;
|
|
1746
|
-
void main() {
|
|
1747
|
-
vec3 center = aMist.xyz;
|
|
1748
|
-
center.y += sin( uTime * 0.22 + aPhase ) * 1.4;
|
|
1749
|
-
float a = uTime * uDrift + aPhase * 0.002;
|
|
1750
|
-
center.xz = mat2( cos( a ), -sin( a ), sin( a ), cos( a ) ) * center.xz;
|
|
1751
|
-
vec3 right = vec3( viewMatrix[ 0 ][ 0 ], viewMatrix[ 1 ][ 0 ], viewMatrix[ 2 ][ 0 ] );
|
|
1752
|
-
vec3 up = vec3( viewMatrix[ 0 ][ 1 ], viewMatrix[ 1 ][ 1 ], viewMatrix[ 2 ][ 1 ] );
|
|
1753
|
-
vec4 view = viewMatrix * vec4( center + ( right * position.x * 1.7 + up * position.y ) * aMist.w, 1.0 );
|
|
1754
|
-
vUv = position.xy;
|
|
1755
|
-
vTint = aTint;
|
|
1756
|
-
vSeed = aPhase;
|
|
1757
|
-
vDepth = -view.z;
|
|
1758
|
-
gl_Position = projectionMatrix * view;
|
|
1759
|
-
}
|
|
1760
|
-
`,X2=`
|
|
1761
|
-
uniform float uTime;
|
|
1762
|
-
uniform vec3 uShadow;
|
|
1763
|
-
uniform vec3 uGlow;
|
|
1764
|
-
uniform vec3 uFogColor;
|
|
1765
|
-
uniform float uDay;
|
|
1766
|
-
varying vec2 vUv;
|
|
1767
|
-
varying vec3 vTint;
|
|
1768
|
-
varying float vSeed;
|
|
1769
|
-
varying float vDepth;
|
|
1770
|
-
float mistHash( vec2 p ) {
|
|
1771
|
-
return fract( sin( dot( p, vec2( 127.1, 311.7 ) ) ) * 43758.5453 );
|
|
1772
|
-
}
|
|
1773
|
-
float mistNoise( vec2 p ) {
|
|
1774
|
-
vec2 i = floor( p );
|
|
1775
|
-
vec2 f = fract( p );
|
|
1776
|
-
f = f * f * ( 3.0 - 2.0 * f );
|
|
1777
|
-
return mix( mix( mistHash( i ), mistHash( i + vec2( 1.0, 0.0 ) ), f.x ), mix( mistHash( i + vec2( 0.0, 1.0 ) ), mistHash( i + vec2( 1.0, 1.0 ) ), f.x ), f.y );
|
|
1778
|
-
}
|
|
1779
|
-
float mistFbm( vec2 p ) {
|
|
1780
|
-
float s = 0.0;
|
|
1781
|
-
float a = 0.5;
|
|
1782
|
-
for ( int i = 0; i < 4; i++ ) {
|
|
1783
|
-
s += mistNoise( p ) * a;
|
|
1784
|
-
p = p * 2.03 + vec2( 17.0, 9.0 );
|
|
1785
|
-
a *= 0.5;
|
|
1786
|
-
}
|
|
1787
|
-
return s;
|
|
1788
|
-
}
|
|
1789
|
-
void main() {
|
|
1790
|
-
vec2 p = vUv;
|
|
1791
|
-
float n = mistFbm( p * 1.8 + vSeed * 7.3 + vec2( uTime * 0.012, 0.0 ) );
|
|
1792
|
-
float density = 1.0 - length( p * vec2( 1.05, 1.35 ) ) + ( n - 0.5 ) * 1.1;
|
|
1793
|
-
float alpha = smoothstep( 0.0, 0.5, density ) * ( 1.0 - smoothstep( 0.72, 1.0, max( abs( p.x ), abs( p.y ) ) ) );
|
|
1794
|
-
if ( alpha < 0.01 ) discard;
|
|
1795
|
-
float lit = smoothstep( -0.75, 0.85, p.y + ( n - 0.5 ) * 1.3 );
|
|
1796
|
-
vec3 col = mix( uShadow, vTint, lit );
|
|
1797
|
-
col = mix( col, uGlow, smoothstep( 0.72, 1.0, lit ) * 0.6 );
|
|
1798
|
-
col *= mix( vec3( 0.2, 0.18, 0.32 ), vec3( 1.0 ), uDay );
|
|
1799
|
-
col = mix( col, uFogColor, smoothstep( 160.0, 420.0, vDepth ) * 0.3 );
|
|
1800
|
-
gl_FragColor = vec4( col, alpha * 0.94 );
|
|
1801
|
-
#include <tonemapping_fragment>
|
|
1802
|
-
#include <colorspace_fragment>
|
|
1803
|
-
}
|
|
1804
|
-
`,Y2=`
|
|
1805
|
-
varying vec3 vWorld;
|
|
1806
|
-
varying vec3 vColor;
|
|
1807
|
-
uniform vec3 uColor;
|
|
1808
|
-
uniform vec3 uSnow;
|
|
1809
|
-
uniform float uSnowLine;
|
|
1810
|
-
uniform float uStrata;
|
|
1811
|
-
uniform float uPeak;
|
|
1812
|
-
uniform float uFloor;
|
|
1813
|
-
uniform float uFade;
|
|
1814
|
-
uniform vec3 uFogColor;
|
|
1815
|
-
uniform float uHaze;
|
|
1816
|
-
uniform vec3 uSunDir;
|
|
1817
|
-
uniform vec3 uSunColor;
|
|
1818
|
-
uniform float uDay;
|
|
1819
|
-
uniform vec3 uReach;
|
|
1820
|
-
uniform vec3 uGlow;
|
|
1821
|
-
uniform float uTime;
|
|
1822
|
-
|
|
1823
|
-
void main() {
|
|
1824
|
-
vec3 n = normalize( cross( dFdx( vWorld ), dFdy( vWorld ) ) );
|
|
1825
|
-
if ( dot( n, cameraPosition - vWorld ) < 0.0 ) n = -n;
|
|
1826
|
-
float height = clamp( ( vWorld.y - uFloor ) / uPeak, 0.0, 1.0 );
|
|
1827
|
-
vec3 col = uColor * vColor * ( 1.0 + uStrata * 0.18 * sin( vWorld.y * 0.9 ) );
|
|
1828
|
-
float snow = smoothstep( uSnowLine - 0.04, uSnowLine + 0.04, height + n.y * 0.12 );
|
|
1829
|
-
col = mix( col, uSnow, snow * step( 0.0, uSnowLine ) );
|
|
1830
|
-
float light = max( dot( n, uSunDir ), 0.0 ) * 0.75 + 0.35;
|
|
1831
|
-
col *= mix( vec3( 0.18 ), uSunColor * light, uDay );
|
|
1832
|
-
float haze = clamp( uHaze + ( 1.0 - smoothstep( -0.15, uFade, height ) ) * ( 1.0 - uHaze ), 0.0, 1.0 );
|
|
1833
|
-
haze = max( haze, smoothstep( uReach.x, uReach.y, distance( vWorld, cameraPosition ) ) * uReach.z );
|
|
1834
|
-
col = mix( col, uFogColor, haze );
|
|
1835
|
-
col += uGlow * max( vColor.r - 1.0, 0.0 ) * ( 0.6 + 0.4 * ( 1.0 - uDay ) ) * ( 0.82 + 0.18 * sin( uTime * 3.1 + vWorld.x * 0.7 + vWorld.z * 0.3 ) );
|
|
1836
|
-
gl_FragColor = vec4( col, 1.0 );
|
|
1837
|
-
#include <tonemapping_fragment>
|
|
1838
|
-
#include <colorspace_fragment>
|
|
1839
|
-
}
|
|
1840
|
-
`;function zr(s,e){const t=De(e),i=[3,5,8,13,21,34,55,89].map((o,a)=>({k:o,phase:t()*Math.PI*2,amp:Math.pow(.62,a)})),n=[2,3,5].map(o=>({k:o,phase:t()*Math.PI*2})),r=Array.from({length:11},()=>({theta:t()*Math.PI*2,half:.045+t()*.1,height:.5+t()*.5,spires:t()<.45?2+Math.floor(t()*3):0,dome:t()<.25}));return o=>{let a=0,l=0,c=0;for(const f of i)a+=Math.sin(f.k*o+f.phase)*f.amp,l+=(1-Math.abs(Math.sin(f.k*o+f.phase)))*f.amp,c+=f.amp;a=.5+.5*(a/c),l/=c;const h=n.reduce((f,p)=>f+Math.sin(p.k*o+p.phase),0)/n.length;if(s==="mesas"){const f=N.smoothstep(a,.48,.53),p=N.smoothstep(a,.36,.4)*.35;return Math.max(f,p)*(.92+l*.1)*(h>-.35?1:.25)}if(s==="crags"){const f=Math.pow(Math.abs(Math.sin(o*97+i[0].phase)*Math.sin(o*151+i[1].phase)),6);return(Math.pow(l,1.6)*1.2+f*.35)*(.6+a*.4)}let d=0,u=0;for(const f of i.slice(0,4))d+=Math.sin(f.k*o+f.phase)*f.amp,u+=f.amp;if(d=.5+.5*(d/u),s==="domes")return .25+.75*Math.pow(d,1.8);if(s==="buttes"){let f=.08+.12*d;for(const p of r){const m=Math.abs(Math.atan2(Math.sin(o-p.theta),Math.cos(o-p.theta)))/p.half;if(m>1.7)continue;const g=p.dome?Math.sqrt(Math.max(0,1-m*m)):1-N.smoothstep(m,.8,.95),w=(1-N.smoothstep(m,.95,1.2))*.6,b=(1-N.smoothstep(m,1.1,1.7))*.3,y=p.spires?Math.pow(Math.max(0,Math.cos(m*p.spires*Math.PI)),6)*.28*(1-N.smoothstep(m,.6,.8)):0;f=Math.max(f,p.height*(Math.max(g*(.9+.1*l),w,b)+y))}return f}if(s==="wall")return(.12+.88*N.smoothstep(Math.abs(Math.cos(o-i[0].phase)),.25,.85))*(.88+.12*l);if(s==="cliff"){const f=Math.abs(Math.atan2(Math.sin(o-i[1].phase),Math.cos(o-i[1].phase)));return Math.max(1-N.smoothstep(f,.55,.6),.1*d)*(.9+.1*l)}if(s==="wave")return .85+.15*d;if(s==="treeline"){const f=Math.abs(o*260/Math.PI%2-1);return(.45+.55*d)*(.9+.1*f)}return Math.pow(l,1.4)*(.35+a*.75)}}function Q2(s,e){const t={peaks:zr("peaks",e+3),crags:zr("crags",e+7),rolling:zr("domes",e+11)},i={peaks:a=>.3+.7*t.peaks(a),crags:a=>.2+.5*t.crags(a),plains:a=>.1+.06*t.rolling(a),hills:a=>.12+.2*t.rolling(a),forest:a=>.13+.05*Math.pow(Math.abs(Math.sin(a*240+Math.sin(a*31)*3)),.5)+.05*t.rolling(a)},n=a=>{const l=Math.sin(Math.round(a/(Math.PI*2)*Pr)*12.9898)*43758.5453;return l-Math.floor(l)},r=s.map(a=>({...a,at:N.degToRad(a.at),half:N.degToRad(a.span/2),blend:N.degToRad(a.blend??12),base:new W(a.color),snowColor:a.snow?new W(a.snow.color):null,beacons:(a.beacons??[]).map(l=>N.degToRad(l)),lights:a.lights?{color:new W(a.lights.color).multiplyScalar(a.lights.bright??2),density:a.lights.density??.3}:null,feature:a.feature?{...a.feature,at:N.degToRad(a.feature.at),half:N.degToRad(a.feature.span/2),color:new W(a.feature.color??a.color),glow:a.feature.glow===void 0?null:new W(a.feature.glow).multiplyScalar(a.feature.bright??1.9),light:a.feature.light===void 0?null:new W(a.feature.light).multiplyScalar(a.feature.bright??2),spires:Array.from({length:a.feature.spires??0},(l,c)=>{const h=De(e*17+c*13+Math.round(a.feature.at)),d=1-Math.abs((c+.5)/(a.feature.spires??1)*2-1);return{at:(c+.5)/(a.feature.spires??1)*1.8-.9+(h()-.5)*.08,height:.35+.65*d*(.75+h()*.25),width:.05+h()*.05}}),streams:Array.from({length:a.feature.streams??0},(l,c)=>{const h=De(e*31+c*7+Math.round(a.feature.at));return{at:(h()-.5)*1.1,reach:.35+h()*.4}})}:null})),o=(a,l)=>Math.atan2(Math.sin(a-l),Math.cos(a-l));return a=>{let l=0,c=0;const h=new W(0,0,0);let d=null,u=null,f=!1,p=null;for(const g of r){const w=1-N.smoothstep(Math.abs(o(a,g.at)),g.half,g.half+g.blend);if(!(w<=0)){if(l+=w,c+=w*i[g.shape](a)*g.height,h.r+=g.base.r*w,h.g+=g.base.g*w,h.b+=g.base.b*w,g.snowColor&&w>.5&&(d={color:g.snowColor,line:g.snow.line}),g.feature){const b=o(a,g.feature.at)/g.feature.half;Math.abs(b)<1&&(u={...g.feature,off:Math.abs(b),side:b})}w>.5&&g.beacons.some(b=>Math.abs(o(a,b))<.006)&&(f=!0),w>.5&&g.lights&&n(a)<g.lights.density&&(p=g.lights.color)}}l>0&&(c/=l,h.multiplyScalar(1/l));let m=c;if(u){const g=u;if(g.kind==="city"){const w=Math.ceil((1-g.off)*(g.tiers??6))/(g.tiers??6),b=g.off<.05?.4:0;m=Math.max(c,c*.55+g.height*(w+b))}else if(g.kind==="volcano"){const w=(1-N.smoothstep(g.off,.03,.1))*.05,b=.025*Math.sin(a*1300)*g.off;m=Math.max(c,g.height*Math.pow(1-g.off,1.7)-w+b)}else if(g.kind==="tower"){const w=(1-g.off)*.4,b=g.off<.3?g.off>.12?1.07:.97:0;m=Math.max(c,g.height*Math.max(w,b))}else if(g.kind==="peak")m=Math.max(c,g.height*Math.pow(1-g.off,1.25)*(1+.05*Math.sin(a*900)*g.off));else if(g.kind==="spires"){let w=0;for(const b of g.spires)w=Math.max(w,b.height*Math.pow(Math.max(0,1-Math.abs(g.side-b.at)/b.width),.55));m=Math.max(c,c*.6+g.height*Math.max(w,(1-g.off)*.3))}else if(g.kind==="gate"){const w=g.off>.76?1:.62,b=Math.sin(a*2600)>.2?.035:0;m=Math.max(c,g.height*w+b)}}return{top:m,land:c,color:h,snow:d,feature:u,beacon:f,light:p}}}const K2=new W(16752704).multiplyScalar(2);function J2({kind:s,radius:e,height:t,seed:i,realms:n}){const r=s==="realms"?Q2(n,i):zr(s,i),o=Pr+1,a=new Float32Array(o*xs.length*3),l=new Float32Array(o*xs.length*3).fill(1),c={mesas:.25,domes:2.6,crags:.7,cliff:.05,wave:.9,wall:1.8,buttes:.3,realms:.6}[s]??1.4;let h=0;for(let f=0;f<o;f++){const p=f/Pr*Math.PI*2,m=s==="realms"?r(p):null,g=(m?m.top:r(p))*t;h=Math.max(h,g);for(let w=0;w<xs.length;w++){const b=xs[w],y=b<0?Math.min(b,g):g*b,C=Math.min(Math.max(0,g-y),t*1.2),_=(s==="mesas"||s==="buttes"||m?.feature?.kind==="city")&&y>g*.6,x=e+C*c*(_?.1:1),T=(f*xs.length+w)*3;if(a[T]=Math.cos(p)*x,a[T+1]=y,a[T+2]=Math.sin(p)*x,m){let M=m.color;const k=m.feature;m.snow&&y>m.snow.line*t&&(M=m.snow.color),k?.kind==="city"&&y>m.land*t*.62&&b>0&&(M=k.light&&b>=.94?k.light:k.color),k?.kind==="gate"&&b>0&&(M=k.color),k?.kind==="spires"&&b>0&&y>m.land*t*.6&&(M=k.light&&b>=.94?k.light:k.color),k?.kind==="peak"&&b>0&&!(m.snow&&y>m.snow.line*t)&&(M=k.color),k?.kind==="tower"&&b>0&&(M=k.glow&&k.off<.12&&b>=.94?k.glow:k.color),k?.kind==="volcano"&&k.glow&&b>0&&(k.streams.some(P=>Math.abs(k.side-P.at)<.035&&b>=1-P.reach)||b>=.97&&k.off<.14)&&(M=k.glow),m.beacon&&b===1&&(M=K2),m.light&&b>=.94&&(M=m.light),l.set([M.r,M.g,M.b],T)}}}const d=[];for(let f=0;f<Pr;f++)for(let p=0;p<xs.length-1;p++){const m=f*xs.length+p,g=(f+1)*xs.length+p;d.push(m,g,m+1,g,g+1,m+1)}const u=new qt;return u.setAttribute("position",new Ue(a,3)),u.setAttribute("color",new Ue(l,3)),u.setIndex(d),{geometry:u,peak:h}}function th({count:s,rock:e,top:t,peak:i,mountains:n=!1}){const r=De(4441),o=new W(e),a=new W(t),l=new W(i??e),c=new W,h=[];for(let d=0;d<s;d++){const u=d/s*Math.PI*2+r()*.5,f=n&&r()<.35,p=n?f?70+r()*70:175+r()*160:150+r()*120,m=n?f?4+r()*7:10+r()*26:10+r()*14,g=n?.4+Math.pow(r(),1.5)*2.4:0,w=n?f?-14+r()*40:-36+r()*96:22+r()*36,b=new Il(1,n?3:1),y=b.attributes.position,C=new Float32Array(y.count*3),_=(M,k,A)=>{const P=Math.sin(M*41.3+k*17.1+A*29.7+d)*43758.5453;return P-Math.floor(P)};for(let M=0;M<y.count;M++){const k=y.getX(M),A=y.getY(M),P=y.getZ(M),$=.85+_(k,A,P)*.3,H=A>.2,q=n?.75+.5*Math.abs(Math.sin(Math.atan2(P,k)*5+d)):1,Y=n?Math.pow(Math.max(0,1-Math.hypot(k,P)),1.6)*g*q*(.85+_(k,P,A)*.3):0,G=n?1.25:1.2;if(n&&!H){const se=.62+_(P,A,k)*.76,xe=1+Math.min(0,A)*.62;y.setXYZ(M,k*se*G*xe,A*(2.6+_(A,P,k)*1.6),P*se*G*xe)}else y.setXYZ(M,k*$*G,H?.3+_(P,k,A)*.08+Y:A*$*2.4,P*$*G);const ee=H?Y>g*.4?l:a:c.copy(o).multiplyScalar(n?.72+.28*(1+A)+.08*Math.sin(A*13+d):1);C.set([ee.r,ee.g,ee.b],M*3)}b.setAttribute("color",new Ue(C,3)),b.deleteAttribute("uv"),b.deleteAttribute("normal");const x=[b];for(let M=0;n&&M<4+Math.floor(r()*5);M++){const k=r()*Math.PI*2,A=Math.sqrt(r())*.55,P=1.2+r()*2.2,$=new Fl(.1+r()*.22,P,5).toNonIndexed();$.rotateX(Math.PI),$.rotateZ((r()-.5)*.3),$.translate(Math.cos(k)*A,-.6-P/2,Math.sin(k)*A),$.deleteAttribute("uv"),$.deleteAttribute("normal");const H=new Float32Array($.attributes.position.count*3);for(let q=0;q<$.attributes.position.count;q++)c.copy(o).multiplyScalar(.55+.25*N.clamp(($.attributes.position.getY(q)+.6+P)/P,0,1)),H.set([c.r,c.g,c.b],q*3);$.setAttribute("color",new Ue(H,3)),x.push($)}const T=x.length>1?Nt(x):b;T.scale(m,m,m),T.translate(Math.cos(u)*p,w,Math.sin(u)*p),h.push(T)}return Nt(h)}function eg({count:s,color:e}){const t=De(9001),i=new Il(1,1);i.deleteAttribute("uv"),i.deleteAttribute("normal");const n=i.attributes.position,r=new Float32Array(n.count*3),o=new W(e),a=(m,g,w,b)=>{const y=Math.sin(m*41.3+g*17.1+w*29.7+b)*43758.5453;return y-Math.floor(y)};for(let m=0;m<n.count;m++){const g=n.getX(m),w=n.getY(m),b=n.getZ(m),y=.72+a(g,w,b,1)*.5;n.setXYZ(m,g*y,w*y,b*y);const C=.72+a(g,w,b,2)*.45;r.set([o.r*C,o.g*C,o.b*C],m*3)}i.setAttribute("color",new Ue(r,3));const l=new Float32Array(s*16),c=new Float32Array(s*4),h=new xt,d=new Fi,u=new F,f=new F,p=new F;for(let m=0;m<s;m++){const g=t(),w=g<.22,b=!w&&g<.62,y=t()*Math.PI*2,C=w?75+t()*90:b?175+t()*90:270+t()*70,_=w?18+t()*30:C*Math.tan(N.degToRad(2+Math.pow(t(),1.4)*32)),x=(w?1.2+t()*3.5:b?1+t()*3:3+t()*11)*(t()<.06?2.2:1);u.set(Math.cos(y)*C,_,Math.sin(y)*C),d.setFromEuler(new Ur(t()*Math.PI*2,t()*Math.PI*2,t()*Math.PI*2)),f.set(x*(.7+t()*.6),x*(.6+t()*.5),x*(.8+t()*.7)),h.compose(u,d,f).toArray(l,m*16),p.set(t()-.5,t()-.5,t()-.5).normalize(),c.set([p.x,p.y,p.z,(.05+t()*.25)*(t()<.5?-1:1)],m*4)}return{geometry:i,matrices:l,instanced:{aSpin:[c,4]},count:s}}function tg({count:s,color:e,tilt:t=14,width:i=10,scatter:n=.2},r){const o=De(7717),a=new F(Math.SQRT1_2,0,Math.SQRT1_2),l=N.degToRad(t),c=new F(0,Math.cos(l),0).addScaledVector(a,Math.sin(l)).normalize(),h=new F().crossVectors(c,a).normalize(),d=new F().crossVectors(h,c).normalize(),u=[],f=[],p=[],m=new F,g=N.degToRad(i);for(;f.length<s;){const C=o()*Math.PI*2,_=Math.sqrt(-2*Math.log(Math.max(1e-6,o())))*Math.cos(o()*Math.PI*2),x=o()<n?(o()-.5)*2.2:_*g;if(m.copy(h).multiplyScalar(Math.cos(C)).addScaledVector(d,Math.sin(C)).multiplyScalar(Math.cos(x)).addScaledVector(c,Math.sin(x)),m.y<-.02)continue;u.push(m.x*320,m.y*320,m.z*320);const T=o();f.push(T<.04?8+o()*6:T<.3?4+o()*3:2.2+o()*2),p.push(.6+o()*.6)}const w=new qt;w.setAttribute("position",new qe(u,3)),w.setAttribute("aSize",new qe(f,1)),w.setAttribute("aShade",new qe(p,1));const b=new Ye({uniforms:{uTime:{value:0},uAxis:{value:c},uColor:{value:new W(e)},uSunDir:r.domeUniforms.uSunDir,uSunColor:r.domeUniforms.uSunColor},vertexShader:q2,fragmentShader:G2,depthTest:!1,depthWrite:!1,fog:!1}),y=new Ru(w,b);return y.frustumCulled=!1,y.renderOrder=-998,{points:y,geometry:w,material:b}}function sg({count:s,colors:e,shadow:t=5909614,glow:i=16773328,near:n=45,drift:r=.006},o,a){const l=De(6113),c=e.map(_=>new W(_)),h=new Float32Array(s*4),d=new Float32Array(s*3),u=new Float32Array(s);for(let _=0;_<s;_++){const x=l()*Math.PI*2,T=n+Math.pow(l(),.8)*280,M=T<165?-62+l()*46:-60+Math.pow(l(),.9)*108;h.set([Math.cos(x)*T,M,Math.sin(x)*T,16+l()*18+T/330*26],_*4);const k=c[Math.floor(l()*c.length)];d.set([k.r,k.g,k.b],_*3),u[_]=l()*Math.PI*2}const f=new Pu().copy(new Ut(2,2));f.instanceCount=s;const p={aMist:[h,4],aTint:[d,3],aPhase:[u,1]},m={};for(const[_,[x,T]]of Object.entries(p))m[_]=new Ze(x.slice(),T),m[_].setUsage(at),f.setAttribute(_,m[_]);const g=new Ye({uniforms:{uTime:{value:0},uDrift:{value:r},uShadow:{value:new W(t)},uGlow:{value:new W(i)},uFogColor:{value:a.color},uDay:o.domeUniforms.uDay},vertexShader:Z2,fragmentShader:X2,transparent:!0,depthWrite:!1,fog:!1}),w=new ke(f,g);w.frustumCulled=!1,w.renderOrder=-890;const b=Array.from({length:s},(_,x)=>x),y=new Float32Array(s);return{mesh:w,material:g,geometry:f,sort:(_,x)=>{for(let T=0;T<s;T++){const M=_*r+u[T]*.002,k=h[T*4]*Math.cos(M)-h[T*4+2]*Math.sin(M),A=h[T*4]*Math.sin(M)+h[T*4+2]*Math.cos(M);y[T]=(k-x.x)**2+(h[T*4+1]-x.y)**2+(A-x.z)**2}b.sort((T,M)=>y[M]-y[T]);for(const[T,[M,k]]of Object.entries(p)){const A=m[T].array;for(let P=0;P<s;P++)A.set(M.subarray(b[P]*k,b[P]*k+k),P*k);m[T].needsUpdate=!0}}}}function ig(s,e,t=24){const i=De(2213);return Array.from({length:s},()=>{const n=i()*Math.PI*2,r=t+i()*(154-t),o=Math.cos(n)*r,a=Math.sin(n)*r;return{x:o,y:gt(o,a,e),z:a}})}function ng(s,e){const t=N.degToRad(s.coast.dir),i={x:Math.cos(t),z:Math.sin(t)},n={x:-i.z,z:i.x},r=s.water?.level??0;return e.map(o=>{const a=i.x*(s.coast.far-4)+n.x*o,l=i.z*(s.coast.far-4)+n.z*o,c=gt(a+i.x*8,l+i.z*8,s);return{x:a,y:r,z:l,height:Math.max(4,c-r)}})}function rg({planet:s,sky:e,fog:t}){const i=s.skyline??(s.aurora?{}:null);if(!i)return null;const n=new Pt;n.name="skyline";const r=i.haze??.55,o=i.kind==="realms"?[{radius:340,height:i.height,haze:r,seed:11,tone:1,realms:i.realms}]:[{radius:340,height:i.height,haze:r,seed:11,tone:.9},{radius:275,height:i.height*.55,haze:r*.55,seed:29,tone:1},...i.layers===3?[{radius:230,height:i.height*.42,haze:r*.3,seed:47,tone:.8}]:[]],a=i.kind?o.map(p=>({...p,...J2({kind:i.kind,...p})})):[];i.floaters?.mountains?a.push({geometry:th(i.floaters),peak:400,floor:-200,haze:.02,tone:1,reach:[160,420,.5],color:16777215}):i.floaters&&a.push({geometry:th(i.floaters),peak:20,haze:.14,tone:1}),i.asteroids&&a.push({...eg(i.asteroids),vertex:j2,drift:i.asteroids.drift??.004,peak:1,haze:.1,tone:1,reach:[170,360,.4]});const l=i.clouds?sg(i.clouds,e,t):null;l&&n.add(l.mesh);const c=i.asteroids?.belt?tg(i.asteroids.belt,e):null;c&&n.add(c.points);const h=s.titanic?vc(s,s.titanic):null,d=[i.jets?ar(i.jets,Lu(s),e):null,i.smoke?ar(i.smoke.jets,i.smoke.at.map(([p,m])=>({x:Math.cos(N.degToRad(p))*345,y:m,z:Math.sin(N.degToRad(p))*345})),e):null,i.falls?ar(i.falls.jets,ng(s,i.falls.at),e):null,i.rays?ar(i.rays.jets,ig(i.rays.count,s,i.rays.from),e):null,i.dome?Xe.createDome(i.dome):null,i.lanterns?Xe.createLanterns(i.lanterns):null,i.ceiling?Xe.createCeiling({...i.ceiling,glowing:s.glowing}):null,i.worldTree?Xe.createWorldTree(i.worldTree):null,i.gummyBear?Xe.createGummyBear({...i.gummyBear,sky:e}):null,s.road?Xe.createRoad({path:jp(s),width:s.road.width,brick:s.road.color,mortar:s.road.mortar,heightAt:(p,m)=>gt(p,m,s)}):null,s.wall?Xe.createIceWall({...s.wall,heightAt:(p,m)=>gt(p,m,s)}):null,h?Xe.createTitanic({at:h.center,heading:h.heading,length:s.titanic.length,heightAt:(p,m)=>gt(p,m,s)}):null,s.wreck?Xe.createWreck({...s.wreck,span:vc(s),heightAt:(p,m)=>gt(p,m,s)}):null,s.underglow?Xe.createUnderglow({...s.underglow,center:{x:Math.cos(N.degToRad(s.underglow.theta))*s.underglow.distance,z:Math.sin(N.degToRad(s.underglow.theta))*s.underglow.distance},level:s.water.level}):null,i.nest?Xe.createNest({...i.nest,heightAt:(p,m)=>gt(p,m,s)}):null,i.dragon?Xe.createDragonFlight({...i.dragon,fog:t}):null,s.aurora?N2({sky:e,amount:s.aurora}):null,i.shards?Xe.createShards(i.shards):null,i.rovs?Xe.createRovs({stations:i.rovs,heightAt:(p,m)=>gt(p,m,s)}):null,s.columns?qp({planet:s,heightAt:(p,m)=>gt(p,m,s)}):null,i.ringPlane?Xe.createRingPlane({spec:i.ringPlane,sky:e}):null,i.deck?Xe.createDeck({spec:i.deck,sky:e,fog:t}):null,i.cloudStream?Xe.createCloudStream({spec:i.cloudStream,sky:e,fog:t}):null,i.glassRain?Xe.createGlassRain({spec:i.glassRain,sky:e}):null].filter(Boolean);for(const p of d)n.add(p.mesh);const u={value:0},f=a.map((p,m)=>{const{geometry:g,peak:w}=p,b=new Ye({uniforms:{uTime:u,uSwell:{value:i.kind==="wave"&&!p.instanced?1:0},uDrift:{value:p.drift??0},uFloor:{value:p.floor??0},uFade:{value:i.fade??.55},uColor:{value:new W(p.color??i.color??16777215).multiplyScalar(p.tone)},uSnow:{value:new W(i.snow?.color??16777215)},uSnowLine:{value:i.snow?i.snow.line:-1},uStrata:{value:i.strata??0},uPeak:{value:Math.max(1,w)},uFogColor:{value:t.color},uHaze:{value:p.haze},uSunDir:e.domeUniforms.uSunDir,uSunColor:e.domeUniforms.uSunColor,uDay:e.domeUniforms.uDay,uReach:{value:new F(...p.reach??[0,1,0])},uGlow:{value:new W(i.glow??0)}},vertexShader:p.vertex??U2,fragmentShader:Y2,vertexColors:!0,side:vt,fog:!1});let y;if(p.instanced){for(const[C,[_,x]]of Object.entries(p.instanced))g.setAttribute(C,new Ze(_,x));y=new zt(g,b,p.count),y.instanceMatrix.array.set(p.matrices),y.instanceMatrix.needsUpdate=!0}else y=new ke(g,b);return y.frustumCulled=!1,y.renderOrder=-900+m,n.add(y),{geometry:g,material:b}});return{mesh:n,update(p,m){u.value=p,l&&(l.material.uniforms.uTime.value=p,m&&l.sort(p,m.position)),c&&(c.material.uniforms.uTime.value=p,m&&c.points.position.copy(m.position));for(const g of d)g.update?.(p,m)},dispose(){for(const p of f)p.geometry.dispose(),p.material.dispose();l?.geometry.dispose(),l?.material.dispose(),c?.geometry.dispose(),c?.material.dispose();for(const p of d)p.dispose()}}}const Yu=4;let lr=null,cr=null;function og(s=512){if(lr)return lr;const e=Ri(s),t=Ri(s),i=e.ctx,n=t.ctx;i.fillStyle="#8e9296",i.fillRect(0,0,s,s),n.fillStyle="#808080",n.fillRect(0,0,s,s);const r=2,o=s/r,a=Math.max(2,Math.round(s/170)),l=lg(24301);for(let d=0;d<r;d++)for(let u=0;u<r;u++){const f=138+Math.round((l()-.5)*16);i.fillStyle=`rgb(${f},${f+3},${f+6})`,i.fillRect(d*o+a,u*o+a,o-a*2,o-a*2)}i.strokeStyle="rgba(40,44,50,0.85)",i.lineWidth=a,n.strokeStyle="#3a3a3a",n.lineWidth=a;for(let d=0;d<=r;d++)for(const u of[i,n])u.beginPath(),u.moveTo(d*o,0),u.lineTo(d*o,s),u.moveTo(0,d*o),u.lineTo(s,d*o),u.stroke();const c=Math.max(2,s/150);for(let d=0;d<=r;d++)for(let u=0;u<=r;u++)for(const[f,p]of[[0,0],[o/2,0],[0,o/2]]){const m=(d*o+f)%s,g=(u*o+p)%s;i.fillStyle="rgba(198,203,209,0.85)",hr(i,m,g,c),n.fillStyle="#e8e8e8",hr(n,m,g,c),i.fillStyle="rgba(30,32,38,0.35)",hr(i,m+c*.5,g+c*.5,c*.8)}for(let d=0;d<s/6;d++){const u=l()*s,f=l()*s,p=(.6+l()*2.4)*(s/128);i.fillStyle=l()>.5?"rgba(255,255,255,0.05)":"rgba(0,0,0,0.07)",hr(i,u,f,p)}return lr={map:$n(e.el,Bi),normalMap:Qu(t,1.7),roughnessMap:$n(e.el,ho)},lr}function ag(s=128){if(cr)return cr;const e=s/2,t=Ri(s,e),i=Ri(s,e),n=Ri(s,e),r=e/2;t.ctx.fillStyle="#3c4148",t.ctx.fillRect(0,0,s,r),i.ctx.fillStyle="#000000",i.ctx.fillRect(0,0,s,e),n.ctx.fillStyle="#606060",n.ctx.fillRect(0,0,s,r);const o=6,a=s/o,l=a*.62;for(let c=0;c<o;c++){const h=c*a+(a-l)/2;t.ctx.fillStyle="#e9edf2",t.ctx.fillRect(h,r*.22,l,r*.56),i.ctx.fillStyle="#ffffff",i.ctx.fillRect(h,r*.22,l,r*.56),n.ctx.fillStyle="#d0d0d0",n.ctx.fillRect(h,r*.18,l,r*.64)}return t.ctx.fillStyle="#e6e9ee",t.ctx.fillRect(0,r,s,e-r),n.ctx.fillStyle="#808080",n.ctx.fillRect(0,r,s,e-r),cr={map:$n(t.el,Bi),emissiveMap:$n(i.el,Bi),normalMap:Qu(n,1.1)},cr}const Qi={top:{v0:.04,v1:.46},side:{u:.5,v:.75}};function Ri(s,e=s){const t=document.createElement("canvas");return t.width=s,t.height=e,{el:t,ctx:t.getContext("2d",{willReadFrequently:!0})}}function hr(s,e,t,i){s.beginPath(),s.arc(e,t,i,0,Math.PI*2),s.fill()}function $n(s,e){const t=new Vn(s);return t.wrapS=yc,t.wrapT=yc,t.colorSpace=e,t.anisotropy=8,t}function Qu({ctx:s,el:e},t){const i=e.width,n=e.height,r=s.getImageData(0,0,i,n).data,o=s.createImageData(i,n),a=(c,h)=>r[((h+n)%n*i+(c+i)%i)*4]/255;for(let c=0;c<n;c++)for(let h=0;h<i;h++){const d=a(h-1,c-1)+2*a(h-1,c)+a(h-1,c+1)-(a(h+1,c-1)+2*a(h+1,c)+a(h+1,c+1)),u=a(h-1,c-1)+2*a(h,c-1)+a(h+1,c-1)-(a(h-1,c+1)+2*a(h,c+1)+a(h+1,c+1)),f=d*t,p=u*t,m=Math.hypot(f,p,1),g=(c*i+h)*4;o.data[g]=(f/m*.5+.5)*255,o.data[g+1]=(p/m*.5+.5)*255,o.data[g+2]=1/m*.5*255+127.5,o.data[g+3]=255}const l=Ri(i,n);return l.ctx.putImageData(o,0,0),$n(l.el,ho)}function lg(s){let e=s>>>0;return function(){e=e+1831565813>>>0;let t=e;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}}const zs={uNight:{value:0},uTime:{value:0},uPlanetTint:{value:new W(1,1,1)},uPlanetTintAmount:{value:0}},cg=1.45,Ku=2,jo=1,hg={[_t.WHITE]:[.55,0],[_t.GREY]:[.46,.22],[_t.SLATE]:[.5,.3],[_t.BLACK]:[.6,.18],[_t.ROCK]:[.95,0],[_t.TRIM]:[.42,.08],[_t.RED]:[.55,.04],[_t.SOLAR_A]:[.16,.7],[_t.SOLAR_B]:[.16,.7]},Ei=si.cols*si.rows,Ju=new Float32Array(Ei).fill(.6),e0=new Float32Array(Ei).fill(0);for(const[s,[e,t]]of Object.entries(hg))Ju[s]=e,e0[s]=t;const dg=Bu([_t.TRIM]),ug=Bu([_t.WHITE,_t.GREY,_t.SLATE]);class fg{constructor(){this.parts=[]}add(e,t={}){const i=Iu(e,"base",{solo:t.solo}),n=t.s??1;n!==1&&i.scale(n,n,n),t.ry&&i.rotateY(t.ry),i.translate(t.x||0,t.y||0,t.z||0);const r=i.attributes.position.count;i.setAttribute("aEmissive",new Ue(new Float32Array(r).fill(t.emissive||0),1));const o=t.spin||0,a=new Float32Array(r).fill(o),l=new Float32Array(r*3);if(o)for(let c=0;c<r;c++)l[c*3]=t.x||0,l[c*3+1]=t.y||0,l[c*3+2]=t.z||0;return i.setAttribute("aSpin",new Ue(a,1)),i.setAttribute("aPivot",new Ue(l,3)),this.parts.push(i),this}ring(e,t,i,n,r={}){for(let o=0;o<t;o++){const a=o/t*Math.PI*2+n()*.5,l=i*(.85+n()*.3);this.add(e,{...r,x:Math.cos(a)*l,z:Math.sin(a)*l,ry:a+Math.PI/2})}return this}finish(){const e=Nt(this.parts,!1);for(const t of this.parts)t.dispose();return e.computeBoundingBox(),e}}const Ms=(s,e)=>e[Math.floor(s()*e.length)],Ka={habitat(s,e){return s.add(Ms(e,["basemodule_A","basemodule_B","basemodule_C","basemodule_D"])),s.add(Ms(e,["roofmodule_base","roofmodule_cargo_A","roofmodule_cargo_B"]),{y:jo}),e()>.45&&s.add("lights",{x:1.15,z:.85,s:.85,ry:e()*6.28}),e()>.6&&s.add("containers_A",{x:-1.15,z:.9,ry:e()*6.28}),"Habitat"},solar(s,e){const t=2+Math.floor(e()*2),i=2+Math.floor(e()*2);for(let n=0;n<t;n++)for(let r=0;r<i;r++)s.add("solarpanel",{x:(n-(t-1)/2)*1.05,z:(r-(i-1)/2)*.62,ry:.06*(e()-.5)});return s.add("lights",{x:t*.6,z:-i*.4,s:.8}),s.add("containers_B",{x:-t*.6,z:i*.35,ry:.4}),"Solar array"},antenna(s,e){const t=e()>.3,[i,n]=t?["windturbine_tall",2.05]:["windturbine_low",.89];return s.add(i,{solo:!0}),s.add(`${i}_fan`,{y:n,spin:.17+e()*.09}),s.add("containers_C",{x:.9,z:.75,ry:e()*6.28}),e()>.5&&s.add("lights",{x:-.95,z:-.7,s:.8}),"Relay mast"},silo(s,e){return s.add(Ms(e,["cargodepot_A","cargodepot_B","cargodepot_C"])),e()>.5&&s.add(Ms(e,["cargo_A_stacked","cargo_B_stacked"]),{x:1.35,z:.4,ry:e()*6.28}),"Storage"},greenhouse(s,e){return s.add("basemodule_E"),s.ring("containers_D",2+Math.floor(e()*2),1.45,e),"Greenhouse"},reactor(s,e){return s.add("drill_structure"),s.ring("cargo_A",3,1.35,e),e()>.5&&s.add("lights",{x:-1.2,z:1,s:.9}),"Reactor"},tower(s,e){return s.add("structure_tall"),s.add("lights",{y:2,s:.7}),e()>.5&&s.add("containers_A",{x:1.15,z:.95,ry:e()*6.28}),"Tower"},workshop(s,e){return s.add("basemodule_garage"),s.add("roofmodule_solarpanels",{y:jo}),e()>.3&&s.add(Ms(e,["spacetruck","spacetruck_large"]),{x:1.55,z:.3,ry:Math.PI/2+(e()-.5)*.5}),e()>.5&&s.add("spacetruck_trailer",{x:1.55,z:1.35,ry:Math.PI/2}),"Workshop"},pad(s,e){return s.add(e()>.35?"landingpad_large":"landingpad_small"),e()>.4?s.add(Ms(e,["lander_A","lander_B"]),{y:.5,ry:e()*6.28}):s.add("lander_base",{y:.5,ry:e()*6.28}),"Landing pad"},lab(s,e){return s.add(Ms(e,["basemodule_C","basemodule_A"])),s.add("roofmodule_cargo_C",{y:jo}),s.ring(Ms(e,["containers_B","containers_C"]),2,1.4,e),"Lab"}},sh=Object.keys(Ka);function pg(s,e){return s.onBeforeCompile=t=>{Object.assign(t.uniforms,e),wt(t),t.vertexShader=t.vertexShader.replace("#include <common>",`#include <common>
|
|
1841
|
-
attribute float aEmissive;
|
|
1842
|
-
attribute float aSpin;
|
|
1843
|
-
attribute vec3 aPivot;
|
|
1844
|
-
varying float vEmissive;
|
|
1845
|
-
varying vec2 vAtlasUv;
|
|
1846
|
-
varying float vLocalY;
|
|
1847
|
-
uniform float uProgress;
|
|
1848
|
-
uniform float uMaxY;
|
|
1849
|
-
uniform float uMinY;
|
|
1850
|
-
uniform float uTime;
|
|
1851
|
-
|
|
1852
|
-
// Turn a point about the Z axis through a hub. The pack's rotors are modelled as
|
|
1853
|
-
// vertical discs facing along Z, which is the axis a wind turbine actually turns on.
|
|
1854
|
-
vec3 botSpin( vec3 p, vec3 hub, float angle ) {
|
|
1855
|
-
vec3 r = p - hub;
|
|
1856
|
-
float s = sin( angle );
|
|
1857
|
-
float c = cos( angle );
|
|
1858
|
-
return hub + vec3( r.x * c - r.y * s, r.x * s + r.y * c, r.z );
|
|
1859
|
-
}`).replace("#include <beginnormal_vertex>",`#include <beginnormal_vertex>
|
|
1860
|
-
if ( aSpin > 0.0 ) objectNormal = botSpin( objectNormal, vec3( 0.0 ), uTime * aSpin );`).replace("#include <begin_vertex>",`#include <begin_vertex>
|
|
1861
|
-
vEmissive = aEmissive;
|
|
1862
|
-
// Our own copy of the UV: three renames its map varying between versions, and the
|
|
1863
|
-
// cell lookup below has to survive that.
|
|
1864
|
-
vAtlasUv = uv;
|
|
1865
|
-
if ( aSpin > 0.0 ) transformed = botSpin( transformed, aPivot, uTime * aSpin );
|
|
1866
|
-
// Measured *after* the rotor has turned, so a blade sweeping past the ground line
|
|
1867
|
-
// is revealed and hidden by the same rule as everything else.
|
|
1868
|
-
vLocalY = transformed.y;
|
|
1869
|
-
// The whole structure is lowered into the ground, and the fragment stage throws
|
|
1870
|
-
// away whatever ends up below the deck. What is on screen is therefore always a
|
|
1871
|
-
// *complete* building, part of it buried — never a sliced one.
|
|
1872
|
-
transformed.y -= ( 1.0 - uProgress ) * ( uMaxY - uMinY );`),t.fragmentShader=t.fragmentShader.replace("#include <common>",`#include <common>
|
|
1873
|
-
varying float vEmissive;
|
|
1874
|
-
varying vec2 vAtlasUv;
|
|
1875
|
-
varying float vLocalY;
|
|
1876
|
-
uniform float uProgress;
|
|
1877
|
-
uniform float uMaxY;
|
|
1878
|
-
uniform float uMinY;
|
|
1879
|
-
uniform vec3 uAccent;
|
|
1880
|
-
uniform float uNight;
|
|
1881
|
-
uniform vec3 uPlanetTint;
|
|
1882
|
-
uniform float uPlanetTintAmount;
|
|
1883
|
-
uniform float uCellAccent[ ${Ei} ];
|
|
1884
|
-
uniform float uCellPlanetTint[ ${Ei} ];
|
|
1885
|
-
uniform float uCellRoughness[ ${Ei} ];
|
|
1886
|
-
uniform float uCellMetalness[ ${Ei} ];
|
|
1887
|
-
|
|
1888
|
-
// Which swatch of the 8x4 gradient atlas this fragment landed in.
|
|
1889
|
-
int atlasCell() {
|
|
1890
|
-
int cx = int( clamp( floor( vAtlasUv.x * ${si.cols}.0 ), 0.0, ${si.cols-1}.0 ) );
|
|
1891
|
-
int cy = int( clamp( floor( vAtlasUv.y * ${si.rows}.0 ), 0.0, ${si.rows-1}.0 ) );
|
|
1892
|
-
return cy * ${si.cols} + cx;
|
|
1893
|
-
}`).replace("#include <clipping_planes_fragment>",`#include <clipping_planes_fragment>
|
|
1894
|
-
// Ground level, in the building's own frame, as it sinks. Measured from the
|
|
1895
|
-
// geometry's real floor rather than from zero: a few parts of the kit — a rover's
|
|
1896
|
-
// wheels, a crate's skids — sit a little proud of it, and testing against zero
|
|
1897
|
-
// would cut them off a building that is otherwise finished.
|
|
1898
|
-
float ground = uMinY + ( 1.0 - uProgress ) * ( uMaxY - uMinY );
|
|
1899
|
-
if ( vLocalY < ground - 0.001 ) discard;
|
|
1900
|
-
int cell = atlasCell();`).replace("#include <color_fragment>",`#include <color_fragment>
|
|
1901
|
-
// The planet's own colour on the neutral hull swatches, before the accent gets
|
|
1902
|
-
// its say — same luminance trick, so panels keep their shading as they change.
|
|
1903
|
-
float tintAmount = uCellPlanetTint[ cell ] * uPlanetTintAmount;
|
|
1904
|
-
if ( tintAmount > 0.0 ) {
|
|
1905
|
-
float tintLum = dot( diffuseColor.rgb, vec3( 0.2126, 0.7152, 0.0722 ) );
|
|
1906
|
-
diffuseColor.rgb = mix( diffuseColor.rgb, uPlanetTint * clamp( tintLum * 1.9, 0.3, 1.5 ), tintAmount );
|
|
1907
|
-
}
|
|
1908
|
-
float accentAmount = uCellAccent[ cell ];
|
|
1909
|
-
if ( accentAmount > 0.0 ) {
|
|
1910
|
-
float lum = dot( diffuseColor.rgb, vec3( 0.2126, 0.7152, 0.0722 ) );
|
|
1911
|
-
diffuseColor.rgb = mix( diffuseColor.rgb, uAccent * clamp( lum * 1.9, 0.3, 1.5 ), accentAmount );
|
|
1912
|
-
}`).replace("#include <roughnessmap_fragment>","float roughnessFactor = uCellRoughness[ cell ];").replace("#include <metalnessmap_fragment>","float metalnessFactor = uCellMetalness[ cell ];").replace("#include <emissivemap_fragment>",`#include <emissivemap_fragment>
|
|
1913
|
-
// Lamps and beacons, flagged per vertex when the recipe placed them.
|
|
1914
|
-
totalEmissiveRadiance += diffuseColor.rgb * vEmissive * ( 0.25 + uNight * 2.4 );
|
|
1915
|
-
// Window strips and trim come on after dark, in the repo's own colour.
|
|
1916
|
-
totalEmissiveRadiance += uAccent * uCellAccent[ cell ] * uNight * 1.15;
|
|
1917
|
-
// The construction line: a bright band riding just above the ground it rises from.
|
|
1918
|
-
float band = 1.0 - smoothstep( 0.0, 0.22, vLocalY - ground );
|
|
1919
|
-
totalEmissiveRadiance += uAccent * band * ( 1.0 - step( 0.999, uProgress ) ) * 1.5;`)},s}function mg(s){const e=new In({depthPacking:Dn});return e.onBeforeCompile=t=>{Object.assign(t.uniforms,s),wt(t),t.vertexShader=t.vertexShader.replace("#include <common>",`#include <common>
|
|
1920
|
-
attribute float aSpin;
|
|
1921
|
-
attribute vec3 aPivot;
|
|
1922
|
-
varying float vLocalY;
|
|
1923
|
-
uniform float uProgress;
|
|
1924
|
-
uniform float uMaxY;
|
|
1925
|
-
uniform float uMinY;
|
|
1926
|
-
uniform float uTime;
|
|
1927
|
-
|
|
1928
|
-
vec3 botSpin( vec3 p, vec3 hub, float angle ) {
|
|
1929
|
-
vec3 r = p - hub;
|
|
1930
|
-
float s = sin( angle );
|
|
1931
|
-
float c = cos( angle );
|
|
1932
|
-
return hub + vec3( r.x * c - r.y * s, r.x * s + r.y * c, r.z );
|
|
1933
|
-
}`).replace("#include <begin_vertex>",`#include <begin_vertex>
|
|
1934
|
-
if ( aSpin > 0.0 ) transformed = botSpin( transformed, aPivot, uTime * aSpin );
|
|
1935
|
-
vLocalY = transformed.y;
|
|
1936
|
-
transformed.y -= ( 1.0 - uProgress ) * ( uMaxY - uMinY );`),t.fragmentShader=t.fragmentShader.replace("#include <common>",`#include <common>
|
|
1937
|
-
varying float vLocalY;
|
|
1938
|
-
uniform float uProgress;
|
|
1939
|
-
uniform float uMaxY;
|
|
1940
|
-
uniform float uMinY;`).replace("#include <clipping_planes_fragment>",`#include <clipping_planes_fragment>
|
|
1941
|
-
if ( vLocalY < uMinY + ( 1.0 - uProgress ) * ( uMaxY - uMinY ) - 0.001 ) discard;`)},e}function gg({seed:s=1,accent:e=13198402,kind:t=null}={}){const i=De(s),n=t&&Ka[t]?t:sh[Math.floor(i()*sh.length)],r=new fg,o=Ka[n](r,i,e),a=r.finish();let l=0;const c=a.getAttribute("position");for(let b=0;b<c.count;b++)l=Math.max(l,Math.hypot(c.getX(b),c.getZ(b)));const h=Math.min(cg,Ku/Math.max(l,.001));a.scale(h,h,h);const d=a.getAttribute("aPivot");if(d){for(let b=0;b<d.count*3;b++)d.array[b]*=h;d.needsUpdate=!0}a.computeBoundingBox();const u=a.boundingBox.max.y,f=Math.max(Math.abs(a.boundingBox.max.x),Math.abs(a.boundingBox.min.x),Math.abs(a.boundingBox.max.z),Math.abs(a.boundingBox.min.z)),p={uProgress:{value:1},uMaxY:{value:u},uMinY:{value:a.boundingBox.min.y},uAccent:{value:new W(e)},uNight:zs.uNight,uTime:zs.uTime,uPlanetTint:zs.uPlanetTint,uPlanetTintAmount:zs.uPlanetTintAmount,uCellAccent:{value:dg},uCellPlanetTint:{value:ug},uCellRoughness:{value:Ju},uCellMetalness:{value:e0}},m=pg(new tt({map:Fu(),roughness:.6,metalness:0,emissive:0,side:Bl}),p),g=new ke(a,m);g.castShadow=!0,g.receiveShadow=!0;const w=mg(p);return w.side=Ou,g.customDepthMaterial=w,g.userData.kind=n,g.userData.label=o,g.userData.height=u,g.userData.footprint=f,g.userData.uniforms=p,g.userData.progress=1,g.userData.setProgress=b=>{const y=N.clamp(b,0,1);g.userData.progress=y,p.uProgress.value=y,g.visible=y>.02},g}class wg{constructor(e,t=256){const i=new Ot(.045,.045,1,5);i.translate(0,.5,0),this.mesh=new zt(i,new tt({color:11570514,roughness:.85,flatShading:!0}),t),this.mesh.castShadow=!0,this.mesh.count=0,this.mesh.frustumCulled=!1,this.mesh.instanceMatrix.setUsage(at),e.add(this.mesh),this.scene=e,this.capacity=t,this._dummy=new co}update(e){const t=this._dummy;let i=0;for(const n of e)for(let r=0;r<4&&i<this.capacity;r++){const o=r/4*Math.PI*2+.78,a=n.x+Math.cos(o)*n.radius,l=n.z+Math.sin(o)*n.radius;n.contains&&!n.contains(a,l)||(t.position.set(a,n.y,l),t.rotation.set(0,o,0),t.scale.set(1,Math.max(.4,n.height),1),t.updateMatrix(),this.mesh.setMatrixAt(i++,t.matrix))}this.mesh.count=i,this.mesh.instanceMatrix.needsUpdate=!0}dispose(){this.mesh.geometry.dispose(),this.mesh.material.dispose(),this.scene.remove(this.mesh)}}const At=[[1,0],[1,-1],[0,-1],[-1,0],[-1,1],[0,1]],yt={q:-2,r:1},qn={q:0,r:0},fo=12,$e=(s,e)=>`${s},${e}`;function li(s,e){return(Math.abs(s.q-e.q)+Math.abs(s.q+s.r-e.q-e.r)+Math.abs(s.r-e.r))/2}function bg(s){const e=new Map;for(const[,a]of s)for(const l of a)e.set($e(l.q,l.r),l);if(e.size<2)return!0;const t=$e(yt.q,yt.r),i=new Set([...e.keys(),t]),[n]=e.keys(),r=new Set([n]),o=[e.get(n)];for(;o.length;){const a=o.pop();for(const[l,c]of At){const h={q:a.q+l,r:a.r+c},d=$e(h.q,h.r);!i.has(d)||r.has(d)||(r.add(d),o.push(h))}}return r.delete(t),r.size===e.size}function Wl(s,e,t){return s.map(i=>({q:i.q+e,r:i.r+t}))}function vg(s,e,t=s[0]){const i=(e%6+6)%6;return s.map(n=>{let r=n.q-t.q,o=n.r-t.r;for(let a=0;a<i;a++)[r,o]=[r+o,-r];return{q:r+t.q,r:o+t.r}})}function Hl(s,e,t,{turns:i=0,pivot:n=s[0]}={}){return Wl(vg(s,i,n),e,t)}function yg(s,e,t,i,n){const r=s.get(e);if(!r?.length)return!1;const o=Hl(r,t,i,n),a=new Set;for(const[c,h]of s)if(c!==e)for(const d of h)a.add($e(d.q,d.r));const l=$e(yt.q,yt.r);for(const c of o){const h=$e(c.q,c.r);if(h===l||a.has(h)||li(c,qn)>=fo)return!1}return!0}function Cg(s){const e=new Map;for(const[r,o]of s)for(const a of o)e.set($e(a.q,a.r),r);const t=$e(yt.q,yt.r),i=[],n=new Set;for(const[r]of s){if(n.has(r))continue;const o=new Set([r]);n.add(r);const a=new Set,l=[...s.get(r)||[]];for(const c of l)a.add($e(c.q,c.r));for(;l.length;){const c=l.pop();for(const[h,d]of At){const u={q:c.q+h,r:c.r+d},f=$e(u.q,u.r);if(a.has(f))continue;const p=e.get(f);!p&&f!==t||(a.add(f),p&&!n.has(p)&&(n.add(p),o.add(p)),l.push(u))}}i.push(o)}return i}function xg(s,e){const t=new Set;for(const[i,n]of s)if(i!==e)for(const r of n)t.add($e(r.q,r.r));t.add($e(yt.q,yt.r));for(const i of s.get(e))for(const[n,r]of At)if(t.has($e(i.q+n,i.r+r)))return!0;return!1}function Mg(s){const e=[{dq:0,dr:0}];for(let t=1;t<=s;t++){let i=-t,n=t;for(const[r,o]of At)for(let a=0;a<t;a++)e.push({dq:i,dr:n}),i+=r,n+=o}return e}const kg=Mg(fo*2);function Tg(s,e,t,i,n){if(!yg(s,e,t,i,n))return null;const r=new Map(s);if(r.set(e,Hl(s.get(e),t,i,n)),s.size>1&&!xg(r,e))return null;const o=Cg(r);if(o.length<2)return r;const a=o.find(f=>f.has(e))||o[0],l=o.reduce((f,p)=>p.size>f.size?p:f,o[0]);if(a.size<l.size)return null;const c=o.filter(f=>f!==a).sort((f,p)=>p.size-f.size),h=$e(yt.q,yt.r),d=new Set;for(const f of a)for(const p of r.get(f))d.add($e(p.q,p.r));const u=new Map(r);for(const f of c){const p=[];for(const g of f)for(const w of r.get(g))p.push(w);const m=kg.find(g=>{let w=!1;for(const b of p){const y=b.q+g.dq,C=b.r+g.dr,_=$e(y,C);if(_===h||d.has(_)||li({q:y,r:C},qn)>=fo)return!1;if(!w){for(const[x,T]of At)if(d.has($e(y+x,C+T))){w=!0;break}}}return w});if(!m)return null;for(const g of f){const w=Wl(r.get(g),m.dq,m.dr);u.set(g,w);for(const b of w)d.add($e(b.q,b.r))}}return u}const Ti=[13198402,5216867,5209801,12096554,9133257,13193099,4171936,13205327,7311183,6062025,13196380,8351689],ts=7.6,pt=ts,hs=ts*.992,$t=.45,_g=.4,qo=$t+_g,Sg=1.6,$g=.55,t0=7,s0=9,Ag=t0*s0,i0=[0,5,4,3,2,1];function Vi(s,e,t=ts){return{x:t*1.5*s,z:t*Math.sqrt(3)*(e+s/2)}}function n0(s,e=$t){const t=[];for(const i of s){const{x:n,z:r}=Vi(i.q,i.r);for(let o=0;o<6;o++){const a=o*Math.PI/3;t.push(new F(n+ts*Math.cos(a),e,r+ts*Math.sin(a)))}}return t}function Cn(s,e,t=ts){const i=s/(t*1.5),n=e/(t*Math.sqrt(3))-i/2;return Eg(i,n)}function Eg(s,e){const t=-s-e;let i=Math.round(s),n=Math.round(e);const r=Math.round(t),o=Math.abs(i-s),a=Math.abs(n-e),l=Math.abs(r-t);return o>a&&o>l?i=-n-r:a>l&&(n=-i-r),{q:i,r:n}}function Pg(s){if(s===0)return[{q:0,r:0}];const e=[];let t=At[4][0]*s,i=At[4][1]*s;for(let n=0;n<6;n++)for(let r=0;r<s;r++)e.push({q:t,r:i}),t+=At[n][0],i+=At[n][1];return e}const ih=s=>Math.max(1,Math.min(s0,Math.ceil(s/t0)));function zg(s,e=new Map){const t=nh(s,e);return bg(t)?t:nh(s,new Map)}function nh(s,e){const t=$e(yt.q,yt.r),i=s.map(f=>{const p=e.get(f.id);let m=ih(f.size);return p&&p.length>m&&(m=Math.min(p.length,ih(f.size+3))),{id:f.id,want:m,org:f.org||null}}),n=i.reduce((f,p)=>f+p.want,0),r=[],o=new Set;let a=0;for(const f of s)for(const p of e.get(f.id)||[])a=Math.max(a,li(p,qn));for(let f=0;(r.length<n+30||f<=a)&&f<fo;f++)for(const p of Pg(f)){const m=$e(p.q,p.r);m!==t&&(r.push(p),o.add(m))}const l=new Map;for(const{id:f,want:p}of i){const m=e.get(f);if(!m||!m.length||!o.has($e(m[0].q,m[0].r)))continue;const g=[];for(const w of m){if(g.length>=p)break;const b=$e(w.q,w.r);o.has(b)&&(o.delete(b),g.push({q:w.q,r:w.r}))}g.length&&l.set(f,g)}const c=new Map;for(const{id:f,want:p}of i){const m=l.get(f);m&&(rh(m,p,o),c.set(f,m))}const h=new Map;i.forEach((f,p)=>{const m=f.org||f.id;h.has(m)||h.set(m,p)});const d=i.map((f,p)=>({...f,i:p})).sort((f,p)=>h.get(f.org||f.id)-h.get(p.org||p.id)||f.i-p.i),u=f=>i.filter(p=>p.org===f&&c.has(p.id)).flatMap(p=>c.get(p.id));for(const{id:f,want:p,org:m}of d){if(c.has(f))continue;const g=m?u(m):[],w=g.length&&Lg(g,o)||r.find(y=>o.has($e(y.q,y.r)));if(!w){c.set(f,[]);continue}o.delete($e(w.q,w.r));const b=[{q:w.q,r:w.r}];rh(b,p,o),c.set(f,b)}return c}function Lg(s,e){const t=s[0];let i=null,n=1/0;for(const r of s)for(const[o,a]of At){const l={q:r.q+o,r:r.r+a};if(!e.has($e(l.q,l.r)))continue;const c=li(l,t)*100+li(l,qn);c<n&&(n=c,i=l)}return i}function rh(s,e,t){const i=s[0];for(;s.length<e;){let n=null,r=1/0;for(const o of s)for(const[a,l]of At){const c={q:o.q+a,r:o.r+l};if(!t.has($e(c.q,c.r)))continue;const h=li(c,i)*100+li(c,qn);h<r&&(r=h,n=c)}if(!n)break;t.delete($e(n.q,n.r)),s.push(n)}}const Js=()=>{const{x:s,z:e}=Vi(yt.q,yt.r);return new F(s,0,e)},Rg=Math.PI/6,Bg=6*hs/Yu;function Fg(s,e,t,i){const n=Math.PI/3*t;return[s+i*Math.cos(n),e+i*Math.sin(n)]}function Og(s,e,t=0,i=0,n=$t){const r=s.attributes.position,o=s.attributes.normal,a=s.attributes.uv,l=new Float32Array(r.count*2);for(let c=0;c<r.count;c++){const h=r.getX(c);r.getY(c);const d=r.getZ(c);Math.abs(o.getY(c))>.5?(l[c*2]=(h+t)/e,l[c*2+1]=(d+i)/e):(l[c*2]=a.getX(c)*Bg,l[c*2+1]=.25+a.getY(c)*(n/e))}s.setAttribute("uv",new Ue(l,2))}function Ig(s){const e=s.attributes.normal,t=s.attributes.uv;for(let i=0;i<t.count;i++)e.getY(i)>.5?t.setY(i,Qi.top.v0+t.getY(i)*(Qi.top.v1-Qi.top.v0)):t.setXY(i,Qi.side.u,Qi.side.v);t.needsUpdate=!0}function Dg(s,e){const t=new Ot(s,s,e,6);return t.rotateY(Rg),t}class Vg{constructor({id:e,name:t,index:i,cells:n,accent:r}){this.id=e,this.name=t,this.index=i,this.cells=n,this.accent=r,this.highlight=0,this.cellKeys=new Set(n.map(d=>$e(d.q,d.r)));const o=Vi(n[0].q,n[0].r);let a=0,l=0;this.localCenters=n.map(d=>{const{x:u,z:f}=Vi(d.q,d.r);return a+=u,l+=f,{x:u-o.x,z:f-o.z}}),this.center=new F(o.x,0,o.z),this.middle=new F(a/n.length,0,l/n.length);let c=this.localCenters[0],h=1/0;for(const d of this.localCenters){const u=d.x-(this.middle.x-o.x),f=d.z-(this.middle.z-o.z),p=u*u+f*f;p<h&&(h=p,c=d)}this.labelAnchor=new F(this.center.x+c.x,0,this.center.z+c.z),this.radius=ts*Math.sqrt(n.length),this.group=new Pt,this.group.position.copy(this.center),this.group.name=`plot:${e}`,this._buildDeck(),this._buildBorder(),this._buildGlow(),this._buildPosts(),this.slots=this._buildSlots(),this._buildClutter()}_buildGlow(){this.glowMaterial=o0(this.accent,Sg),this.glow=new ke(r0(this.cells,this.localCenters,0,$g),this.glowMaterial),this.glow.visible=!1,this.glow.renderOrder=2,this.group.add(this.glow)}_buildDeck(){const e=this.localCenters.map(({x:r,z:o})=>{const a=Dg(hs,qo);return Og(a,Yu,r,o,qo),a.translate(r,$t-qo/2,o),a}),t=Nt(e);e.forEach(r=>r.dispose());const i=new W(this.accent).offsetHSL(0,-.38,0).multiplyScalar(.9),n=og();this.deck=new ke(t,new tt({color:i,map:n.map,normalMap:n.normalMap,roughnessMap:n.roughnessMap,normalScale:new Se(.7,.7),roughness:.82,metalness:.18})),this.deck.receiveShadow=!0,this.group.add(this.deck)}_buildBorder(){const e=[],t=hs*Math.cos(Math.PI/6),i=.32,r=t-.05-i/2,o=r/Math.cos(Math.PI/6);if(this.cells.forEach((c,h)=>{const{x:d,z:u}=this.localCenters[h];for(let f=0;f<6;f++){const p=At[i0[f]];if(this.cellKeys.has($e(c.q+p[0],c.r+p[1])))continue;const m=Math.PI/3*f+Math.PI/6,g=new Dt(i,.14,o*1.02);Ig(g),g.rotateY(-m),g.translate(d+Math.cos(m)*r,$t+.07,u+Math.sin(m)*r),e.push(g)}}),!e.length)return;const a=Nt(e);e.forEach(c=>c.dispose());const l=ag();this.borderMaterial=new tt({color:this.accent,map:l.map,emissive:this.accent,emissiveMap:l.emissiveMap,emissiveIntensity:.5,normalMap:l.normalMap,normalScale:new Se(.5,.5),roughness:.55,metalness:.1}),this.border=new ke(a,this.borderMaterial),this.border.receiveShadow=!0,this.group.add(this.border)}_buildPosts(){const e=[],t=[];this.localCenters.forEach(({x:n,z:r},o)=>{const[a,l]=Fg(n,r,o*2%6,hs*.72),c=new Ot(.055,.085,1.8,6);c.translate(a,$t+.9,l),e.push(c);const h=new Qt(.14,8,6);h.translate(a,$t+1.84,l),t.push(h)});const i=new ke(Nt(e),new tt({color:10132130,roughness:.7,metalness:.3}));i.castShadow=!0,this.lampMaterial=new dt({color:this.accent,toneMapped:!0}),this.lamps=new ke(Nt(t),this.lampMaterial),this._lampBase=new W(this.accent),this.group.add(i,this.lamps),e.forEach(n=>n.dispose()),t.forEach(n=>n.dispose())}_buildClutter(){const e=["containers_A","containers_B","containers_C","containers_D","cargo_A","cargo_B","cargo_A_packed","cargo_B_packed","lights"];if(!e.every(r=>Gp(r)))return;const t=De(bn(this.id)+17),i=[];if(this.clutterSpots=[],this.localCenters.forEach(({x:r,z:o})=>{const a=[];for(let l=0;l<6;l++)t()>.45&&a.push({a:Math.PI/3*l+Math.PI/3,r:hs*(.52+t()*.1)});for(let l=0;l<3;l++)t()>.35&&a.push({a:t()*Math.PI*2,r:hs*(.78+t()*.07)});for(const{a:l,r:c}of a){const h=e[Math.floor(t()*e.length)],d=Iu(h),u=h==="lights"?1.1:1.35;d.scale(u,u,u),d.rotateY(t()*Math.PI*2);const f=r+Math.cos(l)*c,p=o+Math.sin(l)*c;d.computeBoundingBox();const m=d.boundingBox,g=Math.hypot(Math.max(Math.abs(m.min.x),Math.abs(m.max.x)),Math.max(Math.abs(m.min.z),Math.abs(m.max.z)));if(!this.containsLocal(f,p,g+.16)||this.slots.some(w=>Math.hypot(f-w.x,p-w.z)<Ku+g+.4)||this.clutterSpots.some(w=>Math.hypot(f-w.x,p-w.z)<w.r+g+.25)){d.dispose();continue}d.translate(f,$t-m.min.y,p),i.push(d),this.clutterSpots.push({x:f,z:p,r:g})}}),!i.length)return;const n=Nt(i,!1);i.forEach(r=>r.dispose()),this.clutter=new ke(n,new tt({map:Fu(),roughness:.6,metalness:.05})),this.clutter.castShadow=!0,this.clutter.receiveShadow=!0,this.group.add(this.clutter)}_buildSlots(){const e=[];for(const{x:t,z:i}of this.localCenters){e.push({x:t,z:i});for(let n=0;n<6;n++){const r=Math.PI/3*n+Math.PI/6;e.push({x:t+Math.cos(r)*hs*.58,z:i+Math.sin(r)*hs*.58})}}return e}slotFor(e){return this.slots[e%this.slots.length]}containsLocal(e,t,i=0){const n=hs*Math.sqrt(3)/2-i;return this.localCenters.some(r=>{for(let o=0;o<6;o++){const a=o*Math.PI/3+Math.PI/6;if((e-r.x)*Math.cos(a)+(t-r.z)*Math.sin(a)>n)return!1}return!0})}containsWorld(e,t,i=0){return this.containsLocal(e-this.center.x,t-this.center.z,i)}worldSlot(e,t=new F){const i=this.slotFor(e);return t.set(this.center.x+i.x,$t,this.center.z+i.z)}setNight(e,t,i){this.borderMaterial&&(this.borderMaterial.emissiveIntensity=.3+e*1.4+(t?.4+Math.sin(i*3.4)*.32:0)),this.glowMaterial.opacity=this.highlight,this.glow.visible=this.highlight>.01,this.lampMaterial.color.copy(this._lampBase).multiplyScalar((.5+e*2.4)*(1+this.highlight))}dispose(){this.group.traverse(e=>{e.isMesh&&(e.geometry.dispose(),e.material.dispose())})}}const oh=.73,Ng=-.75,ah=4.5,Ki=[4184575,16732889,11566335,16752704,10288983,6065407,16769357,4063176],Wg=.4,Hg=1.3,Ug=1.8,jg=["M4.5 20V5.4A1.4 1.4 0 0 1 5.9 4h6.7A1.4 1.4 0 0 1 14 5.4V20","M14 9h4.1a1.4 1.4 0 0 1 1.4 1.4V20","M3 20h18","M7.5 8h3M7.5 11.5h3M7.5 15h3M16.8 13h.01M16.8 16.5h.01"];let Ji=null;function qg(){if(Ji)return Ji;const s=document.createElement("canvas");s.width=4,s.height=128;const e=s.getContext("2d"),t=e.createLinearGradient(0,128,0,0);t.addColorStop(0,"rgba(255,255,255,0.55)"),t.addColorStop(.35,"rgba(255,255,255,0.2)"),t.addColorStop(1,"rgba(255,255,255,0.06)"),e.fillStyle=t,e.fillRect(0,0,4,128),e.fillStyle="#fff",e.fillRect(0,124,4,4),e.fillStyle="rgba(255,255,255,0.75)",e.fillRect(0,0,4,2);for(let i=10;i<120;i+=9)e.fillStyle="rgba(255,255,255,0.05)",e.fillRect(0,i,4,1);return Ji=new Vn(s),Ji.colorSpace=Bi,Ji}function r0(s,e,t,i){const n=new Set(s.map(l=>$e(l.q,l.r))),r=ts*Math.cos(Math.PI/6),o=[];s.forEach((l,c)=>{const{x:h,z:d}=e[c];for(let u=0;u<6;u++){const f=At[i0[u]];if(n.has($e(l.q+f[0],l.r+f[1])))continue;const p=Math.PI/3*u+Math.PI/6,m=new Ut(ts,i);m.rotateY(Math.PI/2-p),m.translate(h+Math.cos(p)*r,$t+t+i/2,d+Math.sin(p)*r),o.push(m)}});const a=Nt(o);return o.forEach(l=>l.dispose()),a}function o0(s,e){return new dt({color:new W(s).multiplyScalar(e),map:qg(),transparent:!0,opacity:0,blending:ji,depthWrite:!1,side:vt,toneMapped:!1,fog:!1})}function Gg(s,e,t){const i=e.map(l=>Vi(l.q,l.r)),n=r0(e,i,Wg,Hg),r=o0(t,Ug),o=new ke(n,r);o.visible=!1,o.renderOrder=2;const a=Ja(s,t,{district:!0});return a.position.set(i[0].x,ah,i[0].z),{wall:o,label:a,fade(l,c){r.opacity=l,o.visible=l>.01,a.material.opacity=c,a.visible=c>.01},placeLabel(l,c){let h=i[0],d=-1/0;for(const u of i){const f=u.x*l+u.z*c;f>d&&(d=f,h=u)}a.position.set(h.x+l*ts,ah,h.z+c*ts)},dispose(){n.dispose(),r.dispose(),a.userData.dispose?.()}}}function Ja(s,e,{pixelRatio:t=4,district:i=!1}={}){const r=`${i?650:600} 34px ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif`,o=i?"5px":"0px",a=i?s.toUpperCase():s,l=i?34:9,c=10,h=14,d=document.createElement("canvas").getContext("2d");d.font=r,d.letterSpacing=o;const u=Math.ceil(d.measureText(a).width),f=document.createElement("canvas"),p=u+l+c+h*2,m=34+h*2;f.width=Math.ceil(p*t),f.height=Math.ceil(m*t);const g=f.getContext("2d");g.scale(t,t),g.font=r,g.letterSpacing=o,g.textAlign="left",g.textBaseline="middle";const w=h+l+c,b=m/2,y=()=>{if(!i){g.beginPath(),g.arc(h+l/2,b,l/2,0,Math.PI*2),g.fill();return}g.save(),g.translate(h,b-l/2),g.scale(l/24,l/24),g.lineCap="round",g.lineJoin="round";for(const k of jg)g.stroke(new Path2D(k));g.restore()};g.shadowColor="rgba(0,0,0,0.85)",g.shadowBlur=9,g.fillStyle="rgba(0,0,0,0.9)",g.strokeStyle="rgba(0,0,0,0.9)",g.lineWidth=4;for(let k=0;k<3;k++)g.fillText(a,w,b);y();const C="#"+new W(e).getHexString();g.shadowBlur=0,g.fillStyle=C,g.strokeStyle=C,g.lineWidth=2,y(),g.fillStyle=i?"#"+new W(e).lerp(new W(16777215),.3).getHexString():"#f4f2ee",g.fillText(a,w,b);const _=new Vn(f);_.colorSpace=Bi,_.minFilter=On,_.magFilter=qi,_.generateMipmaps=!0,_.anisotropy=8;const x=new Ut(oh*(p/m),oh),T=new dt({map:_,transparent:!0,depthWrite:!1,depthTest:!1,toneMapped:!1,opacity:0});T.onBeforeCompile=k=>{wt(k),k.vertexShader=k.vertexShader.replace("#include <project_vertex>",`vec4 mvPosition = viewMatrix * vec4( bcBend( ( modelMatrix * vec4( 0.0, 0.0, 0.0, 1.0 ) ).xyz ), 1.0 );
|
|
1942
|
-
float dist = -mvPosition.z;
|
|
1943
|
-
mvPosition.xy += position.xy * ( 0.55 + dist * 0.03 );
|
|
1944
|
-
gl_Position = projectionMatrix * mvPosition;`),k.fragmentShader=k.fragmentShader.replace("#include <map_fragment>",Au.map_fragment.replace("texture2D( map, vMapUv )",`texture2D( map, vMapUv, ${Ng.toFixed(2)} )`))};const M=new ke(x,T);return M.renderOrder=8,M.frustumCulled=!1,M.visible=!1,M.layers.set(Vl),M.userData.dispose=()=>{_.dispose(),x.dispose(),T.dispose()},M}function bn(s){let e=2166136261;for(let t=0;t<s.length;t++)e^=s.charCodeAt(t),e=Math.imul(e,16777619);return e>>>0}function Zg(s){const e=new Map;for(const n of s)n.org&&e.set(n.org,[...e.get(n.org)??[],n]);const t=[...e].map(([n,r])=>({name:n,repos:r,count:r.reduce((o,a)=>o+(a.off?0:a.count),0),urgent:r.some(o=>o.urgent)})).sort((n,r)=>r.count-n.count||n.name.localeCompare(r.name)),i=new Set(t.map(n=>n.name));return{orgs:t,loose:s.filter(n=>!i.has(n.org)),grouped:i}}function a0(s){const e=new Map;for(const t of s)t.org&&e.set(t.org,(e.get(t.org)??0)+1);return new Map(s.filter(t=>t.org&&e.get(t.org)>1).map(t=>[t.name,t.org]))}const Go=s=>String(s).split(/[\\/]/).filter(Boolean).pop()||String(s);function l0(s,{everyOrg:e=!1}={}){const t=e?new Map(s.filter(n=>n.org).map(n=>[n.name,n.org])):a0(s),i=new Map;for(const[n,r]of t){const o=`${r}/${Go(n)}`;i.set(o,(i.get(o)??0)+1)}return new Map(s.map(n=>{const r=t.get(n.name);return[n.name,r&&i.get(`${r}/${Go(n.name)}`)===1?Go(n.name):n.name]}))}function Ul(s,e){const t=new Map;for(const n of s)n.project===e&&n.org&&t.set(n.org,(t.get(n.org)??0)+1);let i=null;for(const[n,r]of t)(!i||r>t.get(i))&&(i=n);return i}const c0=15789284,_i=12894132,Lr=13198402,Rr=9409177,h0=8373472,Xg=new Map([[c0,[.48,.05]],[_i,[.62,.08]],[Lr,[.45,.1]],[Rr,[.26,.95]],[h0,[.06,0]],[4869461,[.35,.85]]]),Yg=[.55,.15];class Qg{constructor(e,t){this.group=new Pt,this.group.position.copy(t),this.group.rotation.y=Math.atan2(-t.x,-t.z),this.group.name="ship",e.add(this.group),this.scene=e,this._buildHull(),this._buildRamp(),this._buildLights(),this.traffic=0}_buildHull(){const e=[],t=[],i=(_,x,T)=>{e.push(_),t.push(new W(x))},n=new Qt(2.4,22,16);n.scale(1,.86,1),n.translate(0,3.5,0),i(n,c0);const r=new Ot(1.75,1.15,1.1,20);r.translate(0,1.5,0),i(r,_i);const o=new Qt(1,16,10,0,Math.PI*2,0,Math.PI/2);o.scale(1,.9,1),o.translate(0,5.42,0),i(o,Lr);const a=new Ot(.08,.11,1.4,6);a.translate(0,6,0),i(a,Rr);for(let _=0;_<5;_++){const x=_/5*Math.PI*2+.62,T=new Cc(.4,.07,6,14);T.rotateY(-x+Math.PI/2),T.translate(Math.cos(x)*2.33,3.7,Math.sin(x)*2.33),i(T,_i)}const l=.46,c=2.9,h=1.55,d=2.75,u=h+Math.sin(l)*c,f=d-Math.cos(l)*c;this.footRadius=u;for(let _=0;_<4;_++){const x=_/4*Math.PI*2+Math.PI/4,T=new Ot(.16,.21,c,8);T.rotateZ(l),T.rotateY(-x),T.translate(Math.cos(x)*((h+u)/2),(d+f)/2,Math.sin(x)*((h+u)/2)),i(T,Rr);const M=new Ot(.6,.46,.26,12);M.translate(Math.cos(x)*u,Math.max(.13,f),Math.sin(x)*u),i(M,_i);const k=(h+u)*.36,A=new Ot(.06,.06,1.7,5);A.rotateZ(-.95),A.rotateY(-x),A.translate(Math.cos(x)*(k+.5),1.55,Math.sin(x)*(k+.5)),i(A,Rr)}const p=new Ot(.55,1.05,1,14,1,!0);p.translate(0,.85,0),i(p,4869461);const m=new Ot(.92,.92,.9,16,1,!0);m.rotateX(Math.PI/2),m.translate(0,3.15,2.25),i(m,_i);const g=new Cc(.92,.1,6,20,Math.PI*1.34);g.rotateZ(-Math.PI*.17),g.translate(0,3.15,2.68),i(g,Lr);const w=en(e,t);this.hull=new ke(w,lh()),this.hull.castShadow=!0,this.hull.receiveShadow=!0,this.group.add(this.hull);const b=new ke(new Eo(.9,20),new dt({color:329226,toneMapped:!1}));b.position.set(0,3.15,2.3),this.group.add(b);const y=[],C=[];for(let _=0;_<5;_++){const x=_/5*Math.PI*2+.62,T=new Eo(.36,14);T.rotateY(-x+Math.PI/2),T.translate(Math.cos(x)*2.37,3.7,Math.sin(x)*2.37),y.push(T),C.push(new W(h0))}this.glassMaterial=new dt({vertexColors:!0,toneMapped:!0}),this.glass=new ke(en(y,C),this.glassMaterial),this.group.add(this.glass)}_buildRamp(){const n=2.9899999999999998,r=6.1-2.68,o=Math.hypot(r,n),a=Math.atan2(n,r),l=new Dt(1.8,.14,o);l.translate(0,0,o/2);const c=new tt({color:_i,roughness:.7,metalness:.15});this.ramp=new ke(l,c),this.ramp.position.set(0,3.05,2.68),this.ramp.rotation.x=a,this.ramp.castShadow=!0,this.ramp.receiveShadow=!0,this.group.add(this.ramp);const h=[],d=[],u=Math.max(3,Math.round(o/.55));for(let g=1;g<u;g++){const w=new Dt(1.6,.05,.09);w.translate(0,.09,o*g/u),h.push(w),d.push(new W(9341568))}const f=new ke(en(h,d),lh());this.ramp.add(f);const p=[],m=[];for(const g of[-.82,.82]){const w=new Dt(.1,.07,o-.15);w.translate(g,.09,o/2),p.push(w),m.push(new W(Lr))}this.stripMaterial=new dt({vertexColors:!0,toneMapped:!0}),this.strips=new ke(en(p,m),this.stripMaterial),this.ramp.add(this.strips),this.doorLocal=new F(0,0,6.1+.6),this.airlockLocal=new F(0,3.05+.02,2.68-.3)}_buildLights(){this.beaconMaterial=new dt({color:16734794,toneMapped:!0}),this.beacon=new ke(new Qt(.19,10,8),this.beaconMaterial),this.beacon.position.set(0,6.5,0),this.group.add(this.beacon);const e=[],t=[];for(let n=0;n<8;n++){const r=n/8*Math.PI*2,o=(this.footRadius||3)+1.5,a=new Qt(.12,8,6);a.translate(Math.cos(r)*o,.12,Math.sin(r)*o),e.push(a),t.push(new W(10475775))}this.padMaterial=new dt({vertexColors:!0,toneMapped:!0}),this.padLights=new ke(en(e,t),this.padMaterial),this.group.add(this.padLights);const i=new ke(new Eo((this.footRadius||3)+2.3,32),new tt({color:3091500,roughness:1,transparent:!0,opacity:.65}));i.rotation.x=-Math.PI/2,i.position.y=.05,i.receiveShadow=!0,this.group.add(i)}shipDoor(e=new F){return this.group.updateWorldMatrix(!0,!1),e.copy(this.doorLocal).applyMatrix4(this.group.matrixWorld)}shipAirlock(e=new F){return this.group.updateWorldMatrix(!0,!1),e.copy(this.airlockLocal).applyMatrix4(this.group.matrixWorld)}update(e,t,i){const n=t%2,r=n<.08||n>.2&&n<.28?1:.08;this.beaconMaterial.color.setRGB(3.2*r,.35*r,.28*r);const o=.35+i*2.2;this.padMaterial.color.setRGB(.55*o,.82*o,1.1*o),this.glassMaterial.color.setRGB(.5*o,.78*o,.92*o),this.traffic=Math.max(0,this.traffic-e*1.5);const a=Math.min(1,this.traffic),l=.6+.4*Math.sin(t*4),c=(.5+i*1.2)*(1+a*l*1.6);this.stripMaterial.color.setRGB(1*c,.45*c,.3*c)}ping(){this.traffic=Math.min(2.5,this.traffic+1)}dispose(){this.group.traverse(e=>{e.isMesh&&(e.geometry.dispose(),e.material.dispose())}),this.scene.remove(this.group)}}function en(s,e){s.forEach((i,n)=>{const r=i.attributes.position.count,o=new Float32Array(r*3),a=new Float32Array(r*2),l=e[n],c=Xg.get(e[n].getHex())||Yg;for(let h=0;h<r;h++)o[h*3]=l.r,o[h*3+1]=l.g,o[h*3+2]=l.b,a[h*2]=c[0],a[h*2+1]=c[1];i.setAttribute("color",new Ue(o,3)),i.setAttribute("aSurface",new Ue(a,2)),i.deleteAttribute("uv"),i.attributes.normal||i.computeVertexNormals()});const t=Nt(s,!1);return s.forEach(i=>i.dispose()),t}function lh(){const s=new tt({vertexColors:!0,roughness:.55,metalness:.22,side:vt,shadowSide:Ou});return s.onBeforeCompile=e=>{wt(e),e.vertexShader=e.vertexShader.replace("#include <common>",`#include <common>
|
|
1945
|
-
attribute vec2 aSurface;
|
|
1946
|
-
varying vec2 vSurface;`).replace("#include <begin_vertex>",`#include <begin_vertex>
|
|
1947
|
-
vSurface = aSurface;`),e.fragmentShader=e.fragmentShader.replace("#include <common>",`#include <common>
|
|
1948
|
-
varying vec2 vSurface;`).replace("#include <roughnessmap_fragment>","float roughnessFactor = vSurface.x;").replace("#include <metalnessmap_fragment>","float metalnessFactor = vSurface.y;")},s}const Kt=4,Gr=7,B={idle:0,blink:1,happy:2,work:3,think1:4,think2:5,think3:6,wait:7,alert:8,error:9,sleep:10,wink:11,love:12,cheer:13,boot:14,sad:15,stroll:16,whistleLeft:17,whistle:18,whistleRight:19,strollOpen:20,strollBlink:21,strollGrin:22,strollLookLeft:23,strollLookRight:24,strollBlinkLeft:25,strollBlinkRight:26,sulk:27},Kg=[[2.6,B.stroll],[4.2,B.whistleRight],[5.8,B.whistle],[7.3,B.whistleLeft],[10,B.stroll],[11.4,B.strollOpen],[13.1,B.strollLookLeft],[14.2,B.strollOpen],[16,B.strollLookRight],[17.2,B.strollOpen],[19.4,B.strollGrin],[21,B.stroll],[22.7,B.whistle],[24.2,B.whistleRight],[27,B.stroll]];function Jg(s,e){const t=(s*(.88+e*.24)+e*27)%27;for(const[i,n]of Kg)if(t<i)return n;return B.stroll}const Zr={thinking:[B.think1,B.think2,B.think3,B.think2],delegating:[B.think1,B.think2,B.think3,B.think2],working:[B.work,B.work,B.work,B.happy],celebrating:[B.cheer,B.happy,B.cheer,B.love],done:[B.wait,B.wait,B.alert,B.wait],eager:[B.alert,B.wait,B.alert,B.wait],asking:[B.alert,B.wait,B.alert,B.wait],sulking:[...Array(11).fill(B.sulk),B.wait],broken:[B.error,B.error,B.sad,B.error],error:[B.error,B.error,B.sad,B.error],sleeping:[B.sleep]};function d0(s){return{wait:.6,alert:.55,happy:.85,love:.75,cheer:.85}[s]??(B[s]>=B.stroll?.82:1)}function e4(s=512,e=(t,i)=>t4[i](t)){const t=document.createElement("canvas");t.width=s,t.height=s/Kt*Gr;const i=t.getContext("2d"),n=s/Kt;i.fillStyle="#000",i.fillRect(0,0,t.width,t.height);for(const[o,a]of Object.entries(B)){const l=a%Kt*n,c=Math.floor(a/Kt)*n;i.save(),i.translate(l,c),i.scale(n,n),i.fillStyle="#fff",i.strokeStyle="#fff",i.lineCap="round",i.lineJoin="round",i.globalAlpha=d0(o),e(i,o),i.restore()}const r=new Vn(t);return r.colorSpace=ho,r.minFilter=On,r.magFilter=qi,r.generateMipmaps=!0,r.wrapS=Ya,r.wrapT=Ya,r}const Be=.31,Fe=.69,ie=.55;function Yt(s,e,t,i){s.beginPath(),s.arc(e,t,i,0,Math.PI*2),s.fill()}function nt(s,e,t,i,n){const r=Math.min(i,n)/2;s.beginPath(),s.moveTo(e-i/2+r,t-n/2),s.arcTo(e+i/2,t-n/2,e+i/2,t+n/2,r),s.arcTo(e+i/2,t+n/2,e-i/2,t+n/2,r),s.arcTo(e-i/2,t+n/2,e-i/2,t-n/2,r),s.arcTo(e-i/2,t-n/2,e+i/2,t-n/2,r),s.closePath(),s.fill()}function ii(s,e,t,i,n,r=.055){s.lineWidth=r,s.beginPath(),n?(s.moveTo(e-i/2,t+i*.32),s.quadraticCurveTo(e,t-i*.42,e+i/2,t+i*.32)):(s.moveTo(e-i/2,t-i*.28),s.quadraticCurveTo(e,t+i*.42,e+i/2,t-i*.28)),s.stroke()}function ch(s,e,t,i){s.lineWidth=.055;const n=i/2;s.beginPath(),s.moveTo(e-n,t-n),s.lineTo(e+n,t+n),s.moveTo(e+n,t-n),s.lineTo(e-n,t+n),s.stroke()}function hh(s,e,t,i){s.beginPath(),s.moveTo(e,t+i*.55),s.bezierCurveTo(e-i*1.15,t-i*.18,e-i*.5,t-i*.95,e,t-i*.32),s.bezierCurveTo(e+i*.5,t-i*.95,e+i*1.15,t-i*.18,e,t+i*.55),s.fill()}function ds(s,e,t,i,n=.05){s.lineWidth=n,s.beginPath(),s.moveTo(.5-t/2,e),s.quadraticCurveTo(.5,e+i,.5+t/2,e),s.stroke()}function dh(s,e,t,i){s.beginPath(),s.ellipse(.5,e,t/2,i/2,0,0,Math.PI*2),s.fill()}function dr(s,e,t,i){s.beginPath(),s.ellipse(.5,e,t/2,i,0,0,Math.PI),s.fill()}function Zo(s,e){s.save(),s.globalAlpha*=.42,Yt(s,.14,e,.05),Yt(s,.86,e,.05),s.restore()}function uh(s,e,t){s.beginPath(),s.moveTo(e-.118,t-.016),s.bezierCurveTo(e-.134,t-.04,e-.106,t-.057,e-.09,t-.035),s.quadraticCurveTo(e,t+.036,e+.09,t-.035),s.bezierCurveTo(e+.109,t-.058,e+.133,t-.038,e+.117,t-.014),s.quadraticCurveTo(e,t+.118,e-.118,t-.016),s.fill()}function fh(s,e){s.lineWidth=.048,s.beginPath(),s.moveTo(e-.095,ie+.035),s.bezierCurveTo(e-.055,ie-.105,e+.055,ie-.105,e+.095,ie+.035),s.stroke()}function el(s){fh(s,Be),fh(s,Fe)}function Xo(s,e,t=.75){el(s),Yt(s,e,t,.038)}function Yo(s,e){const t=e*.065;nt(s,Be+t,ie,e>0?.09:.105,.125),nt(s,Fe+t,ie,e<0?.09:.105,.125),s.save(),s.translate(e*.025,0),ds(s,.725,.19,.07,.038),s.restore()}function Qo(s,e){const t=e*.065;ii(s,Be+t,ie,.16,!1,.038),ii(s,Fe+t,ie,.16,!1,.038),s.save(),s.translate(e*.025,0),ds(s,.725,.19,.07,.038),s.restore()}const t4={stroll(s){el(s),ds(s,.725,.19,.07,.038)},whistleLeft(s){Xo(s,.4,.735)},whistle(s){Xo(s,.5)},whistleRight(s){Xo(s,.6,.735)},strollOpen(s){Yo(s,0)},strollBlink(s){Qo(s,0)},strollBlinkLeft(s){Qo(s,-1)},strollBlinkRight(s){Qo(s,1)},strollGrin(s){el(s),dr(s,.72,.2,.06)},strollLookLeft(s){Yo(s,-1)},strollLookRight(s){Yo(s,1)},idle(s){nt(s,Be,ie,.145,.18),nt(s,Fe,ie,.145,.18),ds(s,.73,.23,.09)},blink(s){ii(s,Be,ie,.19,!1),ii(s,Fe,ie,.19,!1),ds(s,.73,.23,.09)},happy(s){ii(s,Be,ie,.2,!0,.055),ii(s,Fe,ie,.2,!0,.055),dr(s,.71,.26,.085),Zo(s,.65)},work(s){nt(s,Be,ie+.01,.18,.095),nt(s,Fe,ie+.01,.18,.095),ds(s,.73,.15,.025)},think1(s){Ko(s,1)},think2(s){Ko(s,2)},think3(s){Ko(s,3)},wait(s){nt(s,Be,ie,.155,.2),nt(s,Fe,ie,.155,.2),s.save(),s.globalCompositeOperation="destination-out",s.globalAlpha=1,Yt(s,Be+.03,ie-.045,.024),Yt(s,Fe+.03,ie-.045,.024),s.restore(),dh(s,.755,.075,.075)},alert(s){nt(s,Be,ie,.17,.22),nt(s,Fe,ie,.17,.22),s.save(),s.globalCompositeOperation="destination-out",s.globalAlpha=1,Yt(s,Be+.035,ie-.05,.026),Yt(s,Fe+.035,ie-.05,.026),s.restore(),dh(s,.755,.09,.085)},error(s){ch(s,Be,ie,.17),ch(s,Fe,ie,.17),s.lineWidth=.05,s.beginPath(),s.moveTo(.38,.74),s.quadraticCurveTo(.44,.68,.5,.74),s.quadraticCurveTo(.56,.8,.62,.74),s.stroke()},sleep(s){uh(s,.29,.55),uh(s,.71,.55),Yt(s,.5,.755,.043)},wink(s){ii(s,Be,ie,.2,!0,.06),nt(s,Fe,ie,.145,.18),ds(s,.73,.24,.09),Zo(s,.65)},love(s){hh(s,Be,ie,.13),hh(s,Fe,ie,.13),dr(s,.72,.24,.075)},cheer(s){s.lineWidth=.055,s.beginPath(),s.moveTo(Be-.09,ie-.08),s.lineTo(Be+.04,ie),s.lineTo(Be-.09,ie+.08),s.moveTo(Fe+.09,ie-.08),s.lineTo(Fe-.04,ie),s.lineTo(Fe+.09,ie+.08),s.stroke(),dr(s,.71,.27,.09),Zo(s,.65)},boot(s){s.globalAlpha=.55;for(let e=0;e<4;e++)s.fillRect(.16,.4+e*.06,.68,.022);s.globalAlpha=1,s.fillRect(.16,.73,.4,.055),s.globalAlpha=.3,s.fillRect(.56,.73,.28,.055)},sad(s){nt(s,Be,ie+.01,.145,.17),nt(s,Fe,ie+.01,.145,.17),s.lineWidth=.045,s.beginPath(),s.moveTo(Be-.1,ie-.12),s.lineTo(Be+.08,ie-.17),s.moveTo(Fe+.1,ie-.12),s.lineTo(Fe-.08,ie-.17),s.stroke(),ds(s,.79,.22,-.09)},sulk(s){nt(s,Be-.02,ie+.03,.15,.085),nt(s,Fe-.02,ie+.03,.15,.085),ds(s,.77,.16,-.03)}};function Ko(s,e){nt(s,Be,ie-.025,.145,.18),nt(s,Fe,ie-.025,.145,.18),s.save(),s.globalCompositeOperation="destination-out",s.globalAlpha=1,Yt(s,Be-.03,ie-.09,.045),Yt(s,Fe-.03,ie-.09,.045),s.restore();for(let t=0;t<e;t++)Yt(s,.38+t*.12,.75,.032)}const xn=10,s4={w:.19,h:.24,x:0,y:0,lid:0,tilt:0,smile:0},ur={w:.19,h:.21,smile:.35},Jo={w:.17,h:.21},fr={w:.22,lid:.76},ea={close:.025,open:.04,mood:.09},i4=.1,n4={idle:{},blink:fr,happy:{w:.2,smile:.5},work:{w:.2,h:.19,y:.01,lid:.2,tilt:.12,smile:.12},think1:{x:-.04,y:-.06,right:{lid:.12}},think2:{x:-.05,y:-.07,right:{lid:.2}},think3:{x:-.06,y:-.065,right:{lid:.28}},wait:{w:.205,h:.26,y:-.02,lid:.06,tilt:-.25},alert:{w:.22,h:.28},error:{w:.2,h:.2,y:.01,lid:.3,tilt:.3,smile:.38},sleep:{w:.22,y:.02,lid:.76,tilt:-.1},wink:{left:{smile:.55}},love:{w:.21,h:.25,lid:.04,tilt:-.3,smile:.42},cheer:{w:.22,h:.23,lid:.12,tilt:.25,smile:.62},boot:{w:.24,h:.035},sad:{w:.18,h:.22,y:.03,lid:.3,tilt:-.6},stroll:ur,whistleLeft:{...ur,x:-.035},whistle:{...ur,smile:.42},whistleRight:{...ur,x:.035},strollOpen:Jo,strollBlink:fr,strollBlinkLeft:{...fr,x:-.065},strollBlinkRight:{...fr,x:.065},strollGrin:{w:.2,h:.22,smile:.55},strollLookLeft:{...Jo,x:-.065},strollLookRight:{...Jo,x:.065},sulk:{w:.2,h:.2,x:-.03,y:.035,lid:.52,tilt:-.12}};function u0(s,e=new Float32Array(xn)){const t={...s4,...n4[s]},i={...t,...t.left},n={...t,...t.right};return e.set([t.w,t.h,t.x,t.y,i.lid,n.lid,i.smile,n.smile,t.tilt,d0(s)]),e}const po=[];for(const[s,e]of Object.entries(B))po[e]=u0(s);const ph=new Set([B.blink,B.strollBlink,B.strollBlinkLeft,B.strollBlinkRight]);function f0(s){const[e,t,i,n]=s,r=s[8];return[-1,1].map(o=>{const a=o<0?0:1,l=i*o<0,c=e*(1-Math.abs(i)*(l?1.6:.5)),h=(o<0?Be:Fe)+i,d=ie+n;return{cx:h,cy:d,w:c,h:t,lidY:d-t/2+s[4+a]*t,lidSlope:-o*r,smileTop:d+t/2-s[6+a]*t,smileRadius:c*.9}})}function r4(s,e){for(const t of f0(e)){const{cx:i,cy:n,w:r,h:o}=t;s.save(),s.beginPath(),s.ellipse(i,n,r/2,o/2,0,0,Math.PI*2),s.clip(),s.beginPath(),s.moveTo(i-r,t.lidY-t.lidSlope*r),s.lineTo(i+r,t.lidY+t.lidSlope*r),s.lineTo(i+r,n+o),s.lineTo(i-r,n+o),s.clip(),s.beginPath(),s.rect(i-r,n-o,r*2,o*2);const a=t.smileRadius;s.moveTo(i+a,t.smileTop+a),s.arc(i,t.smileTop+a,a,0,Math.PI*2),s.fill("evenodd"),s.restore()}}function mh(s=512){return e4(s,(e,t)=>r4(e,po[B[t]]))}function o4(s){return{now:Float32Array.from(po[s]),frame:s,reopen:0}}function a4(s,e,t){const i=po[e];if(e!==s.frame&&(ph.has(s.frame)&&(s.reopen=i4),s.frame=e),t<=0)return s.now.set(i),s;s.reopen=Math.max(0,s.reopen-t);const n=ph.has(e)?ea.close:s.reopen>0?ea.open:ea.mood,r=1-Math.exp(-t/n);for(let o=0;o<xn;o++)s.now[o]+=(i[o]-s.now[o])*r;return s}function l4(s,e,t,i){t.set(s.now,i),t[i+2]+=e.x,t[i+3]+=e.y}const c4=.3,h4={[B.strollOpen]:B.strollBlink,[B.strollLookLeft]:B.strollBlinkLeft,[B.strollLookRight]:B.strollBlinkRight};function d4(s,e,t=1){if(s.faceTimer+=e,s.blinkAt-=e,s.state==="spawning"&&s.stateAge<.8){s.faceFrame=B.boot;return}if(s.state==="leaving"){s.faceFrame=s.stateAge%2<1.4?B.happy:B.wink;return}if(s.beat?.face!==void 0){s.faceFrame=s.beat.face;return}if(s.annoyed>0){s.annoyed-=e,s.faceTimer>c4&&(s.faceTimer=0,s.annoyedIndex=(s.annoyedIndex+1)%Zr.thinking.length),s.faceFrame=Zr.thinking[s.annoyedIndex];return}(s.state==="spawning"||s.state==="walking"||s.state==="at-site"&&s.status==="idle")&&s.status!=="error"&&s.status!=="broken"?s.groundSpeed>.12||s.state==="spawning"?s.walkFaceHold=.3:s.walkFaceHold=Math.max(0,s.walkFaceHold-e):s.walkFaceHold=0;const n=s.walkFaceHold>0;let r;if(n&&(s.walkFaceTime+=e*t,r=Jg(s.walkFaceTime,s.walkPersonality)),s.blinkAt<=0&&(s.status!=="sleeping"||n)&&s.status!=="error"&&s.status!=="broken"){s.faceFrame=n?h4[r]??r:B.blink,s.blinkAt<-.12&&(s.blinkAt=2.4+Math.random()*5);return}if(n){s.faceFrame=r;return}const o=s.loop;if(!o||!o.length){s.faceFrame=B.idle;return}const a=s.status==="working"?.22:.55;s.faceTimer>a&&(s.faceTimer=0,s.faceIndex=(s.faceIndex+1)%o.length),s.faceIndex%=o.length,s.faceFrame=o[s.faceIndex]}const tl=.8,u4=.06,vi={stiffness:55,damping:8.2},pr={lead:.08,x:.05,y:.035},f4=1/60,p4={[B.strollLookLeft]:-1,[B.strollBlinkLeft]:-1,[B.strollLookRight]:1,[B.strollBlinkRight]:1},gh={eager:30,sulk:180},Br={awake:{rate:1.6,glow:1},sulk:{rate:1.1,glow:.6},sleeping:{rate:.5,glow:.25},ease:.8},sl=(s,e,t)=>Math.min(t,Math.max(e,s)),ta=()=>({x:0,v:0,a:0});function p0(s,e){if(s.status==="asking")return"eager";if(s.status!=="done")return null;const t=s.noticedAt||0,i=Math.max(s.thread?.lastActivityAt||0,t),n=i?(e-i)/1e3:0;return n>=gh.sulk?"sulk":n>=gh.eager||t?"eager":"fresh"}const il={seconds:1.8,share:.45};function m4(s,e,t){return!e&&!t?0:s.status!=="working"?1:e&&s.interrupted>0?il.share:0}function g4(s){return(s.status==="asking"||s.status==="done")&&s.waitStage!=="sulk"&&s.state==="at-site"&&s.groundSpeed<=.12}function w4(s){s.interrupted=il.seconds,s.annoyed>0||(s.annoyedIndex=0),s.annoyed=Math.max(s.annoyed||0,il.seconds)}function b4(s,e){const t=p0(s,e);return(t==="eager"||t==="sulk")&&(s.noticedAt=e),t}function v4(s){return 2**(((s>>>0)%7-3)/12)}function y4(s){return s>>>=0,{head:{pitch:ta(),yaw:ta(),roll:ta()},side:s&1?1:-1,voicePitch:v4(s>>>1),flash:0,swell:0,shake:0,pingIn:1+s%7*.4,speech:null,speaking:0,glow:0,glance:null,glanceIn:s%5*.1,gaze:{x:0,y:0},light:{phase:s%7*.9,glow:null,pulse:1}}}function sa(s,e,t,i,n,r=0){return s.a=t*(e-s.x)-i*s.v+r,s.v+=s.a*n,s.x+=s.v*n,s}function C4(s){return Math.min(4,Math.ceil(s/f4))}function x4(s,e){if(!s)return 0;let t=0;for(const[i,n]of s.marks)e<i||(e<=n?t=Math.max(t,Math.min(1,(e-i)/.025)):e<n+.08&&(t=Math.max(t,1-(e-n)/.08)));return t}function M4(s,e,t){if(!e?.length)return;let i=0;for(const[,n]of e)i=Math.max(i,n);s.acting.speech={at:t,marks:e,end:i+.1}}function k4(s,e,t,i,n){const r=s.acting,o=r.side;let a=0,l=0,c=0;switch(s.status){case"asking":case"done":s.waitStage==="sulk"&&s.faceFrame!==B.wait?(l=-.25*o,c=.06*o):s.waitStage==="sulk"&&(a=-.18);break;case"error":case"broken":Math.sin(e*.6+s.phase)>.75&&(l=.22*Math.sin(e*9)*t);break}const h=s.beat?.head;return h&&(a=h.pitch??a,l=(h.yaw??0)*o,c=(h.roll??0)*o),l+=.38*(p4[s.faceFrame]??0),i&&s.status!=="sleeping"&&(l=i.yaw,i.pitch!==null&&(a=Math.min(a,i.pitch))),r.shake>0&&(l+=.3*Math.sin(e*17)*Math.min(1,r.shake*3)*t),n.pitch=a,n.yaw=sl(l,-tl,tl),n.roll=c,n}const yi={pitch:0,yaw:0,roll:0};function T4(s,e,t,i,n){if(e<=0)return;const r=s.acting,{head:o}=r;k4(s,t,i,n,yi);const a=C4(e),l=e/a;for(let h=0;h<a;h++)sa(o.pitch,yi.pitch,vi.stiffness,vi.damping,l),sa(o.yaw,yi.yaw,vi.stiffness,vi.damping,l),sa(o.roll,yi.roll,vi.stiffness,vi.damping,l);if(r.gaze.x=sl((yi.yaw-o.yaw.x)*pr.lead,-.05,pr.x)*i,r.gaze.y=sl((yi.pitch-o.pitch.x)*pr.lead,-.035,pr.y)*i,r.shake=Math.max(0,r.shake-e),r.flash=Math.max(0,r.flash-e*1.2),r.speech){const h=t-r.speech.at;r.speaking=x4(r.speech,h),h>r.speech.end&&(r.speech=null)}else r.speaking=0;const c=s.groundSpeed<=.12&&s.state!=="spawning";if((s.status==="done"||s.status==="asking")&&c&&s.waitStage!=="sulk"&&(r.pingIn-=e,r.pingIn<=0)){const h=s.waitStage==="eager";r.pingIn=h?1.4+Math.random():2.6+Math.random()*1.6,r.flash=Math.max(r.flash,h?1:.8)}}function _4(s,e=null){return s==="sleeping"?Br.sleeping:e==="sulk"?Br.sulk:Br.awake}function S4(s,e){const{rate:t,glow:i}=_4(s.status,s.waitStage),n=s.acting.light;return n.phase+=t*e,n.glow=n.glow===null?i:n.glow+(i-n.glow)*(1-Math.exp(-e/Br.ease)),n.pulse=.55+.45*Math.sin(n.phase),n}function $4(s,e,t,i=1){if(e===t)return;const n=s.acting,{head:r}=n;switch(e){case"celebrating":r.pitch.v-=2.4*i,n.flash=1;break;case"error":case"broken":r.pitch.v-=3*i,n.flash=.6;break;case"done":r.roll.v+=2*n.side*i,n.flash=.8;break;case"asking":r.pitch.v-=2*i,n.flash=1;break;case"working":r.pitch.v+=1.6*i;break}}function A4(s,e){s.acting.shake=Math.max(s.acting.shake,e)}function E4(s,e){return e.set(s.head.pitch.x-s.speaking*u4,s.head.yaw.x,s.head.roll.x,"YXZ")}const P4={shipped:[{seconds:.9,hold:!0,faceCamera:!0,pose:"idle",face:B.alert,head:{pitch:-.12}},{seconds:1.8,hold:!0,faceCamera:!0,pose:"celebrating",face:B.cheer,head:{pitch:-.16},kick:{head:-1.6},flash:1,say:"bot-happy"}],errored:[{seconds:.45,hold:!0,pose:"error",face:B.alert,head:{pitch:-.15}},{seconds:1.1,hold:!0,pose:"idle",face:B.work,head:{pitch:.34,yaw:.5}},{seconds:1.3,hold:!0,pose:"idle",face:B.sad,head:{pitch:.5,roll:.12},say:"bot-worried"}],asks:[{seconds:.6,hold:!0,faceCamera:!0,pose:"idle",face:B.alert,head:{pitch:-.14}}],answered:[{seconds:.8,face:B.happy,flash:.6}],perksUp:[{seconds:1.2,hold:!0,pose:"rise",face:B.happy,flash:.6}],noticed:[{seconds:1.2,hold:!0,faceCamera:!0,pose:"rise",face:B.alert,flash:.6}],standsUp:[{seconds:1.2,hold:!0,pose:"rise"}],greets:[{seconds:1.6,hold:!0,pose:"waiting",face:B.happy,flash:.4},{seconds:.6,face:B.happy}],greetsBack:[{seconds:.5},{seconds:1.6,hold:!0,pose:"waiting",face:B.cheer,flash:.4}],glances:[{seconds:1.5,kick:{head:.9}}],glancesBack:[{seconds:.25},{seconds:1.25,kick:{head:.9}}],inspects:[{seconds:.55,hold:!0,pose:"kneel",face:B.wait,head:{pitch:.35}},{seconds:2.2,hold:!0,pose:"kneel",face:B.wait,head:{pitch:.55,roll:.18}},{seconds:.55,hold:!0,pose:"rise",face:B.happy}],picksUp:[{seconds:.55,hold:!0,pose:"kneel",face:B.wait,head:{pitch:.4}},{seconds:.7,hold:!0,pose:"kneel",face:B.happy,head:{pitch:.5},pickup:!0},{seconds:.55,hold:!0,pose:"rise",face:B.happy,head:{pitch:.1}}],dropsOff:[{seconds:.55,hold:!0,facePile:!0,pose:"kneel",face:B.happy,head:{pitch:.45}},{seconds:.5,hold:!0,facePile:!0,pose:"kneel",face:B.happy,head:{pitch:.5},drop:!0},{seconds:.55,hold:!0,facePile:!0,pose:"rise",face:B.happy,head:{pitch:.3}},{seconds:1.2,hold:!0,facePile:!0,pose:"idle",face:B.love,head:{pitch:.32,roll:.15},flash:.5}]},tn={gap:7,rest:[25,50],wave:.45},Mn={every:[30,70],fetch:.15,pileMax:30};function wh(s){return(s.status==="idle"||s.status==="celebrating")&&(s.state==="at-site"||s.state==="walking")&&!s.story&&!s.carry&&!(s.greetIn>0)}function z4(s,e,t=Math.random){return s.status!=="idle"||s.state!=="at-site"||s.story||s.carry?null:e<Mn.pileMax&&s.pile&&t()<Mn.fetch?"picksUp":"inspects"}function L4(s,e,t=!1){return e==="celebrating"?"shipped":e==="error"||e==="broken"?"errored":(e==="done"||e==="asking")&&(s==="working"||s==="delegating")?"asks":(s==="done"||s==="asking")&&e!=="leaving"?t?"perksUp":"answered":t&&e!=="sleeping"&&e!=="leaving"?"standsUp":null}function sn(s,e,t){const i=P4[e];s.story=i?{name:e,beats:i,at:t,index:-1}:null}function R4(s,e,t){const i=s.story;if(!i)return null;let n=e-i.at,r=0;for(;r<i.beats.length&&n>=i.beats[r].seconds;)n-=i.beats[r].seconds,r++;return r>=i.beats.length?(s.story=null,null):(r!==i.index&&(i.index=r,t?.(i.beats[r])),i.beats[r])}const Xr=30,ia=.9,B4=.45,mr=[{count:7,radius:.15,lift:0},{count:6,radius:.11,lift:.07},{count:5,radius:.075,lift:.13},{count:4,radius:.045,lift:.18},{count:3,radius:.025,lift:.22},{count:2,radius:.012,lift:.255},{count:3,radius:0,lift:.285}],Yr=[9080726,10261385,8223348,10986138,7304315,9734780],Qr=[13198402,5224137,14858314,9399e3,6275706,13789071];function F4(s){return Qr[s%Qr.length]}const O4=s=>(s=Math.imul(s^s>>>15,739982445),s=Math.imul(s^s>>>12,695872825),((s^s>>>15)>>>0)/4294967296);function I4(s,e,t={}){s=Math.min(s,Xr-1);let i=s,n=0;for(;n<mr.length-1&&i>=mr[n].count;)i-=mr[n++].count;const{count:r,radius:o,lift:a}=mr[n],c=e%997/997*Math.PI*2+n*.55+i/r*Math.PI*2,h=O4(e+s*31),d=s%4===3;return t.x=Math.cos(c)*o,t.z=Math.sin(c)*o,t.size=d?.045:.05+h*.02,t.y=a+t.size*.75,t.stretch=d?1.7:.7+h*.25,t.spin=h*Math.PI*2,t.color=d?Qr[(e+(s>>2))%Qr.length]:Yr[Math.floor(h*Yr.length)],t.layer=n,t}class D4{constructor(e=4096,t=256){this.geometry=new Il(1,0),this.material=new tt({roughness:.82,metalness:.08,flatShading:!0}),this.material.onBeforeCompile=i=>{wt(i)},this.piles=new zt(this.geometry,this.material,e),this.held=new zt(this.geometry,this.material,t);for(const i of[this.piles,this.held])i.count=0,i.frustumCulled=!1,i.receiveShadow=!0,i.name=i===this.piles?"trinket-piles":"trinket-held",i.instanceMatrix.setUsage(at);this.meshes=[this.piles,this.held],this._m=new xt,this._q=new Fi,this._e=new Ur,this._p=new F,this._s=new F,this._c=new W,this._item={},this._piles=0,this._held=0}beginPiles(){this._piles=0}pile(e,t,i,n,r){const o=this.piles;for(let a=0;a<Math.min(n,Xr)&&this._piles<o.instanceMatrix.count;a++){const l=I4(a,r,this._item);this._e.set(l.spin*.3,l.spin,l.spin*.2),this._q.setFromEuler(this._e),this._p.set(e+l.x,t+l.y,i+l.z),this._s.set(l.size,l.size*l.stretch,l.size),this._m.compose(this._p,this._q,this._s),o.setMatrixAt(this._piles,this._m),o.setColorAt(this._piles,this._c.setHex(l.color)),this._piles++}}endPiles(){this.piles.count=this._piles,this.piles.instanceMatrix.needsUpdate=!0,this.piles.instanceColor&&(this.piles.instanceColor.needsUpdate=!0)}beginHeld(){this._held=0}hold(e,t,i,n){this._held>=this.held.instanceMatrix.count||(this._m.compose(t,this._q.identity(),this._s.setScalar(i)),this._m.premultiply(e),this.held.setMatrixAt(this._held,this._m),this.held.setColorAt(this._held,this._c.setHex(Yr[n%Yr.length])),this._held++)}endHeld(){this.held.count=this._held,this.held.instanceMatrix.needsUpdate=!0,this.held.instanceColor&&(this.held.instanceColor.needsUpdate=!0)}setShadows(e){for(const t of this.meshes)t.castShadow=e}dispose(){this.geometry.dispose(),this.material.dispose();for(const e of this.meshes)e.dispose()}}const Pi={days:60,bytes:[3e5,1e8],scuffs:.08,stickers:[.2,.5,.8],dents:[.35,.65]},V4=864e5,Fr=s=>Math.min(1,Math.max(0,s));function N4(s,e){const t=Math.max(1,s?.sizeBytes||0),[i,n]=Pi.bytes.map(Math.log10),r=Fr((Math.log10(t)-i)/(n-i)),o=s?.createdAt?Fr((e-s.createdAt)/V4/Pi.days):0;return Fr(r*.6+o*.4)}const W4=`
|
|
1949
|
-
const vec3 WEAR_SPOTS[6] = vec3[6](
|
|
1950
|
-
vec3(-0.75, 0.45, -0.48), vec3(0.72, 0.5, -0.48), vec3(0.0, 0.92, -0.38),
|
|
1951
|
-
vec3(-0.35, 0.15, -0.92), vec3(0.45, -0.1, -0.88), vec3(0.0, 0.55, -0.83));
|
|
1952
|
-
|
|
1953
|
-
vec3 wearSpot( float seed, int k ) {
|
|
1954
|
-
return normalize( WEAR_SPOTS[ ( k + int( seed * 6.0 ) ) % 6 ] );
|
|
1955
|
-
}
|
|
1956
|
-
|
|
1957
|
-
float wearHash( vec3 p ) {
|
|
1958
|
-
return fract( sin( dot( p, vec3( 127.1, 311.7, 74.7 ) ) ) * 43758.5453 );
|
|
1959
|
-
}
|
|
1960
|
-
|
|
1961
|
-
float wearNoise( vec3 p ) {
|
|
1962
|
-
vec3 i = floor( p );
|
|
1963
|
-
vec3 f = fract( p );
|
|
1964
|
-
f = f * f * ( 3.0 - 2.0 * f );
|
|
1965
|
-
return mix(
|
|
1966
|
-
mix( mix( wearHash( i ), wearHash( i + vec3( 1, 0, 0 ) ), f.x ),
|
|
1967
|
-
mix( wearHash( i + vec3( 0, 1, 0 ) ), wearHash( i + vec3( 1, 1, 0 ) ), f.x ), f.y ),
|
|
1968
|
-
mix( mix( wearHash( i + vec3( 0, 0, 1 ) ), wearHash( i + vec3( 1, 0, 1 ) ), f.x ),
|
|
1969
|
-
mix( wearHash( i + vec3( 0, 1, 1 ) ), wearHash( i + vec3( 1, 1, 1 ) ), f.x ), f.y ), f.z );
|
|
1970
|
-
}
|
|
1971
|
-
|
|
1972
|
-
float wearGrime( vec3 p, float amount ) {
|
|
1973
|
-
float n = wearNoise( p );
|
|
1974
|
-
return smoothstep( 1.0 - 0.26 * amount, 1.06 - 0.26 * amount, n ) * amount;
|
|
1975
|
-
}
|
|
1976
|
-
|
|
1977
|
-
vec4 wearSticker( vec3 d, vec3 c, int shape, vec3 accent ) {
|
|
1978
|
-
if ( dot( d, c ) < 0.9 ) return vec4( 0.0 );
|
|
1979
|
-
vec3 u = normalize( cross( c, vec3( 0.001, 1.0, 0.0 ) ) );
|
|
1980
|
-
vec3 v = cross( u, c );
|
|
1981
|
-
vec2 q = vec2( dot( d, u ), dot( d, v ) ) / 0.2;
|
|
1982
|
-
float r = length( q );
|
|
1983
|
-
if ( shape == 0 ) {
|
|
1984
|
-
return vec4( r < 0.4 ? vec3( 0.95 ) : accent, 1.0 - smoothstep( 0.9, 1.0, r ) );
|
|
1985
|
-
}
|
|
1986
|
-
if ( shape == 1 ) {
|
|
1987
|
-
float edge = mix( 0.45, 1.0, pow( 0.5 + 0.5 * cos( 5.0 * atan( q.y, q.x ) ), 2.0 ) );
|
|
1988
|
-
return vec4( accent, 1.0 - smoothstep( edge - 0.1, edge, r ) );
|
|
1989
|
-
}
|
|
1990
|
-
vec2 h = vec2( q.x * 1.15, q.y * 1.2 + 0.3 );
|
|
1991
|
-
float k = dot( h, h ) - 1.0;
|
|
1992
|
-
float heart = k * k * k - h.x * h.x * h.y * h.y * h.y;
|
|
1993
|
-
return vec4( accent, 1.0 - smoothstep( -0.03, 0.03, heart ) );
|
|
1994
|
-
}
|
|
1995
|
-
`;function H4(s,e){const t=i=>i.filter(n=>s>=n).length;return{level:s,scuffs:Fr((s-Pi.scuffs)/(1-Pi.scuffs)),stickers:t(Pi.stickers),dents:t(Pi.dents),accent:F4(e)}}function U4(s,e,t,i,n){ai(s).applyMatrix4(t.matrixWorldInverse);const r=-s.z;return n.visible=r>=t.near&&r<=t.far,n.depth=r,n.radius=t.projectionMatrix.elements[5]*e/Math.max(t.near,r-e),s.applyMatrix4(t.projectionMatrix),n.x=s.x*i,n.y=s.y,n.z=s.z,n}function j4(s,e,t,i=t){if(!t.visible||!i.visible)return 1/0;const n=i.x-t.x,r=i.y-t.y,o=n*n+r*r,a=o>1e-10?Math.max(0,Math.min(1,((s-t.x)*n+(e-t.y)*r)/o)):0,l=t.radius+(i.radius-t.radius)*a;return Math.max(0,Math.hypot(s-t.x-n*a,e-t.y-r*a)-l)}const me={url:"assets/baut.glb",size:.787,scale:.19,lift:.62,ground:.42,parts:["hull","trim","face","visor","crown","rings"],shadows:["hull","trim"],centre:[0,0,-.2],pick:[{at:[0,.1,0],radius:2},{at:[0,2.7,-.4],radius:.8},{at:[2.7,1.5,-1.6],radius:.95},{at:[-2.7,1.5,-1.6],radius:.95},{at:[2.2,-1.3,-1.9],radius:.95},{at:[-2.2,-1.3,-1.9],radius:.95}],carry:[0,-2.5,.1],carrySize:.09,trim:{shade:.62,roughness:.7,env:.5},head:{pitch:.6,up:1,roll:.6},look:{share:.75,max:.6},lights:{crown:[.8,.6],rings:[.95,.75],fault:6.5,swell:.9,attack:.15},halos:{crown:{at:[0,1.955,.535],size:1.8,strength:.24},rings:{x:1.97,r:.8,count:6,size:1,strength:.13}},leaveRise:1.6,badge:1.12,blend:.45},Zs=[{light:"crown",at:me.halos.crown.at,size:me.halos.crown.size},...[-1,1].flatMap(s=>Array.from({length:me.halos.rings.count},(e,t)=>{const i=t/me.halos.rings.count*Math.PI*2,{x:n,r,size:o}=me.halos.rings;return{light:"rings",at:[s*n,Math.sin(i)*r,Math.cos(i)*r],size:o}}))];function q4(s){return .3+.7*(.5+.5*Math.sin(s*me.lights.fault))**2}const vn=me.ground-me.lift,m0=s=>s*s*(3-2*s),nl=(s,e)=>m0(Math.min(Math.max(s/e,0),1)),na=s=>({y:Math.sin(s*1.7)*.05,rx:Math.sin(s*1.3)*.03,rz:Math.sin(s*.9)*.05});function bh(s){const e=s%2,t=e<1.2?Math.sin(e/1.2*Math.PI):0;return{y:.08+Math.sin(s*1.7)*.03,rx:-.04,rz:Math.sin(s*9)*.2*t}}function G4(s){const e=s%4.5;return e<.6?Math.sin(e/.6*Math.PI)*.32:0}function vh(s,e,t=0,i=.7){const n=nl(s,1.2);return{y:vn*n+Math.sin(s*i)*.007*n,rx:e*n,rz:t*n}}const nn={rate:1.15,down:.16,back:.45};function Z4(s){const e=s*nn.rate%1;return e<nn.down?Math.sin(e/nn.down*(Math.PI/2)):Math.max(0,1-(e-nn.down)/nn.back)}const yh={idle:na,moving:s=>({y:Math.sin(s*2.4)*.03}),spawning:s=>{if(s<.5)return{y:vn};const e=Math.min((s-.5)/.9,1),t=1-(1-e)**3;return{y:vn*(1-t)+Math.sin(e*Math.PI)*.07+(e>=1?Math.sin((s-1.4)*1.7)*.05:0)}},working:s=>{const e=Z4(s);return{y:-.04*e+Math.sin(s*1.7)*.02,rx:.17*e}},delegating:s=>({...na(s),ry:Math.sin(s*.7)*.55}),waiting:bh,eager:s=>{const e=bh(s);return e.y+=G4(s),e},sulking:s=>vh(s,.14,.05,.6),error:s=>{const e=s%2.6,t=Math.exp(-e*4);return{y:-.07*(1-t)-.05*t+Math.sin(s*1.2)*.015,rx:-.3*t+.1*(1-t),rz:Math.sin(e*42)*.1*t}},celebrating:s=>{const e=s%1.8,t=Math.min(e/.9,1);return{ry:(t<.5?2*t*t:1-(-2*t+2)**2/2)*Math.PI*2,y:Math.sin(t*Math.PI)*.3+Math.sin(s*1.7)*.02}},sleeping:s=>vh(s,.2),kneel:s=>{const e=nl(s,.55);return{y:vn*.85*e,rx:.16*e}},rise:s=>{const e=nl(s,1),t=na(s);return{y:vn*(1-e)+t.y*e,rx:t.rx*e,rz:t.rz*e}}},X4={sulking:1.2,sleeping:1.2,kneel:.55},Y4=new Set(["sulking","sleeping"]),Q4=.12;function K4(s){if(s.state==="spawning")return"spawning";if((s.groundSpeed||0)>Q4)return"moving";const e=s.beat?.pose;if(e)return e;switch(s.status){case"working":return"working";case"delegating":return"delegating";case"asking":case"done":return s.waitStage==="sulk"?"sulking":s.waitStage==="eager"?"eager":"waiting";case"error":case"broken":return"error";case"celebrating":return"celebrating";case"sleeping":return"sleeping";default:return s.pose.key==="rise"&&s.pose.t<1?"rise":"idle"}}function Ch(s="idle",e=0){return{key:s,t:e,from:s,fromT:e,blend:1,landed:!1,y:0,rx:0,ry:0,rz:0,s:1}}function J4(s,e){return s.key===e?!1:(s.from=s.key,s.fromT=s.t,s.key=e,s.t=0,s.blend=0,s.landed=!1,!0)}const e3=[["y",0],["rx",0],["ry",0],["rz",0],["s",1]];function t3(s,e){s.t+=e,s.fromT+=e,s.blend=Math.min(1,s.blend+e/me.blend);const t=yh[s.key](s.t),i=m0(s.blend),n=i<1?yh[s.from](s.fromT):t;for(const[r,o]of e3){const a=n[r]??o;s[r]=a+((t[r]??o)-a)*i}return s}let rl=null,ra=null;function s3(){return ra||(ra=new Zp().loadAsync(`/${me.url}`).then(s=>{const e={};s.scene.traverse(i=>{i.isMesh&&(e[i.name==="glass"?"visor":i.name]=i.geometry)});const t=me.parts.filter(i=>!e[i]);if(t.length)throw new Error(`baut: baut.glb has no ${t.join(", ")} — run \`pnpm assets\``);return rl={geometries:e},rl})),ra}function i3(){return rl}const ot={working:"#e7c869",delegating:"#7fd2d8",asking:"#8fb4ee",done:"#89d391",error:"#e88b8b",celebrating:"#e89bd6",idle:"#a3a2c8"},g0=[[.59719,.35458,.04823],[.076,.90834,.01566],[.0284,.13383,.83777]],w0=[[1.60475,-.53108,-.07367],[-.10208,1.10813,-.00605],[-.00327,-.07276,1.07602]],Kr=(s,e)=>s.map(t=>t[0]*e[0]+t[1]*e[1]+t[2]*e[2]);function b0(s){const[[e,t,i],[n,r,o],[a,l,c]]=s,h=e*(r*c-o*l)-t*(n*c-o*a)+i*(n*l-r*a);return[[(r*c-o*l)/h,(i*l-t*c)/h,(t*o-i*r)/h],[(o*a-n*c)/h,(e*c-i*a)/h,(i*n-e*o)/h],[(n*l-r*a)/h,(t*a-e*l)/h,(e*r-t*n)/h]]}const n3=b0(g0),r3=b0(w0);function o3(s){const e=1-.983729*s,t=.0245786-.432951*s,i=-(90537e-9+.238081*s);return(-t+Math.sqrt(t*t-4*e*i))/(2*e)}const a3=s=>s<=.04045?s/12.92:((s+.055)/1.055)**2.4;function ol(s){const e=parseInt(s.slice(1),16);return[e>>16&255,e>>8&255,e&255].map(t=>a3(t/255))}function $s(s,e=0){let t=ol(s);const i=Math.max(...t);t=t.map(r=>r*(1+(.97/i-1)*e));const n=Kr(r3,t).map(r=>o3(Math.min(Math.max(r,0),1.01)));return Kr(n3,n).map(r=>Math.round(Math.max(r,0)*.6*1e3)/1e3)}function l3(s){const e=Kr(g0,s.map(t=>t/.6)).map(t=>(t*(t+.0245786)-90537e-9)/(t*(.983729*t+.432951)+.238081));return Kr(w0,e).map(t=>Math.min(Math.max(t,0),1))}const jl=1.55,c3=jl*.77,h3=1.4,Jr=s=>Math.round(s*1e3)/1e3;function ks(s,e=h3,t=1){const i=$s(s);return{trim:i.map(n=>Jr(n*t)),eye:i.map(n=>Jr(n*e/c3))}}const al={working:ks(ot.working),delegating:ks(ot.delegating),asking:ks(ot.asking),done:ks(ot.done),error:ks(ot.error),celebrating:ks(ot.celebrating),idle:ks(ot.idle),sleeping:ks(ot.idle,.8,.55),spawning:{trim:ol("#c96442").map(Jr),eye:[2.4,1.4,.7]},leaving:{trim:ol("#6f7f75").map(Jr),eye:[1,1,1.1]}},xh=[15987180,15262940,16250094,14673128,15854047],Mh=2.1,d3={asking:0,error:1,done:2,working:3,delegating:4,celebrating:5,idle:6,sleeping:7},gr=s=>d3[s.status]??8,u3=7.5,f3=6,kh=5.5,Th=.55,Si=1.22,_h=1.12,wr=2.4,Ts={reach:45,perSecond:5,whirr:2.2,whirrRest:1.2,powerUpGap:.8},p3=Object.freeze({soft:!0}),m3=Ti[0],Sh=.9,br=1.7,oa=.55,vr=Si+.45,g3=6,w3=.4;class b3{constructor(e,t,i=null){this.scene=e,this.settings=t,this.camera=i,this.agents=[],this.byId=new Map,this.capacity=0,this.group=new Pt,this.group.name="astronauts",e.add(this.group),this.reflectionUniforms=t1(),this.faceTexture=mh(Math.min(t.textureSize*2,1024)),this._atlasFaces={value:0},this._buildMeshes(Math.max(64,t.get("maxAgents"))),this.trinkets=new D4;for(const n of this.trinkets.meshes)this.group.add(n);this.trinkets.setShadows(this.settings.shadowSize>0),this.trinketCounts=new Map,this._pilesAt=-1/0,this._pilesDirty=!0,this._lastGreeting=-1/0,this._held=new F,this._machineBudget=Ts.perSecond,this._poweredUpAt=-1/0,this._m=new xt,this._m2=new xt,this._m3=new xt,this._m4=new xt,this._q=new Fi,this._e=new Ur,this._v=new F,this._one=new F(1,1,1),this._color=new W,this._wp=new F,this._sep=new F,this._pickBadge=new F,this._pickLifted=new F,this._pickBody=me.pick.map(()=>({})),this._headTurn=new Ur(0,0,0,"YXZ"),this._haloLocal=Zs.map(n=>new xt().compose(new F(...n.at),new Fi,new F().setScalar(n.size))),this._look={yaw:0,pitch:0},this._clock=0,this.hovered=null,this._drawnAgents=[],this._buckets=new Map,this.nav=null,this._rosters=0,this._queue=[],this._queueTimer=0,this._queueEvery=.3}_buildMeshes(e){this.capacity=e,this.parts={},this.model&&this._buildParts(),this.hoverRing=$h(.52,.6,10475775,.5),this.selectRing=$h(.6,.71,16765578,.9),this.hoverRing.visible=!1,this.selectRing.visible=!1,this.group.add(this.hoverRing,this.selectRing)}setModel(e){!e||this.model===e||(this.model=e,this._disposeParts(),this._buildParts())}_buildParts(){const{geometries:e}=this.model,t=this.capacity,i=this.parts={},n=(a,l={})=>new tt({color:16777215,roughness:a,metalness:.03,...l}),r=e.hull.clone();i.hull=this._mesh(r,this._hullMaterial(n(.42,{vertexColors:!0,envMapIntensity:.9,side:vt})),t),this.hullWear=this._attachWear(r,t,"aWear","aAccent"),i.trim=this._mesh(e.trim.clone(),n(me.trim.roughness,{envMapIntensity:me.trim.env,side:vt}),t),i.face=this._mesh(e.face.clone(),this._faceMaterial(),t),this._attachFrameAttribute(i.face,t),this._attachEyeAttributes(i.face,t),i.visor=this._mesh(e.visor.clone(),this._visorMaterial(),t);const o=new dt({color:16777215,toneMapped:!0});i.crown=this._mesh(e.crown.clone(),o,t),i.rings=this._mesh(e.rings.clone(),o.clone(),t),i.halo=this._mesh(new Ut(1,1),this._haloMaterial(),t*Zs.length);for(const a of Object.values(i))a.frustumCulled=!1,this.group.add(a);this._applyShadowFlags();for(const a of this.agents)a.colorDirty=!0}_disposeParts(){for(const e of Object.values(this.parts??{}))this.group.remove(e),e.geometry.dispose(),e.material.dispose();this.parts={}}_mesh(e,t,i){const n=new zt(e,t,i);n.instanceMatrix.setUsage(at),n.count=0,n.receiveShadow=!1;const r=new W(1,1,1);for(let o=0;o<i;o++)n.setColorAt(o,r);return n.instanceColor.setUsage(at),n}_attachWear(e,t,i,n){const r=new Ze(new Float32Array(t*4),4),o=new Ze(new Float32Array(t*3),3);for(const a of[r,o])a.setUsage(at);return e.setAttribute(i,r),e.setAttribute(n,o),{wear:r,accent:o}}_hullMaterial(e){const t=me.centre.map(i=>i.toFixed(3)).join(", ");return e.onBeforeCompile=i=>{wt(i),i.vertexShader=i.vertexShader.replace("#include <common>",`#include <common>
|
|
1996
|
-
attribute vec4 aWear;
|
|
1997
|
-
attribute vec3 aAccent;
|
|
1998
|
-
varying vec4 vWear;
|
|
1999
|
-
varying vec3 vAccent;
|
|
2000
|
-
varying vec3 vShellDir;
|
|
2001
|
-
varying float vShell;`).replace("#include <begin_vertex>",`#include <begin_vertex>
|
|
2002
|
-
vWear = aWear;
|
|
2003
|
-
vAccent = aAccent;
|
|
2004
|
-
vShellDir = position - vec3( ${t} );
|
|
2005
|
-
vShell = color.r;`),i.fragmentShader=i.fragmentShader.replace("#include <common>",`#include <common>
|
|
2006
|
-
varying vec4 vWear;
|
|
2007
|
-
varying vec3 vAccent;
|
|
2008
|
-
varying vec3 vShellDir;
|
|
2009
|
-
varying float vShell;
|
|
2010
|
-
${W4}`).replace("#include <color_fragment>",`#include <color_fragment>
|
|
2011
|
-
if ( vShell > 0.8 ) {
|
|
2012
|
-
vec3 d = normalize( vShellDir );
|
|
2013
|
-
float seed = vWear.w;
|
|
2014
|
-
diffuseColor.rgb *= 1.0 - 0.32 * wearGrime( d * 9.0 + seed * 31.0, vWear.x );
|
|
2015
|
-
for ( int k = 0; k < 2; k ++ ) {
|
|
2016
|
-
if ( float( k ) >= vWear.z ) break;
|
|
2017
|
-
float a = 1.0 - dot( d, wearSpot( seed, k + 3 ) );
|
|
2018
|
-
float rim = smoothstep( 0.008, 0.012, a ) * ( 1.0 - smoothstep( 0.012, 0.018, a ) );
|
|
2019
|
-
diffuseColor.rgb *= 1.0 - 0.25 * ( 1.0 - smoothstep( 0.004, 0.012, a ) );
|
|
2020
|
-
diffuseColor.rgb += 0.05 * rim;
|
|
2021
|
-
}
|
|
2022
|
-
for ( int k = 0; k < 3; k ++ ) {
|
|
2023
|
-
if ( float( k ) >= vWear.y ) break;
|
|
2024
|
-
vec4 sticker = wearSticker( d, wearSpot( seed, k ), ( k + int( seed * 7.0 ) ) % 3, vAccent );
|
|
2025
|
-
diffuseColor.rgb = mix( diffuseColor.rgb, sticker.rgb, sticker.a );
|
|
2026
|
-
}
|
|
2027
|
-
}`)},e}_haloMaterial(){const e=new dt({color:16777215,transparent:!0,depthWrite:!1,fog:!1,blending:ji});return e.onBeforeCompile=t=>{wt(t),t.vertexShader=t.vertexShader.replace("#include <common>",`#include <common>
|
|
2028
|
-
varying vec2 vHalo;`).replace("#include <project_vertex>",`vec4 haloCentre = modelMatrix * instanceMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );
|
|
2029
|
-
float haloSize = length( ( modelMatrix * instanceMatrix * vec4( 1.0, 0.0, 0.0, 0.0 ) ).xyz );
|
|
2030
|
-
vec4 mvPosition = viewMatrix * vec4( bcBend( haloCentre.xyz ), 1.0 );
|
|
2031
|
-
mvPosition.z += haloSize * 0.35;
|
|
2032
|
-
mvPosition.xy += position.xy * haloSize;
|
|
2033
|
-
vHalo = position.xy * 2.0;
|
|
2034
|
-
gl_Position = projectionMatrix * mvPosition;`),t.fragmentShader=t.fragmentShader.replace("#include <common>",`#include <common>
|
|
2035
|
-
varying vec2 vHalo;`).replace("#include <color_fragment>",`#include <color_fragment>
|
|
2036
|
-
float haloR = dot( vHalo, vHalo );
|
|
2037
|
-
diffuseColor.rgb *= exp( -haloR * 4.0 ) * ( 1.0 - smoothstep( 0.6, 1.0, haloR ) );`)},e}_visorMaterial(){const e=new Eu({color:16777215,roughness:.08,metalness:0,ior:1.46,transparent:!0,opacity:1,depthWrite:!1,envMapIntensity:1});return e.onBeforeCompile=t=>{wt(t),s1(t,this.reflectionUniforms),t.fragmentShader=t.fragmentShader.replace("#include <opaque_fragment>",`float facing = clamp( dot( normal, normalize( vViewPosition ) ), 0.0, 1.0 );
|
|
2038
|
-
float fresnel = 0.035 + 0.965 * pow( 1.0 - facing, 5.0 );
|
|
2039
|
-
// A thin window has two air/glass interfaces. Sum their reflections while
|
|
2040
|
-
// preserving the transmission through to the recessed display.
|
|
2041
|
-
float windowReflectance = 2.0 * fresnel / ( 1.0 + fresnel );
|
|
2042
|
-
diffuseColor.a = windowReflectance;
|
|
2043
|
-
// Physical specular already contains Fresnel. Undo the subsequent alpha
|
|
2044
|
-
// multiplication so glass reflections aren't attenuated a second time.
|
|
2045
|
-
// The background is the actual recessed screen drawn into this same buffer.
|
|
2046
|
-
// Reflect the HDR environment, including the planet's sun/clouds. Analytic
|
|
2047
|
-
// directional specular adds a second, needle-sharp dot to every visor.
|
|
2048
|
-
outgoingLight = reflectedLight.indirectSpecular / max( fresnel, 0.035 );
|
|
2049
|
-
#include <opaque_fragment>`)},e}_faceMaterial(){const e=new dt({map:this.faceTexture,toneMapped:!0});return e.onBeforeCompile=t=>{t.uniforms.uFrameScale={value:new Se(1/Kt,1/Gr)},t.uniforms.uGlow={value:jl},t.uniforms.uAtlasFaces=this._atlasFaces,wt(t),this._faceUniforms=t.uniforms,t.vertexShader=t.vertexShader.replace("#include <common>",`#include <common>
|
|
2050
|
-
attribute vec2 aFrame;
|
|
2051
|
-
attribute vec4 aEyeSize;
|
|
2052
|
-
attribute vec4 aEyeLids;
|
|
2053
|
-
attribute vec2 aEyeMood;
|
|
2054
|
-
uniform vec2 uFrameScale;
|
|
2055
|
-
varying vec2 vScreenUv;
|
|
2056
|
-
varying vec2 vFrameOrigin;
|
|
2057
|
-
varying vec4 vEyeSize;
|
|
2058
|
-
varying vec4 vEyeLids;
|
|
2059
|
-
varying vec2 vEyeMood;`).replace("#include <uv_vertex>",`#include <uv_vertex>
|
|
2060
|
-
vScreenUv = uv;
|
|
2061
|
-
vFrameOrigin = aFrame;
|
|
2062
|
-
vEyeSize = aEyeSize;
|
|
2063
|
-
vEyeLids = aEyeLids;
|
|
2064
|
-
vEyeMood = aEyeMood;`),t.fragmentShader=t.fragmentShader.replace("#include <common>",`#include <common>
|
|
2065
|
-
uniform float uGlow;
|
|
2066
|
-
uniform float uAtlasFaces;
|
|
2067
|
-
uniform vec2 uFrameScale;
|
|
2068
|
-
varying vec2 vScreenUv;
|
|
2069
|
-
varying vec2 vFrameOrigin;
|
|
2070
|
-
varying vec4 vEyeSize;
|
|
2071
|
-
varying vec4 vEyeLids;
|
|
2072
|
-
varying vec2 vEyeMood;
|
|
2073
|
-
float eyeMask( vec2 p, float side, float lid, float smile ) {
|
|
2074
|
-
vec2 gaze = vEyeSize.zw;
|
|
2075
|
-
float w = vEyeSize.x * ( 1.0 - abs( gaze.x ) * ( gaze.x * side < 0.0 ? 1.6 : 0.5 ) );
|
|
2076
|
-
float h = vEyeSize.y;
|
|
2077
|
-
vec2 c = vec2( side < 0.0 ? ${Be.toFixed(4)} : ${Fe.toFixed(4)}, ${ie.toFixed(4)} ) + gaze;
|
|
2078
|
-
vec2 q = p - c;
|
|
2079
|
-
vec2 r = vec2( w, h ) * 0.5;
|
|
2080
|
-
float k = length( q / r );
|
|
2081
|
-
float d = k * ( k - 1.0 ) / max( length( q / ( r * r ) ), 1e-4 );
|
|
2082
|
-
float slope = -side * vEyeMood.x;
|
|
2083
|
-
d = max( d, ( c.y - h * 0.5 + lid * h + slope * q.x - p.y ) / sqrt( 1.0 + slope * slope ) );
|
|
2084
|
-
float radius = w * 0.9;
|
|
2085
|
-
d = max( d, radius - length( p - vec2( c.x, c.y + h * 0.5 - smile * h + radius ) ) );
|
|
2086
|
-
float aa = max( fwidth( d ), 1e-4 );
|
|
2087
|
-
return 1.0 - smoothstep( -aa, aa, d );
|
|
2088
|
-
}`).replace("#include <map_fragment>",`
|
|
2089
|
-
// Static barrel distortion bends the lettering and raster together on the
|
|
2090
|
-
// inner tube; the outer window and its reflections stay undistorted.
|
|
2091
|
-
vec2 tube = ( vScreenUv - 0.5 ) * 2.0;
|
|
2092
|
-
vec2 crtUv = 0.5 + 0.5 * tube * ( 1.0 + 0.085 * dot( tube, tube ) );
|
|
2093
|
-
vec2 atlasUv = clamp( crtUv, 0.003, 0.997 ) * uFrameScale + vFrameOrigin;
|
|
2094
|
-
vec2 eyeUv = vec2( crtUv.x, 1.0 - crtUv.y );
|
|
2095
|
-
float eyes = max(
|
|
2096
|
-
eyeMask( eyeUv, -1.0, vEyeLids.x, vEyeLids.z ),
|
|
2097
|
-
eyeMask( eyeUv, 1.0, vEyeLids.y, vEyeLids.w ) ) * vEyeMood.y;
|
|
2098
|
-
float mask = mix( eyes, texture2D( map, atlasUv ).r, uAtlasFaces );
|
|
2099
|
-
float scanY = crtUv.y * 44.0;
|
|
2100
|
-
float scanDetail = 1.0 - smoothstep( 0.28, 0.5, fwidth( scanY ) );
|
|
2101
|
-
// Keep the average brightness constant as unresolvable lines fade away.
|
|
2102
|
-
float raster = 0.77 - scanDetail * 0.23 * cos( scanY * 6.2831853 );
|
|
2103
|
-
vec2 phosphor = crtUv * vec2( 120.0, 88.0 );
|
|
2104
|
-
float dotDetail = 1.0 - smoothstep( 0.25, 0.5, max( fwidth( phosphor.x ), fwidth( phosphor.y ) ) );
|
|
2105
|
-
float grain = 1.0 - dotDetail * 0.045 * ( 1.0 + cos( phosphor.x * 6.2831853 ) * cos( phosphor.y * 6.2831853 ) );
|
|
2106
|
-
float edge = smoothstep( 0.25, 0.5, length( vScreenUv - 0.5 ) );
|
|
2107
|
-
vec3 screen = vec3( 0.014, 0.031, 0.079 ) * ( 1.0 - edge * 0.48 );
|
|
2108
|
-
// The dim phosphor bed shares the raster, while status colours still belong
|
|
2109
|
-
// to each agent and every existing atlas expression remains available.
|
|
2110
|
-
// Blue phosphor stripes remain visible on the unlit portions of the CRT.
|
|
2111
|
-
vec3 bed = screen * ( 0.74 - scanDetail * 0.26 * cos( scanY * 6.2831853 ) );
|
|
2112
|
-
diffuseColor.rgb = ( bed + vColor.rgb * mask * uGlow * raster ) * grain;
|
|
2113
|
-
diffuseColor.a = 1.0;
|
|
2114
|
-
`).replace("#include <color_fragment>","")},e}_attachFrameAttribute(e,t){const i=new Float32Array(t*2),n=new Ze(i,2);n.setUsage(at),e.geometry.setAttribute("aFrame",n),this.frameAttr=n}_attachEyeAttributes(e,t){const i=new Xp(new Float32Array(t*xn),xn);i.setUsage(at),e.geometry.setAttribute("aEyeSize",new Po(i,4,0)),e.geometry.setAttribute("aEyeLids",new Po(i,4,4)),e.geometry.setAttribute("aEyeMood",new Po(i,2,8)),this.eyeBuffer=i}_applyShadowFlags(){const e=this.settings.shadowSize>0;for(const[t,i]of Object.entries(this.parts))i.castShadow=e&&me.shadows.includes(t);this.trinkets?.setShadows(e)}setNavigation(e){this.nav=e}onSettingsChanged(e){if(e.has("shadows")&&this._applyShadowFlags(),e.has("textureQuality")&&(this.faceTexture.dispose(),this.faceTexture=mh(Math.min(this.settings.textureSize*2,1024)),this.parts.face&&(this.parts.face.material.map=this.faceTexture,this.parts.face.material.needsUpdate=!0)),e.has("maxAgents")){const t=Math.max(64,this.settings.get("maxAgents"));if(t!==this.capacity){this._disposeParts(),this.group.remove(this.hoverRing,this.selectRing),this._buildMeshes(t);for(const i of this.agents)i.index=-1,i.colorDirty=!0}this.roster&&this.setRoster(this.roster)}}setRoster(e,t){this.roster=e,this.world=t||this.world;const i=Math.min(this.capacity,this.settings.get("maxAgents")),n=e.length>i?[...e].sort((d,u)=>gr(d)-gr(u)).slice(0,i):e,r=new Set,o=e.length>i,a=this._rosters++===0;let l=f3;const c=[];for(const d of n){r.add(d.id);const u=this.byId.get(d.id);if(u){this._updateAgent(u,d);continue}if(a){const p=this._spawnAgent(d,!0);p.state="queued",p.scale=0,c.push(p);continue}const f=!d.known&&l>0;f&&l--,this._spawnAgent(d,f)}c.length&&(c.sort((d,u)=>gr(d)-gr(u)),this._queue.push(...c),this._queueEvery=N.clamp(40/this._queue.length,.35,.8),this._queueTimer=.4);const h=o?new Set(e.map(d=>d.id)):r;for(const d of[...this.agents])r.has(d.id)||d.state==="leaving"||(h.has(d.id)?this._drop(d):this._sendHome(d));return this.agents.length}_spawnAgent(e,t=!0){const i=this.world?.shipDoor?.()||new F(0,0,0),n=this.world?.shipAirlock?.()||i,r=()=>(Math.random()-.5)*1.4,o=e.site||i,a=t?new F(n.x,n.y,n.z):new F(o.x+r(),0,o.z+r());if(!t&&this.nav){const d=this.nav.nearestClear(a.x,a.z,3);d&&a.set(d.x,0,d.z)}const l=t?n.clone():null,c=t?new F(i.x+r()*.5,i.y,i.z+r()*.5):null,h={id:e.id,thread:e.thread,status:e.status,site:e.site?e.site.clone():new F,anchor:e.anchor?e.anchor.clone():null,workSpot:new F,workAt:0,pos:a,vel:new F,ramp:t?0:1,rampFrom:l,rampTo:c,yaw:Math.random()*Math.PI*2,targetYaw:0,speed:Mh*(.86+Math.random()*.28),phase:Math.random()*Math.PI*2,bob:0,state:t?"spawning":"walking",stateAge:0,blinkAt:1+Math.random()*4,faceFrame:B.boot,eyes:o4(B.boot),faceTimer:0,faceIndex:0,annoyed:0,annoyedIndex:0,walkFaceTime:0,walkFaceHold:0,walkPersonality:(Xs(e.id)>>>0)/4294967296,acting:y4(Xs(e.id)>>>11),suit:xh[(Xs(e.id)>>>3)%xh.length],repo:e.accent??m3,eye:new W(1,1,1),trim:new W(16777215),hop:0,story:null,beat:null,waitStage:null,noticedAt:0,interrupted:0,greet:null,greetIn:5+Math.random()*20,curiousIn:15+Math.random()*40,carry:!1,carryFor:0,pile:null,pileStand:null,pileKey:null,whirrAt:0,poweredUp:!1,groundAt:t?n.y:null,groundY:t?n.y:null,groundX:0,groundZ:0,groundSpeed:0,blocked:!1,driftBlocked:!1,stuckFor:0,corr:0,wobble:0,wobbleFrom:new F(NaN,0,NaN),wobbleAt:0,calm:0,ghost:0,pose:Ch(t?"spawning":"idle",t?0:Math.random()*4),matrix:new xt,wander:new F,wanderAt:0,scale:t?0:1,alive:!0,path:null,pathAt:0,pathVersion:-1,pathGoal:new F(NaN,0,NaN),colorDirty:!0,index:-1,walkAmp:0,screen:new F};return this._applyStatus(h,e.status),this._wearFor(h),this.agents.push(h),this.byId.set(h.id,h),h}_wearFor(e){const t=Xs(e.id),i=H4(N4(e.thread,Date.now()),t);i.seed=t%1e3/1e3,e.wear=i}_updateAgent(e,t){if(e.thread=t.thread,this._wearFor(e),t.site){const i=e.given||=new F(NaN,0,NaN),n=Number.isNaN(i.x)||Math.hypot(t.site.x-i.x,t.site.z-i.z)>.05;i.copy(t.site),n&&e.site.copy(t.site);const r=Math.hypot(e.site.x-e.pos.x,e.site.z-e.pos.z);n&&e.state==="at-site"&&r>vr&&(e.state="walking",e.stateAge=0,e.pathVersion=-1)}if(t.anchor&&(e.anchor||=new F).copy(t.anchor),t.accent!==void 0&&t.accent!==e.repo&&(e.repo=t.accent,e.colorDirty=!0),t.status!==e.status){const i=e.status,n=Y4.has(e.pose.key);e.status=t.status,this._applyStatus(e,t.status),$4(e,t.status,i,this.settings.get("reducedMotion")?.35:1),sn(e,L4(i,t.status,n),this._clock??0),t.status==="sleeping"&&this._machine(e,"power-down")}}_beat(e,t,i){const{acting:n}=e;t.kick?.head&&(n.head.pitch.v+=t.kick.head*i),t.flash&&(n.flash=Math.max(n.flash,t.flash)),t.say&&this.onSay?.(e,t.say),t.pickup&&(e.carry=!0,e.carryFor=0),t.drop&&e.carry&&this._addTrinket(e)}setTrinkets(e){for(const[t,i]of Object.entries(e||{})){const n=Math.max(0,Math.min(Xr,Math.floor(Number(i)||0)));n>(this.trinketCounts.get(t)??0)&&(this.trinketCounts.set(t,n),this._pilesDirty=!0)}}_addTrinket(e){e.carry=!1;const t=Math.min(Xr,(this.trinketCounts.get(e.id)??0)+1);this.trinketCounts.set(e.id,t),this._pilesDirty=!0,this.onTrinket?.(e.id,t)}_pileFor(e){if(!this.nav)return null;const t=e.given&&!Number.isNaN(e.given.x)?e.given:e.site,i=`${Math.round(t.x*20)},${Math.round(t.z*20)}`;if(e.pileKey===i)return e.pile;e.pileKey=i,e.pile=null,e.pileStand=null;const n=Xs(e.id)%6283/1e3;for(let r=0;r<6;r++){const o=n+r*(Math.PI/3),a=t.x+Math.cos(o)*ia,l=t.z+Math.sin(o)*ia;if(this.nav.isBlocked(a,l)||this.nav.insideKeep(a,l))continue;const c=ia-B4;e.pile=new F(a,0,l),e.pileStand=new F(t.x+Math.cos(o)*c,0,t.z+Math.sin(o)*c);break}return this._pilesDirty=!0,e.pile}_writePiles(e){this._pilesAt=e,this._pilesDirty=!1;const t=this.world?.groundAt;this.trinkets.beginPiles();for(const i of this.agents){if(i.state==="queued"||i.state==="gone")continue;const n=this.trinketCounts.get(i.id)??0,r=n?this._pileFor(i):null;r&&this.trinkets.pile(r.x,t?t(r.x,r.z):0,r.z,n,Xs(i.id))}this.trinkets.endPiles()}_socialize(e,t,i){e.greetIn-=i,e.greet&&!e.story&&(e.greet=null),e.greet&&e.state==="at-site"&&e.groundSpeed<=.12&&this._faceToward(e,e.greet.pos,i);const n=e.acting.glance;if(!n||n.state==="gone"||!wh(e)||!wh(n)||t-this._lastGreeting<tn.gap)return;this._lastGreeting=t;const r=Math.random()<tn.wave,o=[[e,n,r?"greets":"glances"],[n,e,r?"greetsBack":"glancesBack"]];for(const[a,l,c]of o)a.greet=l,a.greetIn=tn.rest[0]+Math.random()*(tn.rest[1]-tn.rest[0]),sn(a,c,t)}_wonder(e,t,i){if(e.carry&&(e.carryFor+=i),e.status!=="idle"||(e.curiousIn-=i)>0)return;e.curiousIn=Mn.every[0]+Math.random()*(Mn.every[1]-Mn.every[0]),this._pileFor(e);const n=z4(e,this.trinketCounts.get(e.id)??0);n&&sn(e,n,t)}_machine(e,t,i=null){!this.onMachine||!this.camera||this._machineBudget<1||this.camera.position.distanceTo(e.pos)>Ts.reach||(this._machineBudget-=1,this.onMachine(e,t,i))}_hearMachinery(e,t){e.state==="spawning"&&!e.poweredUp&&(e.poweredUp=!0,t-this._poweredUpAt>Ts.powerUpGap&&(this._poweredUpAt=t,this._machine(e,"power-up")));const{yaw:i,pitch:n}=e.acting.head,r=Math.abs(i.v)+.5*Math.abs(n.v);r>Ts.whirr&&t>e.whirrAt&&(e.whirrAt=t+Ts.whirrRest,this._machine(e,"servo-whirr",{speed:Math.min(1,.3+(r-Ts.whirr)/3)}))}_waitFor(e,t){const i=p0(e,t);i!==e.waitStage&&(e.waitStage=i,i&&(e.loop=Zr[{fresh:"done",eager:"eager",sulk:"sulking"}[i]],e.faceIndex=0))}_applyStatus(e,t){const i=al[t]||al.idle;if(e.trim.setRGB(...i.trim),e.eye.setRGB(i.eye[0],i.eye[1],i.eye[2]),e.loop=Zr[t]||null,e.faceIndex=0,e.noticedAt=0,e.greet=null,e.carry=!1,e.colorDirty=!0,t==="leaving"){this._sendHome(e);return}e.state!=="spawning"&&e.state!=="queued"&&(e.state="walking"),e.stateAge=0,e.pathVersion=-1}_nearDoor(e){const t=this.world?.shipDoor?.();if(!t)return!1;const i=e.x-t.x,n=e.z-t.z;return i*i+n*n<kh*kh}_drop(e){e.state="gone",e.scale=0}_sendHome(e){if(e.state==="leaving"||e.state==="gone")return;if(e.state==="queued")return this._drop(e);e.state="leaving",e.status="leaving",e.stateAge=0,e.loop=null,e.faceFrame=B.wink,e.pathVersion=-1;const t=this.world?.shipDoor?.();t&&e.site.copy(t)}remove(e){const t=this.byId.get(e);t&&this._sendHome(t)}annoy(e,t){const i=this.byId.get(e);i&&(i.annoyed<=0&&(i.annoyedIndex=0),i.annoyed=t,A4(i,.9))}notice(e){const t=this.byId.get(e);t&&(t.status==="working"?w4(t):b4(t,Date.now())==="sulk"&&sn(t,"noticed",this._clock??0))}speak(e,t){const i=this.byId.get(e);i&&M4(i,t,this._clock)}update(e,t){const n=this.settings.get("reducedMotion")?.35:1;let r=0;this._clock=t;const o=Date.now();this._machineBudget=Math.min(Ts.perSecond,this._machineBudget+e*Ts.perSecond),this._rebuildBuckets(),this._routeBudget=g3,this._releaseQueued(e);for(let a=this.agents.length-1;a>=0;a--){const l=this.agents[a];if(l.state==="queued"){r++;continue}if(l.stateAge+=e,l.beat=R4(l,t,c=>this._beat(l,c,n)),this._waitFor(l,o),this._step(l,e,t,n),this._animate(l,e,n),d4(l,e,n),T4(l,e,t,n,this._lookFor(l,e)),this._socialize(l,t,e),this._wonder(l,t,e),this._hearMachinery(l,t),l.state==="gone"){this.agents.splice(a,1),this.byId.delete(l.id);continue}r++}return(this._pilesDirty||t-this._pilesAt>2)&&this._writePiles(t),this._writeMatrices(t,n,e),r}_lookFor(e,t){const i=this._look;e.interrupted=Math.max(0,(e.interrupted||0)-t);const n=m4(e,e===this.selected,e===this.hovered)||(g4(e)?1:0);if(n>0&&this.camera){const d=this.camera.position,u=d.x-e.pos.x,f=d.z-e.pos.z,p=Math.max(0,Math.atan2(d.y-e.pos.y-me.lift*me.size,Math.hypot(u,f)));return i.yaw=aa(Math.atan2(u,f)-e.yaw)*n,i.pitch=-Math.min(me.look.max,p*me.look.share)*n,i}const r=e.greet;if(r&&e.story&&r.state!=="gone")return i.yaw=aa(Math.atan2(r.pos.x-e.pos.x,r.pos.z-e.pos.z)-e.yaw),i.pitch=null,i;const o=e.acting;if(!(e.state==="at-site"&&e.groundSpeed<=.12&&e.status!=="sleeping"&&e.status!=="working"))return o.glance=null,null;o.glanceIn-=t,o.glanceIn<=0&&(o.glanceIn=.4+Math.random()*.3,o.glance=this._nearestPasser(e));const l=o.glance;if(!l||l.state==="gone")return null;const c=l.pos.x-e.pos.x,h=l.pos.z-e.pos.z;return c*c+h*h>wr*wr||(i.yaw=aa(Math.atan2(c,h)-e.yaw),Math.abs(i.yaw)>tl*1.5)?null:(i.pitch=null,i)}_nearestPasser(e){const t=e.pos.x/2|0,i=e.pos.z/2|0;let n=null,r=wr*wr;for(let o=-1;o<=1;o++)for(let a=-1;a<=1;a++){const l=this._buckets.get((t+o)*10007+(i+a));if(l)for(const c of l){if(c===e||c.groundSpeed<.5)continue;const h=c.pos.x-e.pos.x,d=c.pos.z-e.pos.z,u=h*h+d*d;u<r&&(r=u,n=c)}}return n}_releaseQueued(e){if(!this._queue.length||(this._queueTimer-=e,this._queueTimer>0))return;const t=this._lastOut;if(t&&t.state!=="gone"&&this._queueTimer>-2&&t.ramp<.4)return;this._queueTimer=this._queueEvery;let i=this._queue.shift();for(;i&&(i.state!=="queued"||!this.byId.has(i.id));)i=this._queue.shift();if(!i)return;i.state="spawning",i.stateAge=0,i.pose=Ch("spawning"),i.pathVersion=-1;const n=this.world?.shipAirlock?.(),r=this.world?.shipDoor?.();n&&r&&(i.rampFrom.copy(n),i.rampTo.set(r.x+(Math.random()-.5)*.7,r.y,r.z+(Math.random()-.5)*.7),i.pos.copy(n),i.groundAt=n.y,i.groundY=n.y),this._lastOut=i}_steerTarget(e,t){const i=this.nav;if(!i)return t.copy(e.site);(e.pathVersion!==i.version||e.pathGoal.distanceToSquared(e.site)>.25)&&this._routeBudget>0&&(this._routeBudget--,e.path=i.findPath(e.pos.x,e.pos.z,e.site.x,e.site.z),e.pathAt=0,e.pathVersion=i.version,e.pathGoal.copy(e.site));const r=e.path;if(!r||!r.length)return t.copy(e.site);for(;e.pathAt<r.length-1;){const a=r[e.pathAt],l=a.x-e.pos.x,c=a.z-e.pos.z;if(l*l+c*c>Th*Th)break;e.pathAt++}if(e.pathAt>=r.length)return t.copy(e.site);const o=r[e.pathAt];return t.set(o.x,0,o.z)}_step(e,t,i,n){const r=e.pos.x,o=e.pos.z;e.blocked=!1;const a=e.state==="at-site"?this._wp.copy(e.site):this._steerTarget(e,this._wp),l=this._v.set(a.x-e.pos.x,0,a.z-e.pos.z),c=Math.hypot(e.site.x-e.pos.x,e.site.z-e.pos.z);if(e.beat?.hold&&(e.state==="walking"||e.state==="at-site"))e.vel.set(0,0,0),e.beat.faceCamera&&this.camera?this._faceToward(e,this.camera.position,t):e.beat.facePile&&e.pile&&this._faceToward(e,e.pile,t);else switch(e.state){case"spawning":{if(e.scale=Math.min(1,e.scale+t*2.6),e.ramp<1){e.ramp=Math.min(1,e.ramp+t/br);const f=e.ramp,p=e.rampFrom,m=e.rampTo;e.pos.x=p.x+(m.x-p.x)*f,e.pos.z=p.z+(m.z-p.z)*f;const g=p.y+(m.y-p.y)*f;e.groundAt=g,e.groundY=g,e.vel.set((m.x-p.x)/br,0,(m.z-p.z)/br),e.targetYaw=Math.atan2(e.vel.x,e.vel.z);break}e.stateAge>.9+br&&(e.state="walking"),this._walk(e,l,c,t,.55);break}case"walking":{e.scale=Math.min(1,e.scale+t*3),this._walk(e,l,c,t,1),e.stuckFor>2&&e.stuckFor<2.05&&(e.pathVersion=-1);const f=e.stuckFor>5||e.blocked&&e.stateAge>8||e.stateAge>45,p=c<vr*1.9&&e.stateAge>10;if(c<vr||p||f){const m=this._nearDoor(e.pos);if(f&&c>=vr&&!m&&e.site.copy(e.pos),f&&m){e.stateAge=0,e.pathVersion=-1;break}e.state=e.status==="leaving"?"leaving":"at-site",e.stateAge=0}break}case"at-site":{e.status==="idle"?this._drift(e,t,i):e.status==="working"&&e.anchor?this._workRound(e,t,i):(e.vel.set(0,0,0),(e.status==="done"||e.status==="asking")&&this.camera?this._faceToward(e,this.camera.position,t):e.status!=="sleeping"&&this._faceToward(e,e.site,t),this._settle(e,t)),e.hop=0;break}case"leaving":{e.scale=Math.max(0,e.scale-(c<1.4?t*2.2:0)),this._walk(e,l,c,t,1.15),(e.scale<=.001||c<.9&&e.stateAge>1.5||e.stateAge>22)&&(e.state="gone");break}}const h=Math.hypot(e.pos.x-r,e.pos.z-o),d=Math.max(0,h-e.corr)/Math.max(t,1e-4);e.corr=0,this._watchWobble(e,h,t,i),e.groundSpeed=d>e.groundSpeed?d:N.damp(e.groundSpeed||0,d,20,t),e.phase+=t*(2.2+e.groundSpeed*3.4)*n,e.walkAmp=N.damp(e.walkAmp||0,Math.min(1,e.groundSpeed/Mh),8,t),e.yaw=v3(e.yaw,e.targetYaw,u3,t);const u=e.ramp<1?null:this.world?.groundAt;u&&((e.groundAt===null||Math.abs(e.pos.x-e.groundX)+Math.abs(e.pos.z-e.groundZ)>.2)&&(e.groundX=e.pos.x,e.groundZ=e.pos.z,e.groundAt=u(e.pos.x,e.pos.z)),e.groundY=e.groundY===null?e.groundAt:N.damp(e.groundY,e.groundAt,14,t)),e.pos.y=(e.groundY||0)+e.hop}_walk(e,t,i,n,r){const o=t.length();let a=0,l=0;if(o>.05){const u=t.divideScalar(o);a=u.x,l=u.z;const f=e.speed*r*Math.min(1,i/1.8);e.vel.x=N.damp(e.vel.x,u.x*f,6,n),e.vel.z=N.damp(e.vel.z,u.z*f,6,n)}else e.vel.set(0,0,0);e.ghost>0&&(e.ghost-=n);const c=e.ghost>0?this._sep.set(0,0,0):this._separation(e,this._sep);if(o>.05&&(c.x!==0||c.z!==0)){const u=c.x*a+c.z*l;u<0&&(c.x-=a*u,c.z-=l*u);const f=Math.hypot(c.x,c.z),p=e.speed*.7;f>p&&(c.x*=p/f,c.z*=p/f)}const h=(e.vel.x+c.x)*n,d=(e.vel.z+c.z)*n;this.nav?(this.nav.slide(e.pos,h,d)||(e.vel.multiplyScalar(.4),e.blocked=!0),o>.3&&(e.blocked||(e.groundSpeed||0)<.06)?e.stuckFor+=n:e.stuckFor=0,e.stuckFor>.8&&e.ghost<=0&&(e.ghost=2.5,e.pathVersion=-1)):(e.pos.x+=h,e.pos.z+=d),Math.hypot(e.vel.x,e.vel.z)>.05&&(e.targetYaw=Math.atan2(e.vel.x,e.vel.z))}_rebuildBuckets(){const e=this._buckets;e.clear();for(const t of this.agents){if(t.state==="gone"||t.scale<.2)continue;const i=(t.pos.x/2|0)*10007+(t.pos.z/2|0);let n=e.get(i);n||e.set(i,n=[]),n.push(t)}}_crowded(e,t,i){const n=e/2|0,r=t/2|0;for(let o=-1;o<=1;o++)for(let a=-1;a<=1;a++){const l=this._buckets.get((n+o)*10007+(r+a));if(l)for(const c of l){if(c===i)continue;const h=e-c.pos.x,d=t-c.pos.z;if(h*h+d*d<Si*Si)return!0}}return!1}_separation(e,t){t.set(0,0,0);const i=this._buckets,n=e.pos.x/2|0,r=e.pos.z/2|0;for(let o=-1;o<=1;o++)for(let a=-1;a<=1;a++){const l=i.get((n+o)*10007+(r+a));if(l)for(const c of l){if(c===e)continue;const h=e.pos.x-c.pos.x,d=e.pos.z-c.pos.z,u=h*h+d*d;if(u>Si*Si||u<1e-6)continue;const f=Math.sqrt(u),p=(1-f/Si)*1.2+(f<_h?(1-f/_h)*5:0);t.x+=h/f*p,t.z+=d/f*p}}return t}_drift(e,t,i){if(e.carry&&e.pileStand){const o=this._v.set(e.pileStand.x-e.pos.x,0,e.pileStand.z-e.pos.z),a=o.length();if(a>.2&&e.carryFor<12){this._walk(e,o,a,t,oa);return}e.vel.set(0,0,0),sn(e,"dropsOff",i);return}if(i>e.wanderAt){e.wanderAt=i+3+Math.random()*5,e.wander.copy(e.pos);for(let o=0;o<4;o++){const a=Math.random()*Math.PI*2,l=.8+Math.random()*2,c=e.site.x+Math.cos(a)*l,h=e.site.z+Math.sin(a)*l;if(!(this.nav?.isBlocked(c,h)||this.nav?.insideKeep(c,h))&&!(this.nav&&!this.nav.clearWalk(e.pos.x,e.pos.z,c,h))&&!this._crowded(c,h,e)){e.wander.set(c,0,h);break}}e.driftBlocked=!1}const n=this._v.set(e.wander.x-e.pos.x,0,e.wander.z-e.pos.z),r=n.length();if(r>Sh&&!e.driftBlocked){this._walk(e,n,r,t,oa),(e.blocked||e.stuckFor>1)&&(e.driftBlocked=!0,e.stuckFor=0,e.wanderAt=i+3+Math.random()*3);return}e.vel.set(0,0,0),this._settle(e,t)}_settle(e,t){if(e.calm>0)return;const i=this._separation(e,this._sep);e.status==="sleeping"&&(i.x*=.3,i.z*=.3);const n=e.pos.x,r=e.pos.z;if(this.nav&&(this.nav.isBlocked(n,r)?this.nav.slide(e.pos,0,0):(this.nav.repel(e.pos,i),this.nav.keepOut(e.pos))),i.x!==0||i.z!==0){const o=i.x*t,a=i.z*t;this.nav?this.nav.slide(e.pos,o,a):(e.pos.x+=o,e.pos.z+=a)}e.corr+=Math.hypot(e.pos.x-n,e.pos.z-r)}_workRound(e,t,i){if(i>e.workAt){e.workAt=i+5+Math.random()*7;const o=Math.max(1.6,Math.hypot(e.site.x-e.anchor.x,e.site.z-e.anchor.z)),a=Math.atan2(e.pos.z-e.anchor.z,e.pos.x-e.anchor.x);e.workSpot.copy(e.pos);for(let l=0;l<4;l++){const c=a+(Math.random()>.5?1:-1)*(.3+Math.random()*.5),h=e.anchor.x+Math.cos(c)*o,d=e.anchor.z+Math.sin(c)*o;if(!(this.nav?.isBlocked(h,d)||this.nav?.insideKeep(h,d))&&!(this.nav&&!this.nav.clearWalk(e.pos.x,e.pos.z,h,d))&&!this._crowded(h,d,e)){e.workSpot.set(h,0,d);break}}e.driftBlocked=!1}const n=this._v.set(e.workSpot.x-e.pos.x,0,e.workSpot.z-e.pos.z),r=n.length();if(r>Sh&&!e.driftBlocked){this._walk(e,n,r,t,oa),(e.blocked||e.stuckFor>1)&&(e.driftBlocked=!0,e.stuckFor=0,e.workAt=i+4+Math.random()*3);return}e.vel.set(0,0,0),this._faceToward(e,e.anchor,t),this._settle(e,t)}_watchWobble(e,t,i,n){if(e.calm>0&&(e.calm-=i),e.wobble+=t,Number.isNaN(e.wobbleFrom.x)){e.wobbleFrom.copy(e.pos),e.wobbleAt=n;return}if(n-e.wobbleAt<1)return;const r=Math.hypot(e.pos.x-e.wobbleFrom.x,e.pos.z-e.wobbleFrom.z);e.wobble>.7&&r<.12&&e.state!=="spawning"&&e.state!=="leaving"&&this._unglitch(e),e.wobble=0,e.wobbleFrom.copy(e.pos),e.wobbleAt=n}_unglitch(e){const t=this.nav;if(!t)return;let i=null;const n=e.pos.x,r=e.pos.z;for(let o=0;o<=5&&!i;o+=.4){const a=o===0?1:Math.max(8,Math.round(o*12));for(let l=0;l<a;l++){const c=l/a*Math.PI*2+o*5.1,h=n+Math.cos(c)*o,d=r+Math.sin(c)*o;if(!(t.isBlocked(h,d)||t.insideKeep(h,d)||this._crowded(h,d,e))){i={x:h,z:d};break}}}i&&(e.pos.x=i.x,e.pos.z=i.z),e.vel.set(0,0,0),e.calm=1.5,e.stuckFor=e.state==="walking"?6:0,e.pathVersion=-1,e.driftBlocked=!0}_faceToward(e,t,i){const n=t.x-e.pos.x,r=t.z-e.pos.z;Math.abs(n)+Math.abs(r)>.01&&(e.targetYaw=Math.atan2(n,r))}_animate(e,t,i){const n=e.pose;J4(n,K4(e)),t3(n,t*i);const r=X4[n.key];r!==void 0&&!n.landed&&n.t>=r&&(n.landed=!0,this._machine(e,"bot-clunk",n.key==="kneel"?p3:null))}_writeMatrices(e,t,i=0){const{hull:n,trim:r,face:o,visor:a,crown:l,rings:c,halo:h}=this.parts;if(!n){this.visibleCount=0,this._drawnAgents.length=0;return}const d=[n,r,o,a,l,c],u=this._headTurn,f=this._m,p=this._q,m=this._e,g=this._v,w=this._one,b=this._color,y=this.frameAttr.array,C=this.eyeBuffer.array,_=this.hullWear,x=this._m2,T=me.lights;let M=0,k=!1,A=!1;this.trinkets.beginHeld();for(const $ of this.agents){if(M>=this.capacity)break;if($.state==="gone")continue;const H=$.scale;if(H<=.001)continue;const q=$.pose;E4($.acting,u);const Y=$.state==="leaving"?(1-H)*me.leaveRise:0;m.set(q.rx+u.x*(u.x<0?me.head.up:me.head.pitch),$.yaw+q.ry+u.y,q.rz+u.z*me.head.roll,"YXZ"),p.setFromEuler(m),g.set($.pos.x,$.pos.y+(me.lift+q.y+Y)*me.size,$.pos.z),f.compose(g,p,w.setScalar(H*q.s*me.scale*me.size)),w.setScalar(1),$.matrix.copy(f);for(const he of d)he.setMatrixAt(M,f);$.carry&&this.trinkets.hold(f,this._held.fromArray(me.carry),me.carrySize/me.scale,Xs($.id)),($.index!==M||$.colorDirty)&&($.colorDirty=!1,n.setColorAt(M,b.setHex($.suit)),r.setColorAt(M,b.setHex($.repo).multiplyScalar(me.trim.shade)),o.setColorAt(M,$.eye),A=!0);const G=$.wear;G&&(b.setHex(G.accent),_.wear.setXYZW(M,G.scuffs,G.stickers,G.dents,G.seed),_.accent.setXYZ(M,b.r,b.g,b.b));const{acting:ee}=$,{speaking:se}=ee,xe=S4($,i),we=$.status==="error"?q4(e):xe.pulse;ee.swell+=(Math.max(ee.flash,se*.7)-ee.swell)*(i>0?1-Math.exp(-i/T.attack):1);const U=(T.crown[0]+T.crown[1]*we)*xe.glow*(1+ee.swell*T.swell),re=T.rings[0]+T.rings[1]*we;l.setColorAt(M,b.copy($.eye).multiplyScalar(U)),c.setColorAt(M,b.copy($.trim).multiplyScalar(re));for(let he=0;he<Zs.length;he++){const Ae=Zs[he].light==="crown";x.multiplyMatrices(f,this._haloLocal[he]),h.setMatrixAt(M*Zs.length+he,x),h.setColorAt(M*Zs.length+he,b.copy($.trim).multiplyScalar(Ae?me.halos.crown.strength*U:me.halos.rings.strength*re))}(se>0||$.acting.glow>0)&&(o.setColorAt(M,b.copy($.eye).multiplyScalar(1+se*.7)),$.acting.glow=se,k=!0);const Q=$.faceFrame;y[M*2]=Q%Kt/Kt,y[M*2+1]=1-(Math.floor(Q/Kt)+1)/Gr,a4($.eyes,Q,i),l4($.eyes,$.acting.gaze,C,M*xn),$.index=M,this._drawnAgents[M]=$,M++}const P=M;this.trinkets.endHeld();for(const $ of d)$.count=P,$.instanceMatrix.needsUpdate=!0,(A||$===l||$===c||k&&$===o)&&($.instanceColor.needsUpdate=!0);h.count=P*Zs.length,h.instanceMatrix.needsUpdate=!0,h.instanceColor.needsUpdate=!0,this.frameAttr.needsUpdate=!0,this.eyeBuffer.needsUpdate=!0,_.wear.needsUpdate=!0,_.accent.needsUpdate=!0,this.visibleCount=P,this._drawnAgents.length=P}pick(e,t,i,n,r=.075){let o=null,a=1/0;const l=this._v,c=this._pickBadge,h=this._pickLifted,d=this._pickBody;for(const u of this._drawnAgents){if(u.scale<.3||u.state==="gone")continue;const f=u.scale*me.scale*me.size;for(let b=0;b<me.pick.length;b++){const y=me.pick[b];l.fromArray(y.at).applyMatrix4(u.matrix),U4(l,y.radius*f,e,n,d[b])}let p=1/0;for(const b of d)b.visible&&(p=Math.min(p,b.z));if(p===1/0)continue;u.screen.set(d[0].x/n,d[0].y,d[0].z);let m=1/0;for(let b=1;b<d.length;b++)m=Math.min(m,j4(t*n,i,d[0],d[b]));const g=u.badgeSize||0;if(g>0){ai(c.set(u.pos.x,u.badgeY,u.pos.z)).applyMatrix4(e.matrixWorldInverse);const b=g*(2+-c.z*.22);if(c.y+=b*.5,h.copy(c),h.y+=b*.5,c.applyMatrix4(e.projectionMatrix),h.applyMatrix4(e.projectionMatrix),c.z<=1){const y=Math.abs(h.y-c.y),C=(c.x-t)*n,_=c.y-i,x=Math.max(0,Math.abs(C)-y),T=Math.max(0,Math.abs(_)-y),M=Math.hypot(x,T);M<m&&(m=M)}}if(m>r)continue;const w=m+p*.05;w<a&&(a=w,o=u)}return o}setHover(e){this.hovered=e||null,this.hoverRing.visible=!!e,e&&this.hoverRing.position.set(e.pos.x,e.pos.y+.03,e.pos.z)}setSelected(e){this.selected=e||null,this.selectRing.visible=!!e}updateRings(e){if(this.selected)if(!this.byId.has(this.selected.id))this.setSelected(null);else{const t=this.selected;this.selectRing.position.set(t.pos.x,t.pos.y+.035,t.pos.z),this.selectRing.material.color.copy(t.trim),this.selectRing.rotation.y=e*.6;const i=1+Math.sin(e*3)*.05;this.selectRing.scale.setScalar(i)}this.hoverRing.visible&&(this.hoverRing.rotation.y=-e*.4)}celebrate(e){const t=this.byId.get(e);t&&(t.faceFrame=B.happy,t.blinkAt=1.5,t.hop=.25)}dispose(){this._disposeParts(),this.trinkets.dispose(),this.faceTexture.dispose(),this.scene.remove(this.group)}}function aa(s){for(;s>Math.PI;)s-=Math.PI*2;for(;s<-Math.PI;)s+=Math.PI*2;return s}function v3(s,e,t,i){let n=e-s;for(;n>Math.PI;)n-=Math.PI*2;for(;n<-Math.PI;)n+=Math.PI*2;return s+n*(1-Math.exp(-7.5*i))}function $h(s,e,t,i){const n=new Yp(s,e,32);n.rotateX(-Math.PI/2);const r=new dt({color:t,transparent:!0,opacity:i,depthWrite:!1,side:vt,toneMapped:!1}),o=new ke(n,r);return o.renderOrder=3,o}function Xs(s){let e=2166136261;for(let t=0;t<s.length;t++)e^=s.charCodeAt(t),e=Math.imul(e,16777619);return e>>>0}var y3="M13 14H11V9H13M13 18H11V16H13M1 21H23L12 2L1 21Z",C3="M9,20.42L2.79,14.21L5.62,11.38L9,14.77L18.88,4.88L21.71,7.71L9,20.42Z",x3="M19,1L17.74,3.75L15,5L17.74,6.26L19,9L20.25,6.26L23,5L20.25,3.75M9,4L6.5,9.5L1,12L6.5,14.5L9,20L11.5,14.5L17,12L11.5,9.5M19,15L17.74,17.74L15,19L17.74,20.25L19,23L20.25,20.25L23,19L20.25,17.74",M3="M16,12A2,2 0 0,1 18,10A2,2 0 0,1 20,12A2,2 0 0,1 18,14A2,2 0 0,1 16,12M10,12A2,2 0 0,1 12,10A2,2 0 0,1 14,12A2,2 0 0,1 12,14A2,2 0 0,1 10,12M4,12A2,2 0 0,1 6,10A2,2 0 0,1 8,12A2,2 0 0,1 6,14A2,2 0 0,1 4,12Z",k3="M2 19.63L13.43 8.2L12.72 7.5L14.14 6.07L12 3.89C13.2 2.7 15.09 2.7 16.27 3.89L19.87 7.5L18.45 8.91H21.29L22 9.62L18.45 13.21L17.74 12.5V9.62L16.27 11.04L15.56 10.33L4.13 21.76L2 19.63Z",T3="M15.07,11.25L14.17,12.17C13.45,12.89 13,13.5 13,15H11V14.5C11,13.39 11.45,12.39 12.17,11.67L13.41,10.41C13.78,10.05 14,9.55 14,9C14,7.89 13.1,7 12,7A2,2 0 0,0 10,9H8A4,4 0 0,1 12,5A4,4 0 0,1 16,9C16,9.88 15.64,10.67 15.07,11.25M13,19H11V17H13M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12C22,6.47 17.5,2 12,2Z",_3="M17 7L15.59 8.41L18.17 11H8V13H18.17L15.59 15.58L17 17L22 12M4 5H12V3H4C2.9 3 2 3.9 2 5V19C2 20.1 2.9 21 4 21H12V19H4V5Z",S3="M14.53 1.45L13.45 2.53L15.05 4.13C15.27 4.38 15.38 4.67 15.38 5S15.27 5.64 15.05 5.86L11.5 9.47L12.5 10.55L16.13 6.94C16.66 6.35 16.92 5.7 16.92 5C16.92 4.3 16.66 3.64 16.13 3.05L14.53 1.45M10.55 3.47L9.47 4.55L10.08 5.11C10.3 5.33 10.41 5.63 10.41 6S10.3 6.67 10.08 6.89L9.47 7.45L10.55 8.53L11.11 7.92C11.64 7.33 11.91 6.69 11.91 6C11.91 5.28 11.64 4.63 11.11 4.03L10.55 3.47M21 5.06C20.31 5.06 19.67 5.33 19.08 5.86L13.45 11.5L14.53 12.5L20.11 6.94C20.36 6.69 20.66 6.56 21 6.56S21.64 6.69 21.89 6.94L22.5 7.55L23.53 6.47L22.97 5.86C22.38 5.33 21.72 5.06 21 5.06M7 8L2 22L16 17L7 8M19 11.06C18.3 11.06 17.66 11.33 17.06 11.86L15.47 13.45L16.55 14.53L18.14 12.94C18.39 12.69 18.67 12.56 19 12.56C19.33 12.56 19.63 12.69 19.88 12.94L21.5 14.53L22.55 13.5L20.95 11.86C20.36 11.33 19.7 11.06 19 11.06Z",$3="M23,12H17V10L20.39,6H17V4H23V6L19.62,10H23V12M15,16H9V14L12.39,10H9V8H15V10L11.62,14H15V16M7,20H1V18L4.39,14H1V12H7V14L3.62,18H7V20Z";const ri=4,ll=3,A3=me.badge,fe={none:-1,done:0,error:1,working:2,celebrating:3,asking:4,sleeping:5,spawning:6,leaving:7,delegating:8},E3={[fe.done]:$s(ot.done),[fe.error]:$s(ot.error),[fe.working]:$s(ot.working),[fe.celebrating]:$s(ot.celebrating),[fe.asking]:$s(ot.asking),[fe.sleeping]:$s(ot.idle),[fe.spawning]:[2.3,2.15,1.6],[fe.leaving]:[1.2,1.3,1.35],[fe.delegating]:$s(ot.delegating)},P3={[fe.asking]:0,[fe.done]:0,[fe.error]:0,[fe.celebrating]:.15,[fe.working]:.4,[fe.delegating]:.4,[fe.spawning]:.5,[fe.leaving]:.5,[fe.sleeping]:1};class z3{constructor(e,t,i){this.settings=t,this.capacity=i,this.texture=L3(512);const n=new Ut(1,1);this.frames=new Ze(new Float32Array(i*2),2),this.centers=new Ze(new Float32Array(i*3),3),this.sizes=new Ze(new Float32Array(i),1),this.fades=new Ze(new Float32Array(i),1);for(const o of[this.frames,this.centers,this.sizes,this.fades])o.setUsage(at);n.setAttribute("aFrame",this.frames),n.setAttribute("aCenter",this.centers),n.setAttribute("aSize",this.sizes),n.setAttribute("aFade",this.fades),this.material=this._material(),this.mesh=new zt(n,this.material,i),this.mesh.layers.set(Vl),this.mesh.count=0,this.mesh.frustumCulled=!1,this.mesh.renderOrder=10,e.add(this.mesh),this.scene=e;const r=new W(1,1,1);for(let o=0;o<i;o++)this.mesh.setColorAt(o,r);this.mesh.instanceColor.setUsage(at),this._color=new W}_material(){const e=new dt({map:this.texture,transparent:!0,depthWrite:!1,depthTest:!1,toneMapped:!0,blending:Jp,blendSrc:Kp,blendDst:xc,blendSrcAlpha:Qp,blendDstAlpha:xc});return e.onBeforeCompile=t=>{t.uniforms.uFrameScale={value:new Se(1/ri,1/ll)},wt(t),this.uniforms=t.uniforms,t.vertexShader=t.vertexShader.replace("#include <common>",`#include <common>
|
|
2115
|
-
attribute vec2 aFrame;
|
|
2116
|
-
attribute vec3 aCenter;
|
|
2117
|
-
attribute float aSize;
|
|
2118
|
-
attribute float aFade;
|
|
2119
|
-
varying float vFade;
|
|
2120
|
-
uniform vec2 uFrameScale;`).replace("#include <uv_vertex>",`#include <uv_vertex>
|
|
2121
|
-
vMapUv = uv * uFrameScale + aFrame;`).replace("#include <project_vertex>",`vec4 mvPosition = viewMatrix * vec4( bcBend( ( modelMatrix * vec4( aCenter, 1.0 ) ).xyz ), 1.0 );
|
|
2122
|
-
float dist = -mvPosition.z;
|
|
2123
|
-
// Mostly-constant screen size: the linear term cancels perspective so a badge
|
|
2124
|
-
// stays readable when the camera is pulled right out, while the constant term
|
|
2125
|
-
// lets it grow a little as you lean in, which stops it feeling pasted on.
|
|
2126
|
-
float scale = aSize * ( 2.0 + dist * 0.22 );
|
|
2127
|
-
// Lift by half the badge's own height, so what is pinned above the helmet is the
|
|
2128
|
-
// badge's *bottom edge* rather than its centre. The badge holds a near-constant
|
|
2129
|
-
// size on screen while a world-space offset does not, so a centre that clears the
|
|
2130
|
-
// head when you are leaning in sits right on top of it when you pull out — the
|
|
2131
|
-
// gap shrinks with distance while the thing it has to clear does not.
|
|
2132
|
-
mvPosition.y += scale * 0.5;
|
|
2133
|
-
mvPosition.xy += position.xy * scale;
|
|
2134
|
-
// Low-priority badges (asleep, idle) thin out quickly so a wide shot shows only
|
|
2135
|
-
// what actually wants you, while a close look still reports everything. Urgent
|
|
2136
|
-
// badges carry aFade 0 and never fade at all.
|
|
2137
|
-
vFade = 1.0 - aFade * smoothstep( 19.0, 44.0, dist );
|
|
2138
|
-
gl_Position = projectionMatrix * mvPosition;`),t.fragmentShader=t.fragmentShader.replace("#include <common>",`#include <common>
|
|
2139
|
-
varying float vFade;
|
|
2140
|
-
uniform vec2 uFrameScale;`),t.fragmentShader=t.fragmentShader.replace("#include <map_fragment>",`vec4 badge = texture2D( map, vMapUv );
|
|
2141
|
-
// One texture, three masks: the plate's silhouette in green, a ring straddling its
|
|
2142
|
-
// edge in blue, the symbol in red. A badge is the one thing in the colony you are
|
|
2143
|
-
// meant to spot across a busy plot and click, so it is built like a pin — a solid
|
|
2144
|
-
// card, a ring in its own status colour, and a shadow holding it off the ground.
|
|
2145
|
-
float body = max( badge.g, badge.b );
|
|
2146
|
-
|
|
2147
|
-
// The shadow is the same silhouette read from a blurred mip and offset down-right,
|
|
2148
|
-
// which costs one extra sample instead of a second texture. The plate is inset far
|
|
2149
|
-
// enough inside its cell that neither the offset nor the blur reaches a neighbour.
|
|
2150
|
-
float shadow = texture2D( map, vMapUv + vec2( -0.006, 0.010 ) * uFrameScale, 2.2 ).g;
|
|
2151
|
-
|
|
2152
|
-
vec3 plate = vec3( 0.045, 0.05, 0.07 );
|
|
2153
|
-
vec3 col = mix( plate, vColor.rgb * 0.85, badge.b );
|
|
2154
|
-
col = mix( col, vColor.rgb, badge.r );
|
|
2155
|
-
|
|
2156
|
-
// Where the badge is solid it is the badge; where it is not, what is left of the
|
|
2157
|
-
// offset silhouette is the shadow, and multiplying by alpha takes the colour to
|
|
2158
|
-
// black there without a second branch.
|
|
2159
|
-
diffuseColor.rgb = col * body;
|
|
2160
|
-
diffuseColor.a = max( body, shadow * ( 1.0 - body ) * 0.55 ) * vFade;`),t.fragmentShader=t.fragmentShader.replace("#include <color_fragment>","")},e}update(e,t,i){const n=this.frames.array,r=this.centers.array,o=this.sizes.array,a=this.fades.array;let l=0;for(const c of e){if(c.badgeSize=0,l>=this.capacity)break;if(c.scale<.4||c.state==="gone")continue;const h=i(c);if(h<0)continue;const d=h===fe.asking||h===fe.done||h===fe.error,u=d?3.4:1.6,f=d?.075:.035,p=Math.sin(t*u+c.phase)*f;r[l*3]=c.pos.x,r[l*3+1]=c.pos.y+A3+p,r[l*3+2]=c.pos.z,n[l*2]=h%ri/ri,n[l*2+1]=1-(Math.floor(h/ri)+1)/ll,o[l]=d?.142+Math.sin(t*4.2+c.phase)*.011:.108,a[l]=P3[h]??1,c.badgeSize=o[l],c.badgeY=r[l*3+1];const m=E3[h]||[1,1,1];this._color.setRGB(m[0],m[1],m[2]),this.mesh.setColorAt(l,this._color),l++}this.mesh.count=l,this.frames.needsUpdate=!0,this.centers.needsUpdate=!0,this.sizes.needsUpdate=!0,this.fades.needsUpdate=!0,this.mesh.instanceColor.needsUpdate=!0,this.mesh.instanceMatrix.needsUpdate=!1}dispose(){this.mesh.geometry.dispose(),this.material.dispose(),this.texture.dispose(),this.scene.remove(this.mesh)}}const v0=[C3,y3,k3,S3,T3,$3,x3,_3,M3];function L3(s=512){const e=document.createElement("canvas");e.width=s*ri,e.height=s*ll;const t=e.getContext("2d");t.clearRect(0,0,e.width,e.height),v0.map(r=>new Path2D(r)).forEach((r,o)=>{const a=o%ri*s,l=Math.floor(o/ri)*s;t.save(),t.translate(a,l),t.scale(s,s),t.fillStyle="rgb(0,255,0)",Ah(t),t.fill(),t.save(),t.globalCompositeOperation="lighter",t.strokeStyle="rgb(0,0,255)",t.lineWidth=.055,t.lineJoin="round",Ah(t),t.stroke(),t.fillStyle="rgb(255,0,0)",F3(t,r),t.restore(),t.restore()});const n=new Vn(e);return n.colorSpace=ho,n.minFilter=On,n.magFilter=qi,n.wrapS=n.wrapT=Ya,n.anisotropy=8,n}function Ah(s){s.beginPath(),s.moveTo(.11+.19,.08),s.arcTo(.89,.08,.89,.74,.19),s.arcTo(.89,.74,.11,.74,.19),s.arcTo(.5+.105,.74,.5,.915,.07),s.arcTo(.5,.915,.5-.105,.74,.038),s.arcTo(.5-.105,.74,.11,.74,.07),s.arcTo(.11,.74,.11,.08,.19),s.arcTo(.11,.08,.89,.08,.19),s.closePath()}const Eh=24,yr=.5,R3=.5,B3=.405;function F3(s,e){s.save(),s.translate(R3-yr/2,B3-yr/2),s.scale(yr/Eh,yr/Eh),s.fill(e,"nonzero"),s.restore()}const O3=-3.6,I3={dust:{every:.045,height:[.4,5.4],velocity:[1.6,.1,.7,1.4,0],color:[.78,.55,.4],size:[.16,.24],life:[3,6],drag:.12,gravity:.02},sand:{every:.04,height:[.2,3.2],velocity:[2.4,.15,.4,1.6,.1],color:[.95,.8,.55],size:[.12,.22],life:[2.5,5],drag:.1,gravity:.03},ash:{every:.06,height:[1,7],velocity:[.5,-.1,.3,.8,.1],color:[.45,.42,.4],size:[.1,.2],life:[4,8],drag:.15,gravity:.02},pollen:{every:.09,height:[.4,4],velocity:[0,.2,0,.5,.25],color:[.85,.9,.55],size:[.07,.11],life:[3,6],drag:.12,gravity:-.02},petals:{every:.05,height:[2.5,7],velocity:[.7,-.25,.3,.9,.2],color:[1,.7,.82],size:[.13,.2],life:[5,9],drag:.22,gravity:.06},leaves:{every:.07,height:[2.5,6.5],velocity:[.8,-.3,.2,1,.25],color:[.9,.45,.18],size:[.14,.22],life:[4,8],drag:.2,gravity:.08},snow:{every:.03,height:[4,9],velocity:[.35,-.55,.15,.6,.15],color:[1,1,1],size:[.11,.18],life:[6,11],drag:.05,gravity:.08},spray:{every:.1,height:[.1,1.2],velocity:[.3,.9,.2,.8,.4],color:[.95,.98,1],size:[.1,.18],life:[1.2,2.4],drag:.6,gravity:.25,overWater:!0},embers:{every:.07,height:[.1,1.5],velocity:[.2,1.1,.1,.8,.5],color:[2.6,1.1,.25],size:[.06,.1],life:[2,4.5],drag:.3,gravity:-.04,glow:!0,halo:1},fireflies:{every:.12,height:[.4,2.2],velocity:[0,.05,0,.5,.2],color:[1.6,2.4,.7],size:[.06,.09],life:[3,6],drag:.6,gravity:-.01,glow:!0,nightOnly:!0},spores:{every:.08,height:[.3,5],velocity:[0,.15,0,.4,.2],color:[.5,1.6,2.4],size:[.07,.12],life:[4,8],drag:.5,gravity:-.01,glow:!0,nightOnly:!0},sulfur:{every:.07,height:[.5,6],velocity:[.3,-.15,.2,.5,.1],color:[.95,.88,.45],size:[.1,.16],life:[4,8],drag:.15,gravity:.03},grit:{every:.02,height:[.2,5],velocity:[4.5,.1,1.5,2,.3],color:[.3,.34,.42],size:[.08,.14],life:[2,4],drag:.04,gravity:.02},glass:{every:.015,height:[.2,7],velocity:[7.5,-.4,2.6,2.4,.3],color:[1.5,1.7,2.1],size:[.05,.09],life:[1.4,2.6],drag:.02,gravity:.02,glow:!0},blizzard:{every:.012,height:[.2,6],velocity:[5.5,-.5,2,2.2,.4],color:[.95,.97,1],size:[.08,.14],life:[2,3.5],drag:.02,gravity:.03},rain:{every:.008,height:[9,14],velocity:[.8,-11,.3,.4,1.5],color:[.62,.68,.74],size:[.05,.08],life:[1,1.4],drag:0,gravity:.2},plume:{every:.05,height:[0,.4],velocity:[0,8.5,0,1.8,2],color:[.95,.86,.55],size:[1.4,2.6],life:[4,6.5],drag:.22,gravity:.32,vents:!0},darkplume:{every:.05,height:[0,.4],velocity:[.6,8,.2,1,1.5],color:[.22,.2,.2],size:[1.2,2.2],life:[4,6],drag:.25,gravity:.3,vents:!0},geyser:{every:.05,height:[0,.4],velocity:[0,9,0,1.2,2],color:[.92,.96,1],size:[1.2,2.2],life:[3.5,5.5],drag:.3,gravity:.3,vents:!0},bubbles:{every:.04,height:[0,2],velocity:[0,1.6,0,.4,.6],color:[.8,.95,1],size:[.08,.2],life:[4,8],drag:.4,gravity:-.12},marinesnow:{every:.025,height:[1,10],velocity:[.12,-.12,.08,.2,.06],color:[.72,.76,.8],size:[.05,.1],life:[9,15],drag:.35,gravity:.012},plankton:{every:.14,height:[.3,7],velocity:[0,.03,0,.25,.12],color:[.3,1.3,2.6],size:[.05,.08],life:[1.5,3.5],drag:.7,gravity:0,glow:!0,nightOnly:!0},sprinkles:{every:.03,height:[5,10],velocity:[.2,-.6,.1,.6,.2],color:[1,.5,.8],colors:[[1,.45,.7],[.5,.85,1],[1,.9,.35],[.6,1,.6],[1,1,1]],size:[.08,.12],life:[4,8],drag:.1,gravity:.1},fireworks:{every:1.6,burst:48,reach:[30,70],height:[24,40],velocity:[0,0,0,7,0],color:[2.4,1.4,.5],colors:[[2.6,1.4,.4],[.6,1.8,2.6],[2.4,.6,1.6],[1.6,2.6,.8],[2.6,2.4,2]],size:[.2,.32],life:[1.4,2.4],drag:.9,gravity:.22,glow:!0,nightOnly:!0}},Ph=3,D3=.04;class zh{constructor(e,t){this.capacity=e,this.count=0,this.position=new Float32Array(e*3),this.velocity=new Float32Array(e*3),this.color=new Float32Array(e*3),this.size=new Float32Array(e),this.life=new Float32Array(e),this.maxLife=new Float32Array(e),this.drag=new Float32Array(e),this.gravity=new Float32Array(e),this.floor=new Float32Array(e),this.alpha=new Float32Array(e),this.halo=new Float32Array(e);const i=new qt;i.setAttribute("position",new Ue(this.position,3)),i.setAttribute("color",new Ue(this.color,3)),i.setAttribute("aSize",new Ue(this.size,1)),i.setAttribute("aAlpha",new Ue(this.alpha,1)),i.setAttribute("aHalo",new Ue(this.halo,1)),i.setDrawRange(0,0),this.geometry=i,this.material=new Ye({transparent:!0,depthWrite:!1,blending:t,vertexColors:!0,fog:!0,uniforms:{...es.merge([Hr.fog,{uScale:{value:1}}]),...et},vertexShader:`
|
|
2161
|
-
#include <common>
|
|
2162
|
-
#include <fog_pars_vertex>
|
|
2163
|
-
attribute float aSize;
|
|
2164
|
-
attribute float aAlpha;
|
|
2165
|
-
attribute float aHalo;
|
|
2166
|
-
varying vec3 vColor;
|
|
2167
|
-
varying float vAlpha;
|
|
2168
|
-
varying float vHalo;
|
|
2169
|
-
uniform float uScale;
|
|
2170
|
-
void main() {
|
|
2171
|
-
vColor = color;
|
|
2172
|
-
vAlpha = aAlpha;
|
|
2173
|
-
vHalo = aHalo;
|
|
2174
|
-
// Particles are authored in world space, so the bend goes straight on the position.
|
|
2175
|
-
vec4 mvPosition = viewMatrix * vec4( bcBend( position ), 1.0 );
|
|
2176
|
-
// Perspective-correct point size, clamped so a particle right under the camera
|
|
2177
|
-
// cannot blow up into a full-screen quad.
|
|
2178
|
-
gl_PointSize = clamp( aSize * uScale * ( 260.0 / -mvPosition.z ) * ( 1.0 + 2.0 * aHalo ), 1.0, 90.0 );
|
|
2179
|
-
gl_Position = projectionMatrix * mvPosition;
|
|
2180
|
-
#include <fog_vertex>
|
|
2181
|
-
}
|
|
2182
|
-
`,fragmentShader:`
|
|
2183
|
-
#include <common>
|
|
2184
|
-
#include <fog_pars_fragment>
|
|
2185
|
-
varying vec3 vColor;
|
|
2186
|
-
varying float vAlpha;
|
|
2187
|
-
varying float vHalo;
|
|
2188
|
-
void main() {
|
|
2189
|
-
vec2 d = gl_PointCoord - 0.5;
|
|
2190
|
-
float r = length( d );
|
|
2191
|
-
if ( r > 0.5 ) discard;
|
|
2192
|
-
// Soft core with a fast falloff — reads as a spark rather than a disc.
|
|
2193
|
-
float core = pow( max( 0.0, 1.0 - r * 2.0 * ( 1.0 + 2.0 * vHalo ) ), 1.6 );
|
|
2194
|
-
float a = ( core + vHalo * 0.22 * pow( 1.0 - r * 2.0, 2.0 ) ) * vAlpha;
|
|
2195
|
-
gl_FragColor = vec4( vColor, a );
|
|
2196
|
-
#include <fog_fragment>
|
|
2197
|
-
}
|
|
2198
|
-
`}),this.points=new Ru(i,this.material),this.points.frustumCulled=!1,this.points.renderOrder=5}spawn(e,t,i,n,r,o,a,l,c,h,d,u=1.2,f=1,p=0,m=0){if(this.count>=this.capacity)return!1;const g=this.count++,w=g*3;return this.position[w]=e,this.position[w+1]=t,this.position[w+2]=i,this.velocity[w]=n,this.velocity[w+1]=r,this.velocity[w+2]=o,this.color[w]=a,this.color[w+1]=l,this.color[w+2]=c,this.size[g]=h,this.life[g]=d,this.maxLife[g]=d,this.drag[g]=u,this.gravity[g]=f,this.floor[g]=p+D3,this.alpha[g]=1,this.halo[g]=m,!0}update(e){const{position:t,velocity:i,life:n,maxLife:r,drag:o,gravity:a,floor:l,alpha:c,halo:h}=this;let d=0;for(;d<this.count;){if(n[d]-=e,n[d]<=0){const m=--this.count;if(m!==d){const g=d*3,w=m*3;for(let b=0;b<3;b++)t[g+b]=t[w+b],i[g+b]=i[w+b],this.color[g+b]=this.color[w+b];this.size[d]=this.size[m],n[d]=n[m],r[d]=r[m],o[d]=o[m],a[d]=a[m],l[d]=l[m],c[d]=c[m],h[d]=h[m]}continue}const u=d*3,f=Math.max(0,1-o[d]*e);i[u]*=f,i[u+1]=i[u+1]*f+O3*a[d]*e,i[u+2]*=f,t[u]+=i[u]*e,t[u+1]+=i[u+1]*e,t[u+2]+=i[u+2]*e,t[u+1]<l[d]&&i[u+1]<0&&(t[u+1]=l[d],i[u+1]*=-.32,i[u]*=.6,i[u+2]*=.6);const p=n[d]/r[d];c[d]=p>.85?(1-p)/.15:p/.85,h[d]>0&&(c[d]*=.78+.22*Math.sin(n[d]*7.3+r[d]*13)),d++}this.geometry.setDrawRange(0,this.count),this.geometry.attributes.position.needsUpdate=!0,this.geometry.attributes.color.needsUpdate=!0,this.geometry.attributes.aSize.needsUpdate=!0,this.geometry.attributes.aAlpha.needsUpdate=!0,this.geometry.attributes.aHalo.needsUpdate=!0}clear(){this.count=0,this.geometry.setDrawRange(0,0)}dispose(){this.geometry.dispose(),this.material.dispose()}}class V3{constructor(e,t){this.scene=e,this.settings=t,this.enabled=t.particleBudget>0;const i=Math.max(64,t.particleBudget);this.glow=new zh(Math.ceil(i*.6),ji),this.dust=new zh(Math.ceil(i*.4),zu),e.add(this.glow.points,this.dust.points),this._ambientTimer=0,this.setEnabled(this.enabled)}setEnabled(e){this.enabled=e,this.glow.points.visible=e,this.dust.points.visible=e,e||(this.glow.clear(),this.dust.clear())}onSettingsChanged(e){e.has("particles")&&this.setEnabled(this.settings.particleBudget>0)}weld(e,t,i,n,r=0){if(!this.enabled)return;const o=this.settings.get("particles")==="full"?3:1;for(let a=0;a<o;a++){const l=Math.random()*Math.PI*2,c=.9+Math.random()*2.4;this.glow.spawn(e+(Math.random()-.5)*.16,t+(Math.random()-.5)*.12,i+(Math.random()-.5)*.16,Math.cos(l)*c*.5,1.1+Math.random()*2.2,Math.sin(l)*c*.5,n.r*2.4,n.g*2.2,n.b*1.6,.055+Math.random()*.05,.35+Math.random()*.5,1.6,1,r)}}step(e,t,i,n,r=0){if(!this.enabled)return;const o=Math.random()*Math.PI*2;this.dust.spawn(e,t+.03,i,Math.cos(o)*.28,.24+Math.random()*.2,Math.sin(o)*.28,n.r,n.g,n.b,.12+Math.random()*.14,.5+Math.random()*.4,2.4,.12,r)}cheer(e,t,i,n,r=0){if(!this.enabled)return;const o=this.settings.get("particles")==="full"?14:6;for(let a=0;a<o;a++){const l=Math.random()*Math.PI*2,c=.6+Math.random()*1.6;this.glow.spawn(e,t+.8,i,Math.cos(l)*c,2.4+Math.random()*2.4,Math.sin(l)*c,n.r*(1.4+Math.random()),n.g*(1.4+Math.random()),n.b*(1.4+Math.random()),.07+Math.random()*.07,1.1+Math.random()*.9,.7,.8,r)}}thruster(e,t,i){if(this.enabled)for(let n=0;n<6;n++){const r=Math.random()*Math.PI*2,o=Math.random()*1.4;this.dust.spawn(e+Math.cos(r)*o,t+.1,i+Math.sin(r)*o,Math.cos(r)*(1.6+Math.random()*2),.5+Math.random()*.7,Math.sin(r)*(1.6+Math.random()*2),.55,.5,.46,.3+Math.random()*.3,.9+Math.random()*.6,1.6,.08)}}mote(e,t,i,n,r=.06,o=4){if(!this.enabled)return;const a=Math.random()*Math.PI*2;this.glow.spawn(e,t,i,Math.cos(a)*.18,.06+Math.random()*.14,Math.sin(a)*.18,n.r,n.g,n.b,r*(.7+Math.random()*.6),o*(.7+Math.random()*.6),.9,-.006)}churn(e,t,i,n,r,o,a,l,c=0){if(!this.enabled)return;const h=.82+Math.random()*.28;this.dust.spawn(e,t,i,n,r,o,a.r*h,a.g*h,a.b*h,l,1.6+Math.random()*1.6,.55,.6,c)}spice(e,t,i,n,r,o,a,l=0){this.enabled&&this.glow.spawn(e,t,i,n,r,o,a.r,a.g,a.b,.12+Math.random()*.12,1.8+Math.random()*1.8,.9,.12,l,1)}snooze(e,t,i){this.enabled&&this.glow.spawn(e,t,i,.12,.42,.05,.55,.6,1.1,.075,1.9,.35,-.02)}ambient(e,t,i,n=0,r=null){if(!this.enabled)return;const o=i.weather||(i.dust?[{kind:"dust",rate:i.dust}]:null);if(!o?.length)return;const a=this.settings.get("particles")==="full"?1:.42,l=this._weatherTimers||(this._weatherTimers=new Map);for(const c of o){const h=I3[c.kind];if(!h)continue;const d=h.nightOnly?n*n:1;if(d<=.02)continue;let u=(l.get(c.kind)??0)-e;if(u>0){l.set(c.kind,u);continue}l.set(c.kind,h.every/(Math.max(.01,c.rate)*a*d));let f,p;if(h.burst){const C=Math.random()*Math.PI*2,_=h.reach[0]+Math.random()*(h.reach[1]-h.reach[0]),x=t.position.x+Math.cos(C)*_,T=t.position.z+Math.sin(C)*_,M=(r?r(x,T):0)+h.height[0]+Math.random()*(h.height[1]-h.height[0]),k=h.colors[Math.floor(Math.random()*h.colors.length)],A=h.velocity[3];for(let P=0;P<Math.round(h.burst*a);P++){const $=Math.random()*2-1,H=Math.random()*Math.PI*2,q=Math.sqrt(1-$*$)*A*(.8+Math.random()*.4);this.glow.spawn(x,M,T,Math.cos(H)*q,$*A,Math.sin(H)*q,k[0],k[1],k[2],h.size[0]+Math.random()*(h.size[1]-h.size[0]),h.life[0]+Math.random()*(h.life[1]-h.life[0]),h.drag,h.gravity,M-50)}continue}if(h.vents){const C=this._vents(i),_=C[Math.floor(Math.random()*C.length)];f=_.x,p=_.z}else{const C=Math.random()*Math.PI*2,_=8+Math.random()*36;f=t.position.x+Math.cos(C)*_,p=t.position.z+Math.sin(C)*_}const m=r?r(f,p):0,g=m+h.height[0]+Math.random()*(h.height[1]-h.height[0]);if(h.overWater!==void 0&&r&&i.water&&m<i.water.level!==h.overWater)continue;const w=h.glow?this.glow:this.dust,b=h.colors?h.colors[Math.floor(Math.random()*h.colors.length)]:h.color,y=h.velocity;w.spawn(f,g,p,y[0]+(Math.random()-.5)*y[3],y[1]+(Math.random()-.5)*y[4],y[2]+(Math.random()-.5)*y[3],b[0]*(.9+Math.random()*.2),b[1]*(.9+Math.random()*.2),b[2]*(.9+Math.random()*.2),h.size[0]+Math.random()*(h.size[1]-h.size[0]),h.life[0]+Math.random()*(h.life[1]-h.life[0]),h.drag,h.gravity,m,h.halo??0)}}_vents(e){if(this._ventsFor===e.id)return this._ventSpots;let t=0;for(const n of e.id)t=(t*31+n.charCodeAt(0))%997;this._ventsFor=e.id;const i=Lu(e);return i.length?(this._ventSpots=i,i):(this._ventSpots=Array.from({length:Ph},(n,r)=>{const o=r/Ph*Math.PI*2+t*.37,a=66+(t+r*17)%22;return{x:Math.cos(o)*a,z:Math.sin(o)*a}}),this._ventSpots)}update(e){this.enabled&&(this.glow.update(e),this.dust.update(e))}get liveCount(){return this.glow.count+this.dust.count}dispose(){this.scene.remove(this.glow.points,this.dust.points),this.glow.dispose(),this.dust.dispose()}}const la=.5,Lh=56,N3=24e3,Rh=Math.SQRT2,ca=[];class W3{constructor(){this.cell=la,this.half=Lh,this.size=Math.ceil(Lh*2/la);const e=this.size*this.size;this.blocked=new Uint8Array(e),this.gScore=new Float32Array(e),this.parent=new Int32Array(e),this.stamp=new Int32Array(e),this.closed=new Uint8Array(e),this.heap=new Int32Array(e),this.heapKey=new Float32Array(e),this.heapSize=0,this.generation=0,this.version=0,this.solids=[],this._solidBuckets=new Map,this._bucket=4}_bucketKey(e,t){return e*100003+t}_solidsNear(e,t,i){i.length=0;const n=this._bucket,r=Math.floor(e/n),o=Math.floor(t/n),a=this._solidBuckets.get(this._bucketKey(r,o));if(a)for(let l=0;l<a.length;l++)i.push(a[l]);return i}toCell(e){return Math.floor((e+this.half)/this.cell)}toWorld(e){return e*this.cell-this.half+this.cell*.5}inBounds(e,t){return e>=0&&t>=0&&e<this.size&&t<this.size}isBlocked(e,t){const i=this.toCell(e),n=this.toCell(t);return this.inBounds(i,n)?this.blocked[n*this.size+i]===1:!0}rebuild(e){this.blocked.fill(0);const{size:t,cell:i}=this;this.solids=e.filter(r=>r.keep>0),this._solidBuckets.clear();const n=this._bucket;for(const r of this.solids){const o=Math.floor((r.x-r.keep)/n),a=Math.floor((r.x+r.keep)/n),l=Math.floor((r.z-r.keep)/n),c=Math.floor((r.z+r.keep)/n);for(let h=o;h<=a;h++)for(let d=l;d<=c;d++){const u=this._bucketKey(h,d);let f=this._solidBuckets.get(u);f||this._solidBuckets.set(u,f=[]),f.push(r)}}for(const r of e){const o=r.r;if(!(o>0))continue;const a=Math.max(0,this.toCell(r.x-o)),l=Math.min(t-1,this.toCell(r.x+o)),c=Math.max(0,this.toCell(r.z-o)),h=Math.min(t-1,this.toCell(r.z+o)),d=o*o;for(let u=c;u<=h;u++){const p=this.toWorld(u)-r.z,m=u*t;for(let g=a;g<=l;g++){const w=this.toWorld(g)-r.x;w*w+p*p<=d&&(this.blocked[m+g]=1)}}}this.version++}repel(e,t){const i=this._solidsNear(e.x,e.z,ca);for(let n=0;n<i.length;n++){const r=i[n],o=e.x-r.x,a=e.z-r.z,l=r.keep,c=o*o+a*a;if(c>=l*l)continue;const h=Math.sqrt(c);if(h<1e-4){t.x+=l*2;continue}const d=(1-h/l)*6+.4;t.x+=o/h*d,t.z+=a/h*d}return t}keepOut(e){const t=e.x,i=e.z;for(let n=0;n<3;n++){const r=this._solidsNear(e.x,e.z,ca);let o=!1;for(let a=0;a<r.length;a++){const l=r[a],c=e.x-l.x,h=e.z-l.z,d=l.keep,u=c*c+h*h;if(u>=d*d)continue;const f=Math.sqrt(u);if(f<1e-4){e.x=l.x+d;continue}const p=l.x+c/f*d,m=l.z+h/f*d;if(o=!0,!this.isBlocked(p,m)){e.x=p,e.z=m;continue}const g=Math.atan2(h,c);for(let w=1;w<=9;w++){const b=w*.2;for(const y of[1,-1]){const C=g+y*b,_=l.x+Math.cos(C)*d,x=l.z+Math.sin(C)*d;if(this.isBlocked(_,x))continue;const T=Math.hypot(_-e.x,x-e.z)||1,M=Math.min(T,.05),k=e.x+(_-e.x)/T*M,A=e.z+(x-e.z)/T*M;if(!this.isBlocked(k,A)){e.x=k,e.z=A,w=99;break}}}}if(!o)break}return this.insideKeep(e.x,e.z)&&this.insideKeep(t,i)?(e.x=t,e.z=i,0):Math.hypot(e.x-t,e.z-i)}nearestClear(e,t,i=5,n=()=>!0){if(!this.isBlocked(e,t)&&!this.insideKeep(e,t)&&n(e,t))return{x:e,z:t};for(let r=.35;r<=i;r+=.35){const o=Math.max(8,Math.round(r*14)),a=r*7.3%(Math.PI*2);for(let l=0;l<o;l++){const c=a+l/o*Math.PI*2,h=e+Math.cos(c)*r,d=t+Math.sin(c)*r;if(!(this.isBlocked(h,d)||this.insideKeep(h,d))&&n(h,d))return{x:h,z:d}}}return null}insideKeep(e,t){const i=this._solidsNear(e,t,ca);for(let n=0;n<i.length;n++){const r=i[n],o=e-r.x,a=t-r.z;if(o*o+a*a<r.keep*r.keep)return!0}return!1}clearWalk(e,t,i,n){const r=Math.max(1,Math.ceil(Math.hypot(i-e,n-t)/(la*.5)));for(let o=1;o<=r;o++){const a=o/r,l=e+(i-e)*a,c=t+(n-t)*a;if(this.isBlocked(l,c)||this.insideKeep(l,c))return!1}return!0}nearestFree(e,t,i=24){const n=this.toCell(e),r=this.toCell(t);if(this.inBounds(n,r)&&this.blocked[r*this.size+n]===0)return{ix:n,iz:r};for(let o=1;o<=i;o++){let a=null,l=1/0;for(let c=-o;c<=o;c++)for(let h=-o;h<=o;h++){if(Math.max(Math.abs(h),Math.abs(c))!==o)continue;const d=n+h,u=r+c;if(!this.inBounds(d,u)||this.blocked[u*this.size+d]===1)continue;const f=h*h+c*c;f<l&&(l=f,a={ix:d,iz:u})}if(a)return a}return null}lineOfSight(e,t,i,n){const r=i-e,o=n-t,a=Math.hypot(r,o),l=Math.ceil(a/(this.cell*.5));if(l===0)return!this.isBlocked(e,t);for(let c=0;c<=l;c++){const h=c/l;if(this.isBlocked(e+r*h,t+o*h))return!1}return!0}findPath(e,t,i,n){const r=this.nearestFree(e,t),o=this.nearestFree(i,n);if(!r||!o)return null;const a=this.size,l=r.iz*a+r.ix,c=o.iz*a+o.ix,h=this.isBlocked(i,n)?this.toWorld(o.ix):i,d=this.isBlocked(i,n)?this.toWorld(o.iz):n;if(this.lineOfSight(e,t,h,d))return[{x:h,z:d}];const u=++this.generation,{gScore:f,parent:p,stamp:m,closed:g}=this;this.heapSize=0,f[l]=0,p[l]=-1,m[l]=u,g[l]=0,this._push(l,this._heuristic(r.ix,r.iz,o.ix,o.iz));let w=0,b=!1,y=l,C=this._heuristic(r.ix,r.iz,o.ix,o.iz);for(;this.heapSize>0;){const A=this._pop();if(g[A]===1)continue;if(g[A]=1,A===c){b=!0;break}if(++w>N3)break;const P=A%a,$=(A-P)/a,H=f[A],q=this._heuristic(P,$,o.ix,o.iz);q<C&&(C=q,y=A);for(let Y=0;Y<8;Y++){const G=P+Bh[Y*2],ee=$+Bh[Y*2+1];if(!this.inBounds(G,ee))continue;const se=ee*a+G;if(this.blocked[se]===1||m[se]===u&&g[se]===1)continue;const xe=Y>=4;if(xe&&(this.blocked[$*a+G]===1||this.blocked[ee*a+P]===1))continue;const we=H+(xe?Rh:1);m[se]===u&&we>=f[se]||(m[se]=u,g[se]=0,f[se]=we,p[se]=A,this._push(se,we+this._heuristic(G,ee,o.ix,o.iz)))}}const _=b?c:y;if(!b&&y===l)return null;const x=[];let T=_;for(;T!==-1;)x.push(T),T=p[T];x.reverse();const M=b?h:this.toWorld(_%a),k=b?d:this.toWorld((_-_%a)/a);return this._smooth(x,e,t,M,k)}_heuristic(e,t,i,n){const r=Math.abs(e-i),o=Math.abs(t-n);return r+o+(Rh-2)*Math.min(r,o)}_smooth(e,t,i,n,r){const o=this.size,a=e.map(u=>{const f=u%o,p=(u-f)/o;return{x:this.toWorld(f),z:this.toWorld(p)}});a[a.length-1]={x:n,z:r};const l=[];let c=t,h=i,d=0;for(;d<a.length;){let u=d;for(let p=a.length-1;p>d;p--)if(this.lineOfSight(c,h,a[p].x,a[p].z)){u=p;break}const f=a[u];if(l.push(f),c=f.x,h=f.z,u===a.length-1)break;d=u+1}return l.length?l:[{x:n,z:r}]}slide(e,t,i){if(this.isBlocked(e.x,e.z)){const o=this.nearestFree(e.x,e.z);if(o){const a=this.toWorld(o.ix),l=this.toWorld(o.iz),c=Math.hypot(a-e.x,l-e.z)||1,h=Math.min(c,Math.hypot(t,i)+.04);e.x+=(a-e.x)/c*h,e.z+=(l-e.z)/c*h}return!1}const n=e.x+t,r=e.z+i;return this.isBlocked(n,r)?t!==0&&!this.isBlocked(n,e.z)?(e.x=n,!0):i!==0&&!this.isBlocked(e.x,r)?(e.z=r,!0):!1:(e.x=n,e.z=r,!0)}_push(e,t){let i=this.heapSize++;for(this.heap[i]=e,this.heapKey[i]=t;i>0;){const n=i-1>>1;if(this.heapKey[n]<=this.heapKey[i])break;this._swap(i,n),i=n}}_pop(){const e=this.heap[0],t=--this.heapSize;this.heap[0]=this.heap[t],this.heapKey[0]=this.heapKey[t];let i=0;for(;;){const n=i*2+1,r=n+1;let o=i;if(n<this.heapSize&&this.heapKey[n]<this.heapKey[o]&&(o=n),r<this.heapSize&&this.heapKey[r]<this.heapKey[o]&&(o=r),o===i)break;this._swap(i,o),i=o}return e}_swap(e,t){const i=this.heap[e];this.heap[e]=this.heap[t],this.heap[t]=i;const n=this.heapKey[e];this.heapKey[e]=this.heapKey[t],this.heapKey[t]=n}}const Bh=new Int8Array([1,0,-1,0,0,1,0,-1,1,1,1,-1,-1,1,-1,-1]);function H3(s,e){const t=String(e||"");return!t||s.includes(t)?[...s]:[...s,t]}function U3(s,e){const t=String(e||"");return s.filter(i=>i!==t)}function j3(s,e,t){const i=e instanceof Set?e:new Set(e),n=t instanceof Set?t:new Set(t);return s.filter(r=>!r.archived&&!i.has(r.id)&&!n.has(r.project||"unknown"))}function q3(s,e,t,i){const n=e instanceof Set?e:new Set(e),r=t instanceof Set?t:new Set(t),o=new Map;for(const l of s){const c=l.project||"unknown";if(r.has(c))continue;o.has(c)||o.set(c,{live:[],retired:[]});const h=o.get(c);l.archived||n.has(l.id)?h.retired.push(l):h.live.push(l)}const a=[];for(const{live:l,retired:c}of o.values())c.sort((h,d)=>(d.lastActivityAt??0)-(h.lastActivityAt??0)),a.push(...l,...c.slice(0,Math.max(0,i-l.length)));return a}function G3(s,e){return[...new Set(s.map(String).filter(Boolean))].sort((i,n)=>i.localeCompare(n)).map(i=>({name:i,count:e.filter(n=>!n.archived&&(n.project||"unknown")===i).length}))}const y0=4320*60*1e3,cl=["asking","error","done","working","delegating","celebrating","idle","sleeping"],Fh={working:"Working",delegating:"Waiting on agents",asking:"Needs you",done:"Done",error:"Error",celebrating:"Shipped",idle:"Idle",sleeping:"Dormant",spawning:"Arriving",leaving:"Heading home"},C0=(s,e=Date.now())=>!!s.hasError&&e-s.lastActivityAt<=y0;function An(s,e=Date.now()){return s.needsInput?"asking":C0(s,e)?"error":s.awaitingSubagents?"delegating":s.running?"working":s.prState==="MERGED"?"celebrating":s.unread?"done":e-s.lastActivityAt>y0?"sleeping":"idle"}const Z3=new Set(["island","crags","headland","fjord"]),Oh=s=>Z3.has(s.shape)||s.fissures?.hug!==void 0,Ci=.26,Cr=.12,X3=.004,Y3=80,Q3=.8,K3=.45,J3=8e3,e5={asking:fe.asking,done:fe.done,error:fe.error,working:fe.working,delegating:fe.delegating,celebrating:fe.celebrating,sleeping:fe.none,idle:fe.none,spawning:fe.spawning,leaving:fe.leaving};class t5{constructor(e,t,i,n){this.scene=e,this.settings=t,this.camera=i,this.renderer=n,this.planet=Wt[t.get("planet")]||Wt.moon,this._applyPlanetTint(),this.sky=new em(e,t,n),this.sky.setPlanet(this.planet),this.sky.setTime(t.get("timeOfDay")),this.plots=new Map,this.plotOrder=[],this.plotCells=new Map,this.districts=new Map,this.orgAccents=new Map,this.arrangeDistricts=!1,this.buildings=new Map,this.buildingSurfaces=new J1(this.buildings,(r,o)=>this.surfaceAt(r,o)),this.threads=new Map,this.usedAccents=new Set,this.worldGroup=new Pt,this.worldGroup.name="world",e.add(this.worldGroup),this.ship=new Qg(e,Js()),this.astronauts=new b3(e,t,i),this.astronauts.world=this._world(),this.indicators=new z3(e,t,Mm),this.particles=new V3(e,t),this.scaffolds=new wg(e,320),this.fauna=new K1(e,t),this.reflections=new i1({scene:e,renderer:n,settings:t,sky:this.sky,astronauts:this.astronauts,excluded:()=>[this.labelGroup,this.indicators.mesh,this.particles.points,this.fauna.group,this.grass?.mesh,this.mist?.mesh]}),this.onSound=null,this.nav=new W3,this.astronauts.setNavigation(this.nav),this.plotGroup=new Pt,this.labelGroup=new Pt,e.add(this.plotGroup,this.labelGroup),this.uiVisible=!0,this.hoveredPlot=null,this.hoveredOrg=null,this.selectedPlot=null,this.activePlots=new Set,this._dustTint=new W(this.planet.stepDust??this.planet.ground.high),this._c=new W,this._c2=new W,this.stats={agents:0,projects:0,working:0,done:0,error:0},this._buildTerrain()}_buildTerrain(){for(const e of this._worldSteps())e.run()}_worldSteps(){const e=this.planet;return[{stage:"ground",shown:!0,run:()=>this._buildGround()},{stage:"island",shown:e.shape==="sky",run:()=>this._buildIsland()},{stage:"water",shown:!!e.water,run:()=>this._buildWater()},...this._scatterSteps(),{stage:"horizon",shown:!!(e.skyline||e.mist),run:()=>this._buildAtmosphere()},{stage:"wildlife",shown:!1,run:()=>this._settleWorld()}]}_buildGround(){this.terrain&&(this.worldGroup.remove(this.terrain),this.terrain.geometry.dispose(),this.terrain.material.dispose()),this.scatterGroup&&(this.worldGroup.remove(this.scatterGroup),rn(this.scatterGroup)),Oh(this.planet)&&tm(this._footprintCells(),pt),this.terrain=sm(this.planet,this.settings.get("groundDetail")),this.worldGroup.add(this.terrain),this.worm?.dispose(),this.worm=this.planet.worm?Xe.createWorm({spec:this.planet.worm,terrain:this.terrain,footprint:()=>this._footprintCells(),cell:pt,particles:this.particles,settings:this.settings,sand:this.planet.stepDust??this.planet.ground.high}):null}_settleWorld(){const e=Js();this.ship.group.position.y=gt(e.x,e.z,this.planet),this._dustTint.set(this.planet.stepDust??this.planet.ground.high),this._faunaPlanet!==this.planet.id&&(this._faunaPlanet=this.planet.id,this.fauna.setPlanet(this.planet,{heightAt:(t,i)=>this.groundAt(t,i),parcelSurfaceAt:(t,i)=>this.buildingSurfaces.at(t,i),waterLevel:this.planet.water?.level??null,waterHeightAt:this.water?(t,i,n)=>this.water.heightAt(t,i,n):void 0})),this._syncFaunaSites()}_syncFaunaSites(){const e=[];for(const[i,n]of this.buildings){if(n.retiring)continue;const r=n.mesh.position;e.push({x:r.x,y:r.y,z:r.z,radius:n.mesh.userData.footprint,active:this._isActive(i)})}const t=Js();t.y=this.ship.group.position.y,this.fauna.setSites({ship:this.ship.shipDoor(),pad:t,sites:e})}_buildIsland(){if(this.island&&(this.worldGroup.remove(this.island.group),this.island.dispose(),this.island=null),this.rock&&(this.rock.dispose(),this.rock=null),this.planet.shape!=="sky")return;const e=this.settings.get("groundDetail");this.island=$2({planet:this.planet,heightAt:(t,i)=>gt(t,i,this.planet),rimRadius:this._footprintRadius()+6,quality:e==="high"?"high":e==="low"?"low":"medium"}),this.island.meshes.underside.visible=!1,this.island.meshes.vines.visible=!1,this.island.meshes.sea.visible=this.planet.skyIsland?.clouds!==!1,this.island.meshes.puffs.visible=this.planet.skyIsland?.clouds!==!1,this.island.setDaylight(this.sky.dayFactor??1),this.worldGroup.add(this.island.group),this._syncIslandRock()}_footprintCells(){const e=[];for(const i of this.plotOrder)for(const n of i.localCenters)e.push({x:i.center.x+n.x,z:i.center.z+n.z});const t=Js();return e.push({x:t.x,z:t.z}),e.slice(0,im)}_footprintRadius(){let e=pt;for(const t of this._footprintCells())e=Math.max(e,Math.hypot(t.x,t.z)+pt);return e}onIsland(e,t){if(this.planet.shape!=="sky")return!0;const i=(pt+zo)*.86;for(const n of this._footprintCells()){const r=e-n.x,o=t-n.z;if(r*r+o*o<i*i)return!0}return!1}_syncIslandRock(){if(this.planet.shape!=="sky")return;this.rock&&(this.rock.dispose(),this.rock=null);const e=this._footprintCells();this.terrain.userData.setFootprint?.(e,pt+zo);const t=this.settings.get("groundDetail"),i=this.planet.skyIsland||{},n={city:Xe.createPlatform,branch:Xe.createBranch}[i.style]??E2;this.rock=n({cells:e,cellRadius:pt,margin:zo,palette:{soil:i.soil,rock:i.rock,vine:i.vine,moss:this.planet.ground.low,hull:i.hull,trim:i.trim,deck:i.deck,lights:i.lights,shell:i.shell,scute:i.scute,skin:i.skin,belly:i.belly,bark:i.bark,toward:i.toward,trunk:i.trunk,seam:i.seam,rough:i.rough,spikes:i.spikes,vines:i.vines},quality:t==="low"?"low":"medium"}),this.worldGroup.add(this.rock.group)}_buildWater(){this.water&&(this.worldGroup.remove(this.water.mesh),this.water.dispose(),this.water=null);const e=this.settings.get("groundDetail");this.water=b1({planet:this.planet,heightAt:(t,i)=>gt(t,i,this.planet),quality:e==="high"?"high":e==="low"?"low":"medium"}),this.water&&this.worldGroup.add(this.water.mesh)}_buildAtmosphere(){for(const t of[this.mist,this.skyline])t&&(this.worldGroup.remove(t.mesh),t.dispose());const e=this.settings.get("groundDetail");this.mist=F2({planet:this.planet,quality:e==="low"?"low":"medium"}),this.skyline=rg({planet:this.planet,sky:this.sky,fog:this.scene.fog});for(const t of[this.mist,this.skyline])t&&this.worldGroup.add(t.mesh)}ripple(e,t,i=1){this.water&&(gt(e,t,this.planet)>=this.planet.water.level||this.water.ripple(e,t,i))}_buildScatter(){for(const e of this._scatterSteps())e.run()}_scatterSteps(){return[{stage:"scatter",shown:!0,run:()=>this._placeScatter()},{stage:"grass",shown:!!this.planet.grass,run:()=>this._buildGrass(this._scatterClearings())},{stage:"paths",shown:!0,run:()=>this.nav&&this._rebuildNavigation()}]}_placeScatter(){this.scatterGroup&&(this.worldGroup.remove(this.scatterGroup),rn(this.scatterGroup));const e=this._scatterClearings();this.scatterGroup=nm(this.planet,this.settings.get("scatterDensity"),e,4242,(t,i)=>this.onIsland(t,i)),this.worldGroup.add(this.scatterGroup),this._scatterFootprint=this._plotFootprint()}_scatterClearings(){const e=[];for(const i of this.plotOrder)for(const n of i.localCenters)e.push({x:i.center.x+n.x,z:i.center.z+n.z,r:8.6});const t=Js();return e.push({x:t.x,z:t.z,r:7.5}),e}_buildGrass(e){const t=e[e.length-1];this.grass&&(this.grass.dispose(),this.grass=null);const i=this.settings.get("groundDetail");this.grass=f2({planet:this.planet,heightAt:(n,r)=>gt(n,r,this.planet),blocked:(n,r)=>!this.onIsland(n,r)||rm(n,r,this.planet)>-.6||this.plotOrder.some(o=>o.containsWorld(n,r,-.4))||t&&(n-t.x)**2+(r-t.z)**2<t.r*t.r,density:this.settings.get("scatterDensity"),quality:i==="high"?"high":i==="low"?"low":"medium"}),this.grass&&this.worldGroup.add(this.grass.mesh)}_plotFootprint(){return this.plotOrder.map(e=>e.signature).join("|")}onAssetsReady(){this._buildTerrain()}setPlanet(e){const t=Wt[e];if(!(!t||t===this.planet))return this.planet=t,this.reflections.invalidate(),this._applyPlanetTint(),this._buildWorldInStages(t)}async _buildWorldInStages(e){const t=this._worldBuildId=(this._worldBuildId??0)+1,i=()=>t===this._worldBuildId,n=[{stage:"sky",shown:!0,run:()=>this.sky.setPlanet(e)},...this._worldSteps()],r=n.filter(c=>c.shown).length+2,o={bots:this.astronauts.agents.length};let a=0;const l=c=>this.onWorldStage?.({build:t,planet:e,stage:c,done:a,total:r,facts:{...o}});try{for(const u of n){if(u.shown){if(l(u.stage),await Ih(),!i())return!1;a++}u.run(),u.stage==="scatter"&&(o.scatter=s5(this.scatterGroup)),u.stage==="grass"&&(o.grass=this.grass?.count??0)}if(l("shaders"),await Ih(),!i())return!1;const c=this.renderer.info.programs,h=c?.length??0,d=this._compileShaders();o.shaders=Math.max(0,(c?.length??0)-h),l("shaders"),d&&await Promise.race([d,i5(J3)]),a++}catch(c){console.error(c)}return i()?(l("landing"),!0):!1}_compileShaders(){const e=this.renderer;if(!e.compileAsync)return null;const t=e.getRenderTarget();e.setRenderTarget(this.sceneTarget?.()??null);try{return e.compileAsync(this.scene,this.camera)}finally{e.setRenderTarget(t)}}_applyPlanetTint(){const e=this.planet.buildingTint;zs.uPlanetTint.value.set(e??16777215),zs.uPlanetTintAmount.value=e!=null?1:0}onSettingsChanged(e,t){e.has("planet")?this.setPlanet(this.settings.get("planet")):t.world&&this._buildTerrain(),this.sky.onSettingsChanged(e),this.astronauts.onSettingsChanged(e),this.particles.onSettingsChanged(e),this.fauna.onSettingsChanged(e),e.has("clouds")&&this.sky.setPlanet(this.planet),e.has("showLabels")&&this._syncLabels(),e.has("timeOfDay")&&this.sky.setTime(this.settings.get("timeOfDay"))}setThreads(e,t=new Set,i=new Set,n=new Set){const r=Date.now(),o=j3(e,t,i),a=new Set(o.map(w=>w.id)),l=q3(e,t,i,Ag),c=new Map;for(const w of l){const b=w.project||"unknown";c.has(b)||c.set(b,[]),c.get(b).push(w)}const h=new Set;if(this.settings.get("hideDormant")){for(const[w,b]of c)b.every(y=>An(y,r)==="sleeping")&&h.add(w);h.size===c.size&&h.clear();for(const w of h)c.delete(w)}this.dormantProjects=h;const d=[...c.entries()].sort((w,b)=>b[1].length!==w[1].length?b[1].length-w[1].length:w[0].localeCompare(b[0]));this._syncPlots(d);for(const w of[...i,...h]){const b=this.plotCells.get(w);b&&(this.plotCells.delete(w),this.plotCells.set(w,b))}const u=[],f=new Set,p={agents:0,projects:d.length};for(const w of cl)p[w]=0;const m=new Set,g=new Set;for(const[w,b]of d){const y=this.plots.get(w);if(!y)continue;b.sort((x,T)=>x.createdAt-T.createdAt);const C=y.slotOf||(y.slotOf=new Map);for(const x of[...C.keys()])b.some(T=>T.id===x)||C.delete(x);const _=new Set(C.values());for(const x of b){if(C.has(x.id))continue;let T=0;for(;_.has(T);)T++;_.add(T),C.set(x.id,T)}b.forEach(x=>{const T=C.get(x.id),M=this._syncBuilding(x,y,T);if(f.add(x.id),!a.has(x.id))return;const k=An(x,r);p[k]!==void 0&&p[k]++,(k==="asking"||k==="done"||k==="error")&&m.add(y.id),(k==="asking"||k==="done"||k==="error"||k==="working"||k==="delegating")&&g.add(y.id),p.agents++,u.push({id:x.id,thread:x,status:k,site:null,anchor:M.mesh.position.clone(),accent:y.accent,known:n.has(x.id)})})}for(const[w,b]of this.buildings)f.has(w)||this._removeBuilding(w,b);this.threads=new Map(o.map(w=>[w.id,w])),this.urgentPlots=m,this.activePlots=g,this._rebuildNavigation();for(const w of u){const b=this.buildings.get(w.id);w.site=this._workSite(this.plots.get(b.plot),b,b.slot)}return this._syncFaunaSites(),this.stats=p,this.astronauts.setRoster(u,this._world()),this.stats}_syncPlots(e){const t=e.map(([c,h])=>({name:c,org:Ul(h,c)})),i=!!this.settings.get("districts"),n=i?a0(t):new Map,r=i?l0(t):new Map,o=this.arrangeDistricts,a=zg(e.map(([c,h])=>({id:c,size:h.length,org:n.get(c)||null})),o?new Map:this.plotCells);o&&(this.arrangeDistricts=!1);for(const[c,h]of a)this.plotCells.delete(c),this.plotCells.set(c,h);for(;this.plotCells.size>Y3;)this.plotCells.delete(this.plotCells.keys().next().value);const l=new Map;for(const[c,h]of a)l.set(c,`${c}:${h.map(d=>`${d.q},${d.r}`).join("/")}`);for(const[c,h]of this.plots)l.get(c)!==h.signature&&(this.plotGroup.remove(h.group),h.label&&(this.labelGroup.remove(h.label),h.label.userData.dispose?.()),this.usedAccents.delete(h.accent),h.dispose(),this.plots.delete(c));e.forEach(([c],h)=>{if(this.plots.has(c))return;const d=a.get(c);if(!d?.length)return;const u=this._pickAccent(c),f=new Vg({id:c,name:c,index:h,cells:d,accent:u});f.signature=l.get(c),this.plots.set(c,f),this.plotGroup.add(f.group);const p=r.get(c)??c,m=Ja(p,u);m.position.set(f.labelAnchor.x,3.2,f.labelAnchor.z),f.label=m,f.labelText=p,this.labelGroup.add(m)});for(const c of this.plots.values()){const h=r.get(c.name)??c.name;if(!c.label||c.labelText===h)continue;const d=c.label,u=Ja(h,c.accent);u.position.copy(d.position),u.material.opacity=d.material.opacity,u.visible=d.visible,this.labelGroup.remove(d),d.userData.dispose?.(),this.labelGroup.add(u),c.label=u,c.labelText=h}this.plotOrder=[...this.plots.values()],this._syncDistricts(n),this.scatterGroup&&this._plotFootprint()!==this._scatterFootprint&&(Oh(this.planet)?this._buildTerrain():(this._buildScatter(),(this.island||this.rock)&&this._syncIslandRock())),this.deckedCells=new Set;for(const c of this.plotOrder)for(const h of c.cells)this.deckedCells.add(`${h.q},${h.r}`);this._syncLabels()}_world(){return{shipDoor:()=>this.ship.shipDoor(),shipAirlock:()=>this.ship.shipAirlock(),groundAt:(e,t)=>this.groundAt(e,t)}}groundAt(e,t){const i=Cn(e,t);return this.deckedCells?.has(`${i.q},${i.r}`)?$t:gt(e,t,this.planet)}surfaceAt(e,t){const i=this.groundAt(e,t),n=this.planet.water?.level;return n!==void 0&&i<n?n:i}_pickAccent(e){const t=bn(e)%Ti.length;for(let i=0;i<Ti.length;i++){const n=Ti[(t+i)%Ti.length];if(!this.usedAccents.has(n))return this.usedAccents.add(n),n}return Ti[t]}_syncBuilding(e,t,i){let n=this.buildings.get(e.id);const r=1;if(n){const o=t.worldSlot(i,this._slotAt||(this._slotAt=new F));(n.plot!==t.id||n.slot!==i||n.mesh.position.distanceToSquared(o)>1e-4)&&(n.plot=t.id,n.slot=i,n.mesh.position.copy(o))}else{const o=gg({seed:bn(e.id),accent:t.accent}),a=t.worldSlot(i);o.position.copy(a),o.rotation.y=(bn(e.id)>>>8)%360*(Math.PI/180),o.userData.setProgress(0),this.worldGroup.add(o),n={mesh:o,plot:t.id,slot:i,progress:0,target:r,retiring:!1},this.buildings.set(e.id,n)}return n.target=r,n.accent=t.accent,n.retiring=!1,n}_removeBuilding(e,t){t.retiring=!0,t.target=0,t.progress<=.02&&(this.worldGroup.remove(t.mesh),t.mesh.geometry.dispose(),t.mesh.material.dispose(),t.mesh.customDepthMaterial?.dispose(),this.buildings.delete(e))}_rebuildNavigation(){const e=[];for(const n of this.buildings.values()){if(n.retiring)continue;const r=n.mesh.position,o=n.mesh.userData.footprint||1.2,a=o*.8+Cr;e.push({x:r.x,z:r.z,r:a,keep:o*.92+Ci})}for(const n of this.plotOrder)for(const r of n.clutterSpots||[])e.push({x:n.center.x+r.x,z:n.center.z+r.z,r:r.r+Cr,keep:r.r+Ci+.1});const t=this._navMatrix||(this._navMatrix=new xt);for(const n of this.scatterGroup?.children||[]){if(!n.isInstancedMesh||!n.count)continue;n.geometry.boundingBox||n.geometry.computeBoundingBox();const r=n.geometry.boundingBox,o=Math.max(r.max.x-r.min.x,r.max.z-r.min.z)*.5;for(let a=0;a<n.count;a++){n.getMatrixAt(a,t);const l=Math.hypot(t.elements[0],t.elements[1],t.elements[2]),c=o*l*.65;c<.55||e.push({x:t.elements[12],z:t.elements[14],r:c+Cr,keep:c+Ci+.1})}}for(const n of this._scaffoldSites(!0))for(let r=0;r<4;r++){const o=r/4*Math.PI*2+.78,a=n.x+Math.cos(o)*n.radius,l=n.z+Math.sin(o)*n.radius;n.contains&&!n.contains(a,l)||e.push({x:a,z:l,r:.14+Cr,keep:.14+Ci+.12})}const i=Js();e.push({x:i.x,z:i.z,r:3.4+Ci}),this.nav.rebuild(e)}plotAt(e,t){let i=null,n=1/0;for(const r of this.plotOrder)for(const o of r.localCenters){const a=e-(r.center.x+o.x),l=t-(r.center.z+o.z),c=a*a+l*l;c<n&&(n=c,i=r)}return n<=pt*pt?i:null}pickLabel(e,t){const i=this._labelView||(this._labelView=new F),n=this.camera.projectionMatrix.elements;let r=null,o=1/0;for(const a of this.plotOrder){const l=a.label;if(!l)continue;const c=-ai(i.copy(l.position)).applyMatrix4(this.camera.matrixWorldInverse).z;if(c<=.01||c>=o)continue;const h=l.geometry.parameters,d=.55+c*.03,u=i.x*n[0]/c,f=i.y*n[5]/c;Math.abs(e-u)>h.width/2*d*n[0]/c||Math.abs(t-f)>h.height/2*d*n[5]/c||(o=c,r=a)}return r}restoreLayout(e){const t=new Map;for(const[i,n]of Object.entries(e||{})){if(!Array.isArray(n))continue;const r=[];for(const o of n){const a=Array.isArray(o)?o[0]:o?.q,l=Array.isArray(o)?o[1]:o?.r;Number.isInteger(a)&&Number.isInteger(l)&&r.push({q:a,r:l})}r.length&&t.set(String(i),r)}this.plotCells=t}layoutForSave(){const e={};for(const[t,i]of this.plotCells)e[t]=i.map(n=>[n.q,n.r]);return e}setHoveredPlot(e){this.hoveredPlot=e||null}setHoveredOrg(e){this.hoveredOrg=e||null}setSelectedPlot(e){this.selectedPlot=e||null}visibleLayout(){const e=new Map;for(const[t,i]of this.plots)e.set(t,i.cells);return e}get middle(){const e=this.footprint();let t=1/0,i=-1/0,n=1/0,r=-1/0;for(const o of e)t=Math.min(t,o.x),i=Math.max(i,o.x),n=Math.min(n,o.z),r=Math.max(r,o.z);return new F((t+i)/2,0,(n+r)/2)}footprint(){const e=[yt];for(const n of this.plots.values())e.push(...n.cells);const t=n0(e);for(const n of this.buildings.values()){if(n.retiring)continue;const r=n.mesh.position;t.push(new F(r.x,r.y+(n.mesh.userData.height||0),r.z))}const i=new Mc().setFromObject(this.ship.group);if(!i.isEmpty())for(const n of[i.min.x,i.max.x])for(const r of[i.min.z,i.max.z])t.push(new F(n,i.max.y,r));return t}movePlot(e,t,i){const n=this.plotCells.get(e);!n||!t&&!i||this.plotCells.set(e,Wl(n,t,i))}applyLayout(e){if(e)for(const[t,i]of e)this.plotCells.has(t)&&this.plotCells.set(t,i)}setPlotLift(e,t){const i=this.plots.get(e);if(!i)return;i.group.position.y=t,i.label&&(i.label.position.y=3.2+t);const n=t>0;i.group.traverse(r=>{!r.isMesh||r===i.glow||(r.material.transparent=n,r.material.opacity=n?.55:1)});for(const r of this.buildings.values())r.plot===e&&(r.mesh.position.y=$t+t)}_updateLabels(e){const t=this.uiVisible&&this.settings.get("showLabels");for(const o of this.plotOrder){const a=o.label;if(!a)continue;const l=t&&(this.activePlots.has(o.id)||this.hoveredPlot===o)?1:0,c=N.damp(a.material.opacity,l,9,e);a.material.opacity=c,a.visible=c>.01;const h=this.uiVisible?o===this.selectedPlot?1:o===this.hoveredPlot?K3:0:0;o.highlight=N.damp(o.highlight,h,8,e)}if(!this.districts.size)return;const i=this.camera.getWorldDirection(this._districtForward||(this._districtForward=new F)),n=Math.hypot(i.x,i.z)||1,r=this.hoveredPlot?.name;for(const[o,a]of this.districts){const l=this.uiVisible&&(a.plots?.has(r)||this.hoveredOrg===o)?1:0;a.shown=N.damp(a.shown,l,7,e),a.shown<.002&&(a.shown=0),a.fade(a.shown,t?a.shown*Q3:0),a.label.visible&&a.placeLabel(i.x/n,i.z/n)}}_syncDistricts(e){const t=new Map;for(const n of this.plotOrder){const r=e.get(n.name);r&&t.set(r,[...t.get(r)??[],n])}const i=new Map;for(const[n,r]of t){if(r.length<2)continue;const o=r.flatMap(a=>a.cells);i.set(n,{cells:o,names:new Set(r.map(a=>a.name)),signature:o.map(a=>`${a.q},${a.r}`).sort().join("/")})}for(const[n,r]of this.districts)i.get(n)?.signature!==r.signature&&(this.plotGroup.remove(r.wall),this.labelGroup.remove(r.label),r.dispose(),this.districts.delete(n));for(const[n,{cells:r,names:o,signature:a}]of i){if(!this.districts.has(n)){const l=Gg(n,r,this.orgAccent(n));l.signature=a,l.shown=0,this.plotGroup.add(l.wall),this.labelGroup.add(l.label),this.districts.set(n,l)}this.districts.get(n).plots=o}}districtOf(e){for(const[t,i]of this.districts)if(i.plots?.has(e))return{org:t,accent:this.orgAccent(t),label:this.plots.get(e)?.labelText??e};return null}orgAccent(e){if(this.orgAccents.has(e))return this.orgAccents.get(e);const t=new Set(this.orgAccents.values()),i=bn(e)%Ki.length;let n=Ki[i];for(let r=0;r<Ki.length;r++){const o=Ki[(i+r)%Ki.length];if(!t.has(o)){n=o;break}}return this.orgAccents.set(e,n),n}_workSite(e,t,i){const n=t.mesh.position,r=e.middle||e.center,o=n.x-r.x,a=n.z-r.z,c=Math.hypot(o,a)>.2?Math.atan2(a,o):i*2.4%(Math.PI*2),h=(t.mesh.userData.footprint||1.2)*.92+Ci,d=Math.max(2.35,h+.5);let u=new F(n.x+Math.cos(c)*d,0,n.z+Math.sin(c)*d);const f=m=>{const g=Cn(m.x,m.z);return e.cellKeys.has(`${g.q},${g.r}`)};if(!f(u)){const m=new F(n.x-Math.cos(c)*d,0,n.z-Math.sin(c)*d);f(m)&&(u=m)}const p=this.nav?.nearestClear(u.x,u.z,pt,(m,g)=>{const w=Cn(m,g);return e.cellKeys.has(`${w.q},${w.r}`)})||this.nav?.nearestClear(u.x,u.z,pt*2);return p&&u.set(p.x,0,p.z),u}update(e,t,i){i&&this.sky.setFocus(i),this.sky.update(e,t,this.camera)&&(this.settings.values.timeOfDay=this.sky.time);const r=this.sky.nightFactor??0;zs.uNight.value=r,om.value=r,am.value=t,zs.uTime.value=t,this.ship.update(e,t,r),this._growBuildings(e),this.astronauts.update(e,t),this.astronauts.updateRings(t),this.indicators.update(this.astronauts.agents,t,o=>this._badgeFor(o)),this._emit(e,t),this._emitMotes(e,r),this.particles.ambient(e,this.camera,this.planet,r,(o,a)=>this.surfaceAt(o,a)),this.particles.update(e),this.water?.update(e,t,this.camera,r,this.sky.sunDir),this.grass?.update(e,t,r),this.mist?.update(t,this.sky.dayFactor??1),this.skyline?.update(t,this.camera),this.worm?.update(e,t,this.stats.working),this.island&&(this.island.update(e,t,this.camera),this.island.setDaylight(this.sky.dayFactor??1)),this.rock?.update(e,t),this.fauna.update(e,t,this.camera,r,this._faunaHooks||(this._faunaHooks={ripple:(o,a,l)=>this.ripple(o,a,l),sound:(o,a,l,c)=>this.onSound?.(o,a,l,c)})),this._updatePlots(r,t),this._updateScaffolds(),this._updateLabels(e),this.reflections.update(e,i||this.sky.focus,this.camera)}_growBuildings(e){for(const[t,i]of this.buildings){!i.retiring&&this._isLive(t)&&(i.target=Math.min(1,i.target+X3*e));const n=N.damp(i.progress,i.target,1.8,e);Math.abs(n-i.progress)>5e-4&&(i.progress=n,i.mesh.userData.setProgress(n)),i.retiring&&i.progress<=.02&&this._removeBuilding(t,i)}}_isLive(e){const t=this.threads.get(e);return!!(t&&t.running)}_isActive(e){const t=this.threads.get(e);return!!(t&&(t.running||t.needsInput||t.awaitingSubagents||t.unread||C0(t)))}_badgeFor(e){return e.state==="spawning"?fe.spawning:e.state==="leaving"?fe.leaving:e5[e.status]??fe.none}_emit(e,t){if(!this.particles.enabled)return;const i=this.settings.get("particles")==="full";for(const n of this.astronauts.agents){if(n.scale<.5)continue;const r=n.groundY||0;if(n.state==="at-site"&&n.status==="working"){const o=Math.sin(n.workSwing);if(o<-.75&&!n._sparked){n._sparked=!0;const a=this._c.set(10479808);this.particles.weld(n.pos.x+Math.sin(n.yaw)*.55,n.pos.y+.55,n.pos.z+Math.cos(n.yaw)*.55,a,r)}else o>0&&(n._sparked=!1)}if(n.state==="at-site"&&n.status==="celebrating"&&n.hop>.18&&!n._cheered?(n._cheered=!0,this.particles.cheer(n.pos.x,n.pos.y,n.pos.z,this._c.set(16762986),r)):n.hop<.05&&(n._cheered=!1),n.state==="at-site"&&n.status==="sleeping"&&Math.random()<e*.35&&this.particles.snooze(n.pos.x+.2,n.pos.y+1.05,n.pos.z+.15),i&&(n.walkAmp||0)>.4){const o=Math.sin(n.phase);o<-.9&&!n._stepped?(n._stepped=!0,this.particles.step(n.pos.x,n.pos.y,n.pos.z,this._dustTint,r)):o>0&&(n._stepped=!1)}(n.state==="spawning"||n.state==="leaving"&&n.scale<.6)&&Math.random()<e*3&&this.ship.ping()}}_emitMotes(e,t){if(!this.particles.enabled)return;const i=this.settings.get("particles")==="full",n=this.sky.focus,r=this._c,a=this.planet.scatter!=="rocks"&&t>.35,l=i?48:34,c=l*l;for(const[f,p]of this.buildings){if(p.retiring||p.progress<.5)continue;const m=p.mesh.position,g=m.x-n.x,w=m.z-n.z;if(g*g+w*w>c)continue;const y=(this._isActive(f)?.9:.28)*(i?1:.55)*(.6+t*.9);if(Math.random()<e*y){const C=.9+Math.random()*1.4,_=Math.random()*Math.PI*2;t>.35?r.set(p.accent).lerp(this._c2.set(16773312),.35).multiplyScalar(2.2):r.set(16773840).multiplyScalar(1.6),this.particles.mote(m.x+Math.cos(_)*C,m.y+.4+Math.random()*1.8,m.z+Math.sin(_)*C,r,.055,4)}if(a&&Math.random()<e*(i?.7:.35)*t){const C=1.5+Math.random()*3.5,_=Math.random()*Math.PI*2;r.setRGB(1.5,2.3,.55),this.particles.mote(m.x+Math.cos(_)*C,m.y+.2+Math.random()*1.2,m.z+Math.sin(_)*C,r,.07,5)}}const h=this.ship.group.position,d=h.x-n.x,u=h.z-n.z;if(d*d+u*u<c&&Math.random()<e*(.8+t*1.4)){const f=Math.random()*Math.PI*2,p=2+Math.random()*3;r.setRGB(.7,1.4,2.4),this.particles.mote(h.x+Math.cos(f)*p,h.y+.3+Math.random()*5,h.z+Math.sin(f)*p,r,.06,5)}}_updatePlots(e,t){const i=this.urgentPlots;for(const n of this.plotOrder)n.setNight(e,i?.has(n.id)??!1,t)}_scaffoldSites(e=!1){const t=[];for(const[i,n]of this.buildings){if(n.retiring||!e&&n.progress<=.03||!this._isActive(i))continue;const r=n.mesh.position;t.push({id:i,x:r.x,z:r.z,y:r.y,radius:(n.mesh.userData.footprint||1.4)+.25,contains:(o,a)=>this.plots.get(n.plot)?.containsWorld(o,a,.2),height:Math.max(.6,n.mesh.userData.height*n.progress+.5)})}return t}_updateScaffolds(){const e=this._scaffoldSites();this.scaffolds.update(e);const t=e.map(i=>i.id).join("|");t!==this._scaffoldSignature&&(this._scaffoldSignature=t,this.nav&&this._rebuildNavigation())}pick(e,t,i,n){return this.astronauts.pick(this.camera,e,t,i,n)}plotOnRay(e,t=1/0){const i=this._rayBox||(this._rayBox=new Mc),n=this._rayHit||(this._rayHit=new F);let r=null,o=t;for(const a of this.buildings.values()){if(a.retiring||a.progress<.5||!e.intersectBox(i.setFromObject(a.mesh),n))continue;const l=n.distanceTo(e.origin);if(l>=o)continue;const c=this.plotOrder.find(h=>h.id===a.plot);c&&(r=c,o=l)}return r}agentFor(e){return this.astronauts.byId.get(e)}setUiVisible(e){this.uiVisible=e,this._syncLabels()}_syncLabels(){this.labelGroup.visible=!0}dispose(){this.reflections.dispose(),this.sky.dispose(),this.fauna.dispose(),this.grass?.dispose(),this.island?.dispose(),this.rock?.dispose(),this.water?.dispose(),this.mist?.dispose(),this.skyline?.dispose(),this.ship.dispose(),this.astronauts.dispose(),this.indicators.dispose(),this.particles.dispose(),this.scaffolds.dispose(),rn(this.worldGroup),rn(this.plotGroup),rn(this.labelGroup),this.scene.remove(this.worldGroup,this.plotGroup,this.labelGroup)}}function rn(s){s.traverse(e=>{!e.isMesh&&!e.isPoints||(e.geometry?.dispose(),Array.isArray(e.material)?e.material.forEach(t=>t.dispose()):e.material?.dispose(),e.customDepthMaterial?.dispose())})}function s5(s){let e=0;for(const t of s?.children||[])t.isInstancedMesh&&(e+=t.count);return e}function Ih(){return new Promise(s=>{document.hidden?setTimeout(s,0):requestAnimationFrame(()=>setTimeout(s,0))})}function i5(s){return new Promise(e=>setTimeout(e,s))}const n5=Object.freeze(["ocean","atoll","bamboo","basalt","canyon","desert","fjord","forest","frozenlake","hollow","terra","moors","sakura","savanna","beach","tundra","sky","valley","autumn","mercury","venus","moon","mars","pluto"]),r5=Object.freeze({"2026-10-30":Object.freeze(["challenger","titanic","phobos","ceres","jupiter","redspot","io","europa","ganymede","callisto","saturnrings","enceladus","titan","iapetus","miranda","triton","halley","proxima","trappist","kepler16b","kepler186f","cancri","draugr","hd189733b","j1407b","aldargon","arrakesh","dagmora","deadstar","endral","horth","jakhara","kaladorn","kashiwa","lt2230","lt4260","milners","muspel","nabora","pandora","qubitron","ring","tatawin","vespera","yavora4","crystal","dragonnest","garden","glimmer","lanternnight","middangard","oz","sugarvale","north","undersea","worldtree"])}),o5=new Set(n5),a5=new Map(Object.entries(r5).flatMap(([s,e])=>e.map(t=>[t,Date.parse(`${s}T00:00:00Z`)/1e3]))),x0="https://threadnauts.io/pro",hl=s=>!o5.has(s),l5=s=>a5.get(s)??1/0,dl=(s,e)=>!hl(s)||l5(s)<=(e?.proThrough??0),c5=(s,e,t,i)=>(n,r)=>{if(n!=="planet")return r;const o=dl(r,e);return o&&t[r]?(delete s.held.planet,r):(o&&i[r]?s.held.planet=r:delete s.held.planet,"moon")},Dh={key_missing:"Paste your license key first.",key_not_valid:"That key isn’t active. Check it in Polar’s customer portal, or renew your subscription.",device_limit:"That key is already on as many computers as it allows. Remove one in Polar’s customer portal, then try again.",device_removed:"This computer was removed from your license key. Enter the key again to add it back.",license_not_valid:"Your license couldn’t be renewed. Enter your key again.",license_rejected:"This version of Threadnauts can’t check that license. Update Threadnauts, then try again.",polar_unavailable:"Polar didn’t answer. Try again in a minute.",offline:"Couldn’t reach Threadcrumbs. Check your internet connection, then try again.",unavailable:"Couldn’t reach Threadcrumbs. Try again in a minute."},h5=new Set(["device_removed","license_not_valid","license_rejected"]),d5="https://threadcrumbs.io/portal",ha="customer portal",ql=s=>Dh[s]??Dh.unavailable,u5=s=>h5.has(s?.error)?ql(s.error):"",ul=s=>new Date(s*1e3).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"});function f5({proThrough:s=0}={},e=Date.now()/1e3){return s===1/0?"Every Pro world is open while you work on Threadnauts.":s>e?`Pro is unlocked on this computer, paid through ${ul(s)}.`:s>0?`Your subscription ended on ${ul(s)}. Worlds released before then stay unlocked.`:"Enter your Threadcrumbs license key to unlock every Pro world. Your key is in Polar’s customer portal."}const da=({proThrough:s=0}={},e=Date.now()/1e3)=>s!==1/0&&s<=e,p5={offline:"Couldn’t download the Pro worlds. Check your internet connection, then try again.",corrupt:"The Pro worlds didn’t download cleanly. Try again in a minute.",not_saved:"Couldn’t save the Pro worlds on this computer. Check that the disk has free space, then try again.",license_expired:"Your license needs renewing before the Pro worlds can download. Connect to the internet, then try again."},m5=s=>p5[s]??ql(s);function Vh({proThrough:s=0}={}){return s>0?`That key’s subscription ended on ${ul(s)}, before this world was released. Renew it to unlock this world.`:"That key doesn’t include Threadnauts Pro. Switch to a plan with it in Polar’s customer portal."}function S(s){if(!s)throw new Error("Assertion failed.")}const g5=Math.PI/180,fl=180/Math.PI,eo=s=>{const e=(s%360+360)%360;if(e===0||e===90||e===180||e===270)return e;throw new Error(`Invalid rotation ${s}.`)},M0=[1,0,0,0,1,0,0,0,1],w5=(s,e,t)=>{const[i,n,,r,o]=s,a=Math.abs(i)*e+Math.abs(r)*t,l=Math.abs(n)*e+Math.abs(o)*t;return to(to(Nh(-e/2,-t/2),s),Nh(a/2,l/2))},b5=s=>{const[e,t]=s,i=Math.atan2(t,v5(s)?-e:e);return eo(pl(i*fl,90))},v5=s=>{const[e,t,,i,n]=s;return e*n-t*i<0},k0=s=>{const e=s*g5,t=Math.round(Math.cos(e)),i=Math.round(Math.sin(e));return[t,i,0,-i,t,0,0,0,1]},Nh=(s,e)=>[1,0,0,0,1,0,s,e,1],y5=(s,e)=>[s,0,0,0,e,0,0,0,1],to=(s,e)=>{const t=new Array(9);for(let i=0;i<3;i++)for(let n=0;n<3;n++)t[3*i+n]=s[3*i]*e[n]+s[3*i+1]*e[3+n]+s[3*i+2]*e[6+n];return t},C5=(s,e,t,i)=>({rotation:eo(s+(e?-t:t)),flip:e!==i}),kt=s=>s&&s[s.length-1],vs=s=>s>=0&&s<2**32,x5=s=>s>=-2147483648&&s<2**31,V=s=>{let e=0;for(;s.readBits(1)===0&&e<32;)e++;if(e>=32)throw new Error("Invalid exponential-Golomb code.");return 2**e-1+s.readBits(e)},ms=s=>{const e=V(s);return e%2===0?-(e/2):(e+1)/2},M5=(s,e,t,i)=>{for(let n=e;n<t;n++){const r=Math.floor(n/8);let o=s[r];const a=7-(n&7);o&=~(1<<a),o|=(i&1<<t-n-1)>>t-n-1<<a,s[r]=o}},Ke=s=>s.constructor===Uint8Array?s:ArrayBuffer.isView(s)?new Uint8Array(s.buffer,s.byteOffset,s.byteLength):new Uint8Array(s),Ht=s=>s.constructor===DataView?s:ArrayBuffer.isView(s)?new DataView(s.buffer,s.byteOffset,s.byteLength):new DataView(s),k5=typeof globalThis.TextEncoder<"u"?globalThis.TextEncoder:class{constructor(){this.encoding="utf-8"}encode(e=""){const t=new Uint8Array(3*e.length);let i=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r<128)t[i++]=r;else if(r<2048)t[i++]=192|r>>6,t[i++]=128|r&63;else if(r<55296||r>57343)t[i++]=224|r>>12,t[i++]=128|r>>6&63,t[i++]=128|r&63;else{const o=n+1<e.length?e.charCodeAt(n+1):0;r<56320&&o>=56320&&o<=57343?(r=65536+(r-55296<<10)+(o-56320),n++,t[i++]=240|r>>18,t[i++]=128|r>>12&63,t[i++]=128|r>>6&63,t[i++]=128|r&63):(t[i++]=239,t[i++]=191,t[i++]=189)}}return t.slice(0,i)}},bt=new k5,di={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},ui={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},fi={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},T0=s=>!s||s.primaries==null&&s.transfer==null&&s.matrix==null&&s.fullRange==null,mo=s=>s instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&s instanceof SharedArrayBuffer||ArrayBuffer.isView(s);class _0{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}async acquire(){let e;const t=new Promise(n=>{let r=!1;e=()=>{r||(n(),this.pending--,r=!0)}}),i=this.currentPromise;return this.currentPromise=t,this.pending++,await i,e}}const Wh=s=>[...s].map(e=>e.toString(16).padStart(2,"0")).join(""),Hh=s=>(s=s>>1&1431655765|(s&1431655765)<<1,s=s>>2&858993459|(s&858993459)<<2,s=s>>4&252645135|(s&252645135)<<4,s=s>>8&16711935|(s&16711935)<<8,s=s>>16&65535|(s&65535)<<16,s>>>0),Uh=(s,e,t)=>{let i=0,n=s.length-1,r=-1;for(;i<=n;){const o=i+(n-i+1)/2|0;t(s[o])<=e?(r=o,i=o+1):n=o-1}return r},Gn=()=>{let s,e;return{promise:new Promise((i,n)=>{s=i,e=n}),resolve:s,reject:e}},Gt=s=>{throw new Error(`Unexpected value: ${s}`)},T5=(s,e,t)=>{const i=s.getUint8(e),n=s.getUint8(e+1),r=s.getUint8(e+2);return i<<16|n<<8|r},Gl=(s,e,t,i)=>{t=t>>>0,t=t&16777215,i?(s.setUint8(e,t&255),s.setUint8(e+1,t>>>8&255),s.setUint8(e+2,t>>>16&255)):(s.setUint8(e,t>>>16&255),s.setUint8(e+1,t>>>8&255),s.setUint8(e+2,t&255))},_5=(s,e,t,i)=>{t=ct(t,-8388608,8388607),t<0&&(t=t+16777216&16777215),Gl(s,e,t,i)},ct=(s,e,t)=>Math.max(e,Math.min(t,s)),S5=(s,e,t)=>s+(e-s)*t,S0="und",pl=(s,e)=>Math.round(s/e)*e,so=(s,e)=>Math.round(s*e)/e,jh=(s,e)=>Math.floor(s*e)/e,$5=s=>{let e=0;for(;s!==0;)s&=s-1,e++;return e},A5=/^[a-z]{3}$/,E5=s=>A5.test(s),Ls=1e6*(1+Number.EPSILON),P5=(s,e)=>{const t=s<0?-1:1;s=Math.abs(s);let i=0,n=1,r=1,o=0,a=s;for(;;){const l=Math.floor(a),c=l*r+i,h=l*o+n;if(h>e)return{num:t*r,den:o};if(i=r,n=o,r=c,o=h,a=1/(a-l),!isFinite(a))break}return{num:t*r,den:o}};class $0{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let ua=null;const go=()=>ua!==null?ua:ua=!!(typeof navigator<"u"&&(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent)));let fa=null;const En=()=>fa!==null?fa:fa=typeof navigator<"u"&&navigator.userAgent?.includes("Firefox");let pa=null;const z5=()=>pa!==null?pa:pa=!!(typeof navigator<"u"&&(navigator.vendor?.includes("Google Inc")||/Chrome/.test(navigator.userAgent)));let ma=null;const L5=()=>{if(ma!==null)return ma;if(typeof navigator>"u")return null;const s=/\bChrome\/(\d+)/.exec(navigator.userAgent);return s?ma=Number(s[1]):null},A0=s=>typeof globalThis.isSecureContext<"u"&&!globalThis.isSecureContext?`${s} is not available in this environment; this may be because this page is running in an insecure context. Try serving your page over HTTPS or use localhost.`:`${s} is not available in this environment.`,R5=s=>s instanceof DOMException&&s.name==="QuotaExceededError"&&/reclaimed/i.test(s.message),B5=(async()=>{})().constructor,Is=s=>s instanceof B5||s instanceof Promise?!0:typeof s?.then=="function",Zl=function*(s){for(const e in s){const t=s[e];t!==void 0&&(yield{key:e,value:t})}},F5=s=>{switch(s.toLowerCase()){case"image/jpeg":case"image/jpg":return".jpg";case"image/png":return".png";case"image/gif":return".gif";case"image/webp":return".webp";case"image/bmp":return".bmp";case"image/svg+xml":return".svg";case"image/tiff":return".tiff";case"image/avif":return".avif";case"image/x-icon":case"image/vnd.microsoft.icon":return".ico";default:return null}},O5=(s,e)=>{if(s.length!==e.length)return!1;for(let t=0;t<s.length;t++)if(s[t]!==e[t])return!1;return!0},I5=()=>{Symbol.dispose??=Symbol("Symbol.dispose")},E0=s=>typeof s=="number"&&!Number.isNaN(s),D5=(s,e)=>{let t=-1,i=1/0;for(let n=0;n<s.length;n++){const r=e(s[n]);(t===-1||r<i)&&(i=r,t=n)}return t},Xl=s=>{S(Number.isInteger(s.num)),S(Number.isInteger(s.den)),S(s.den!==0);let e=Math.abs(s.num),t=Math.abs(s.den);for(;t!==0;){const n=e%t;e=t,t=n}const i=e||1;return{num:s.num/i,den:s.den/i}},ga=(s,e)=>{if(typeof s!="object"||!s)throw new TypeError(`${e} must be an object.`);if(!Number.isInteger(s.left)||s.left<0)throw new TypeError(`${e}.left must be a non-negative integer.`);if(!Number.isInteger(s.top)||s.top<0)throw new TypeError(`${e}.top must be a non-negative integer.`);if(!Number.isInteger(s.width)||s.width<0)throw new TypeError(`${e}.width must be a non-negative integer.`);if(!Number.isInteger(s.height)||s.height<0)throw new TypeError(`${e}.height must be a non-negative integer.`)};let on,V5=1;const qh=new Map,Yl=new Map,P0=()=>typeof window>"u",N5=()=>{const s=new Map,e=new Map;self.onmessage=t=>{const i=t.data;switch(i.type){case"set-timeout":{const n=setTimeout(()=>{s.delete(i.timerId),self.postMessage({type:"fire",timerId:i.timerId})},i.delay);s.set(i.timerId,n)}break;case"set-interval":{const n=setInterval(()=>{self.postMessage({type:"fire",timerId:i.timerId})},i.delay);e.set(i.timerId,n)}break;case"clear-timeout":{const n=s.get(i.timerId);n!==void 0&&(clearTimeout(n),s.delete(i.timerId))}break;case"clear-interval":{const n=e.get(i.timerId);n!==void 0&&(clearInterval(n),e.delete(i.timerId))}break}}},z0=()=>{if(on)return on;const s=`(${N5.toString()})();`,e=URL.createObjectURL(new Blob([s],{type:"text/javascript"}));return on=new Worker(e),URL.revokeObjectURL(e),on.onmessage=t=>{const i=t.data,n=qh.get(i.timerId);if(n){qh.delete(i.timerId),n();return}const r=Yl.get(i.timerId);r&&r()},on},W5=(s,e)=>{if(P0())return{id:setInterval(s,e)};const t=V5++;return Yl.set(t,()=>{s()}),z0().postMessage({type:"set-interval",timerId:t,delay:e}),{id:t}},H5=s=>{if(P0()){clearInterval(s.id);return}S(typeof s.id=="number"),Yl.delete(s.id),z0().postMessage({type:"clear-interval",timerId:s.id})},U5=s=>new Promise(e=>setTimeout(e,s)),Gh=s=>Array.isArray(s)?s:[s];class Ql{constructor(){this._listeners=new Map}on(e,t,i){this._listeners.has(e)||this._listeners.set(e,new Set);const n={fn:t,once:i?.once??!1};return this._listeners.get(e).add(n),()=>{this._listeners.get(e)?.delete(n)}}_emit(...e){const[t,i]=e,n=this._listeners.get(t);if(n)for(const r of n){try{r.fn(i)}catch(o){console.error(o)}r.once&&n.delete(r)}}}const j5=s=>s!==null&&typeof s=="object"&&Object.getPrototypeOf(s)===Object.prototype&&Object.values(s).every(e=>typeof e=="string");var os;(function(s){s[s.Silent=0]="Silent",s[s.Errors=1]="Errors",s[s.Warnings=2]="Warnings",s[s.Info=3]="Info"})(os||(os={}));class Re{constructor(){}static get level(){return Re._level}static set level(e){if(e!==os.Silent&&e!==os.Errors&&e!==os.Warnings&&e!==os.Info)throw new TypeError("Invalid log level. Use one of the values of the LogLevel enum.");Re._level=e}static get _emitter(){return Re._emitterInstance??=new Ql}static on(e,t,i){return Re._emitter.on(e,t,i)}static _error(...e){Re._emitter._emit("error",e),Re._level>=os.Errors&&console.error(...e)}static _warn(...e){Re._emitter._emit("warn",e),Re._level>=os.Warnings&&console.warn(...e)}static _info(...e){Re._emitter._emit("info",e),Re._level>=os.Info&&console.info(...e)}}Re._level=os.Info;Re._emitterInstance=null;class L0{constructor(e,t){if(this.data=e,this.mimeType=t,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(typeof t!="string")throw new TypeError("mimeType must be a string.")}}class R0{constructor(e,t,i,n){if(this.data=e,this.mimeType=t,this.name=i,this.description=n,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(t!==void 0&&typeof t!="string")throw new TypeError("mimeType, when provided, must be a string.");if(i!==void 0&&typeof i!="string")throw new TypeError("name, when provided, must be a string.");if(n!==void 0&&typeof n!="string")throw new TypeError("description, when provided, must be a string.")}}const q5=s=>{if(!s||typeof s!="object")throw new TypeError("tags must be an object.");if(s.title!==void 0&&typeof s.title!="string")throw new TypeError("tags.title, when provided, must be a string.");if(s.description!==void 0&&typeof s.description!="string")throw new TypeError("tags.description, when provided, must be a string.");if(s.artist!==void 0&&typeof s.artist!="string")throw new TypeError("tags.artist, when provided, must be a string.");if(s.album!==void 0&&typeof s.album!="string")throw new TypeError("tags.album, when provided, must be a string.");if(s.albumArtist!==void 0&&typeof s.albumArtist!="string")throw new TypeError("tags.albumArtist, when provided, must be a string.");if(s.trackNumber!==void 0&&(!Number.isInteger(s.trackNumber)||s.trackNumber<=0))throw new TypeError("tags.trackNumber, when provided, must be a positive integer.");if(s.tracksTotal!==void 0&&(!Number.isInteger(s.tracksTotal)||s.tracksTotal<=0))throw new TypeError("tags.tracksTotal, when provided, must be a positive integer.");if(s.discNumber!==void 0&&(!Number.isInteger(s.discNumber)||s.discNumber<=0))throw new TypeError("tags.discNumber, when provided, must be a positive integer.");if(s.discsTotal!==void 0&&(!Number.isInteger(s.discsTotal)||s.discsTotal<=0))throw new TypeError("tags.discsTotal, when provided, must be a positive integer.");if(s.genre!==void 0&&typeof s.genre!="string")throw new TypeError("tags.genre, when provided, must be a string.");if(s.date!==void 0&&(!(s.date instanceof Date)||Number.isNaN(s.date.getTime())))throw new TypeError("tags.date, when provided, must be a valid Date.");if(s.beatsPerMinute!==void 0&&(!Number.isInteger(s.beatsPerMinute)||s.beatsPerMinute<=0))throw new TypeError("tags.beatsPerMinute, when provided, must be a positive integer.");if(s.lyrics!==void 0&&typeof s.lyrics!="string")throw new TypeError("tags.lyrics, when provided, must be a string.");if(s.images!==void 0){if(!Array.isArray(s.images))throw new TypeError("tags.images, when provided, must be an array.");for(const e of s.images){if(!e||typeof e!="object")throw new TypeError("Each image in tags.images must be an object.");if(!(e.data instanceof Uint8Array))throw new TypeError("Each image.data must be a Uint8Array.");if(typeof e.mimeType!="string")throw new TypeError("Each image.mimeType must be a string.");if(!["coverFront","coverBack","unknown"].includes(e.kind))throw new TypeError("Each image.kind must be 'coverFront', 'coverBack', or 'unknown'.")}}if(s.comment!==void 0&&typeof s.comment!="string")throw new TypeError("tags.comment, when provided, must be a string.");if(s.raw!==void 0){if(!s.raw||typeof s.raw!="object")throw new TypeError("tags.raw, when provided, must be an object.");for(const e of Object.values(s.raw))if(e!==null&&typeof e!="string"&&!(Array.isArray(e)&&e.every(t=>typeof t=="string"))&&!(e instanceof Uint8Array)&&!(Array.isArray(e)&&e.every(t=>t instanceof Uint8Array))&&!(e instanceof L0)&&!(e instanceof R0)&&!j5(e))throw new TypeError("Each value in tags.raw must be a string, string array, Uint8Array, Uint8Array array, RichImageData, AttachedFile, Record<string, string>, or null.")}},G5=s=>{if(!s||typeof s!="object")throw new TypeError("disposition must be an object.");if(s.default!==void 0&&typeof s.default!="boolean")throw new TypeError("disposition.default must be a boolean.");if(s.primary!==void 0&&typeof s.primary!="boolean")throw new TypeError("disposition.primary must be a boolean.");if(s.forced!==void 0&&typeof s.forced!="boolean")throw new TypeError("disposition.forced must be a boolean.");if(s.original!==void 0&&typeof s.original!="boolean")throw new TypeError("disposition.original must be a boolean.");if(s.commentary!==void 0&&typeof s.commentary!="boolean")throw new TypeError("disposition.commentary must be a boolean.");if(s.hearingImpaired!==void 0&&typeof s.hearingImpaired!="boolean")throw new TypeError("disposition.hearingImpaired must be a boolean.");if(s.visuallyImpaired!==void 0&&typeof s.visuallyImpaired!="boolean")throw new TypeError("disposition.visuallyImpaired must be a boolean.")};class je{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){const e=Math.floor(this.pos/8),t=this.bytes[e]??0,i=7-(this.pos&7),n=(t&1<<i)>>i;return this.pos++,n}readBits(e){if(e===1)return this.readBit();let t=0;for(let i=0;i<e;i++)t<<=1,t|=this.readBit();return t}writeBits(e,t){const i=this.pos+e;for(let n=this.pos;n<i;n++){const r=Math.floor(n/8);let o=this.bytes[r];const a=7-(n&7);o&=~(1<<a),o|=(t&1<<i-n-1)>>i-n-1<<a,this.bytes[r]=o}this.pos=i}copyBits(e,t){let i=0;for(i;i<e-7;i+=8)this.writeBits(8,t.readBits(8));const n=e-i;n>0&&this.writeBits(n,t.readBits(n))}readAlignedByte(){if(this.pos%8!==0)throw new Error("Bitstream is not byte-aligned.");const e=this.pos/8,t=this.bytes[e]??0;return this.pos+=8,t}skipBits(e){this.pos+=e}getBitsLeft(){return this.bytes.length*8-this.pos}clone(){const e=new je(this.bytes);return e.pos=this.pos,e}}const Ni=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],wo=[-1,1,2,3,4,5,6,8],Z5=[1,2,3,4,6,7,17,19,20,21,22],B0=s=>{if(!s||s.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");const e=new je(s),t=wa(e),{frequencyIndex:i,sampleRate:n}=ba(e),r=e.readBits(4);let o=null;r>=1&&r<=7&&(o=wo[r]);let a=t,l=!1,c=n;(t===5||t===29)&&(l=t===29,c=ba(e).sampleRate,a=wa(e),a===22&&e.skipBits(4));let h=1024;if(Z5.includes(a)&&(h=e.readBits(1)?960:1024),t!==5&&t!==29)for(;e.getBitsLeft()>15;){const d=e.pos;if(e.readBits(11)!==695){e.pos=d+1;continue}wa(e)===5&&e.readBits(1)&&(c=ba(e).sampleRate,e.getBitsLeft()>11&&e.readBits(11)===1352&&(l=!!e.readBits(1)));break}return o!==null&&o>1&&(l=!1),{objectType:t,coreObjectType:a,frequencyIndex:i,channelConfiguration:r,coreSampleRate:n,outputSampleRate:c,outputNumberOfChannels:l&&o===1?2:o,frameLength:h}},wa=s=>{const e=s.readBits(5);return e===31?32+s.readBits(6):e},ba=s=>{const e=s.readBits(4);return e===15?{frequencyIndex:e,sampleRate:s.readBits(24)}:{frequencyIndex:e,sampleRate:e<Ni.length?Ni[e]:null}},Kl=s=>{const e=s.objectType===5||s.objectType===29,t=s.objectType===29,i=e?s.outputSampleRate/2:s.outputSampleRate,n=t?1:s.outputNumberOfChannels,r=wo.indexOf(n);if(r===-1)throw new TypeError(`Unsupported number of channels: ${s.outputNumberOfChannels}`);let o=16;s.objectType>=32&&(o+=6),ml(i)===15&&(o+=24),e&&(o+=9,ml(s.outputSampleRate)===15&&(o+=24));const a=Math.ceil(o/8),l=new Uint8Array(a),c=new je(l);return Zh(c,s.objectType),Xh(c,i),c.writeBits(4,r),e&&(Xh(c,s.outputSampleRate),Zh(c,2)),c.writeBits(3,0),l},Zh=(s,e)=>{e<32?s.writeBits(5,e):(s.writeBits(5,31),s.writeBits(6,e-32))},Xh=(s,e)=>{const t=ml(e);s.writeBits(4,t),t===15&&s.writeBits(24,e)},ml=s=>{const e=Ni.indexOf(s);return e===-1?15:e};const X5=4;var Yh;(function(s){s[s.FrameCount=1]="FrameCount",s[s.FileSize=2]="FileSize",s[s.Toc=4]="Toc"})(Yh||(Yh={}));const Y5=[48e3,44100,32e3],Q5=[24e3,22050,16e3];const K5="1.63.0",kn=`Mediabunny v${K5}`;var gs;(function(s){s[s.NON_IDR_SLICE=1]="NON_IDR_SLICE",s[s.SLICE_DPA=2]="SLICE_DPA",s[s.SLICE_DPB=3]="SLICE_DPB",s[s.SLICE_DPC=4]="SLICE_DPC",s[s.IDR=5]="IDR",s[s.SEI=6]="SEI",s[s.SPS=7]="SPS",s[s.PPS=8]="PPS",s[s.AUD=9]="AUD",s[s.SPS_EXT=13]="SPS_EXT"})(gs||(gs={}));var Ft;(function(s){s[s.RASL_N=8]="RASL_N",s[s.RASL_R=9]="RASL_R",s[s.BLA_W_LP=16]="BLA_W_LP",s[s.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",s[s.VPS_NUT=32]="VPS_NUT",s[s.SPS_NUT=33]="SPS_NUT",s[s.PPS_NUT=34]="PPS_NUT",s[s.AUD_NUT=35]="AUD_NUT",s[s.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",s[s.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"})(Ft||(Ft={}));const Zn=function*(s){let e=0,t=-1;for(;e<s.length-2;){const i=s.indexOf(0,e);if(i===-1||i>=s.length-2)break;e=i;let n=0;if(e+3<s.length&&s[e+1]===0&&s[e+2]===0&&s[e+3]===1?n=4:s[e+1]===0&&s[e+2]===1&&(n=3),n===0){e++;continue}t!==-1&&e>t&&(yield{offset:t,length:e-t}),t=e+n,e=t}t!==-1&&t<s.length&&(yield{offset:t,length:s.length-t})},F0=function*(s,e){let t=0;const i=new DataView(s.buffer,s.byteOffset,s.byteLength);for(;t+e<=s.length;){let n;e===1?n=i.getUint8(t):e===2?n=i.getUint16(t,!1):e===3?n=T5(i,t):(S(e===4),n=i.getUint32(t,!1)),t+=e,yield{offset:t,length:n},t+=n}},J5=(s,e)=>{if(e.description){const n=(Ke(e.description)[4]&3)+1;return F0(s,n)}else return Zn(s)},O0=s=>s&31,bo=s=>{const e=new Uint8Array(s.length),t=s.length;let i=0;for(let n=0;n<t;n++)n+2<t&&s[n]===0&&s[n+1]===0&&s[n+2]===3?(e[i++]=0,e[i++]=0,n+=2):e[i++]=s[n];return e.subarray(0,i)},ew=(s,e)=>{const t=s.reduce((r,o)=>r+e+o.byteLength,0),i=new Uint8Array(t);let n=0;for(const r of s){const o=new DataView(i.buffer,i.byteOffset,i.byteLength);switch(e){case 1:o.setUint8(n,r.byteLength);break;case 2:o.setUint16(n,r.byteLength,!1);break;case 3:Gl(o,n,r.byteLength,!1);break;case 4:o.setUint32(n,r.byteLength,!1);break}n+=e,i.set(r,n),n+=r.byteLength}return i},I0=s=>{try{const e=[],t=[],i=[];for(const a of Zn(s)){const l=s.subarray(a.offset,a.offset+a.length),c=O0(l[0]);c===gs.SPS&&e.length<31?e.push(l):c===gs.PPS&&t.length<255?t.push(l):c===gs.SPS_EXT&&i.length<255&&i.push(l)}if(e.length===0||t.length===0)return null;const n=e[0],r=sw(n);if(!r)return null;const o=r.profileIdc===100||r.profileIdc===110||r.profileIdc===122||r.profileIdc===144;return{configurationVersion:1,avcProfileIndication:r.profileIdc,profileCompatibility:r.constraintFlags,avcLevelIndication:r.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:e,pictureParameterSets:t,chromaFormat:o?r.chromaFormatIdc:null,bitDepthLumaMinus8:o?r.bitDepthLumaMinus8:null,bitDepthChromaMinus8:o?r.bitDepthChromaMinus8:null,sequenceParameterSetExt:o?i:null}}catch(e){return Re._error("Error building AVC Decoder Configuration Record:",e),null}},D0=s=>{const e=[];e.push(s.configurationVersion),e.push(s.avcProfileIndication),e.push(s.profileCompatibility),e.push(s.avcLevelIndication),e.push(252|s.lengthSizeMinusOne&3),e.push(224|s.sequenceParameterSets.length&31);for(const t of s.sequenceParameterSets){const i=t.byteLength;e.push(i>>8),e.push(i&255);for(let n=0;n<i;n++)e.push(t[n])}e.push(s.pictureParameterSets.length);for(const t of s.pictureParameterSets){const i=t.byteLength;e.push(i>>8),e.push(i&255);for(let n=0;n<i;n++)e.push(t[n])}if((s.avcProfileIndication===100||s.avcProfileIndication===110||s.avcProfileIndication===122||s.avcProfileIndication===144)&&s.chromaFormat!==null){S(s.bitDepthLumaMinus8!==null),S(s.bitDepthChromaMinus8!==null),S(s.sequenceParameterSetExt!==null),e.push(252|s.chromaFormat&3),e.push(248|s.bitDepthLumaMinus8&7),e.push(248|s.bitDepthChromaMinus8&7),e.push(s.sequenceParameterSetExt.length);for(const t of s.sequenceParameterSetExt){const i=t.byteLength;e.push(i>>8),e.push(i&255);for(let n=0;n<i;n++)e.push(t[n])}}return new Uint8Array(e)},tw=s=>{try{const e=Ht(s);let t=0;const i=e.getUint8(t++),n=e.getUint8(t++),r=e.getUint8(t++),o=e.getUint8(t++),a=e.getUint8(t++)&3,l=e.getUint8(t++)&31,c=[];for(let f=0;f<l;f++){const p=e.getUint16(t,!1);t+=2,c.push(s.subarray(t,t+p)),t+=p}const h=e.getUint8(t++),d=[];for(let f=0;f<h;f++){const p=e.getUint16(t,!1);t+=2,d.push(s.subarray(t,t+p)),t+=p}const u={configurationVersion:i,avcProfileIndication:n,profileCompatibility:r,avcLevelIndication:o,lengthSizeMinusOne:a,sequenceParameterSets:c,pictureParameterSets:d,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((n===100||n===110||n===122||n===144)&&t+4<=s.length){const f=e.getUint8(t++)&3,p=e.getUint8(t++)&7,m=e.getUint8(t++)&7,g=e.getUint8(t++);u.chromaFormat=f,u.bitDepthLumaMinus8=p,u.bitDepthChromaMinus8=m;const w=[];for(let b=0;b<g;b++){const y=e.getUint16(t,!1);t+=2,w.push(s.subarray(t,t+y)),t+=y}u.sequenceParameterSetExt=w}return u}catch(e){return Re._error("Error deserializing AVC Decoder Configuration Record:",e),null}},V0={1:{num:1,den:1},2:{num:12,den:11},3:{num:10,den:11},4:{num:16,den:11},5:{num:40,den:33},6:{num:24,den:11},7:{num:20,den:11},8:{num:32,den:11},9:{num:80,den:33},10:{num:18,den:11},11:{num:15,den:11},12:{num:64,den:33},13:{num:160,den:99},14:{num:4,den:3},15:{num:3,den:2},16:{num:2,den:1}},sw=s=>{try{const e=bo(s),t=new je(e);if(t.skipBits(1),t.skipBits(2),t.readBits(5)!==7)return null;const n=t.readAlignedByte(),r=t.readAlignedByte(),o=t.readAlignedByte();V(t);let a=1,l=0,c=0,h=0;if((n===100||n===110||n===122||n===244||n===44||n===83||n===86||n===118||n===128)&&(a=V(t),a===3&&(h=t.readBits(1)),l=V(t),c=V(t),t.skipBits(1),t.readBits(1))){for(let G=0;G<(a!==3?8:12);G++)if(t.readBits(1)){const se=G<6?16:64;let xe=8,we=8;for(let U=0;U<se;U++){if(we!==0){const re=ms(t);we=(xe+re+256)%256}xe=we===0?xe:we}}}V(t);const d=V(t);if(d===0)V(t);else if(d===1){t.skipBits(1),ms(t),ms(t);const Y=V(t);for(let G=0;G<Y;G++)ms(t)}V(t),t.skipBits(1);const u=V(t),f=V(t),p=16*(u+1),m=16*(f+1);let g=p,w=m;const b=t.readBits(1);if(b||t.skipBits(1),t.skipBits(1),t.readBits(1)){const Y=V(t),G=V(t),ee=V(t),se=V(t);let xe,we;if((h===0?a:0)===0)xe=1,we=2-b;else{const re=a===3?1:2,Q=a===1?2:1;xe=re,we=Q*(2-b)}g-=xe*(Y+G),w-=we*(ee+se)}if(g<=0||w<=0)return null;let C=2,_=2,x=2,T=0,M={num:1,den:1},k=null,A=null,P=null,$=null;const H=t.pos;if(t.readBits(1)){if(t.readBits(1)){const re=t.readBits(8);if(re===255)M={num:t.readBits(16),den:t.readBits(16)};else{const Q=V0[re];Q&&(M=Q)}}t.readBits(1)&&t.skipBits(1),t.readBits(1)&&(t.skipBits(3),T=t.readBits(1),t.readBits(1)&&(C=t.readBits(8),_=t.readBits(8),x=t.readBits(8))),t.readBits(1)&&(V(t),V(t)),t.readBits(1)&&(t.skipBits(32),t.skipBits(32),t.skipBits(1));const we=t.readBits(1);we&&Qh(t);const U=t.readBits(1);U&&Qh(t),(we||U)&&t.skipBits(1),t.skipBits(1),P=t.pos,$=t.readBits(1),$&&(t.skipBits(1),V(t),V(t),V(t),V(t),k=Math.min(V(t),16),A=Math.min(V(t),16))}if(k===null){S(A===null);const Y=r&16;if((n===44||n===86||n===100||n===110||n===122||n===244)&&Y)k=0,A=0;else{const G=u+1,ee=f+1,se=(2-b)*ee,xe=io.find(U=>U.level>=o)??kt(io),we=Math.min(Math.floor(xe.maxDpbMbs/(G*se)),16);k=we,A=we}}return S(A!==null),{emulationUnpreventedBytes:e,profileIdc:n,constraintFlags:r,levelIdc:o,frameMbsOnlyFlag:b,chromaFormatIdc:a,bitDepthLumaMinus8:l,bitDepthChromaMinus8:c,codedWidth:p,codedHeight:m,displayWidth:g,displayHeight:w,pixelAspectRatio:M,colourPrimaries:C,matrixCoefficients:x,transferCharacteristics:_,fullRangeFlag:T,numReorderFrames:k,maxDecFrameBuffering:A,vuiParametersFlagBitOffset:H,bitstreamRestrictionFlagBitOffset:P,bitstreamRestrictionFlag:$}}catch(e){return Re._error("Error parsing AVC SPS:",e),null}},Qh=s=>{const e=V(s);s.skipBits(4),s.skipBits(4);for(let t=0;t<=e;t++)V(s),V(s),s.skipBits(1);s.skipBits(5),s.skipBits(5),s.skipBits(5),s.skipBits(5)},iw=(s,e)=>{if(e.description){const n=(Ke(e.description)[21]&3)+1;return F0(s,n)}else return Zn(s)},gl=s=>s>>1&63,nw=s=>{try{const e=new je(bo(s));e.skipBits(16),e.readBits(4);const t=e.readBits(3),i=e.readBits(1),{general_profile_space:n,general_tier_flag:r,general_profile_idc:o,general_profile_compatibility_flags:a,general_constraint_indicator_flags:l,general_level_idc:c}=rw(e,t);V(e);const h=V(e);let d=0;h===3&&(d=e.readBits(1));const u=V(e),f=V(e);let p=u,m=f;if(e.readBits(1)){const $=V(e),H=V(e),q=V(e),Y=V(e);let G=1,ee=1;const se=d===0?h:0;se===1?(G=2,ee=2):se===2&&(G=2,ee=1),p-=($+H)*G,m-=(q+Y)*ee}if(p<=0||m<=0)return null;const g=V(e),w=V(e);V(e);const y=e.readBits(1)?0:t;let C=0;for(let $=y;$<=t;$++)V(e),C=V(e),V(e);V(e),V(e),V(e),V(e),V(e),V(e),e.readBits(1)&&e.readBits(1)&&ow(e),e.skipBits(1),e.skipBits(1),e.readBits(1)&&(e.skipBits(4),e.skipBits(4),V(e),V(e),e.skipBits(1));const _=V(e);if(aw(e,_),e.readBits(1)){const $=V(e);for(let H=0;H<$;H++)V(e),e.skipBits(1)}e.skipBits(1),e.skipBits(1);let x=2,T=2,M=2,k=0,A=0,P={num:1,den:1};if(e.readBits(1)){const $=cw(e,t);P=$.pixelAspectRatio,x=$.colourPrimaries,T=$.transferCharacteristics,M=$.matrixCoefficients,k=$.fullRangeFlag,A=$.minSpatialSegmentationIdc}return{displayWidth:p,displayHeight:m,pixelAspectRatio:P,colourPrimaries:x,transferCharacteristics:T,matrixCoefficients:M,fullRangeFlag:k,maxDecFrameBuffering:Math.min(C+1,16),spsMaxSubLayersMinus1:t,spsTemporalIdNestingFlag:i,generalProfileSpace:n,generalTierFlag:r,generalProfileIdc:o,generalProfileCompatibilityFlags:a,generalConstraintIndicatorFlags:l,generalLevelIdc:c,chromaFormatIdc:h,bitDepthLumaMinus8:g,bitDepthChromaMinus8:w,minSpatialSegmentationIdc:A}}catch(e){return Re._error("Error parsing HEVC SPS:",e),null}},N0=s=>{try{const e=[],t=[],i=[],n=[];for(const h of Zn(s)){const d=s.subarray(h.offset,h.offset+h.length),u=gl(d[0]);u===Ft.VPS_NUT&&e.length<65535?e.push(d):u===Ft.SPS_NUT&&t.length<65535?t.push(d):u===Ft.PPS_NUT&&i.length<65535?i.push(d):(u===Ft.PREFIX_SEI_NUT||u===Ft.SUFFIX_SEI_NUT)&&n.length<65535&&n.push(d)}if(t.length===0||i.length===0)return null;const o=nw(t[0]);if(!o)return null;let a=0;if(i.length>0){const h=i[0],d=new je(bo(h));d.skipBits(16),V(d),V(d),d.skipBits(1),d.skipBits(1),d.skipBits(3),d.skipBits(1),d.skipBits(1),V(d),V(d),ms(d),d.skipBits(1),d.skipBits(1),d.readBits(1)&&V(d),ms(d),ms(d),d.skipBits(1),d.skipBits(1),d.skipBits(1),d.skipBits(1);const u=d.readBits(1),f=d.readBits(1);!u&&!f?a=0:u&&!f?a=2:!u&&f?a=3:a=0}const l=[...e.length?[{arrayCompleteness:1,nalUnitType:Ft.VPS_NUT,nalUnits:e}]:[],...t.length?[{arrayCompleteness:1,nalUnitType:Ft.SPS_NUT,nalUnits:t}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:Ft.PPS_NUT,nalUnits:i}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:gl(n[0][0]),nalUnits:n}]:[]];return{configurationVersion:1,generalProfileSpace:o.generalProfileSpace,generalTierFlag:o.generalTierFlag,generalProfileIdc:o.generalProfileIdc,generalProfileCompatibilityFlags:o.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:o.generalConstraintIndicatorFlags,generalLevelIdc:o.generalLevelIdc,minSpatialSegmentationIdc:o.minSpatialSegmentationIdc,parallelismType:a,chromaFormatIdc:o.chromaFormatIdc,bitDepthLumaMinus8:o.bitDepthLumaMinus8,bitDepthChromaMinus8:o.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:o.spsMaxSubLayersMinus1+1,temporalIdNested:o.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:l}}catch(e){return Re._error("Error building HEVC Decoder Configuration Record:",e),null}},rw=(s,e)=>{const t=s.readBits(2),i=s.readBits(1),n=s.readBits(5);let r=0;for(let h=0;h<32;h++)r=r<<1|s.readBits(1);const o=new Uint8Array(6);for(let h=0;h<6;h++)o[h]=s.readBits(8);const a=s.readBits(8),l=[],c=[];for(let h=0;h<e;h++)l.push(s.readBits(1)),c.push(s.readBits(1));if(e>0)for(let h=e;h<8;h++)s.skipBits(2);for(let h=0;h<e;h++)l[h]&&s.skipBits(88),c[h]&&s.skipBits(8);return{general_profile_space:t,general_tier_flag:i,general_profile_idc:n,general_profile_compatibility_flags:r,general_constraint_indicator_flags:o,general_level_idc:a}},ow=s=>{for(let e=0;e<4;e++)for(let t=0;t<(e===3?2:6);t++)if(!s.readBits(1))V(s);else{const n=Math.min(64,1<<4+(e<<1));e>1&&ms(s);for(let r=0;r<n;r++)ms(s)}},aw=(s,e)=>{const t=[];for(let i=0;i<e;i++)t[i]=lw(s,i,e,t)},lw=(s,e,t,i)=>{let n=0,r=0,o=0;if(e!==0&&(r=s.readBits(1)),r){if(e===t){const l=V(s);o=e-(l+1)}else o=e-1;s.readBits(1),V(s);const a=i[o]??0;for(let l=0;l<=a;l++)s.readBits(1)||s.readBits(1);n=i[o]}else{const a=V(s),l=V(s);for(let c=0;c<a;c++)V(s),s.readBits(1);for(let c=0;c<l;c++)V(s),s.readBits(1);n=a+l}return n},cw=(s,e)=>{let t=2,i=2,n=2,r=0,o=0,a={num:1,den:1};if(s.readBits(1)){const l=s.readBits(8);if(l===255)a={num:s.readBits(16),den:s.readBits(16)};else{const c=V0[l];c&&(a=c)}}return s.readBits(1)&&s.readBits(1),s.readBits(1)&&(s.readBits(3),r=s.readBits(1),s.readBits(1)&&(t=s.readBits(8),i=s.readBits(8),n=s.readBits(8))),s.readBits(1)&&(V(s),V(s)),s.readBits(1),s.readBits(1),s.readBits(1),s.readBits(1)&&(V(s),V(s),V(s),V(s)),s.readBits(1)&&(s.readBits(32),s.readBits(32),s.readBits(1)&&V(s),s.readBits(1)&&hw(s,!0,e)),s.readBits(1)&&(s.readBits(1),s.readBits(1),s.readBits(1),o=V(s),V(s),V(s),V(s),V(s)),{pixelAspectRatio:a,colourPrimaries:t,transferCharacteristics:i,matrixCoefficients:n,fullRangeFlag:r,minSpatialSegmentationIdc:o}},hw=(s,e,t)=>{let i=!1,n=!1,r=!1;i=s.readBits(1)===1,n=s.readBits(1)===1,(i||n)&&(r=s.readBits(1)===1,r&&(s.readBits(8),s.readBits(5),s.readBits(1),s.readBits(5)),s.readBits(4),s.readBits(4),r&&s.readBits(4),s.readBits(5),s.readBits(5),s.readBits(5));for(let o=0;o<=t;o++){const a=s.readBits(1)===1;let l=!0;a||(l=s.readBits(1)===1);let c=!1;l?V(s):c=s.readBits(1)===1;let h=1;c||(h=V(s)+1),i&&Kh(s,h,r),n&&Kh(s,h,r)}},Kh=(s,e,t)=>{for(let i=0;i<e;i++)V(s),V(s),t&&(V(s),V(s)),s.readBits(1)},dw=s=>{const e=[];e.push(s.configurationVersion),e.push((s.generalProfileSpace&3)<<6|(s.generalTierFlag&1)<<5|s.generalProfileIdc&31),e.push(s.generalProfileCompatibilityFlags>>>24&255),e.push(s.generalProfileCompatibilityFlags>>>16&255),e.push(s.generalProfileCompatibilityFlags>>>8&255),e.push(s.generalProfileCompatibilityFlags&255),e.push(...s.generalConstraintIndicatorFlags),e.push(s.generalLevelIdc&255),e.push(240|s.minSpatialSegmentationIdc>>8&15),e.push(s.minSpatialSegmentationIdc&255),e.push(252|s.parallelismType&3),e.push(252|s.chromaFormatIdc&3),e.push(248|s.bitDepthLumaMinus8&7),e.push(248|s.bitDepthChromaMinus8&7),e.push(s.avgFrameRate>>8&255),e.push(s.avgFrameRate&255),e.push((s.constantFrameRate&3)<<6|(s.numTemporalLayers&7)<<3|(s.temporalIdNested&1)<<2|s.lengthSizeMinusOne&3),e.push(s.arrays.length&255);for(const t of s.arrays){e.push((t.arrayCompleteness&1)<<7|0|t.nalUnitType&63),e.push(t.nalUnits.length>>8&255),e.push(t.nalUnits.length&255);for(const i of t.nalUnits){e.push(i.length>>8&255),e.push(i.length&255);for(let n=0;n<i.length;n++)e.push(i[n])}}return new Uint8Array(e)};var Jh;(function(s){s[s.audAllowed=0]="audAllowed",s[s.beforeFirstVcl=1]="beforeFirstVcl",s[s.afterFirstVcl=2]="afterFirstVcl",s[s.eoBitstreamAllowed=3]="eoBitstreamAllowed",s[s.noMoreDataAllowed=4]="noMoreDataAllowed"})(Jh||(Jh={}));const uw={1:{colourPrimaries:5,transferCharacteristics:6,matrixCoefficients:5},2:{colourPrimaries:1,transferCharacteristics:1,matrixCoefficients:1},3:{colourPrimaries:6,transferCharacteristics:6,matrixCoefficients:6},4:{colourPrimaries:7,transferCharacteristics:7,matrixCoefficients:7},5:{colourPrimaries:9,transferCharacteristics:14,matrixCoefficients:9},7:{colourPrimaries:1,transferCharacteristics:13,matrixCoefficients:0}},fw=s=>{const e=new je(s);if(e.readBits(2)!==2)return null;const i=e.readBits(1),r=(e.readBits(1)<<1)+i;if(r===3&&e.skipBits(1),e.readBits(1)===1||e.readBits(1)!==0||(e.skipBits(2),e.readBits(24)!==4817730))return null;let c=8;r>=2&&(c=e.readBits(1)?12:10);const h=e.readBits(3);let d=0,u=0;if(h!==7)if(u=e.readBits(1),r===1||r===3){const M=e.readBits(1),k=e.readBits(1);d=!M&&!k?3:M&&!k?2:1,e.skipBits(1)}else d=1;else d=3,u=1;const f=e.readBits(16),p=e.readBits(16),m=f+1,g=p+1,w=m*g;let b=kt(Rs).level;for(const T of Rs)if(w<=T.maxPictureSize){b=T.level;break}const y=uw[h],C=y?.colourPrimaries??2,_=y?.transferCharacteristics??2,x=y?.matrixCoefficients??2;return{profile:r,level:b,bitDepth:c,chromaSubsampling:d,videoFullRangeFlag:u,colourPrimaries:C,transferCharacteristics:_,matrixCoefficients:x}},W0=function*(s){const e=new je(s),t=()=>{let i=0;for(let n=0;n<8;n++){const r=e.readAlignedByte();if(i+=(r&127)*2**(n*7),!(r&128))break;if(n===7&&r&128)return null}return i>2**32-1?null:i};for(;e.getBitsLeft()>=8;){e.skipBits(1);const i=e.readBits(4),n=e.readBits(1),r=e.readBits(1);e.skipBits(1),n&&e.skipBits(8);let o;if(r){const a=t();if(a===null)return;o=a}else o=Math.floor(e.getBitsLeft()/8);S(e.pos%8===0),yield{type:i,data:s.subarray(e.pos/8,e.pos/8+o)},e.skipBits(o*8)}},pw=s=>{for(const{type:e,data:t}of W0(s)){if(e!==1)continue;const i=new je(t),n=i.readBits(3);i.readBits(1);const r=i.readBits(1);let o=0,a=0,l=0;if(r)o=i.readBits(5);else{const k=i.readBits(1);let A=0;if(k){if(i.skipBits(32),i.skipBits(32),i.readBits(1)){let q=0;for(;q<32&&!i.readBits(1);)q++;q<32&&i.skipBits(q)}A=i.readBits(1),A&&(l=i.readBits(5),i.skipBits(32),i.skipBits(5),i.skipBits(5))}const P=i.readBits(1),$=i.readBits(5);for(let H=0;H<=$;H++){i.skipBits(12);const q=i.readBits(5);if(H===0&&(o=q),q>7){const Y=i.readBits(1);H===0&&(a=Y)}if(A&&i.readBits(1)){const G=l+1;i.skipBits(G),i.skipBits(G),i.skipBits(1)}P&&i.readBits(1)&&i.skipBits(4)}}const c=i.readBits(4),h=i.readBits(4),d=c+1;i.skipBits(d);const u=h+1;i.skipBits(u);let f=0;if(r?f=0:f=i.readBits(1),f&&(i.skipBits(4),i.skipBits(3)),i.skipBits(1),i.skipBits(1),i.skipBits(1),!r){i.skipBits(1),i.skipBits(1),i.skipBits(1),i.skipBits(1);const k=i.readBits(1);k&&(i.skipBits(1),i.skipBits(1));const A=i.readBits(1);let P=0;A?P=2:P=i.readBits(1),P>0&&(i.readBits(1)||i.skipBits(1)),k&&i.skipBits(3)}i.skipBits(1),i.skipBits(1),i.skipBits(1);const p=i.readBits(1);let m=8;n===2&&p?m=i.readBits(1)?12:10:n<=2&&(m=p?10:8);let g=0;n!==1&&(g=i.readBits(1));let w=2,b=2,y=2;i.readBits(1)&&(w=i.readBits(8),b=i.readBits(8),y=i.readBits(8));let _=0,x=1,T=1,M=0;return g?_=i.readBits(1):w===1&&b===13&&y===0?(_=1,x=0,T=0):(_=i.readBits(1),n===0?(x=1,T=1):n===1?(x=0,T=0):m===12?(x=i.readBits(1),T=x?i.readBits(1):0):(x=1,T=0),x&&T&&(M=i.readBits(2))),{profile:n,level:o,tier:a,bitDepth:m,monochrome:g,chromaSubsamplingX:x,chromaSubsamplingY:T,chromaSamplePosition:M,videoFullRangeFlag:_,colourPrimaries:w,transferCharacteristics:b,matrixCoefficients:y}}return null},mw=s=>s.colourPrimaries!==2||s.transferCharacteristics!==2||s.matrixCoefficients!==2,H0=s=>{if(s.byteLength<19)throw new Error("Invalid Opus identification header: too short.");const e=Ht(s),t=e.getUint8(9),i=e.getUint16(10,!0),n=e.getUint32(12,!0),r=e.getInt16(16,!0),o=e.getUint8(18);let a=null;return o&&(a=s.subarray(19,21+t)),{outputChannelCount:t,preSkip:i,inputSampleRate:n,outputGain:r,channelMappingFamily:o,channelMappingTable:a}},gw=[480,960,1920,2880,480,960,1920,2880,480,960,1920,2880,480,960,480,960,120,240,480,960,120,240,480,960,120,240,480,960,120,240,480,960],ww=s=>{const e=s[0]>>3,t=s[0]&3;let i;return t===0?i=1:t===1||t===2?i=2:i=s[1]&63,{durationInSamples:gw[e]*i}},bw=(s,e,t)=>{switch(s){case"avc":{for(const i of J5(t,e)){const n=t[i.offset],r=O0(n);if(r>=gs.NON_IDR_SLICE&&r<=gs.SLICE_DPC)return"delta";if(r===gs.IDR)return"key";if(r===gs.SEI&&!z5()){const o=t.subarray(i.offset,i.offset+i.length),a=bo(o);let l=1;do{let c=0;for(;;){const u=a[l++];if(u===void 0||(c+=u,u<255))break}let h=0;for(;;){const u=a[l++];if(u===void 0||(h+=u,u<255))break}if(c===6){const u=new je(a);u.pos=8*l;let f=-1;try{f=V(u)}catch{}const p=u.readBits(1);if(f===0&&p===1)return"key"}l+=h}while(l<a.length-1)}}return"delta"}case"hevc":{for(const i of iw(t,e)){const n=gl(t[i.offset]);if(n<Ft.BLA_W_LP)return"delta";if(n<=Ft.RSV_IRAP_VCL23)return"key"}return"delta"}case"vp8":return(t[0]&1)===0?"key":"delta";case"vp9":{const i=new je(t);if(i.readBits(2)!==2)return null;const n=i.readBits(1);return(i.readBits(1)<<1)+n===3&&i.skipBits(1),i.readBits(1)?null:i.readBits(1)===0?"key":"delta"}case"av1":{let i=!1;for(const{type:n,data:r}of W0(t))if(n===1){const o=new je(r);o.skipBits(4),i=!!o.readBits(1)}else if(n===3||n===6||n===7){if(i)return"key";const o=new je(r);return o.readBits(1)?null:o.readBits(2)===0?"key":"delta"}return null}case"prores":return"key";default:Gt(s),S(!1)}};var ed;(function(s){s[s.STREAMINFO=0]="STREAMINFO",s[s.VORBIS_COMMENT=4]="VORBIS_COMMENT",s[s.PICTURE=6]="PICTURE"})(ed||(ed={}));const vw=s=>{if(s.length<7||s[0]!==11||s[1]!==119)return null;const e=new je(s);e.skipBits(16),e.skipBits(16);const t=e.readBits(2);if(t===3)return null;const i=e.readBits(6),n=e.readBits(5);if(n>8)return null;const r=e.readBits(3),o=e.readBits(3);(o&1)!==0&&o!==1&&e.skipBits(2),(o&4)!==0&&e.skipBits(2),o===2&&e.skipBits(2);const a=e.readBits(1),l=Math.floor(i/2);return{fscod:t,bsid:n,bsmod:r,acmod:o,lfeon:a,bitRateCode:l}},yw=[1,2,3,6],Cw=s=>{if(s.length<6||s[0]!==11||s[1]!==119)return null;const e=new je(s);e.skipBits(16);const t=e.readBits(2);if(e.skipBits(3),t!==0&&t!==2)return null;const i=e.readBits(11),n=e.readBits(2);let r=0,o;n===3?(r=e.readBits(2),o=3):o=e.readBits(2);const a=e.readBits(3),l=e.readBits(1),c=e.readBits(5);if(c<11||c>16)return null;const h=yw[o];let d;return n<3?d=Y5[n]/1e3:d=Q5[r]/1e3,{dataRate:Math.round((i+1)*d/(h*16)),substreams:[{fscod:n,fscod2:r,bsid:c,bsmod:0,acmod:a,lfeon:l,numDepSub:0,chanLoc:0}]}},xw=1683496997,Mw=18,kw=10,td=32,Tw=20,_w=8,Sw=[0,8e3,16e3,32e3,0,0,11025,22050,44100,0,0,12e3,24e3,48e3,96e3,192e3],$w=[32e3,56e3,64e3,96e3,112e3,128e3,192e3,224e3,256e3,32e4,384e3,448e3,512e3,576e3,64e4,768e3,96e4,1024e3,1152e3,128e4,1344e3,1408e3,1411200,1472e3,1536e3,192e4,2048e3,3072e3,384e4,0,0,0],Aw=[16,16,20,20,0,24,24,0],sd=[1,2,2,2,2,3,3,4,4,5,6,6,6,7,8,8],Ew=[1,2,2,2,2,3,18,19,6,7,518,323,83,519,582,535],Pw=8,zw=[32e3,44100,48e3,0],Lw=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],Rw=[512,1024,2048,4096],Bw=s=>{const e=Fw(s),t=Ht(s);let i=e?Math.ceil(e.frameSize/4)*4:0,n=null;for(;i+4<=s.length&&t.getUint32(i)===xw;){const o=Ow(s.subarray(i));if(!o)break;n??=o,i+=o.frameSize}if(e)return{frameSize:n?i:e.frameSize,sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels,sampleCount:e.sampleCount,channelLayout:e.channelLayout,pcmResolution:e.pcmResolution,bitRate:e.bitRate,core:e,hasExtensions:n!==null};if(!n?.asset)return null;const{asset:r}=n;return{frameSize:i,sampleRate:r.sampleRate,numberOfChannels:r.numberOfChannels,sampleCount:r.sampleCount,channelLayout:r.channelLayout,pcmResolution:r.pcmResolution,bitRate:0,core:null,hasExtensions:!0}},Fw=s=>{if(s.length<Mw||s[0]!==127||s[1]!==254||s[2]!==128||s[3]!==1)return null;const e=new je(s);if(e.skipBits(32),e.skipBits(1),e.readBits(5)!==td-1)return null;const t=e.readBits(1),i=e.readBits(7)+1;if(i%_w!==0)return null;const n=e.readBits(14)+1;if(n<96)return null;const r=e.readBits(6);if(r>=sd.length)return null;const o=Sw[e.readBits(4)];if(o===0)return null;const a=$w[e.readBits(5)];if(e.readBits(1)!==0)return null;e.skipBits(4),e.skipBits(5);const l=e.readBits(2);if(l===3)return null;e.skipBits(1),t&&e.skipBits(16),e.skipBits(7);const c=Aw[e.readBits(3)];if(c===0)return null;const h=l!==0;return{frameSize:n,sampleRate:o,numberOfChannels:sd[r]+(h?1:0),sampleCount:i*td,channelLayout:Ew[r]|(h?Pw:0),amode:r,lfePresent:h,bitRate:a,pcmResolution:c}},Ow=s=>{if(s.length<kw||s[0]!==100||s[1]!==88||s[2]!==32||s[3]!==37)return null;const e=new je(s);e.skipBits(32),e.skipBits(8);const t=e.readBits(2),i=e.readBits(1),n=8+4*i,r=16+4*i;e.skipBits(n);const o=e.readBits(r)+1,a={frameSize:o,asset:null};if(!e.readBits(1))return a;const l=zw[e.readBits(2)],c=512*(e.readBits(3)+1);e.readBits(1)&&e.skipBits(36);const h=e.readBits(3)+1,d=e.readBits(3)+1,u=[];for(let w=0;w<h;w++)u.push(e.readBits(t+1));for(const w of u)e.skipBits(8*$5(w));if(e.readBits(1)){e.skipBits(2);const w=e.readBits(2)+1<<2,b=e.readBits(2)+1;e.skipBits(b*w)}for(let w=0;w<d;w++)e.skipBits(r);e.skipBits(9),e.skipBits(3),e.readBits(1)&&e.skipBits(4),e.readBits(1)&&e.skipBits(24),e.readBits(1)&&e.skipBits(8*(e.readBits(10)+1));const f=e.readBits(5)+1,p=Lw[e.readBits(4)],m=e.readBits(8)+1;let g=0;if(e.readBits(1)&&(m>2&&e.skipBits(1),m>6&&e.skipBits(1),e.readBits(1))){const w=e.readBits(2)+1<<2;g=e.readBits(w)}return l===0||e.getBitsLeft()<0?a:{frameSize:o,asset:{sampleRate:p,numberOfChannels:m,sampleCount:Math.round(c*p/l),channelLayout:g,pcmResolution:f}}},Iw=s=>{const e=new Uint8Array(Tw),t=Ht(e);t.setUint32(0,s.sampleRate),t.setUint32(4,s.bitRate),t.setUint32(8,s.bitRate),e[12]=s.pcmResolution;const i=s.core&&!s.hasExtensions?1:0,n=new je(e);return n.seekToByte(13),n.writeBits(2,Math.max(Rw.indexOf(s.sampleCount),0)),n.writeBits(5,i),n.writeBits(1,s.core?.lfePresent?1:0),n.writeBits(6,s.core?.amode??0),n.writeBits(14,s.core?s.core.frameSize-1:0),n.writeBits(1,0),n.writeBits(3,0),n.writeBits(16,s.channelLayout),n.writeBits(1,0),n.writeBits(1,0),n.writeBits(1,0),n.writeBits(5,0),e};const ss=["avc","hevc","vp9","av1","vp8","prores"],Lt=["pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be","pcm-u8","pcm-s8","ulaw","alaw"],vo=["aac","opus","mp3","vorbis","flac","ac3","eac3","dts"],Vs=[...vo,...Lt],ci=["webvtt"],io=[{maxMacroblocks:99,maxBitrate:64e3,maxDpbMbs:396,level:10},{maxMacroblocks:396,maxBitrate:192e3,maxDpbMbs:900,level:11},{maxMacroblocks:396,maxBitrate:384e3,maxDpbMbs:2376,level:12},{maxMacroblocks:396,maxBitrate:768e3,maxDpbMbs:2376,level:13},{maxMacroblocks:396,maxBitrate:2e6,maxDpbMbs:2376,level:20},{maxMacroblocks:792,maxBitrate:4e6,maxDpbMbs:4752,level:21},{maxMacroblocks:1620,maxBitrate:4e6,maxDpbMbs:8100,level:22},{maxMacroblocks:1620,maxBitrate:1e7,maxDpbMbs:8100,level:30},{maxMacroblocks:3600,maxBitrate:14e6,maxDpbMbs:18e3,level:31},{maxMacroblocks:5120,maxBitrate:2e7,maxDpbMbs:20480,level:32},{maxMacroblocks:8192,maxBitrate:2e7,maxDpbMbs:32768,level:40},{maxMacroblocks:8192,maxBitrate:5e7,maxDpbMbs:32768,level:41},{maxMacroblocks:8704,maxBitrate:5e7,maxDpbMbs:34816,level:42},{maxMacroblocks:22080,maxBitrate:135e6,maxDpbMbs:110400,level:50},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:51},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:52},{maxMacroblocks:139264,maxBitrate:24e7,maxDpbMbs:696320,level:60},{maxMacroblocks:139264,maxBitrate:48e7,maxDpbMbs:696320,level:61},{maxMacroblocks:139264,maxBitrate:8e8,maxDpbMbs:696320,level:62}],id=[{maxPictureSize:36864,maxBitrate:128e3,tier:"L",level:30},{maxPictureSize:122880,maxBitrate:15e5,tier:"L",level:60},{maxPictureSize:245760,maxBitrate:3e6,tier:"L",level:63},{maxPictureSize:552960,maxBitrate:6e6,tier:"L",level:90},{maxPictureSize:983040,maxBitrate:1e7,tier:"L",level:93},{maxPictureSize:2228224,maxBitrate:12e6,tier:"L",level:120},{maxPictureSize:2228224,maxBitrate:3e7,tier:"H",level:120},{maxPictureSize:2228224,maxBitrate:2e7,tier:"L",level:123},{maxPictureSize:2228224,maxBitrate:5e7,tier:"H",level:123},{maxPictureSize:8912896,maxBitrate:25e6,tier:"L",level:150},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:150},{maxPictureSize:8912896,maxBitrate:4e7,tier:"L",level:153},{maxPictureSize:8912896,maxBitrate:16e7,tier:"H",level:153},{maxPictureSize:8912896,maxBitrate:6e7,tier:"L",level:156},{maxPictureSize:8912896,maxBitrate:24e7,tier:"H",level:156},{maxPictureSize:35651584,maxBitrate:6e7,tier:"L",level:180},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:180},{maxPictureSize:35651584,maxBitrate:12e7,tier:"L",level:183},{maxPictureSize:35651584,maxBitrate:48e7,tier:"H",level:183},{maxPictureSize:35651584,maxBitrate:24e7,tier:"L",level:186},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:186}],Rs=[{maxPictureSize:36864,maxBitrate:2e5,level:10},{maxPictureSize:73728,maxBitrate:8e5,level:11},{maxPictureSize:122880,maxBitrate:18e5,level:20},{maxPictureSize:245760,maxBitrate:36e5,level:21},{maxPictureSize:552960,maxBitrate:72e5,level:30},{maxPictureSize:983040,maxBitrate:12e6,level:31},{maxPictureSize:2228224,maxBitrate:18e6,level:40},{maxPictureSize:2228224,maxBitrate:3e7,level:41},{maxPictureSize:8912896,maxBitrate:6e7,level:50},{maxPictureSize:8912896,maxBitrate:12e7,level:51},{maxPictureSize:8912896,maxBitrate:18e7,level:52},{maxPictureSize:35651584,maxBitrate:18e7,level:60},{maxPictureSize:35651584,maxBitrate:24e7,level:61},{maxPictureSize:35651584,maxBitrate:48e7,level:62}],nd=[{maxPictureSize:147456,maxBitrate:15e5,tier:"M",level:0},{maxPictureSize:278784,maxBitrate:3e6,tier:"M",level:1},{maxPictureSize:665856,maxBitrate:6e6,tier:"M",level:4},{maxPictureSize:1065024,maxBitrate:1e7,tier:"M",level:5},{maxPictureSize:2359296,maxBitrate:12e6,tier:"M",level:8},{maxPictureSize:2359296,maxBitrate:3e7,tier:"H",level:8},{maxPictureSize:2359296,maxBitrate:2e7,tier:"M",level:9},{maxPictureSize:2359296,maxBitrate:5e7,tier:"H",level:9},{maxPictureSize:8912896,maxBitrate:3e7,tier:"M",level:12},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:12},{maxPictureSize:8912896,maxBitrate:4e7,tier:"M",level:13},{maxPictureSize:8912896,maxBitrate:16e7,tier:"H",level:13},{maxPictureSize:8912896,maxBitrate:6e7,tier:"M",level:14},{maxPictureSize:8912896,maxBitrate:24e7,tier:"H",level:14},{maxPictureSize:35651584,maxBitrate:6e7,tier:"M",level:15},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:15},{maxPictureSize:35651584,maxBitrate:6e7,tier:"M",level:16},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:16},{maxPictureSize:35651584,maxBitrate:1e8,tier:"M",level:17},{maxPictureSize:35651584,maxBitrate:48e7,tier:"H",level:17},{maxPictureSize:35651584,maxBitrate:16e7,tier:"M",level:18},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:18},{maxPictureSize:35651584,maxBitrate:16e7,tier:"M",level:19},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:19}],rd=".01.01.01.01.00",od=".0.110.01.01.01.0",Tn=["ap4x","ap4h","apch","apcn","apcs","apco"],wl=["dtsc","dtsh","dtsl","dtse"],Dw=[{fourCc:"apco",bitrate:45e6,alpha:!1},{fourCc:"apcs",bitrate:102e6,alpha:!1},{fourCc:"apcn",bitrate:147e6,alpha:!1},{fourCc:"apch",bitrate:22e7,alpha:!1},{fourCc:"ap4h",bitrate:33e7,alpha:!0},{fourCc:"ap4x",bitrate:5e8,alpha:!0}],Vw=(s,e,t,i,n)=>{if(s==="avc"){const r=go(),o=r?66:100,a=Math.ceil(e/16)*Math.ceil(t/16),l=io.find(f=>a<=f.maxMacroblocks&&i<=f.maxBitrate)??kt(io),c=l?l.level:0,h=o.toString(16).padStart(2,"0"),d=r?"40":"00",u=c.toString(16).padStart(2,"0");return`avc1.${h}${d}${u}`}else if(s==="hevc"){const l=e*t,c=id.find(d=>l<=d.maxPictureSize&&i<=d.maxBitrate)??kt(id);return`hev1.1.6.${c.tier}${c.level}.B0`}else{if(s==="vp8")return"vp8";if(s==="vp9"){const o=e*t;return`vp09.00.${(Rs.find(c=>o<=c.maxPictureSize&&i<=c.maxBitrate)??kt(Rs)).level.toString().padStart(2,"0")}.08`}else if(s==="av1"){const o=e*t,a=nd.find(h=>o<=h.maxPictureSize&&i<=h.maxBitrate)??kt(nd);return`av01.0.${a.level.toString().padStart(2,"0")}${a.tier}.08`}else if(s==="prores"){const o=Math.pow(e*t/2073600,.95),a=Dw.filter(h=>h.alpha===n);let l=a[0].fourCc,c=1/0;for(const{fourCc:h,bitrate:d}of a){const u=Math.abs(d*o-i);u<c&&(c=u,l=h)}return l}else Gt(s)}throw new TypeError(`Unhandled codec '${String(s)}'.`)},Nw=s=>{const e=s.split("."),t=Number(e[1]),i=Number(e[2]),n=Number(e[3]),r=e[4]?Number(e[4]):1;return[1,1,t,2,1,i,3,1,n,4,1,r]},U0=s=>{const e=s.split("."),n=(1<<7)+1,r=Number(e[1]),o=e[2],a=Number(o.slice(0,-1)),l=(r<<5)+a,c=o.slice(-1)==="H"?1:0,h=Number(e[3]),d=h===8?0:1,u=h===12?1:0,f=e[4]?Number(e[4]):0,p=e[5]?Number(e[5][0]):1,m=e[5]?Number(e[5][1]):1,g=e[5]?Number(e[5][2]):0,w=(c<<7)+(d<<6)+(u<<5)+(f<<4)+(p<<3)+(m<<2)+g;return[n,l,w,0]},Ww=s=>{const{codec:e,codecDescription:t,colorSpace:i,avcCodecInfo:n,hevcCodecInfo:r,vp9CodecInfo:o,av1CodecInfo:a,proresFormat:l}=s;if(e==="avc"){if(S(s.avcType!==null),n){const c=new Uint8Array([n.avcProfileIndication,n.profileCompatibility,n.avcLevelIndication]);return`avc${s.avcType}.${Wh(c)}`}if(!t||t.byteLength<4)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${s.avcType}.${Wh(t.subarray(1,4))}`}else if(e==="hevc"){let c,h,d,u,f,p;if(r)c=r.generalProfileSpace,h=r.generalProfileIdc,d=Hh(r.generalProfileCompatibilityFlags),u=r.generalTierFlag,f=r.generalLevelIdc,p=[...r.generalConstraintIndicatorFlags];else{if(!t||t.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");const g=Ht(t),w=g.getUint8(1);c=w>>6&3,h=w&31,d=Hh(g.getUint32(2)),u=w>>5&1,f=g.getUint8(12),p=[];for(let b=0;b<6;b++)p.push(g.getUint8(6+b))}let m="hev1.";for(m+=["","A","B","C"][c]+h,m+=".",m+=d.toString(16).toUpperCase(),m+=".",m+=u===0?"L":"H",m+=f;p.length>0&&p[p.length-1]===0;)p.pop();return p.length>0&&(m+=".",m+=p.map(g=>g.toString(16).toUpperCase()).join(".")),m}else{if(e==="vp8")return"vp8";if(e==="vp9"){if(!o){const b=s.width*s.height;let y=kt(Rs).level;for(const C of Rs)if(b<=C.maxPictureSize){y=C.level;break}return`vp09.00.${y.toString().padStart(2,"0")}.08`}const c=o.profile.toString().padStart(2,"0"),h=o.level.toString().padStart(2,"0"),d=o.bitDepth.toString().padStart(2,"0"),u=o.chromaSubsampling.toString().padStart(2,"0"),f=o.colourPrimaries.toString().padStart(2,"0"),p=o.transferCharacteristics.toString().padStart(2,"0"),m=o.matrixCoefficients.toString().padStart(2,"0"),g=o.videoFullRangeFlag.toString().padStart(2,"0");let w=`vp09.${c}.${h}.${d}.${u}`;return w+=`.${f}.${p}.${m}.${g}`,w.endsWith(rd)&&(w=w.slice(0,-rd.length)),w}else if(e==="av1"){if(!a){const C=s.width*s.height;let _=kt(Rs).level;for(const x of Rs)if(C<=x.maxPictureSize){_=x.level;break}return`av01.0.${_.toString().padStart(2,"0")}M.08`}const c=a.profile,h=a.level.toString().padStart(2,"0"),d=a.tier?"H":"M",u=a.bitDepth.toString().padStart(2,"0"),f=a.monochrome?"1":"0",p=100*a.chromaSubsamplingX+10*a.chromaSubsamplingY+1*(a.chromaSubsamplingX&&a.chromaSubsamplingY?a.chromaSamplePosition:0);let m,g,w,b;mw(a)?(m=a.colourPrimaries,g=a.transferCharacteristics,w=a.matrixCoefficients,b=a.videoFullRangeFlag):(m=i?.primaries?di[i.primaries]:1,g=i?.transfer?ui[i.transfer]:1,w=i?.matrix?fi[i.matrix]:1,b=i?.fullRange?1:0);let y=`av01.${c}.${h}${d}.${u}`;return y+=`.${f}.${p.toString().padStart(3,"0")}`,y+=`.${m.toString().padStart(2,"0")}`,y+=`.${g.toString().padStart(2,"0")}`,y+=`.${w.toString().padStart(2,"0")}`,y+=`.${b}`,y.endsWith(od)&&(y=y.slice(0,-od.length)),y}else{if(e==="prores")return l??"apch";e!==null&&Gt(e)}}throw new TypeError(`Unhandled codec '${e}'.`)},Hw=(s,e,t)=>{if(s==="aac")return e>=2&&t<=24e3?"mp4a.40.29":t<=24e3?"mp4a.40.5":"mp4a.40.2";if(s==="mp3")return"mp3";if(s==="opus")return"opus";if(s==="vorbis")return"vorbis";if(s==="flac")return"flac";if(s==="ac3")return"ac-3";if(s==="eac3")return"ec-3";if(s==="dts")return"dtsc";if(Lt.includes(s))return s;throw new TypeError(`Unhandled codec '${s}'.`)},Uw=(s,e)=>{switch(s){case"aac":{if(!e.description)return 1024/e.sampleRate;const t=B0(Ke(e.description));if(t.coreSampleRate===null)throw new Error("Invalid AAC sampling frequency index.");return t.frameLength/t.coreSampleRate}case"opus":return .08;case"mp3":{const{sampleRate:t,numberOfChannels:i}=e,n=t>=32e3,r=n?1152:576,o=n?32e3:8e3,a=n?511:255,l=n?i===1?17:32:i===1?9:17,h=Math.floor(r/8*o/t)-X5-l;return(1+Math.ceil(a/h))*r/t}case"vorbis":{S(e.description);const t=Ke(e.description);let i=1,n=2;for(;n>0;)t[i++]<255&&n--;return(1<<(t[i+28]>>4))/2/e.sampleRate}case"ac3":case"eac3":return 256/e.sampleRate;case"dts":return 512/e.sampleRate;case"flac":case"pcm-s16":case"pcm-s16be":case"pcm-s24":case"pcm-s24be":case"pcm-s32":case"pcm-s32be":case"pcm-f32":case"pcm-f32be":case"pcm-f64":case"pcm-f64be":case"pcm-u8":case"pcm-s8":case"ulaw":case"alaw":return 0;default:Gt(s),S(!1)}},j0=48e3,q0=/^pcm-([usf])(\d+)(be)?$/,Ns=s=>{if(S(Lt.includes(s)),s==="ulaw")return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if(s==="alaw")return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};const e=q0.exec(s);S(e);let t;e[1]==="u"?t="unsigned":e[1]==="s"?t="signed":t="float";const i=Number(e[2])/8,n=e[3]!=="be",r=s==="pcm-u8"?2**7:0;return{dataType:t,sampleSize:i,littleEndian:n,silentValue:r}},yo=s=>s.startsWith("avc1")||s.startsWith("avc3")?"avc":s.startsWith("hev1")||s.startsWith("hvc1")?"hevc":s==="vp8"?"vp8":s.startsWith("vp09")?"vp9":s.startsWith("av01")?"av1":Tn.includes(s)?"prores":s==="mp3"||s==="mp4a.69"||s==="mp4a.6B"||s==="mp4a.6b"||s==="mp4a.40.34"?"mp3":s.startsWith("mp4a.40.")||s==="mp4a.67"?"aac":s==="opus"||s==="Opus"?"opus":s==="vorbis"?"vorbis":s==="flac"?"flac":s==="ac-3"||s==="ac3"?"ac3":s==="ec-3"||s==="eac3"?"eac3":wl.includes(s)?"dts":s==="ulaw"?"ulaw":s==="alaw"?"alaw":q0.test(s)?s:s==="webvtt"?"webvtt":null,jw=s=>s==="avc"?{avc:{format:"avc"}}:s==="hevc"?{hevc:{format:"hevc"}}:{},G0=s=>s==="aac"?{aac:{format:"aac"}}:s==="opus"?{opus:{format:"opus"}}:{},qw=["avc1","avc3","hev1","hvc1","vp8","vp09","av01",...Tn],Gw=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,Zw=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,Xw=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,Yw=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,Jl=(s,e)=>{if(!s)throw new TypeError("Video chunk metadata must be provided.");if(typeof s!="object")throw new TypeError("Video chunk metadata must be an object.");if(!s.decoderConfig)throw new TypeError("Video chunk metadata must include a decoder configuration.");if(typeof s.decoderConfig!="object")throw new TypeError("Video chunk metadata decoder configuration must be an object.");if(typeof s.decoderConfig.codec!="string")throw new TypeError("Video chunk metadata decoder configuration must specify a codec string.");if(!qw.some(t=>s.decoderConfig.codec.startsWith(t)))throw new TypeError("Video chunk metadata decoder configuration codec string must be a valid video codec string as specified in the Mediabunny Codec Registry.");if(!Number.isInteger(s.decoderConfig.codedWidth)||s.decoderConfig.codedWidth<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).");if(!Number.isInteger(s.decoderConfig.codedHeight)||s.decoderConfig.codedHeight<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).");if(s.decoderConfig.displayAspectWidth!==void 0&&(!Number.isInteger(s.decoderConfig.displayAspectWidth)||s.decoderConfig.displayAspectWidth<=0))throw new TypeError("Video chunk metadata decoder configuration displayAspectWidth, when defined, must be a positive integer.");if(s.decoderConfig.displayAspectHeight!==void 0&&(!Number.isInteger(s.decoderConfig.displayAspectHeight)||s.decoderConfig.displayAspectHeight<=0))throw new TypeError("Video chunk metadata decoder configuration displayAspectHeight, when defined, must be a positive integer.");if(s.decoderConfig.displayAspectWidth!==void 0!=(s.decoderConfig.displayAspectHeight!==void 0))throw new TypeError("Video chunk metadata decoder configuration must specify both displayAspectWidth and displayAspectHeight, or neither.");if(s.decoderConfig.description!==void 0&&!mo(s.decoderConfig.description))throw new TypeError("Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(s.decoderConfig.colorSpace!==void 0){const{colorSpace:t}=s.decoderConfig;if(typeof t!="object")throw new TypeError("Video chunk metadata decoder configuration colorSpace, when provided, must be an object.");const i=Object.keys(di);if(t.primaries!=null&&!i.includes(t.primaries))throw new TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${i.join(", ")}.`);const n=Object.keys(ui);if(t.transfer!=null&&!n.includes(t.transfer))throw new TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${n.join(", ")}.`);const r=Object.keys(fi);if(t.matrix!=null&&!r.includes(t.matrix))throw new TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${r.join(", ")}.`);if(t.fullRange!=null&&typeof t.fullRange!="boolean")throw new TypeError("Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.")}if(s.decoderConfig.codec.startsWith("avc1")||s.decoderConfig.codec.startsWith("avc3")){if(!Gw.test(s.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for AVC must be a valid AVC codec string as specified in Section 3.4 of RFC 6381.")}else if(s.decoderConfig.codec.startsWith("hev1")||s.decoderConfig.codec.startsWith("hvc1")){if(!Zw.test(s.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for HEVC must be a valid HEVC codec string as specified in Section E.3 of ISO 14496-15.")}else if(s.decoderConfig.codec.startsWith("vp8")){if(s.decoderConfig.codec!=="vp8")throw new TypeError('Video chunk metadata decoder configuration codec string for VP8 must be "vp8".')}else if(s.decoderConfig.codec.startsWith("vp09")){if(!Xw.test(s.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for VP9 must be a valid VP9 codec string as specified in Section "Codecs Parameter String" of https://www.webmproject.org/vp9/mp4/.')}else if(s.decoderConfig.codec.startsWith("av01")){if(!Yw.test(s.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for AV1 must be a valid AV1 codec string as specified in Section "Codecs Parameter String" of https://aomediacodec.github.io/av1-isobmff/.')}else if(Tn.some(t=>s.decoderConfig.codec.startsWith(t))&&!Tn.some(t=>s.decoderConfig.codec===t))throw new TypeError(`Video chunk metadata decoder configuration codec string for ProRes must be one of the valid ProRes four-character codes: ${Tn.join(", ")}.`);if(e!==null&&yo(s.decoderConfig.codec)!==e)throw new TypeError(`Video chunk metadata decoder configuration codec string '${s.decoderConfig.codec}' does not fit to the track codec '${e}'.`)},Qw=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm","ac-3","ec-3","dts"],ec=(s,e)=>{if(!s)throw new TypeError("Audio chunk metadata must be provided.");if(typeof s!="object")throw new TypeError("Audio chunk metadata must be an object.");if(!s.decoderConfig)throw new TypeError("Audio chunk metadata must include a decoder configuration.");if(typeof s.decoderConfig!="object")throw new TypeError("Audio chunk metadata decoder configuration must be an object.");if(typeof s.decoderConfig.codec!="string")throw new TypeError("Audio chunk metadata decoder configuration must specify a codec string.");if(!Qw.some(t=>s.decoderConfig.codec.startsWith(t)))throw new TypeError("Audio chunk metadata decoder configuration codec string must be a valid audio codec string as specified in the Mediabunny Codec Registry.");if(!Number.isInteger(s.decoderConfig.sampleRate)||s.decoderConfig.sampleRate<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).");if(!Number.isInteger(s.decoderConfig.numberOfChannels)||s.decoderConfig.numberOfChannels<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).");if(s.decoderConfig.description!==void 0&&!mo(s.decoderConfig.description))throw new TypeError("Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(s.decoderConfig.codec.startsWith("mp4a")&&s.decoderConfig.codec!=="mp4a.69"&&s.decoderConfig.codec!=="mp4a.6B"&&s.decoderConfig.codec!=="mp4a.6b"){if(!["mp4a.40.2","mp4a.40.02","mp4a.40.5","mp4a.40.05","mp4a.40.29","mp4a.67"].includes(s.decoderConfig.codec))throw new TypeError("Audio chunk metadata decoder configuration codec string for AAC must be a valid AAC codec string as specified in https://www.w3.org/TR/webcodecs-aac-codec-registration/.")}else if(s.decoderConfig.codec.startsWith("mp3")||s.decoderConfig.codec.startsWith("mp4a")){if(s.decoderConfig.codec!=="mp3"&&s.decoderConfig.codec!=="mp4a.69"&&s.decoderConfig.codec!=="mp4a.6B"&&s.decoderConfig.codec!=="mp4a.6b")throw new TypeError('Audio chunk metadata decoder configuration codec string for MP3 must be "mp3", "mp4a.69" or "mp4a.6B".')}else if(s.decoderConfig.codec.startsWith("opus")){if(s.decoderConfig.codec!=="opus")throw new TypeError('Audio chunk metadata decoder configuration codec string for Opus must be "opus".');if(s.decoderConfig.description&&s.decoderConfig.description.byteLength<18)throw new TypeError("Audio chunk metadata decoder configuration description, when specified, is expected to be an Identification Header as specified in Section 5.1 of RFC 7845.")}else if(s.decoderConfig.codec.startsWith("vorbis")){if(s.decoderConfig.codec!=="vorbis")throw new TypeError('Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".');if(!s.decoderConfig.description)throw new TypeError("Audio chunk metadata decoder configuration for Vorbis must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-vorbis-codec-registration/.")}else if(s.decoderConfig.codec.startsWith("flac")){if(s.decoderConfig.codec!=="flac")throw new TypeError('Audio chunk metadata decoder configuration codec string for FLAC must be "flac".');if(!s.decoderConfig.description||s.decoderConfig.description.byteLength<42)throw new TypeError("Audio chunk metadata decoder configuration for FLAC must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-flac-codec-registration/.")}else if(s.decoderConfig.codec.startsWith("ac-3")||s.decoderConfig.codec.startsWith("ac3")){if(s.decoderConfig.codec!=="ac-3")throw new TypeError('Audio chunk metadata decoder configuration codec string for AC-3 must be "ac-3".')}else if(s.decoderConfig.codec.startsWith("ec-3")||s.decoderConfig.codec.startsWith("eac3")){if(s.decoderConfig.codec!=="ec-3")throw new TypeError('Audio chunk metadata decoder configuration codec string for EC-3 must be "ec-3".')}else if(s.decoderConfig.codec.startsWith("dts")){if(!wl.includes(s.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for DTS must be one of the following four-character codes: ${wl.join(", ")}.`)}else if((s.decoderConfig.codec.startsWith("pcm")||s.decoderConfig.codec.startsWith("ulaw")||s.decoderConfig.codec.startsWith("alaw"))&&!Lt.includes(s.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${Lt.join(", ")}).`);if(e!==null&&yo(s.decoderConfig.codec)!==e)throw new TypeError(`Audio chunk metadata decoder configuration codec string '${s.decoderConfig.codec}' does not fit to the track codec '${e}'.`)},Z0=s=>{if(!s)throw new TypeError("Subtitle metadata must be provided.");if(typeof s!="object")throw new TypeError("Subtitle metadata must be an object.");if(!s.config)throw new TypeError("Subtitle metadata must include a config object.");if(typeof s.config!="object")throw new TypeError("Subtitle metadata config must be an object.");if(typeof s.config.description!="string")throw new TypeError("Subtitle metadata config description must be a string.")};const ad=new Uint8Array(0);class ls{constructor(e,t,i,n,r=-1,o,a){if(this.data=e,this.type=t,this.timestamp=i,this.duration=n,this.sequenceNumber=r,e===ad&&o===void 0)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(o===void 0&&(o=e.byteLength),!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(t!=="key"&&t!=="delta")throw new TypeError('type must be either "key" or "delta".');if(!Number.isFinite(i))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(n)||n<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(r))throw new TypeError("sequenceNumber must be a number.");if(!Number.isInteger(o)||o<0)throw new TypeError("byteLength must be a non-negative integer.");if(a!==void 0&&(typeof a!="object"||!a))throw new TypeError("sideData, when provided, must be an object.");if(a?.alpha!==void 0&&!(a.alpha instanceof Uint8Array))throw new TypeError("sideData.alpha, when provided, must be a Uint8Array.");if(a?.alphaByteLength!==void 0&&(!Number.isInteger(a.alphaByteLength)||a.alphaByteLength<0))throw new TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=o,this.sideData=a??{},this.sideData.alpha&&this.sideData.alphaByteLength===void 0&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===ad}get microsecondTimestamp(){return Math.trunc(Ls*this.timestamp)}get microsecondDuration(){return Math.trunc(Ls*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("EncodedVideoChunk is not available in this environment.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw new TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("EncodedVideoChunk is not available in this environment.");return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if(typeof EncodedAudioChunk>"u")throw new Error("EncodedAudioChunk is not available in this environment.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(e,t){if(!(e instanceof EncodedVideoChunk||e instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");const i=new Uint8Array(e.byteLength);return e.copyTo(i),new ls(i,e.type,e.timestamp/1e6,(e.duration??0)/1e6,void 0,void 0,t)}clone(e){if(e!==void 0&&(typeof e!="object"||e===null))throw new TypeError("options, when provided, must be an object.");if(e?.data!==void 0&&!(e.data instanceof Uint8Array))throw new TypeError("options.data, when provided, must be a Uint8Array.");if(e?.type!==void 0&&e.type!=="key"&&e.type!=="delta")throw new TypeError('options.type, when provided, must be either "key" or "delta".');if(e?.timestamp!==void 0&&!Number.isFinite(e.timestamp))throw new TypeError("options.timestamp, when provided, must be a number.");if(e?.duration!==void 0&&!Number.isFinite(e.duration))throw new TypeError("options.duration, when provided, must be a number.");if(e?.sequenceNumber!==void 0&&!Number.isFinite(e.sequenceNumber))throw new TypeError("options.sequenceNumber, when provided, must be a number.");if(e?.sideData!==void 0&&(typeof e.sideData!="object"||e.sideData===null))throw new TypeError("options.sideData, when provided, must be an object.");return new ls(e?.data??this.data,e?.type??this.type,e?.timestamp??this.timestamp,e?.duration??this.duration,e?.sequenceNumber??this.sequenceNumber,this.byteLength,e?.sideData??this.sideData)}}const Kw=s=>{let t=(s.hasVideo?"video/":s.hasAudio?"audio/":"application/")+(s.isQuickTime?"quicktime":"mp4");if(s.codecStrings.length>0){const i=[...new Set(s.codecStrings)];t+=`; codecs="${i.join(", ")}"`}return t};const va=8,ld=16,ya=s=>{let e=0;for(let t=0;t<4;t++){e<<=7;const i=ei(s);if(e|=i&127,(i&128)===0)break}return e},Jw=s=>{if(ei(s)!==3)throw new Error("Invalid esds: expected ES_Descriptor.");ya(s),s.skip(2);const t=ei(s),i=(t&128)!==0,n=(t&64)!==0,r=(t&32)!==0;if(i&&s.skip(2),n){const d=ei(s);s.skip(d)}if(r&&s.skip(2),ei(s)!==4)throw new Error("Invalid esds: expected DecoderConfigDescriptor.");const a=ya(s),l=s.filePos,c=ei(s);s.skip(12);let h=null;if(a>s.filePos-l){if(ei(s)!==5)throw new Error("Invalid esds: expected DecoderSpecificInfo.");const u=ya(s);h=af(s,u)}return{objectTypeIndication:c,decoderSpecificInfo:h}};class yn{constructor(e){this.value=e}}class bl{constructor(e){this.value=e}}class X0{constructor(e){this.value=e}}class As{constructor(e){this.value=e}}var E;(function(s){s[s.EBML=440786851]="EBML",s[s.EBMLVersion=17030]="EBMLVersion",s[s.EBMLReadVersion=17143]="EBMLReadVersion",s[s.EBMLMaxIDLength=17138]="EBMLMaxIDLength",s[s.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",s[s.DocType=17026]="DocType",s[s.DocTypeVersion=17031]="DocTypeVersion",s[s.DocTypeReadVersion=17029]="DocTypeReadVersion",s[s.Void=236]="Void",s[s.Segment=408125543]="Segment",s[s.SeekHead=290298740]="SeekHead",s[s.Seek=19899]="Seek",s[s.SeekID=21419]="SeekID",s[s.SeekPosition=21420]="SeekPosition",s[s.Duration=17545]="Duration",s[s.Info=357149030]="Info",s[s.TimestampScale=2807729]="TimestampScale",s[s.MuxingApp=19840]="MuxingApp",s[s.WritingApp=22337]="WritingApp",s[s.Tracks=374648427]="Tracks",s[s.TrackEntry=174]="TrackEntry",s[s.TrackNumber=215]="TrackNumber",s[s.TrackUID=29637]="TrackUID",s[s.TrackType=131]="TrackType",s[s.FlagEnabled=185]="FlagEnabled",s[s.FlagDefault=136]="FlagDefault",s[s.FlagForced=21930]="FlagForced",s[s.FlagOriginal=21934]="FlagOriginal",s[s.FlagHearingImpaired=21931]="FlagHearingImpaired",s[s.FlagVisualImpaired=21932]="FlagVisualImpaired",s[s.FlagCommentary=21935]="FlagCommentary",s[s.FlagLacing=156]="FlagLacing",s[s.Name=21358]="Name",s[s.Language=2274716]="Language",s[s.LanguageBCP47=2274717]="LanguageBCP47",s[s.CodecID=134]="CodecID",s[s.CodecPrivate=25506]="CodecPrivate",s[s.CodecDelay=22186]="CodecDelay",s[s.SeekPreRoll=22203]="SeekPreRoll",s[s.DefaultDuration=2352003]="DefaultDuration",s[s.Video=224]="Video",s[s.PixelWidth=176]="PixelWidth",s[s.PixelHeight=186]="PixelHeight",s[s.DisplayWidth=21680]="DisplayWidth",s[s.DisplayHeight=21690]="DisplayHeight",s[s.DisplayUnit=21682]="DisplayUnit",s[s.AlphaMode=21440]="AlphaMode",s[s.Audio=225]="Audio",s[s.SamplingFrequency=181]="SamplingFrequency",s[s.Channels=159]="Channels",s[s.BitDepth=25188]="BitDepth",s[s.SimpleBlock=163]="SimpleBlock",s[s.BlockGroup=160]="BlockGroup",s[s.Block=161]="Block",s[s.BlockAdditions=30113]="BlockAdditions",s[s.BlockMore=166]="BlockMore",s[s.BlockAdditional=165]="BlockAdditional",s[s.BlockAddID=238]="BlockAddID",s[s.BlockDuration=155]="BlockDuration",s[s.ReferenceBlock=251]="ReferenceBlock",s[s.Cluster=524531317]="Cluster",s[s.Timestamp=231]="Timestamp",s[s.Cues=475249515]="Cues",s[s.CuePoint=187]="CuePoint",s[s.CueTime=179]="CueTime",s[s.CueTrackPositions=183]="CueTrackPositions",s[s.CueTrack=247]="CueTrack",s[s.CueClusterPosition=241]="CueClusterPosition",s[s.CueRelativePosition=240]="CueRelativePosition",s[s.Colour=21936]="Colour",s[s.MatrixCoefficients=21937]="MatrixCoefficients",s[s.TransferCharacteristics=21946]="TransferCharacteristics",s[s.Primaries=21947]="Primaries",s[s.Range=21945]="Range",s[s.Projection=30320]="Projection",s[s.ProjectionType=30321]="ProjectionType",s[s.ProjectionPoseYaw=30323]="ProjectionPoseYaw",s[s.ProjectionPosePitch=30324]="ProjectionPosePitch",s[s.ProjectionPoseRoll=30325]="ProjectionPoseRoll",s[s.Attachments=423732329]="Attachments",s[s.AttachedFile=24999]="AttachedFile",s[s.FileDescription=18046]="FileDescription",s[s.FileName=18030]="FileName",s[s.FileMediaType=18016]="FileMediaType",s[s.FileData=18012]="FileData",s[s.FileUID=18094]="FileUID",s[s.Chapters=272869232]="Chapters",s[s.Tags=307544935]="Tags",s[s.Tag=29555]="Tag",s[s.Targets=25536]="Targets",s[s.TargetTypeValue=26826]="TargetTypeValue",s[s.TargetType=25546]="TargetType",s[s.TagTrackUID=25541]="TagTrackUID",s[s.TagEditionUID=25545]="TagEditionUID",s[s.TagChapterUID=25540]="TagChapterUID",s[s.TagAttachmentUID=25542]="TagAttachmentUID",s[s.SimpleTag=26568]="SimpleTag",s[s.TagName=17827]="TagName",s[s.TagLanguage=17530]="TagLanguage",s[s.TagString=17543]="TagString",s[s.TagBinary=17541]="TagBinary",s[s.ContentEncodings=28032]="ContentEncodings",s[s.ContentEncoding=25152]="ContentEncoding",s[s.ContentEncodingOrder=20529]="ContentEncodingOrder",s[s.ContentEncodingScope=20530]="ContentEncodingScope",s[s.ContentCompression=20532]="ContentCompression",s[s.ContentCompAlgo=16980]="ContentCompAlgo",s[s.ContentCompSettings=16981]="ContentCompSettings",s[s.ContentEncryption=20533]="ContentEncryption"})(E||(E={}));E.EBML,E.Segment;E.SeekHead,E.Info,E.Cluster,E.Tracks,E.Cues,E.Attachments,E.Chapters,E.Tags;const cd=s=>s<256?1:s<65536?2:s<1<<24?3:s<2**32?4:s<2**40?5:6,hd=s=>s<1n<<8n?1:s<1n<<16n?2:s<1n<<24n?3:s<1n<<32n?4:s<1n<<40n?5:s<1n<<48n?6:s<1n<<56n?7:8,dd=s=>s>=-64&&s<64?1:s>=-8192&&s<8192?2:s>=-1048576&&s<1<<20?3:s>=-134217728&&s<1<<27?4:s>=-17179869184&&s<2**34?5:6,eb=s=>{if(s<127)return 1;if(s<16383)return 2;if(s<(1<<21)-1)return 3;if(s<(1<<28)-1)return 4;if(s<2**35-1)return 5;if(s<2**42-1)return 6;throw new Error("EBML varint size not supported "+s)};class tb{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap,this.dataOffsets=new WeakMap}writeByte(e){this.helperView.setUint8(0,e),this.writer.write(this.helper.subarray(0,1))}writeFloat32(e){this.helperView.setFloat32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeFloat64(e){this.helperView.setFloat64(0,e,!1),this.writer.write(this.helper)}writeUnsignedInt(e,t=cd(e)){let i=0;switch(t){case 6:this.helperView.setUint8(i++,e/2**40|0);case 5:this.helperView.setUint8(i++,e/2**32|0);case 4:this.helperView.setUint8(i++,e>>24);case 3:this.helperView.setUint8(i++,e>>16);case 2:this.helperView.setUint8(i++,e>>8);case 1:this.helperView.setUint8(i++,e);break;default:throw new Error("Bad unsigned int size "+t)}this.writer.write(this.helper.subarray(0,i))}writeUnsignedBigInt(e,t=hd(e)){let i=0;for(let n=t-1;n>=0;n--)this.helperView.setUint8(i++,Number(e>>BigInt(n*8)&0xffn));this.writer.write(this.helper.subarray(0,i))}writeSignedInt(e,t=dd(e)){e<0&&(e+=2**(t*8)),this.writeUnsignedInt(e,t)}writeVarInt(e,t=eb(e)){let i=0;switch(t){case 1:this.helperView.setUint8(i++,128|e);break;case 2:this.helperView.setUint8(i++,64|e>>8),this.helperView.setUint8(i++,e);break;case 3:this.helperView.setUint8(i++,32|e>>16),this.helperView.setUint8(i++,e>>8),this.helperView.setUint8(i++,e);break;case 4:this.helperView.setUint8(i++,16|e>>24),this.helperView.setUint8(i++,e>>16),this.helperView.setUint8(i++,e>>8),this.helperView.setUint8(i++,e);break;case 5:this.helperView.setUint8(i++,8|e/2**32&7),this.helperView.setUint8(i++,e>>24),this.helperView.setUint8(i++,e>>16),this.helperView.setUint8(i++,e>>8),this.helperView.setUint8(i++,e);break;case 6:this.helperView.setUint8(i++,4|e/2**40&3),this.helperView.setUint8(i++,e/2**32|0),this.helperView.setUint8(i++,e>>24),this.helperView.setUint8(i++,e>>16),this.helperView.setUint8(i++,e>>8),this.helperView.setUint8(i++,e);break;default:throw new Error("Bad EBML varint size "+t)}this.writer.write(this.helper.subarray(0,i))}writeAsciiString(e){this.writer.write(new Uint8Array(e.split("").map(t=>t.charCodeAt(0))))}writeEBML(e){if(e!==null)if(e instanceof Uint8Array)this.writer.write(e);else if(Array.isArray(e))for(const t of e)this.writeEBML(t);else if(this.offsets.set(e,this.writer.getPos()),this.writeUnsignedInt(e.id),Array.isArray(e.data)){const t=this.writer.getPos(),i=e.size===-1?1:e.size??4;e.size===-1?this.writeByte(255):this.writer.seek(this.writer.getPos()+i);const n=this.writer.getPos();if(this.dataOffsets.set(e,n),this.writeEBML(e.data),e.size!==-1){const r=this.writer.getPos()-n,o=this.writer.getPos();this.writer.seek(t),this.writeVarInt(r,i),this.writer.seek(o)}}else if(typeof e.data=="number"){const t=e.size??cd(e.data);this.writeVarInt(t),this.writeUnsignedInt(e.data,t)}else if(typeof e.data=="bigint"){const t=e.size??hd(e.data);this.writeVarInt(t),this.writeUnsignedBigInt(e.data,t)}else if(typeof e.data=="string")this.writeVarInt(e.data.length),this.writeAsciiString(e.data);else if(e.data instanceof Uint8Array)this.writeVarInt(e.data.byteLength,e.size),this.writer.write(e.data);else if(e.data instanceof yn)this.writeVarInt(4),this.writeFloat32(e.data.value);else if(e.data instanceof bl)this.writeVarInt(8),this.writeFloat64(e.data.value);else if(e.data instanceof X0){const t=e.size??dd(e.data.value);this.writeVarInt(t),this.writeSignedInt(e.data.value,t)}else if(e.data instanceof As){const t=bt.encode(e.data.value);this.writeVarInt(t.length),this.writer.write(t)}else Gt(e.data)}}const sb={avc:"V_MPEG4/ISO/AVC",hevc:"V_MPEGH/ISO/HEVC",vp8:"V_VP8",vp9:"V_VP9",av1:"V_AV1",prores:"V_PRORES",aac:"A_AAC",mp3:"A_MPEG/L3",opus:"A_OPUS",vorbis:"A_VORBIS",flac:"A_FLAC",ac3:"A_AC3",eac3:"A_EAC3",dts:"A_DTS","pcm-u8":"A_PCM/INT/LIT","pcm-s16":"A_PCM/INT/LIT","pcm-s16be":"A_PCM/INT/BIG","pcm-s24":"A_PCM/INT/LIT","pcm-s24be":"A_PCM/INT/BIG","pcm-s32":"A_PCM/INT/LIT","pcm-s32be":"A_PCM/INT/BIG","pcm-f32":"A_PCM/FLOAT/IEEE","pcm-f64":"A_PCM/FLOAT/IEEE",webvtt:"S_TEXT/WEBVTT"};const ib=s=>{let t=(s.hasVideo?"video/":s.hasAudio?"audio/":"application/")+(s.isWebM?"webm":"x-matroska");if(s.codecStrings.length>0){const i=[...new Set(s.codecStrings.filter(Boolean))];t+=`; codecs="${i.join(", ")}"`}return t};const no=7,Y0=9,ro=s=>{const e=s.filePos;if(s.remainingLength<no)return null;const t=af(s,no),i=new je(t);if(i.readBits(12)!==4095||(i.skipBits(1),i.readBits(2)!==0))return null;const o=i.readBits(1),a=i.readBits(2)+1,l=i.readBits(4);if(l>=Ni.length)return null;i.skipBits(1);const c=i.readBits(3);if(c===0)throw new Error("ADTS frames with channel configuration 0 are not supported.");i.skipBits(1),i.skipBits(1),i.skipBits(1),i.skipBits(1);const h=i.readBits(13);i.skipBits(11);const d=i.readBits(2)+1;if(d!==1)throw new Error("ADTS frames with more than one AAC frame are not supported.");let u=null;if(o===0){if(s.remainingLength<2)return null;u=kb(s)}return h<s.filePos-e?null:{objectType:a,samplingFrequencyIndex:l,channelConfiguration:c,frameLength:h,numberOfAacFrames:d,crcCheck:u,startPos:e}};var nb=function(s,e,t){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var i,n;if(t){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");i=e[Symbol.asyncDispose]}if(i===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");i=e[Symbol.dispose],t&&(n=i)}if(typeof i!="function")throw new TypeError("Object not disposable.");n&&(i=function(){try{n.call(this)}catch(r){return Promise.reject(r)}}),s.stack.push({value:e,dispose:i,async:t})}else t&&s.stack.push({async:!0});return e},rb=(function(s){return function(e){function t(o){e.error=e.hasError?new s(o,e.error,"An error was suppressed during disposal."):o,e.hasError=!0}var i,n=0;function r(){for(;i=e.stack.pop();)try{if(!i.async&&n===1)return n=0,e.stack.push(i),Promise.resolve().then(r);if(i.dispose){var o=i.dispose.call(i.value);if(i.async)return n|=2,Promise.resolve(o).then(r,function(a){return t(a),r()})}else n|=1}catch(a){t(a)}if(n===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return r()}})(typeof SuppressedError=="function"?SuppressedError:function(s,e,t){var i=new Error(t);return i.name="SuppressedError",i.error=s,i.suppressed=e,i});I5();let ud=-1/0,fd=-1/0,Pn=null;typeof FinalizationRegistry<"u"&&(Pn=new FinalizationRegistry(s=>{const e=performance.now();s.type==="video"?(e-ud>=1e3&&(Re._error("A VideoSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your VideoSamples as soon as you're done using them."),ud=e),typeof VideoFrame<"u"&&s.data instanceof VideoFrame&&s.data.close()):(e-fd>=1e3&&(Re._error("An AudioSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your AudioSamples as soon as you're done using them."),fd=e),typeof AudioData<"u"&&s.data instanceof AudioData&&s.data.close())}));class Ys{constructor(){this._referenceCount=0,this._lastAllocationBuffer=null}}const vl=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],ob=new Set(vl);class St{get codedWidth(){return this.visibleRect.width}get codedHeight(){return this.visibleRect.height}get displayWidth(){return this.rotation%180===0?this.squarePixelWidth:this.squarePixelHeight}get displayHeight(){return this.rotation%180===0?this.squarePixelHeight:this.squarePixelWidth}get microsecondTimestamp(){return Math.trunc(Ls*this.timestamp)}get microsecondDuration(){return Math.trunc(Ls*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor(e,t){if(this._closed=!1,e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e)){if(!t||typeof t!="object")throw new TypeError("init must be an object.");if(t.format===void 0||!ob.has(t.format))throw new TypeError("init.format must be one of: "+vl.join(", "));if(!Number.isInteger(t.codedWidth)||t.codedWidth<=0)throw new TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(t.codedHeight)||t.codedHeight<=0)throw new TypeError("init.codedHeight must be a positive integer.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(t.flip!==void 0&&typeof t.flip!="boolean")throw new TypeError("init.flip, when provided, must be a boolean.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(t.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(t.layout!==void 0){if(!Array.isArray(t.layout))throw new TypeError("init.layout, when provided, must be an array.");for(const r of t.layout){if(!r||typeof r!="object"||Array.isArray(r))throw new TypeError("Each entry in init.layout must be an object.");if(!Number.isInteger(r.offset)||r.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(r.stride)||r.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(t.visibleRect!==void 0&&ga(t.visibleRect,"init.visibleRect"),t.displayWidth!==void 0&&(!Number.isInteger(t.displayWidth)||t.displayWidth<=0))throw new TypeError("init.displayWidth, when provided, must be a positive integer.");if(t.displayHeight!==void 0&&(!Number.isInteger(t.displayHeight)||t.displayHeight<=0))throw new TypeError("init.displayHeight, when provided, must be a positive integer.");if(t.displayWidth!==void 0!=(t.displayHeight!==void 0))throw new TypeError("init.displayWidth and init.displayHeight must be either both provided or both omitted.");this.format=t.format,this.rotation=t.rotation??0,this.flip=t.flip??!1,this.timestamp=t.timestamp,this.duration=t.duration??0;const i=t.layout??cb(t.format,t.codedWidth,t.codedHeight);let n=t.colorSpace??null;n===null&&(this.format==="RGBA"||this.format==="RGBX"||this.format==="BGRA"||this.format==="BGRX"?n={primaries:"bt709",transfer:"iec61966-2-1",matrix:"rgb",fullRange:!0}:n={primaries:"bt709",transfer:"bt709",matrix:"bt709",fullRange:!1}),this.visibleRect={left:t.visibleRect?.left??0,top:t.visibleRect?.top??0,width:t.visibleRect?.width??t.codedWidth,height:t.visibleRect?.height??t.codedHeight},t.displayWidth!==void 0?(this.squarePixelWidth=this.rotation%180===0?t.displayWidth:t.displayHeight,this.squarePixelHeight=this.rotation%180===0?t.displayHeight:t.displayWidth):(this.squarePixelWidth=this.visibleRect.width,this.squarePixelHeight=this.visibleRect.height),this._data=t._doNotCopy?Ke(e):Ke(e).slice(),this._layout=i,this.colorSpace=new Ca(n)}else if(typeof VideoFrame<"u"&&e instanceof VideoFrame){if(t?.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(t?.flip!==void 0&&typeof t.flip!="boolean")throw new TypeError("init.flip, when provided, must be a boolean.");if(t?.timestamp!==void 0&&!Number.isFinite(t?.timestamp))throw new TypeError("init.timestamp, when provided, must be a number.");if(t?.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");t?.visibleRect!==void 0&&ga(t.visibleRect,"init.visibleRect"),this._data=e,this._layout=null,this.format=e.format,this.visibleRect={left:e.visibleRect?.x??0,top:e.visibleRect?.y??0,width:e.visibleRect?.width??e.codedWidth,height:e.visibleRect?.height??e.codedHeight},this.rotation=t?.rotation??0,this.flip=t?.flip??!1,this.squarePixelWidth=e.displayWidth,this.squarePixelHeight=e.displayHeight,this.timestamp=t?.timestamp??e.timestamp/1e6,this.duration=t?.duration??(e.duration??0)/1e6;const{primaries:i,transfer:n,matrix:r,fullRange:o}=e.colorSpace;this.colorSpace=new Ca({primaries:i!==null&&i in di?i:null,transfer:n!==null&&n in ui?n:null,matrix:r!==null&&r in fi?r:null,fullRange:o})}else if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof SVGImageElement<"u"&&e instanceof SVGImageElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap||typeof HTMLVideoElement<"u"&&e instanceof HTMLVideoElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas){if(!t||typeof t!="object")throw new TypeError("init must be an object.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(t.flip!==void 0&&typeof t.flip!="boolean")throw new TypeError("init.flip, when provided, must be a boolean.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(t.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(t.visibleRect!==void 0&&ga(t.visibleRect,"init.visibleRect"),typeof VideoFrame<"u")return new St(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*Ls),duration:Math.trunc((t.duration??0)*Ls)||void 0,visibleRect:t.visibleRect&&{x:t.visibleRect.left,y:t.visibleRect.top,width:t.visibleRect.width,height:t.visibleRect.height}}),t);let i=0,n=0;if("naturalWidth"in e?(i=e.naturalWidth,n=e.naturalHeight):"videoWidth"in e?(i=e.videoWidth,n=e.videoHeight):"width"in e&&(i=Number(e.width),n=Number(e.height)),!i||!n)throw new TypeError("Could not determine dimensions.");const r=t.visibleRect??{left:0,top:0,width:i,height:n},o=new OffscreenCanvas(r.width,r.height),a=o.getContext("2d",{alpha:En(),willReadFrequently:!0});if(!a)throw new Error("OffscreenCanvas must have support for the '2d' context in order to create a VideoSample from this data.");a.drawImage(e,-r.left,-r.top),this._data=o,this._layout=null,this.format="RGBX",this.visibleRect={left:0,top:0,width:r.width,height:r.height},this.squarePixelWidth=r.width,this.squarePixelHeight=r.height,this.rotation=t.rotation??0,this.flip=t.flip??!1,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=new Ca({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else if(e instanceof Ys){if(!t||typeof t!="object")throw new TypeError("init must be an object.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(t.flip!==void 0&&typeof t.flip!="boolean")throw new TypeError("init.flip, when provided, must be a boolean.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(t.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(this._data=e,e._referenceCount++,this.format=e.getFormat(),this.format!==null&&!vl.includes(this.format))throw new TypeError("getFormat() must return a VideoSamplePixelFormat or null.");if(this.visibleRect={left:0,top:0,width:e.getCodedWidth(),height:e.getCodedHeight()},!Number.isInteger(this.visibleRect.width)||this.visibleRect.width<=0)throw new TypeError("getCodedWidth() must return a positive integer.");if(!Number.isInteger(this.visibleRect.height)||this.visibleRect.height<=0)throw new TypeError("getCodedHeight() must return a positive integer.");if(this.squarePixelWidth=e.getSquarePixelWidth(),!Number.isInteger(this.squarePixelWidth)||this.squarePixelWidth<=0)throw new TypeError("getSquarePixelWidth() must return a positive integer.");if(this.squarePixelHeight=e.getSquarePixelHeight(),!Number.isInteger(this.squarePixelHeight)||this.squarePixelHeight<=0)throw new TypeError("getSquarePixelHeight() must return a positive integer.");this.rotation=t.rotation??0,this.flip=t.flip??!1,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=e.getColorSpace()}else throw new TypeError("Invalid data type: Must be a BufferSource, CanvasImageSource, or VideoSampleResource.");this.encodeOptions=t?.encodeOptions??{},this.pixelAspectRatio=Xl({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),Pn?.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return S(this._data!==null),this._data instanceof Ys?new St(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,flip:this.flip,encodeOptions:this.encodeOptions}):ln(this._data)?new St(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,flip:this.flip,encodeOptions:this.encodeOptions}):this._data instanceof Uint8Array?(S(this._layout),new St(this._data,{format:this.format,layout:this._layout,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,flip:this.flip,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions,_doNotCopy:!0})):new St(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,flip:this.flip,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions})}close(){this._closed||(Pn?.unregister(this),this._data instanceof Ys?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):ln(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(wd(e),this._closed)throw new Error("VideoSample is closed.");if((e.format??this.format)==null)throw new Error("Cannot get allocation size when format is null.");return ln(this._data)?this._data.allocationSize(e):bd(this,e).allocationSize}async copyTo(e,t={}){if(!mo(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(wd(t),this._closed)throw new Error("VideoSample is closed.");if((t.format??this.format)==null)throw new Error("Cannot copy video sample data when format is null.");if(S(this._data!==null),ln(this._data))return this._data.copyTo(e,t);if(t.format&&!["RGBA","RGBX","BGRA","BGRX"].includes(this.format)&&["RGBA","RGBX","BGRA","BGRX"].includes(t.format))if(this._data instanceof Ys){const c={stack:[],error:void 0,hasError:!1};try{const h=nb(c,await this._data.toRgbSample({timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,flip:this.flip},t.colorSpace??"srgb"),!1);if(!(h instanceof St))throw new TypeError("toRgbSample() must return a VideoSample.");if(!["RGBA","RGBX","BGRA","BGRX"].includes(h.format))throw new Error(`Sample returned by toRgbSample was expected to have an RGB format, got '${h.format}' instead.`);return await h.copyTo(e,t)}catch(h){c.error=h,c.hasError=!0}finally{rb(c)}}else{if(typeof VideoFrame>"u")throw new Error("For this sample, converting from a non-RGB to an RGB format requires VideoFrame to be defined.");const c=this.toVideoFrame(),h=await c.copyTo(e,t);return c.close(),h}const i=bd(this,t);S(this.format);const n=Ke(e);if(n.byteLength<i.allocationSize)throw new TypeError(`Destination buffer too small. Required: ${i.allocationSize}, Available: ${n.byteLength}`);const r=Co(this.format);let o;if(this._data instanceof Ys){let c=this._data.getDataPlanes();if(Is(c)&&(c=await c),!Array.isArray(c)||c.some(h=>!(h.data instanceof Uint8Array)||!Number.isInteger(h.stride)||h.stride<0))throw new TypeError('getDataPlanes() must return an array of objects with a Uint8Array "data" property and a non-negative integer "stride" property.');o=c}else if(this._data instanceof Uint8Array)S(this._layout),S(this._layout.length===r.length),o=this._layout.map((c,h)=>{const d=Math.ceil(this.codedHeight/r[h].heightDivisor);return{data:this._data.subarray(c.offset,c.offset+c.stride*d),stride:c.stride}});else{const h=this._data.getContext("2d");S(h);const d=h.getImageData(0,0,this.codedWidth,this.codedHeight);o=[{data:Ke(d.data),stride:4*this.codedWidth}]}const a=[],l=r.length;for(let c=0;c<l;c++){const h=i.computedLayouts[c],d=o[c].stride,u=o[c].data;let f=h.sourceTop*d;f+=h.sourceLeftBytes;let p=h.destinationOffset;const m=h.sourceWidthBytes,g={offset:p,stride:h.destinationStride};for(let w=0;w<h.sourceHeight;w++){if(f+m>u.byteLength)throw new Error("Source buffer OOB read.");if(p+m>n.byteLength)throw new Error("Destination buffer OOB write.");const b=u.subarray(f,f+m);n.set(b,p),f+=d,p+=h.destinationStride}a.push(g)}if(t.format!==void 0){const c=this.format.startsWith("RGB")!==t.format.startsWith("RGB"),h=this.format.includes("X")&&t.format.includes("A");if(c||h)for(let d=0;d<i.allocationSize;d+=4){if(c){const u=n[d],f=n[d+2];n[d]=f,n[d+2]=u}h&&(n[d+3]=255)}}return a}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");if(S(this._data!==null),this._data instanceof Ys){if(this.format===null)throw new Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if format is null.");const e=this._data.getDataPlanes();if(Is(e))throw new Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if getDataPlanes() returns a promise.");const t=e.reduce((o,a)=>o+a.data.byteLength,0),i=new Uint8Array(t);let n=0;const r=[];for(const o of e)i.set(o.data,n),r.push(n),n+=o.data.byteLength;return new VideoFrame(i,{format:this.format,layout:e.map((o,a)=>({offset:r[a],stride:o.stride})),codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})}else return ln(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?(S(this._layout),new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,layout:this._layout,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,t,i,n,r,o,a,l,c){let h=0,d=0,u=this.displayWidth,f=this.displayHeight,p=0,m=0,g=this.displayWidth,w=this.displayHeight;if(o!==void 0?(h=t,d=i,u=n,f=r,p=o,m=a,l!==void 0?(g=l,w=c):(g=u,w=f)):(p=t,m=i,n!==void 0&&(g=n,w=r)),!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(h))throw new TypeError("sx must be a number.");if(!Number.isFinite(d))throw new TypeError("sy must be a number.");if(!Number.isFinite(u)||u<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(f)||f<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(p))throw new TypeError("dx must be a number.");if(!Number.isFinite(m))throw new TypeError("dy must be a number.");if(!Number.isFinite(g)||g<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(w)||w<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");({sx:h,sy:d,sWidth:u,sHeight:f}=this._unmapSourceRegion(h,d,u,f,this.rotation,this.flip));const b=this.toCanvasImageSource();e.save();const y=p+g/2,C=m+w/2;e.translate(y,C),this.flip&&e.scale(-1,1),e.rotate(this.rotation*Math.PI/180);const _=this.rotation%180===0?1:g/w;e.scale(1/_,_),e.drawImage(b,h,d,u,f,-g/2,-w/2,g,w),e.restore()}drawWithFit(e,t){if(!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(!["fill","contain","cover"].includes(t.fit))throw new TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");if(t.flip!==void 0&&typeof t.flip!="boolean")throw new TypeError("options.flip, when provided, must be a boolean.");t.crop!==void 0&&yl(t.crop,"options.");const i=e.canvas.width,n=e.canvas.height,r=t.rotation??this.rotation,o=t.flip??this.flip,[a,l]=r%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let c=t.crop;c&&(c=gd(c,a,l));let h,d,u,f;const{sx:p,sy:m,sWidth:g,sHeight:w}=this._unmapSourceRegion(t.crop?.left??0,t.crop?.top??0,t.crop?.width??a,t.crop?.height??l,r,o);if(t.fit==="fill")h=0,d=0,u=i,f=n;else{const[y,C]=t.crop?[t.crop.width,t.crop.height]:[a,l],_=t.fit==="contain"?Math.min(i/y,n/C):Math.max(i/y,n/C);u=y*_,f=C*_,h=(i-u)/2,d=(n-f)/2}e.save();const b=r%180===0?1:u/f;e.translate(i/2,n/2),o&&e.scale(-1,1),e.rotate(r*Math.PI/180),e.scale(1/b,b),e.translate(-i/2,-n/2),e.drawImage(this.toCanvasImageSource(),p,m,g,w,h,d,u,f),e.restore()}_unmapSourceRegion(e,t,i,n,r,o){return o&&(e=(r%180===0?this.squarePixelWidth:this.squarePixelHeight)-e-i),r===90?[e,t,i,n]=[t,this.squarePixelHeight-e-i,n,i]:r===180?[e,t]=[this.squarePixelWidth-e-i,this.squarePixelHeight-t-n]:r===270&&([e,t,i,n]=[this.squarePixelWidth-t-n,e,n,i]),{sx:e,sy:t,sWidth:i,sHeight:n}}_drawWithFitAndMipmapping(e,t,i){const n=e.width,r=e.height,[o,a]=i.rotation%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],l=i.crop?i.crop.width:o,c=i.crop?i.crop.height:a;let h=0;2*n<l&&2*r<c&&(h=Math.floor(Math.log2(Math.min(l/n,c/r))));const d=n*2**h,u=r*2**h,{canvas:f,context:p,isNew:m}=h>0?md(d,u):{canvas:e,context:t,isNew:i.targetIsFresh};p.imageSmoothingQuality="high",i.fillBlack?(p.fillStyle="black",p.fillRect(0,0,d,u)):m||p.clearRect(0,0,d,u),this.drawWithFit(p,{fit:i.fit,rotation:i.rotation,flip:i.flip,crop:i.crop}),p.globalCompositeOperation="copy";for(let g=h;g>1;g--){const w=n*2**g,b=r*2**g;p.drawImage(f,0,0,w,b,0,0,w/2,b/2)}p.globalCompositeOperation="source-over",h>0&&(t.imageSmoothingQuality="high",t.globalCompositeOperation="copy",t.drawImage(f,0,0,2*n,2*r,0,0,n,r),t.globalCompositeOperation="source-over")}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(S(this._data!==null),this._data instanceof Ys||this._data instanceof Uint8Array){const e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}else return this._data}async transform(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.width!==void 0&&(!Number.isInteger(e.width)||e.width<=0))throw new TypeError("options.width, when provided, must be a positive integer.");if(e.height!==void 0&&(!Number.isInteger(e.height)||e.height<=0))throw new TypeError("options.height, when provided, must be a positive integer.");if(e.roundDimensionsTo!==void 0&&(!Number.isInteger(e.roundDimensionsTo)||e.roundDimensionsTo<=0))throw new TypeError("options.roundDimensionsTo, when provided, must be a positive integer.");if(e.fit!==void 0&&!["fill","contain","cover"].includes(e.fit))throw new TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(e.width!==void 0&&e.height!==void 0&&e.fit===void 0)throw new TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(e.rotate!==void 0&&![0,90,180,270].includes(e.rotate))throw new TypeError("options.rotate, when provided, must be 0, 90, 180 or 270.");if(e.flip!==void 0&&typeof e.flip!="boolean")throw new TypeError("options.flip, when provided, must be a boolean.");if(e.crop!==void 0&&yl(e.crop,"options."),e.alpha!==void 0&&!["keep","discard"].includes(e.alpha))throw new TypeError("options.alpha, when provided, must be 'keep' or 'discard'.");const{rotation:t,flip:i}=C5(this.rotation,this.flip,e.rotate??0,e.flip??!1),[n,r]=t%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let o=e.crop;o&&(o=gd(o,n,r));const a=o?o.width:n,l=o?o.height:r,c=a/l;let h,d;e.width!==void 0&&e.height===void 0?(h=e.width,d=h/c):e.width===void 0&&e.height!==void 0?(d=e.height,h=d*c):e.width!==void 0&&e.height!==void 0?(h=e.width,d=e.height):(h=a,d=l),h=pl(h,e.roundDimensionsTo??1),d=pl(d,e.roundDimensionsTo??1);const u={width:h,height:d,fit:e.fit??"fill",rotation:t,flip:i,crop:o??{left:0,top:0,width:n,height:r},alpha:e.alpha??"keep"};for(const g of ab){let w=g(this,u);if(Is(w)&&(w=await w),w!==null)return w}const{canvas:f,context:p,isNew:m}=md(u.width,u.height);return this._drawWithFitAndMipmapping(f,p,{fit:u.fit,rotation:u.rotation,flip:u.flip,crop:u.crop,targetIsFresh:m,fillBlack:u.alpha==="discard"}),new St(f,{timestamp:this.timestamp,duration:this.duration,rotation:0,flip:!1})}setRotation(e){if(![0,90,180,270].includes(e))throw new TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=e}setFlip(e){if(typeof e!="boolean")throw new TypeError("newFlip must be a boolean.");this.flip=e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}setDuration(e){if(!Number.isFinite(e)||e<0)throw new TypeError("newDuration must be a non-negative number.");this.duration=e}setEncodeOptions(e){if(!e||typeof e!="object")throw new TypeError("newEncodeOptions must be an object.");this.encodeOptions=e}[Symbol.dispose](){this.close()}}const ab=[],lb=3,an=[];let pd=0;const md=(s,e)=>{for(const n of an)if(n.canvas.width===s&&n.canvas.height===e)return n.age=pd++,{canvas:n.canvas,context:n.context,isNew:!1};let t;if(typeof OffscreenCanvas<"u")t=new OffscreenCanvas(s,e);else{if(typeof window>"u"||typeof document>"u")throw new Error("Cannot transform VideoSamples in this environment. Either run in an environment with OffscreenCanvas or HTMLCanvasElement, or supply a custom VideoSample transformer using registerVideoSampleTransformer().");t=document.createElement("canvas"),t.width=s,t.height=e}const i=t.getContext("2d",{alpha:!0,willReadFrequently:!1});if(!i)throw new Error("The '2d' canvas context is required to transform VideoSamples. Register a custom transformer using registerVideoSampleTransformer to work around this limitation.");return an.length>=lb&&an.splice(D5(an,n=>n.age),1),an.push({canvas:t,context:i,age:pd++}),{canvas:t,context:i,isNew:!0}};class Ca{constructor(e){if(e!==void 0){if(!e||typeof e!="object")throw new TypeError("init.colorSpace, when provided, must be an object.");const t=Object.keys(di);if(e.primaries!=null&&!t.includes(e.primaries))throw new TypeError(`init.colorSpace.primaries, when provided, must be one of ${t.join(", ")}.`);const i=Object.keys(ui);if(e.transfer!=null&&!i.includes(e.transfer))throw new TypeError(`init.colorSpace.transfer, when provided, must be one of ${i.join(", ")}.`);const n=Object.keys(fi);if(e.matrix!=null&&!n.includes(e.matrix))throw new TypeError(`init.colorSpace.matrix, when provided, must be one of ${n.join(", ")}.`);if(e.fullRange!=null&&typeof e.fullRange!="boolean")throw new TypeError("init.colorSpace.fullRange, when provided, must be a boolean.")}this.primaries=e?.primaries??null,this.transfer=e?.transfer??null,this.matrix=e?.matrix??null,this.fullRange=e?.fullRange??null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}}const ln=s=>typeof VideoFrame<"u"&&s instanceof VideoFrame,gd=(s,e,t)=>{const i=Math.min(s.left,e),n=Math.min(s.top,t),r=Math.min(s.width,e-i),o=Math.min(s.height,t-n);return S(r>=0),S(o>=0),{left:i,top:n,width:r,height:o}},yl=(s,e)=>{if(!s||typeof s!="object")throw new TypeError(e+"crop, when provided, must be an object.");if(!Number.isInteger(s.left)||s.left<0)throw new TypeError(e+"crop.left must be a non-negative integer.");if(!Number.isInteger(s.top)||s.top<0)throw new TypeError(e+"crop.top must be a non-negative integer.");if(!Number.isInteger(s.width)||s.width<0)throw new TypeError(e+"crop.width must be a non-negative integer.");if(!Number.isInteger(s.height)||s.height<0)throw new TypeError(e+"crop.height must be a non-negative integer.")},wd=s=>{if(!s||typeof s!="object")throw new TypeError("options must be an object.");if(s.colorSpace!==void 0&&!["display-p3","srgb"].includes(s.colorSpace))throw new TypeError("options.colorSpace, when provided, must be 'display-p3' or 'srgb'.");if(s.format!==void 0&&typeof s.format!="string")throw new TypeError("options.format, when provided, must be a string.");if(s.layout!==void 0){if(!Array.isArray(s.layout))throw new TypeError("options.layout, when provided, must be an array.");for(const e of s.layout){if(!e||typeof e!="object")throw new TypeError("Each entry in options.layout must be an object.");if(!Number.isInteger(e.offset)||e.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(e.stride)||e.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(s.rect!==void 0){if(!s.rect||typeof s.rect!="object")throw new TypeError("options.rect, when provided, must be an object.");if(s.rect.x!==void 0&&(!Number.isInteger(s.rect.x)||s.rect.x<0))throw new TypeError("options.rect.x, when provided, must be a non-negative integer.");if(s.rect.y!==void 0&&(!Number.isInteger(s.rect.y)||s.rect.y<0))throw new TypeError("options.rect.y, when provided, must be a non-negative integer.");if(s.rect.width!==void 0&&(!Number.isInteger(s.rect.width)||s.rect.width<0))throw new TypeError("options.rect.width, when provided, must be a non-negative integer.");if(s.rect.height!==void 0&&(!Number.isInteger(s.rect.height)||s.rect.height<0))throw new TypeError("options.rect.height, when provided, must be a non-negative integer.")}},cb=(s,e,t)=>{const i=Co(s),n=[];let r=0;for(const o of i){const a=Math.ceil(e/o.widthDivisor),l=Math.ceil(t/o.heightDivisor),c=a*o.sampleBytes,h=c*l;n.push({offset:r,stride:c}),r+=h}return n},Co=s=>{const e=(t,i,n,r,o)=>{const a=[{sampleBytes:t,widthDivisor:1,heightDivisor:1},{sampleBytes:i,widthDivisor:n,heightDivisor:r},{sampleBytes:i,widthDivisor:n,heightDivisor:r}];return o&&a.push({sampleBytes:t,widthDivisor:1,heightDivisor:1}),a};switch(s){case"I420":return e(1,1,2,2,!1);case"I420P10":case"I420P12":return e(2,2,2,2,!1);case"I420A":return e(1,1,2,2,!0);case"I420AP10":case"I420AP12":return e(2,2,2,2,!0);case"I422":return e(1,1,2,1,!1);case"I422P10":case"I422P12":return e(2,2,2,1,!1);case"I422A":return e(1,1,2,1,!0);case"I422AP10":case"I422AP12":return e(2,2,2,1,!0);case"I444":return e(1,1,1,1,!1);case"I444P10":case"I444P12":return e(2,2,1,1,!1);case"I444A":return e(1,1,1,1,!0);case"I444AP10":case"I444AP12":return e(2,2,1,1,!0);case"NV12":return[{sampleBytes:1,widthDivisor:1,heightDivisor:1},{sampleBytes:2,widthDivisor:2,heightDivisor:2}];case"RGBA":case"RGBX":case"BGRA":case"BGRX":return[{sampleBytes:4,widthDivisor:1,heightDivisor:1}];default:Gt(s),S(!1)}},bd=(s,e)=>{const t={left:0,top:0,width:s.codedWidth,height:s.codedHeight},i=e.rect,n=hb(t,i,s.codedWidth,s.codedHeight,s.format),r=e.layout;let o;if(!e.format||e.format===s.format)o=s.format;else if(["RGBA","RGBX","BGRA","BGRX"].includes(e.format))o=e.format;else throw new Error("NotSupportedError: Invalid destination format.");return ub(n,o,r)},hb=(s,e,t,i,n)=>{const r={...s};if(e!==void 0){if(e.width===0||e.height===0)throw new TypeError("visibleRect dimensions cannot be zero.");if((e.x||0)+(e.width||0)>t)throw new TypeError("visibleRect exceeds codedWidth.");if((e.y||0)+(e.height||0)>i)throw new TypeError("visibleRect exceeds codedHeight.");r.x=e.x||0,r.y=e.y||0,r.width=e.width||0,r.height=e.height||0}if(!db(n,r))throw new TypeError("visibleRect alignment is invalid for the format.");return r},db=(s,e)=>{if(s===null)return!0;const t=Co(s);for(let i=0;i<t.length;i++){const n=t[i],r=n.widthDivisor,o=n.heightDivisor;if((e.x||0)%r!==0||(e.y||0)%o!==0)return!1}return!0},ub=(s,e,t)=>{const i=Co(e),n=i.length;if(t!==void 0&&t.length!==n)throw new TypeError(`Layout must have ${n} planes.`);let r=0;const o=[],a=[];for(let l=0;l<n;l++){const c=i[l],h=c.sampleBytes,d=c.widthDivisor,u=c.heightDivisor,f={destinationOffset:0,destinationStride:0,sourceTop:0,sourceHeight:0,sourceLeftBytes:0,sourceWidthBytes:0};if(f.sourceTop=Math.ceil(Math.trunc(s.y||0)/u),f.sourceHeight=Math.ceil(Math.trunc(s.height||0)/u),f.sourceLeftBytes=Math.floor(Math.trunc(s.x||0)/d)*h,f.sourceWidthBytes=Math.floor(Math.trunc(s.width||0)/d)*h,t!==void 0){const g=t[l];if(g.stride<f.sourceWidthBytes)throw new TypeError(`Stride for plane ${l} is too small.`);f.destinationOffset=g.offset,f.destinationStride=g.stride}else f.destinationOffset=r,f.destinationStride=f.sourceWidthBytes;const m=f.destinationStride*f.sourceHeight+f.destinationOffset;if(m>4294967295)throw new TypeError("Allocation size exceeds limit.");a.push(m),r=Math.max(r,m);for(let g=0;g<l;g++){const w=o[g];if(!(a[l]<=w.destinationOffset||a[g]<=f.destinationOffset))throw new TypeError("Planes overlap.")}o.push(f)}return{allocationSize:r,computedLayouts:o}},xr=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]);class cn{constructor(){this._referenceCount=0}}class Mt{get microsecondTimestamp(){return Math.trunc(Ls*this.timestamp)}get microsecondDuration(){return Math.trunc(Ls*this.duration)}constructor(e){if(this._closed=!1,hn(e)){if(e.format===null)throw new TypeError("AudioData with null format is not supported.");this._data=e,this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=e.numberOfFrames,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp/1e6,this.duration=e.numberOfFrames/e.sampleRate}else if(e instanceof cn){if(this._data=e,e._referenceCount++,this.format=e.getFormat(),!xr.has(this.format))throw new TypeError("getFormat() must return an AudioSampleFormat.");if(this.sampleRate=e.getSampleRate(),!Number.isInteger(this.sampleRate)||this.sampleRate<=0)throw new TypeError("getSampleRate() must return a positive integer.");if(this.numberOfFrames=e.getNumberOfFrames(),!Number.isInteger(this.numberOfFrames)||this.numberOfFrames<0)throw new TypeError("getNumberOfFrames() must return a non-negative integer.");if(this.numberOfChannels=e.getNumberOfChannels(),!Number.isInteger(this.numberOfChannels)||this.numberOfChannels<=0)throw new TypeError("getNumberOfChannels() must return a positive integer.");if(this.timestamp=e.getTimestamp(),!Number.isFinite(this.timestamp))throw new TypeError("getTimestamp() must return a finite number.");this.duration=this.numberOfFrames/this.sampleRate}else{if(!e||typeof e!="object")throw new TypeError("Invalid AudioDataInit: must be an object.");if(!xr.has(e.format))throw new TypeError("Invalid AudioDataInit: invalid format.");if(!Number.isFinite(e.sampleRate)||e.sampleRate<=0)throw new TypeError("Invalid AudioDataInit: sampleRate must be > 0.");if(!Number.isInteger(e.numberOfChannels)||e.numberOfChannels===0)throw new TypeError("Invalid AudioDataInit: numberOfChannels must be an integer > 0.");if(!Number.isFinite(e?.timestamp))throw new TypeError("init.timestamp must be a number.");const t=e.data.byteLength/(Es(e.format)*e.numberOfChannels);if(!Number.isInteger(t))throw new TypeError("Invalid AudioDataInit: data size is not a multiple of frame size.");this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=t,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp,this.duration=t/e.sampleRate;let i;if(e.data instanceof ArrayBuffer)i=new Uint8Array(e.data);else if(ArrayBuffer.isView(e.data))i=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength);else throw new TypeError("Invalid AudioDataInit: data is not a BufferSource.");const n=this.numberOfFrames*this.numberOfChannels*Es(this.format);if(i.byteLength<n)throw new TypeError("Invalid AudioDataInit: insufficient data size.");this._data=i}Pn?.register(this,{type:"audio",data:this._data},this)}allocationSize(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(!Number.isInteger(e.planeIndex)||e.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(e.format!==void 0&&!xr.has(e.format))throw new TypeError("Invalid format.");if(e.frameOffset!==void 0&&(!Number.isInteger(e.frameOffset)||e.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(e.frameCount!==void 0&&(!Number.isInteger(e.frameCount)||e.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");const t=e.format??this.format,i=e.frameOffset??0;if(i>=this.numberOfFrames)throw new RangeError("frameOffset out of range");const n=e.frameCount!==void 0?e.frameCount:this.numberOfFrames-i;if(n>this.numberOfFrames-i)throw new RangeError("frameCount out of range");const r=Es(t),o=ni(t);if(o&&e.planeIndex>=this.numberOfChannels)throw new RangeError("planeIndex out of range");if(!o&&e.planeIndex!==0)throw new RangeError("planeIndex out of range");return(o?n:n*this.numberOfChannels)*r}copyTo(e,t){if(!mo(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(!Number.isInteger(t.planeIndex)||t.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(t.format!==void 0&&!xr.has(t.format))throw new TypeError("Invalid format.");if(t.frameOffset!==void 0&&(!Number.isInteger(t.frameOffset)||t.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(t.frameCount!==void 0&&(!Number.isInteger(t.frameCount)||t.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");const{format:i,frameCount:n,frameOffset:r}=t;let{planeIndex:o}=t,a=this.format;const l=i??this.format;if(!l)throw new Error("Destination format not determined");const c=this.numberOfFrames,h=this.numberOfChannels,d=r??0;if(d>=c)throw new RangeError("frameOffset out of range");const u=n!==void 0?n:c-d;if(u>c-d)throw new RangeError("frameCount out of range");const f=Es(l),p=ni(l);if(p&&o>=h)throw new RangeError("planeIndex out of range");if(!p&&o!==0)throw new RangeError("planeIndex out of range");const g=(p?u:u*h)*f;if(e.byteLength<g)throw new RangeError("Destination buffer is too small");const w=Ht(e),b=K0(l);if(hn(this._data))if(go()&&h>2&&l!==a){pb(this._data,w,a,l,h,o,d,u);return}else try{this._data.copyTo(e,{planeIndex:o,frameOffset:d,frameCount:u,format:l});return}catch(M){if(l==="f32-planar")throw M;a="f32-planar"}const y=Q0(a),C=Es(a),_=ni(a);let x;if(this._data instanceof cn){const M=k=>{const A=this._data.getDataPlane(k);if(!(A instanceof Uint8Array))throw new TypeError("getDataPlane() must return a Uint8Array.");const P=c*C*(_?1:h);if(A.byteLength!==P)throw new TypeError(`Data plane ${k} has invalid size. Expected exactly ${P} bytes, got ${A.byteLength} bytes.`);return A};if(_)if(p)x=M(o),o=0;else{x=new Uint8Array(c*C*h);for(let k=0;k<h;k++){const A=M(k);x.set(A,k*c*C)}}else x=M(0)}else if(this._data instanceof Uint8Array)x=this._data;else if(S(a==="f32-planar"),p)x=new Uint8Array(this._data.allocationSize({format:"f32-planar",planeIndex:o})),this._data.copyTo(x,{format:"f32-planar",planeIndex:o}),o=0;else{x=new Uint8Array(this._data.allocationSize({format:"f32-planar",planeIndex:0})*h);for(let M=0;M<h;M++)this._data.copyTo(x.subarray(M*c*C,(M+1)*c*C),{format:"f32-planar",planeIndex:M})}const T=Ht(x);for(let M=0;M<u;M++)if(p){const k=M*f;let A;_?A=(o*c+(M+d))*C:A=((M+d)*h+o)*C;const P=y(T,A);b(w,k,P)}else for(let k=0;k<h;k++){const P=(M*h+k)*f;let $;_?$=(k*c+(M+d))*C:$=((M+d)*h+k)*C;const H=y(T,$);b(w,P,H)}}clone(){if(this._closed)throw new Error("AudioSample is closed.");if(this._data instanceof cn){const e=new Mt(this._data);return e.setTimestamp(this.timestamp),e}else if(hn(this._data)){const e=new Mt(this._data.clone());return e.setTimestamp(this.timestamp),e}else return new Mt({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data})}trim(e,t=this.numberOfFrames){if(!Number.isInteger(e)||e<0)throw new TypeError("startFrame must be a non-negative integer.");if(!Number.isInteger(t)||t<0)throw new TypeError("endFrame must be a non-negative integer.");if(e>this.numberOfFrames)throw new RangeError("startFrame out of range.");if(t>this.numberOfFrames)throw new RangeError("endFrame out of range.");if(t<e)throw new RangeError("endFrame must not be less than startFrame.");if(this._closed)throw new Error("AudioSample is closed.");const i=t-e,n=Es(this.format);let r;if(ni(this.format)){const o=i*n;if(r=new Uint8Array(o*this.numberOfChannels),i>0)for(let a=0;a<this.numberOfChannels;a++)this.copyTo(r.subarray(a*o,(a+1)*o),{planeIndex:a,format:this.format,frameOffset:e,frameCount:i})}else r=new Uint8Array(i*this.numberOfChannels*n),i>0&&this.copyTo(r,{planeIndex:0,format:this.format,frameOffset:e,frameCount:i});return new Mt({data:r,format:this.format,sampleRate:this.sampleRate,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp+e/this.sampleRate})}close(){this._closed||(Pn?.unregister(this),this._data instanceof cn?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):hn(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw new Error("AudioSample is closed.");return this._data instanceof cn?this._createAudioDataFromData():hn(this._data)?this._data.timestamp===this.microsecondTimestamp?this._data.clone():this._createAudioDataFromData():new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:this._data.buffer instanceof ArrayBuffer?this._data.buffer:this._data.slice()})}_createAudioDataFromData(){if(ni(this.format)){const e=this.allocationSize({planeIndex:0,format:this.format}),t=new ArrayBuffer(e*this.numberOfChannels);for(let i=0;i<this.numberOfChannels;i++)this.copyTo(new Uint8Array(t,i*e,e),{planeIndex:i,format:this.format});return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:t})}else{const e=new ArrayBuffer(this.allocationSize({planeIndex:0,format:this.format}));return this.copyTo(e,{planeIndex:0,format:this.format}),new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:e})}}toAudioBuffer(){if(this._closed)throw new Error("AudioSample is closed.");const e=new AudioBuffer({numberOfChannels:this.numberOfChannels,length:this.numberOfFrames,sampleRate:this.sampleRate}),t=new Float32Array(this.allocationSize({planeIndex:0,format:"f32-planar"})/4);for(let i=0;i<this.numberOfChannels;i++)this.copyTo(t,{planeIndex:i,format:"f32-planar"}),e.copyToChannel(t,i);return e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}[Symbol.dispose](){this.close()}static*_fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");const i=48e3*5,n=e.numberOfChannels,r=e.sampleRate,o=e.length,a=Math.floor(i/n);let l=0,c=o;for(;c>0;){const h=Math.min(a,c),d=new Float32Array(n*h);for(let u=0;u<n;u++)e.copyFromChannel(d.subarray(u*h,(u+1)*h),u,l);yield new Mt({format:"f32-planar",sampleRate:r,numberOfFrames:h,numberOfChannels:n,timestamp:t+l/r,data:d}),l+=h,c-=h}}static fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");const i=48e3*5,n=e.numberOfChannels,r=e.sampleRate,o=e.length,a=Math.floor(i/n);let l=0,c=o;const h=[];for(;c>0;){const d=Math.min(a,c),u=new Float32Array(n*d);for(let p=0;p<n;p++)e.copyFromChannel(u.subarray(p*d,(p+1)*d),p,l);const f=new Mt({format:"f32-planar",sampleRate:r,numberOfFrames:d,numberOfChannels:n,timestamp:t+l/r,data:u});h.push(f),l+=d,c-=d}return h}}const Es=s=>{switch(s){case"u8":case"u8-planar":return 1;case"s16":case"s16-planar":return 2;case"s32":case"s32-planar":return 4;case"f32":case"f32-planar":return 4;default:throw new Error("Unknown AudioSampleFormat")}},ni=s=>{switch(s){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},Q0=s=>{switch(s){case"u8":case"u8-planar":return(e,t)=>(e.getUint8(t)-128)/128;case"s16":case"s16-planar":return(e,t)=>e.getInt16(t,!0)/32768;case"s32":case"s32-planar":return(e,t)=>e.getInt32(t,!0)/2147483648;case"f32":case"f32-planar":return(e,t)=>e.getFloat32(t,!0)}},K0=s=>{switch(s){case"u8":case"u8-planar":return(e,t,i)=>e.setUint8(t,ct(Math.round(i*128)+128,0,255));case"s16":case"s16-planar":return(e,t,i)=>e.setInt16(t,ct(Math.round(i*32768),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,i)=>e.setInt32(t,ct(Math.round(i*2147483648),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,i)=>e.setFloat32(t,i,!0)}},hn=s=>typeof AudioData<"u"&&s instanceof AudioData,fb=s=>{switch(s){case"u8-planar":return"u8";case"s16-planar":return"s16";case"s32-planar":return"s32";case"f32-planar":return"f32";default:return s}},pb=(s,e,t,i,n,r,o,a)=>{const l=Q0(t),c=K0(i),h=Es(t),d=Es(i),u=ni(t);if(ni(i))if(u){const p=new ArrayBuffer(a*h),m=Ht(p);s.copyTo(p,{planeIndex:r,frameOffset:o,frameCount:a,format:t});for(let g=0;g<a;g++){const w=g*h,b=g*d,y=l(m,w);c(e,b,y)}}else{const p=new ArrayBuffer(a*n*h),m=Ht(p);s.copyTo(p,{planeIndex:0,frameOffset:o,frameCount:a,format:t});for(let g=0;g<a;g++){const w=(g*n+r)*h,b=g*d,y=l(m,w);c(e,b,y)}}else if(u){const p=a*h,m=new ArrayBuffer(p),g=Ht(m);for(let w=0;w<n;w++){s.copyTo(m,{planeIndex:w,frameOffset:o,frameCount:a,format:t});for(let b=0;b<a;b++){const y=b*h,C=(b*n+w)*d,_=l(g,y);c(e,C,_)}}}else{const p=new ArrayBuffer(a*n*h),m=Ht(p);s.copyTo(p,{planeIndex:0,frameOffset:o,frameCount:a,format:t});for(let g=0;g<a;g++)for(let w=0;w<n;w++){const b=g*n+w,y=b*h,C=b*d,_=l(m,y);c(e,C,_)}}},mb=(s,e)=>{const t=s.allocationSize({format:e,planeIndex:0}),i=new ArrayBuffer(t);return s.copyTo(i,{format:e,planeIndex:0}),new Mt({data:i,format:e,numberOfChannels:s.numberOfChannels,sampleRate:s.sampleRate,timestamp:s.timestamp,duration:s.duration})};const vd=new Map,yd=new Map,gb=s=>{if(!s||typeof s!="object")throw new TypeError("Encoding config must be an object.");if(!ss.includes(s.codec))throw new TypeError(`Invalid video codec '${s.codec}'. Must be one of: ${ss.join(", ")}.`);const e=s.bitrate;if(s.quality===void 0&&e===void 0)throw new TypeError("config.quality must be provided.");if(s.quality!==void 0&&e!==void 0)throw new TypeError("config.quality and config.bitrate cannot both be provided.");if(s.quality!==void 0&&!(s.quality instanceof Tt))throw new TypeError("config.quality, when provided, must be a Quality.");if(e!==void 0&&!(e instanceof Tt)&&(!Number.isInteger(e)||e<=0))throw new TypeError("config.bitrate, when provided, must be a positive integer or a quality.");if(s.keyFrameInterval!==void 0&&(!Number.isFinite(s.keyFrameInterval)||s.keyFrameInterval<0))throw new TypeError("config.keyFrameInterval, when provided, must be a non-negative number.");if(s.sizeChangeBehavior!==void 0&&!["deny","passThrough","fill","contain","cover"].includes(s.sizeChangeBehavior))throw new TypeError("config.sizeChangeBehavior, when provided, must be 'deny', 'passThrough', 'fill', 'contain' or 'cover'.");if(s.transform!==void 0){if(typeof s.transform!="object"||!s.transform)throw new TypeError("config.transform, when provided, must be an object.");if(s.transform.width!==void 0&&(!Number.isInteger(s.transform.width)||s.transform.width<=0))throw new TypeError("config.transform.width, when provided, must be a positive integer.");if(s.transform.height!==void 0&&(!Number.isInteger(s.transform.height)||s.transform.height<=0))throw new TypeError("config.transform.height, when provided, must be a positive integer.");if(s.transform.fit!==void 0&&!["fill","contain","cover"].includes(s.transform.fit))throw new TypeError('config.transform.fit, when provided, must be one of "fill", "contain", or "cover".');if(s.transform.width!==void 0&&s.transform.height!==void 0&&s.transform.fit===void 0&&!["fill","contain","cover"].includes(s.sizeChangeBehavior))throw new TypeError("When both config.transform.width and config.transform.height are provided, config.transform.fit must also be provided.");if(s.transform.fit!==void 0&&["fill","contain","cover"].includes(s.sizeChangeBehavior)&&s.transform.fit!==s.sizeChangeBehavior)throw new TypeError("config.transform.fit, when provided, cannot differ from config.sizeChangeBehavior when config.sizeChangeBehavior is 'fill', 'contain' or 'cover', as sizeChangeBehavior already determines the fitting algorithm.");if(s.transform.rotate!==void 0&&![0,90,180,270].includes(s.transform.rotate))throw new TypeError("config.transform.rotate, when provided, must be 0, 90, 180 or 270.");if(s.transform.flip!==void 0&&typeof s.transform.flip!="boolean")throw new TypeError("config.transform.flip, when provided, must be a boolean.");if(s.transform.crop!==void 0&&yl(s.transform.crop,"config.transform."),s.transform.process!==void 0&&typeof s.transform.process!="function")throw new TypeError("config.transform.process, when provided, must be a function.");if(s.transform.frameRate!==void 0&&(!Number.isFinite(s.transform.frameRate)||s.transform.frameRate<=0))throw new TypeError("config.transform.frameRate, when provided, must be a finite positive number.");if(s.transform.force!==void 0&&typeof s.transform.force!="boolean")throw new TypeError("config.transform.force, when provided, must be a boolean.")}if(s.onEncodedPacket!==void 0&&typeof s.onEncodedPacket!="function")throw new TypeError("config.onEncodedPacket, when provided, must be a function.");if(s.onEncoderConfig!==void 0&&typeof s.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.");if(s.onEncodedSample!==void 0&&typeof s.onEncodedSample!="function")throw new TypeError("config.onEncodedSample, when provided, must be a function.");J0(s.codec,s)},J0=(s,e)=>{if(!e||typeof e!="object")throw new TypeError("Encoding options must be an object.");if(e.alpha!==void 0&&!["discard","keep"].includes(e.alpha))throw new TypeError("options.alpha, when provided, must be 'discard' or 'keep'.");const t=e.bitrateMode;if(t!==void 0&&!["constant","variable"].includes(t))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(e.latencyMode!==void 0&&!["quality","realtime"].includes(e.latencyMode))throw new TypeError("latencyMode, when provided, must be 'quality' or 'realtime'.");if(e.fullCodecString!==void 0&&typeof e.fullCodecString!="string")throw new TypeError("fullCodecString, when provided, must be a string.");if(e.fullCodecString!==void 0&&yo(e.fullCodecString)!==s)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${s}).`);if(e.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(e.hardwareAcceleration))throw new TypeError("hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(e.scalabilityMode!==void 0&&typeof e.scalabilityMode!="string")throw new TypeError("scalabilityMode, when provided, must be a string.");if(e.contentHint!==void 0&&typeof e.contentHint!="string")throw new TypeError("contentHint, when provided, must be a string.")},ef=s=>{const e=s.bitrateMode,t=s.quality._toVideoRateControl(s.codec,s.width,s.height,e),i=(r,o,a)=>({codec:s.fullCodecString??Vw(s.codec,s.width,s.height,a,s.alpha==="keep"),width:s.width,height:s.height,displayWidth:s.squarePixelWidth,displayHeight:s.squarePixelHeight,bitrate:r,bitrateMode:o,alpha:s.alpha??"discard",framerate:s.framerate,latencyMode:s.latencyMode,hardwareAcceleration:s.hardwareAcceleration,scalabilityMode:s.scalabilityMode,contentHint:s.contentHint,...jw(s.codec)}),n=[];return t.quantizer!==null&&n.push({config:i(void 0,"quantizer",t.bitrate),quantizer:t.quantizer}),t.bitrateMode!=="quantizer"&&n.push({config:i(t.bitrate,t.bitrateMode,t.bitrate),quantizer:null}),S(n.length>0),n},wb=s=>{if(!s||typeof s!="object")throw new TypeError("Encoding config must be an object.");if(!Vs.includes(s.codec))throw new TypeError(`Invalid audio codec '${s.codec}'. Must be one of: ${Vs.join(", ")}.`);const e=s.bitrate;if(s.quality===void 0&&e===void 0&&!(Lt.includes(s.codec)||s.codec==="flac"))throw new TypeError("config.quality must be provided for compressed audio codecs.");if(s.quality!==void 0&&e!==void 0)throw new TypeError("config.quality and config.bitrate cannot both be provided.");if(s.quality!==void 0&&!(s.quality instanceof Tt))throw new TypeError("config.quality, when provided, must be a Quality.");if(e!==void 0&&!(e instanceof Tt)&&(!Number.isInteger(e)||e<=0))throw new TypeError("config.bitrate, when provided, must be a positive integer or a quality.");if(s.transform!==void 0){if(typeof s.transform!="object"||!s.transform)throw new TypeError("config.transform, when provided, must be an object.");if(s.transform.numberOfChannels!==void 0&&(!Number.isInteger(s.transform.numberOfChannels)||s.transform.numberOfChannels<=0))throw new TypeError("config.transform.numberOfChannels, when provided, must be a positive integer.");if(s.transform.sampleRate!==void 0&&(!Number.isInteger(s.transform.sampleRate)||s.transform.sampleRate<=0))throw new TypeError("config.transform.sampleRate, when provided, must be a positive integer.");if(s.transform.sampleFormat!==void 0&&!["u8","s16","s32","f32"].includes(s.transform.sampleFormat))throw new TypeError("config.transform.sampleFormat, when provided, must be one of: u8, s16, s32, f32.");if(s.transform.process!==void 0&&typeof s.transform.process!="function")throw new TypeError("config.transform.process, when provided, must be a function.")}if(s.onEncodedPacket!==void 0&&typeof s.onEncodedPacket!="function")throw new TypeError("config.onEncodedPacket, when provided, must be a function.");if(s.onEncoderConfig!==void 0&&typeof s.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.");if(s.onEncodedSample!==void 0&&typeof s.onEncodedSample!="function")throw new TypeError("config.onEncodedSample, when provided, must be a function.");tf(s.codec,s)},tf=(s,e)=>{if(!e||typeof e!="object")throw new TypeError("Encoding options must be an object.");const t=e.bitrateMode;if(t!==void 0&&!["constant","variable"].includes(t))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(e.fullCodecString!==void 0&&typeof e.fullCodecString!="string")throw new TypeError("fullCodecString, when provided, must be a string.");if(e.fullCodecString!==void 0&&yo(e.fullCodecString)!==s)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${s}).`)},sf=s=>{const e=s.bitrateMode;return{codec:s.fullCodecString??Hw(s.codec,s.numberOfChannels,s.sampleRate),numberOfChannels:s.numberOfChannels,sampleRate:s.sampleRate,bitrate:s.quality?._toAudioBitrate(s.codec),bitrateMode:s.quality?._bitrateMode??e,...G0(s.codec)}};class Tt{constructor(e){if((typeof e=="number"||typeof e=="string")&&(e={quality:e}),!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.bitrateMode!==void 0&&!["constant","variable"].includes(e.bitrateMode))throw new TypeError("options.bitrateMode, when provided, must be 'constant' or 'variable'.");if("quality"in e){if(typeof e.quality=="string"?!(e.quality in Cd):typeof e.quality!="number"||Number.isNaN(e.quality))throw new TypeError("options.quality must be a number, or one of 'very-low', 'low', 'medium', 'high' or 'very-high'.");if(e.preferBitrate!==void 0&&typeof e.preferBitrate!="boolean")throw new TypeError("options.preferBitrate, when provided, must be a boolean.");if("bitrate"in e||"quantizer"in e)throw new TypeError("options.quality cannot be combined with options.bitrate or options.quantizer.");this._quality=typeof e.quality=="string"?Cd[e.quality]:e.quality,this._preferBitrate=e.preferBitrate??!1,this._bitrate=void 0,this._quantizer=void 0}else{if(e.bitrate!==void 0&&(!Number.isInteger(e.bitrate)||e.bitrate<=0))throw new TypeError("options.bitrate, when provided, must be a positive integer.");if(e.quantizer!==void 0&&(!Number.isInteger(e.quantizer)||e.quantizer<0))throw new TypeError("options.quantizer, when provided, must be a non-negative integer.");if(e.bitrate===void 0&&e.quantizer===void 0)throw new TypeError("At least one of options.bitrate or options.quantizer must be set.");if("preferBitrate"in e)throw new TypeError("options.preferBitrate can only be combined with options.quality.");this._quality=void 0,this._preferBitrate=!1,this._bitrate=e.bitrate,this._quantizer=e.quantizer}this._bitrateMode=e.bitrateMode}_toVideoRateControl(e,t,i,n){const r=bb[e];let o=null,a=this._bitrateMode??n??"variable";if(this._quantizer!==void 0){if(r)if(this._quantizer<r.min||this._quantizer>r.max){if(this._bitrate===void 0)throw new Error(`Quantizer ${this._quantizer} is out of range for codec '${e}'; must be between ${r.min} and ${r.max}.`)}else o=this._quantizer,this._bitrate===void 0&&(a="quantizer");else if(this._bitrate===void 0)throw new Error(`Codec '${e}' does not support quantizer-based encoding. Provide a bitrate in the Quality to define a fallback.`)}else this._bitrate===void 0&&r&&!this._preferBitrate&&(S(this._quality!==void 0),o=ct(Math.round(S5(r.worst,r.best,this._quality)),r.min,r.max));let l;if(this._bitrate!==void 0)l=this._bitrate;else{let c=this._quality;c===void 0&&(S(o!==null&&r),c=ct((o-r.worst)/(r.best-r.worst),0,1)),l=xd(e,t,i,xa(c))}return{quantizer:o,bitrate:l,bitrateMode:a}}_toVideoBitrate(e,t,i){return this._bitrate!==void 0?this._bitrate:(S(this._quality!==void 0),xd(e,t,i,xa(this._quality)))}_toAudioBitrate(e){if(Lt.includes(e)||e==="flac")return;if(this._bitrate!==void 0)return this._bitrate;if(this._quality===void 0)throw new Error("This Quality defines neither a quality level nor a bitrate and therefore cannot be used for audio encoding.");const t=xa(this._quality),n={aac:128e3,opus:64e3,mp3:16e4,vorbis:64e3,ac3:384e3,eac3:192e3,dts:768e3}[e];if(!n)throw new Error(`Unhandled codec: ${e}`);let r=n*t;return e==="aac"?r=[96e3,128e3,16e4,192e3].reduce((a,l)=>Math.abs(l-r)<Math.abs(a-r)?l:a):e==="opus"||e==="vorbis"?r=Math.max(6e3,r):e==="mp3"&&(r=[8e3,16e3,24e3,32e3,4e4,48e3,64e3,8e4,96e3,112e3,128e3,16e4,192e3,224e3,256e3,32e4].reduce((a,l)=>Math.abs(l-r)<Math.abs(a-r)?l:a)),Math.round(r/1e3)*1e3}}const Cd={"very-low":0,low:.25,medium:.5,high:.75,"very-high":1},bb={avc:{min:0,max:51,worst:41,best:16},hevc:{min:0,max:51,worst:41,best:16},vp9:(L5()??1/0)<145?{min:0,max:63,worst:52,best:20}:{min:0,max:255,worst:208,best:80},av1:{min:0,max:255,worst:208,best:80}},xa=s=>.3*Math.exp(2.5538*s),xd=(s,e,t,i)=>{const n=e*t,r=1920*1080,o=3e6,a=Math.pow(n/r,.95),l=o*a,c={avc:1,hevc:.6,vp9:.6,av1:.4,vp8:1.2,prores:22e7/o},d=l*c[s]*i;return Math.ceil(d/1e3)*1e3},nf=(s,e)=>{if(s==="avc")return{avc:{quantizer:e}};if(s==="hevc")return{hevc:{quantizer:e}};if(s==="vp9")return{vp9:{quantizer:e}};if(s==="av1")return{av1:{quantizer:e}};S(!1)},Md=new Tt("medium"),Cl=new Tt("high"),vb=async(s,e={})=>{const{width:t=1280,height:i=720,quality:n,bitrate:r,frameRate:o,...a}=e;if(!ss.includes(s))return!1;if(!Number.isInteger(t)||t<=0)throw new TypeError("width must be a positive integer.");if(!Number.isInteger(i)||i<=0)throw new TypeError("height must be a positive integer.");if(n!==void 0&&!(n instanceof Tt))throw new TypeError("quality, when provided, must be a Quality.");if(n!==void 0&&r!==void 0)throw new TypeError("quality and bitrate cannot both be provided.");if(r!==void 0&&!(r instanceof Tt)&&(!Number.isInteger(r)||r<=0))throw new TypeError("bitrate must be a positive integer or a quality.");if(o!==void 0&&(!Number.isFinite(o)||o<=0))throw new TypeError("frameRate, when provided, must be a finite positive number.");J0(s,a);const l=xo(n,r)??new Tt("medium");let c;try{c=ef({codec:s,width:t,height:i,quality:l,framerate:o,...a,alpha:"discard"})}catch{return!1}const h=JSON.stringify(c),d=vd.get(h);if(d)return d;const u=(async()=>{for(const{config:p}of c)if(rf.some(m=>m.supports(s,p)))return!0;if(typeof VideoEncoder>"u"||(t%2===1||i%2===1)&&(s==="avc"||s==="hevc"))return!1;for(const{config:p,quantizer:m}of c){try{if(!(await VideoEncoder.isConfigSupported(p)).supported)continue}catch{continue}if(!En()||await new Promise(async w=>{try{const b=new VideoEncoder({output:()=>{},error:()=>w(!1)});b.configure(p);const y=new Uint8Array(t*i*4),C=new VideoFrame(y,{format:"RGBA",codedWidth:t,codedHeight:i,timestamp:0});b.encode(C,m!==null?nf(s,m):void 0),C.close(),await b.flush(),w(!0)}catch{w(!1)}}))return!0}return!1})();return vd.set(h,u),u},yb=async(s,e={})=>{const{numberOfChannels:t=2,sampleRate:i=48e3,quality:n,bitrate:r,...o}=e;if(!Vs.includes(s))return!1;if(!Number.isInteger(t)||t<=0)throw new TypeError("numberOfChannels must be a positive integer.");if(!Number.isInteger(i)||i<=0)throw new TypeError("sampleRate must be a positive integer.");if(n!==void 0&&!(n instanceof Tt))throw new TypeError("quality, when provided, must be a Quality.");if(n!==void 0&&r!==void 0)throw new TypeError("quality and bitrate cannot both be provided.");if(r!==void 0&&!(r instanceof Tt)&&(!Number.isInteger(r)||r<=0))throw new TypeError("bitrate must be a positive integer.");tf(s,o);const a=xo(n,r)??new Tt("medium"),l=sf({codec:s,numberOfChannels:t,sampleRate:i,quality:a,...o}),c=JSON.stringify(l),h=yd.get(c);if(h)return h;const d=(async()=>{if(of.some(u=>u.supports(s,l))||Lt.includes(s))return!0;if(typeof AudioEncoder>"u")return!1;try{return(await AudioEncoder.isConfigSupported(l)).supported===!0}catch{return!1}})();return yd.set(c,d),d},xo=(s,e)=>{if(s!==void 0)return s;if(e!==void 0)return e instanceof Tt?e:new Tt({bitrate:e})},kd=async(s,e)=>{for(const t of s)if(await vb(t,e))return t;return null},Cb=async(s,e)=>{for(const t of s)if(await yb(t,e))return t;return null};const rf=[],of=[];const xb=s=>{let i=s>>2,n=4096,r=0,o=12,a=0;for(i<0&&(i=-i,r=128),i+=33,i>8191&&(i=8191);(i&n)!==n&&o>=5;)n>>=1,o--;return a=i>>o-4&15,~(r|o-5<<4|a)&255},Mb=s=>{let t=2048,i=0,n=11,r=0,o=s>>3;for(o<0?o=-o-1:i=128,o>4095&&(o=4095);(o&t)!==t&&n>=5;)t>>=1,n--;return r=o>>(n===4?1:n-4)&15,(i|n-4<<4|r)^85};class Ws{constructor(e,t,i,n,r){this.bytes=e,this.view=t,this.offset=i,this.start=n,this.end=r,this.bufferPos=n-i}static tempFromBytes(e){return new Ws(e,Ht(e),0,0,e.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos(e){this.bufferPos=e-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip(e){this.bufferPos+=e}slice(e,t=this.end-e){if(e<this.start||e+t>this.end)throw new RangeError("Slicing outside of original slice.");return new Ws(this.bytes,this.view,this.offset,e,e+t)}}const tc=(s,e)=>{if(e<0||s.filePos<s.start||s.filePos+e>s.end)throw new RangeError(`Tried reading [${s.filePos}, ${s.filePos+e}), but slice is [${s.start}, ${s.end}). This is likely an internal error, please report it alongside the file that caused it.`)},af=(s,e)=>{tc(s,e);const t=s.bytes.subarray(s.bufferPos,s.bufferPos+e);return s.bufferPos+=e,t},ei=s=>(tc(s,1),s.view.getUint8(s.bufferPos++)),kb=s=>{tc(s,2);const e=s.view.getUint16(s.bufferPos,!1);return s.bufferPos+=2,e};class lf{constructor(e){this.mutex=new _0,this.trackTimestampInfo=new WeakMap,this.output=e}onTrackClose(e){}validateTimestamp(e,t,i){let n=this.trackTimestampInfo.get(e);if(n){if(i&&(n.maxTimestampBeforeLastKeyPacket=n.maxTimestamp),n.maxTimestampBeforeLastKeyPacket!==null&&t<n.maxTimestampBeforeLastKeyPacket)throw new Error(`Timestamps cannot be smaller than the largest timestamp of the previous GOP (a GOP begins with a key packet and ends right before the next key packet). Got ${t}s, but largest timestamp is ${n.maxTimestampBeforeLastKeyPacket}s.`);n.maxTimestamp=Math.max(n.maxTimestamp,t)}else{if(!i)throw new Error("First packet must be a key packet.");n={maxTimestamp:t,maxTimestampBeforeLastKeyPacket:null},this.trackTimestampInfo.set(e,n)}}}const oo=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,Tb=/(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})/,_b=s=>{const e=Tb.exec(s);if(!e)throw new Error("Expected match.");return 3600*1e3*Number(e[1]||"0")+60*1e3*Number(e[2])+1e3*Number(e[3])+Number(e[4])},cf=s=>{const e=Math.floor(s/36e5),t=Math.floor(s%(3600*1e3)/(60*1e3)),i=Math.floor(s%(60*1e3)/1e3),n=s%1e3;return e.toString().padStart(2,"0")+":"+t.toString().padStart(2,"0")+":"+i.toString().padStart(2,"0")+"."+n.toString().padStart(3,"0")};class Mr{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(e){this.helperView.setUint32(0,Math.floor(e/2**32),!1),this.helperView.setUint32(4,e,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(e){for(let t=0;t<e.length;t++)this.helperView.setUint8(t%8,e.charCodeAt(t)),t%8===7&&this.writer.write(this.helper);e.length%8!==0&&this.writer.write(this.helper.subarray(0,e.length%8))}writeBox(e){if(this.offsets.set(e,this.writer.getPos()),e.contents&&!e.children)this.writeBoxHeader(e,e.size??e.contents.byteLength+8),this.writer.write(e.contents);else{const t=this.writer.getPos();if(this.writeBoxHeader(e,0),e.contents&&this.writer.write(e.contents),e.children)for(const r of e.children)r&&this.writeBox(r);const i=this.writer.getPos(),n=e.size??i-t;this.writer.seek(t),this.writeBoxHeader(e,n),this.writer.seek(i)}}writeBoxHeader(e,t){this.writeU32(e.largeSize?1:t),this.writeAscii(e.type),e.largeSize&&this.writeU64(t)}measureBoxHeader(e){return 8+(e.largeSize?8:0)}patchBox(e){const t=this.offsets.get(e);S(t!==void 0);const i=this.writer.getPos();this.writer.seek(t),this.writeBox(e),this.writer.seek(i)}measureBox(e){if(e.contents&&!e.children)return this.measureBoxHeader(e)+e.contents.byteLength;{let t=this.measureBoxHeader(e);if(e.contents&&(t+=e.contents.byteLength),e.children)for(const i of e.children)i&&(t+=this.measureBox(i));return t}}}const ue=new Uint8Array(8),jt=new DataView(ue.buffer),We=s=>[(s%256+256)%256],K=s=>(jt.setUint16(0,s,!1),[ue[0],ue[1]]),Mo=s=>(jt.setInt16(0,s,!1),[ue[0],ue[1]]),hf=s=>(jt.setUint32(0,s,!1),[ue[1],ue[2],ue[3]]),R=s=>(jt.setUint32(0,s,!1),[ue[0],ue[1],ue[2],ue[3]]),as=s=>(jt.setInt32(0,s,!1),[ue[0],ue[1],ue[2],ue[3]]),is=s=>(jt.setUint32(0,Math.floor(s/2**32),!1),jt.setUint32(4,s,!1),[ue[0],ue[1],ue[2],ue[3],ue[4],ue[5],ue[6],ue[7]]),Td=s=>(jt.setInt32(0,Math.floor(s/2**32),!1),jt.setUint32(4,s,!1),[ue[0],ue[1],ue[2],ue[3],ue[4],ue[5],ue[6],ue[7]]),df=s=>(jt.setInt16(0,2**8*s,!1),[ue[0],ue[1]]),Vt=s=>(jt.setInt32(0,2**16*s,!1),[ue[0],ue[1],ue[2],ue[3]]),Ma=s=>(jt.setInt32(0,2**30*s,!1),[ue[0],ue[1],ue[2],ue[3]]),ka=(s,e)=>{const t=[];let i=s;do{let n=i&127;i>>=7,t.length>0&&(n|=128),t.push(n)}while(i>0||e);return t.reverse()},Te=(s,e=!1)=>{const t=Array(s.length).fill(null).map((i,n)=>s.charCodeAt(n));return e&&t.push(0),t},uf=s=>[Vt(s[0]),Vt(s[1]),Ma(s[2]),Vt(s[3]),Vt(s[4]),Ma(s[5]),Vt(s[6]),Vt(s[7]),Ma(s[8])],X=(s,e,t)=>({type:s,contents:e&&new Uint8Array(e.flat(10)),children:t}),Ce=(s,e,t,i,n)=>X(s,[We(e),hf(t),i??[]],n),Sb=s=>s.isQuickTime?X("ftyp",[Te("qt "),R(512),Te("qt ")]):s.fragmented?s.cmaf?X("ftyp",[Te("iso5"),R(512),Te("iso5"),Te("iso6"),Te("mp41"),Te("cmfc"),Te("dash")]):X("ftyp",[Te("iso5"),R(512),Te("iso5"),Te("iso6"),Te("mp41")]):X("ftyp",[Te("isom"),R(512),Te("isom"),s.holdsAvc?Te("avc1"):[],Te("mp41")]),_d=()=>X("styp",[Te("iso5"),R(0),Te("iso5"),Te("iso6"),Te("mp41"),Te("cmfc"),Te("dash")]),Sd=(s,e)=>{const t=Math.max(0,s.minWrittenTimestamp);let i=Math.max(0,s.maxWrittenEndTimestamp-t);return Number.isFinite(i)||(i=0),Ce("sidx",1,0,[R(1),R(Et),is(ze(t,Et)),is(0),K(0),K(1),R(e&2147483647),R(ze(i,Et)),R(0)])},kr=s=>({type:"mdat",largeSize:s}),$b=s=>({type:"free",size:s}),dn=s=>X("moov",void 0,[Ab(s.creationTime,s.trackDatas),...s.trackDatas.map(e=>Eb(e,s.creationTime)),s.isFragmented?gv(s.trackDatas):null,Av(s)]),Ab=(s,e)=>{const t=Math.max(0,...e.map(o=>Math.max(0,ze(Wi(o),Et)+ze(o.startTimestampOffset??0,Et)))),i=Math.max(0,...e.map(o=>o.track.id))+1,n=!vs(s)||!vs(t),r=n?is:R;return Ce("mvhd",+n,0,[r(s),r(s),R(Et),r(t),Vt(1),df(1),Array(10).fill(0),uf(M0),Array(24).fill(0),R(i)])},Eb=(s,e)=>{const t=Vv(s),i=s.startTimestampOffset!==null&&s.startTimestampOffset!==0;return X("trak",void 0,[Pb(s,e),i?zb(s):null,Lb(s,e),t.name!==void 0?X("udta",void 0,[X("name",[...bt.encode(t.name)])]):null])},Pb=(s,e)=>{const t=Math.max(0,ze(Wi(s),Et)+ze(s.startTimestampOffset??0,Et)),i=!vs(e)||!vs(t),n=i?is:R;let r;if(s.type==="video"&&s.track.metadata.transformationMatrix)r=s.track.metadata.transformationMatrix;else if(s.type==="video"){const{rotation:l,flip:c}=s.track.metadata,h=to(k0(l??0),y5(c?-1:1,1));r=w5(h,s.info.width,s.info.height)}else r=M0;let o=2;s.track.metadata.disposition?.default!==!1&&(o|=1);const a=s.type==="video"?0:s.type==="audio"?1:s.type==="subtitle"?2:Gt(s);return Ce("tkhd",+i,o,[n(e),n(e),R(s.track.id),R(0),n(t),Array(8).fill(0),K(0),K(a),df(s.type==="audio"?1:0),K(0),uf(r),Vt(s.type==="video"?s.info.width:0),Vt(s.type==="video"?s.info.height:0)])},zb=s=>{const e=s.startTimestampOffset;if(S(e!==null),e>0){const t=ze(e,Et),i=ze(Wi(s),Et),n=!vs(t)||!vs(i),r=n?is:R,o=n?Td:as;return X("edts",void 0,[Ce("elst",n?1:0,0,[R(2),r(t),o(-1),Vt(1),r(i),o(0),Vt(1)])])}else{const t=ze(-e,s.timescale),i=Math.max(0,ze(Wi(s),Et)+ze(e,Et)),n=!x5(t)||!vs(i),r=n?is:R,o=n?Td:as;return X("edts",void 0,[Ce("elst",n?1:0,0,[R(1),r(i),o(t),Vt(1)])])}},Lb=(s,e)=>X("mdia",void 0,[Rb(s,e),sc(!0,Bb[s.type],Fb[s.type]),Ob(s)]),Rb=(s,e)=>{const t=ze(Wi(s),s.timescale),i=!vs(e)||!vs(t),n=i?is:R;return Ce("mdhd",+i,0,[n(e),n(e),R(s.timescale),n(t),K(wf(s.track.metadata.languageCode??S0)),K(0)])},Bb={video:"vide",audio:"soun",subtitle:"text"},Fb={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},sc=(s,e,t,i="\0\0\0\0")=>Ce("hdlr",0,0,[s?Te("mhlr"):R(0),Te(e),Te(i),R(0),R(0),Te(t,!0)]),Ob=s=>X("minf",void 0,[Nb[s.type](),Wb(),jb(s)]),Ib=()=>Ce("vmhd",0,1,[K(0),K(0),K(0),K(0)]),Db=()=>Ce("smhd",0,0,[K(0),K(0)]),Vb=()=>Ce("nmhd",0,0),Nb={video:Ib,audio:Db,subtitle:Vb},Wb=()=>X("dinf",void 0,[Hb()]),Hb=()=>Ce("dref",0,0,[R(1)],[Ub()]),Ub=()=>Ce("url ",0,1),jb=s=>{const e=s.compositionTimeOffsetTable.length>1||s.compositionTimeOffsetTable.some(t=>t.sampleCompositionTimeOffset!==0);return X("stbl",void 0,[qb(s),cv(s),e?pv(s):null,e?mv(s):null,dv(s),uv(s),fv(s),hv(s),...ff(s.samples,!1)])},qb=s=>{let e;if(s.type==="video")e=Gb(Lv(s.track.source._codec,s.info.decoderConfig.codec),s);else if(s.type==="audio"){const t=gf(s.track.source._codec,s.info.decoderConfig.codec,s.muxer.isQuickTime);S(t),e=Jb(t,s)}else s.type==="subtitle"&&(e=av(Fv[s.track.source._codec],s));return S(e),Ce("stsd",0,0,[R(1)],[e])},Gb=(s,e)=>X(s,[Array(6).fill(0),K(1),K(0),K(0),Array(12).fill(0),K(e.info.width),K(e.info.height),R(4718592),R(4718592),R(0),K(1),We(kn.length),Te(kn),Array(31-kn.length).fill(0),K(e.info.hasAlphaChannel?32:24),Mo(65535)],[Rv[e.track.source._codec]?.(e)??null,Zb(e),T0(e.info.decoderConfig.colorSpace)?null:Xb(e),ic(e)]),ic=s=>s.avgBitrate===0&&s.maxBitrate===0?null:X("btrt",[R(0),R(s.maxBitrate),R(s.avgBitrate)]),Zb=s=>s.info.pixelAspectRatio.num===s.info.pixelAspectRatio.den?null:X("pasp",[R(s.info.pixelAspectRatio.num),R(s.info.pixelAspectRatio.den)]),Xb=s=>{const e=s.info.decoderConfig.colorSpace;return X("colr",[Te(s.muxer.isQuickTime?"nclc":"nclx"),K(e?.primaries!=null?di[e.primaries]:2),K(e?.transfer!=null?ui[e.transfer]:2),K(e?.matrix!=null?fi[e.matrix]:2),s.muxer.isQuickTime?[]:We((e?.fullRange?1:0)<<7)])},Yb=s=>s.info.decoderConfig&&X("avcC",[...Ke(s.info.decoderConfig.description)]),Qb=s=>s.info.decoderConfig&&X("hvcC",[...Ke(s.info.decoderConfig.description)]),$d=s=>{if(!s.info.decoderConfig)return null;const e=s.info.decoderConfig,t=e.codec.split("."),i=Number(t[1]),n=Number(t[2]),r=Number(t[3]),o=t[4]?Number(t[4]):1,a=t[8]?Number(t[8]):Number(e.colorSpace?.fullRange??0),l=(r<<4)+(o<<1)+a,c=t[5]?Number(t[5]):e.colorSpace?.primaries?di[e.colorSpace.primaries]:1,h=t[6]?Number(t[6]):e.colorSpace?.transfer?ui[e.colorSpace.transfer]:1,d=t[7]?Number(t[7]):e.colorSpace?.matrix?fi[e.colorSpace.matrix]:1;return Ce("vpcC",1,0,[We(i),We(n),We(l),We(c),We(h),We(d),K(0)])},Kb=s=>X("av1C",U0(s.info.decoderConfig.codec)),Jb=(s,e)=>{let t=0,i,n=16;const r=Lt.includes(e.track.source._codec);if(r){const o=e.track.source._codec,{sampleSize:a}=Ns(o);n=8*a,n>16&&(t=1)}if(e.muxer.isQuickTime&&(t=1),t===0)i=[Array(6).fill(0),K(1),K(t),K(0),R(0),K(e.info.numberOfChannels),K(n),K(0),K(0),K(e.info.sampleRate<2**16?e.info.sampleRate:0),K(0)];else{const o=r?0:-2;i=[Array(6).fill(0),K(1),K(t),K(0),R(0),K(e.info.numberOfChannels),K(Math.min(n,16)),Mo(o),K(0),K(e.info.sampleRate<2**16?e.info.sampleRate:0),K(0),r?[R(1),R(n/8),R(e.info.numberOfChannels*n/8)]:[R(0),R(0),R(0)],R(2)]}return X(s,i,[Bv(e.track.source._codec,e.muxer.isQuickTime)?.(e)??null,ic(e)])},Ta=s=>{let e;switch(s.track.source._codec){case"aac":e=64;break;case"mp3":e=107;break;case"vorbis":e=221;break;default:throw new Error(`Unhandled audio codec: ${s.track.source._codec}`)}let t=[...We(e),...We(21),...hf(0),...R(s.maxBitrate),...R(s.avgBitrate)];if(s.info.decoderConfig.description){const i=Ke(s.info.decoderConfig.description);t=[...t,...We(5),...ka(i.byteLength),...i]}return t=[...K(1),...We(0),...We(4),...ka(t.length),...t,...We(6),...We(1),...We(2)],t=[...We(3),...ka(t.length),...t],Ce("esds",0,0,t)},_s=s=>X("wave",void 0,[ev(s),tv(s),X("\0\0\0\0")]),ev=s=>X("frma",[Te(gf(s.track.source._codec,s.info.decoderConfig.codec,s.muxer.isQuickTime))]),tv=s=>{const{littleEndian:e}=Ns(s.track.source._codec);return X("enda",[K(+e)])},sv=s=>{let e=s.info.numberOfChannels,t=312,i=s.info.sampleRate,n=0,r=0,o=new Uint8Array(0);const a=s.info.decoderConfig?.description;if(a){S(a.byteLength>=18);const l=Ke(a),c=H0(l);e=c.outputChannelCount,t=c.preSkip,i=c.inputSampleRate,n=c.outputGain,r=c.channelMappingFamily,c.channelMappingTable&&(o=c.channelMappingTable)}return X("dOps",[We(0),We(e),K(t),R(i),Mo(n),We(r),...o])},iv=s=>{const e=s.info.decoderConfig?.description;S(e);const t=Ke(e);return Ce("dfLa",0,0,[...t.subarray(4)])},ns=s=>{const{littleEndian:e,sampleSize:t}=Ns(s.track.source._codec),i=+e;return Ce("pcmC",0,0,[We(i),We(8*t)])},nv=s=>{S(s.info.primingPacket);const e=vw(s.info.primingPacket.data);if(!e)throw new Error("Couldn't extract AC-3 frame info from the audio packet. Ensure the packets contain valid AC-3 sync frames (as specified in ETSI TS 102 366).");const t=new Uint8Array(3),i=new je(t);return i.writeBits(2,e.fscod),i.writeBits(5,e.bsid),i.writeBits(3,e.bsmod),i.writeBits(3,e.acmod),i.writeBits(1,e.lfeon),i.writeBits(5,e.bitRateCode),i.writeBits(5,0),X("dac3",[...t])},rv=s=>{S(s.info.primingPacket);const e=Cw(s.info.primingPacket.data);if(!e)throw new Error("Couldn't extract E-AC-3 frame info from the audio packet. Ensure the packets contain valid E-AC-3 sync frames (as specified in ETSI TS 102 366).");let t=16;for(const o of e.substreams)t+=23,o.numDepSub>0?t+=9:t+=1;const i=Math.ceil(t/8),n=new Uint8Array(i),r=new je(n);r.writeBits(13,e.dataRate),r.writeBits(3,e.substreams.length-1);for(const o of e.substreams)r.writeBits(2,o.fscod),r.writeBits(5,o.bsid),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(3,o.bsmod),r.writeBits(3,o.acmod),r.writeBits(1,o.lfeon),r.writeBits(3,0),r.writeBits(4,o.numDepSub),o.numDepSub>0?r.writeBits(9,o.chanLoc):r.writeBits(1,0);return X("dec3",[...n])},ov=s=>{S(s.info.primingPacket);const e=Bw(s.info.primingPacket.data);if(!e)throw new Error("Couldn't extract DTS frame info from the audio packet. Ensure the packets contain valid DTS frames as specified in ETSI TS 102 114.");return X("ddts",[...Iw(e)])},av=(s,e)=>X(s,[Array(6).fill(0),K(1)],[Ov[e.track.source._codec](e),ic(e)]),lv=s=>X("vttC",[...bt.encode(s.info.config.description)]),cv=s=>Ce("stts",0,0,[R(s.timeToSampleTable.length),s.timeToSampleTable.map(e=>[R(e.sampleCount),R(e.sampleDelta)])]),hv=s=>{if(s.samples.every(t=>t.type==="key"))return null;const e=[...s.samples.entries()].filter(([,t])=>t.type==="key");return Ce("stss",0,0,[R(e.length),e.map(([t])=>R(t+1))])},dv=s=>Ce("stsc",0,0,[R(s.compactlyCodedChunkTable.length),s.compactlyCodedChunkTable.map(e=>[R(e.firstChunk),R(e.samplesPerChunk),R(1)])]),uv=s=>{if(s.type==="audio"&&s.info.requiresPcmTransformation){const{sampleSize:e}=Ns(s.track.source._codec);return Ce("stsz",0,0,[R(e*s.info.numberOfChannels),R(s.samples.reduce((t,i)=>t+ze(i.duration,s.timescale),0))])}return Ce("stsz",0,0,[R(0),R(s.samples.length),s.samples.map(e=>R(e.size))])},fv=s=>s.finalizedChunks.length>0&&kt(s.finalizedChunks).offset>=2**32?Ce("co64",0,0,[R(s.finalizedChunks.length),s.finalizedChunks.map(e=>is(e.offset))]):Ce("stco",0,0,[R(s.finalizedChunks.length),s.finalizedChunks.map(e=>R(e.offset))]),pv=s=>Ce("ctts",1,0,[R(s.compositionTimeOffsetTable.length),s.compositionTimeOffsetTable.map(e=>[R(e.sampleCount),as(e.sampleCompositionTimeOffset)])]),mv=s=>{let e=1/0,t=-1/0,i=1/0,n=-1/0;S(s.compositionTimeOffsetTable.length>0),S(s.samples.length>0);for(let o=0;o<s.compositionTimeOffsetTable.length;o++){const a=s.compositionTimeOffsetTable[o];e=Math.min(e,a.sampleCompositionTimeOffset),t=Math.max(t,a.sampleCompositionTimeOffset)}for(let o=0;o<s.samples.length;o++){const a=s.samples[o];i=Math.min(i,ze(a.timestamp,s.timescale)),n=Math.max(n,ze(a.timestamp+a.duration,s.timescale))}const r=Math.max(-e,0);return n>=2**31?null:Ce("cslg",0,0,[as(r),as(e),as(t),as(i),as(n)])},ff=(s,e)=>{const t=[];for(const r of s)if(t.length===0)t.push({sampleCount:1,prerollSamples:r.prerollSamples});else{const o=t[t.length-1];o.prerollSamples===r.prerollSamples?o.sampleCount++:t.push({sampleCount:1,prerollSamples:r.prerollSamples})}const i=t.filter(r=>r.prerollSamples!==0);if(i.length===0)return[];let n=e?65537:1;return[Ce("sgpd",1,0,[Te("roll"),R(2),R(i.length),...i.map(r=>Mo(r.prerollSamples))]),Ce("sbgp",0,0,[Te("roll"),R(t.length),...t.map(r=>[R(r.sampleCount),R(r.prerollSamples!==0?n++:0)])])]},gv=s=>X("mvex",void 0,s.map(wv)),wv=s=>Ce("trex",0,0,[R(s.track.id),R(1),R(0),R(0),R(0)]),Ad=(s,e)=>X("moof",void 0,[bv(s),...e.map(vv)]),bv=s=>Ce("mfhd",0,0,[R(s)]),pf=s=>{let e=0,t=0;const i=0,n=0,r=s.type==="delta";return t|=+r,r?e|=1:e|=2,e<<24|t<<16|i<<8|n},vv=s=>X("traf",void 0,[yv(s),Cv(s),xv(s),...ff(s.currentChunk.samples,!0)]),yv=s=>{S(s.currentChunk);let e=0;e|=8,e|=16,e|=32,e|=131072;const t=s.currentChunk.samples[1]??s.currentChunk.samples[0],i={duration:t.timescaleUnitsToNextSample,size:t.size,flags:pf(t)};return Ce("tfhd",0,e,[R(s.track.id),R(i.duration),R(i.size),R(i.flags)])},Cv=s=>(S(s.currentChunk),Ce("tfdt",1,0,[is(ze(s.currentChunk.startTimestamp,s.timescale))])),xv=s=>{S(s.currentChunk);const e=s.currentChunk.samples.map(m=>m.timescaleUnitsToNextSample),t=s.currentChunk.samples.map(m=>m.size),i=s.currentChunk.samples.map(pf),n=s.currentChunk.samples.map(m=>ze(m.timestamp-m.decodeTimestamp,s.timescale)),r=new Set(e),o=new Set(t),a=new Set(i),l=new Set(n),c=a.size===2&&i[0]!==i[1],h=r.size>1,d=o.size>1,u=!c&&a.size>1,f=l.size>1||[...l].some(m=>m!==0);let p=0;return p|=1,p|=4*+c,p|=256*+h,p|=512*+d,p|=1024*+u,p|=2048*+f,Ce("trun",1,p,[R(s.currentChunk.samples.length),R(s.currentChunk.offset-s.currentChunk.moofOffset||0),c?R(i[0]):[],s.currentChunk.samples.map((m,g)=>[h?R(e[g]):[],d?R(t[g]):[],u?R(i[g]):[],f?as(n[g]):[]])])},Mv=s=>X("mfra",void 0,[...s.map(kv),Tv()]),kv=s=>{const t=[];for(const i of s.finalizedChunks){const n=i.samples.findIndex(o=>o.type==="key");if(n===-1)continue;const r=i.samples[n];t.push([is(ze(r.timestamp,s.timescale)),is(i.moofOffset),R(i.trafIndex+1),R(1),R(n+1)])}return Ce("tfra",1,0,[R(s.track.id),R(63),R(t.length),t])},Tv=()=>Ce("mfro",0,0,[R(0)]),_v=()=>X("vtte"),Sv=(s,e,t,i,n)=>X("vttc",void 0,[n!==null?X("vsid",[as(n)]):null,t!==null?X("iden",[...bt.encode(t)]):null,e!==null?X("ctim",[...bt.encode(cf(e))]):null,i!==null?X("sttg",[...bt.encode(i)]):null,X("payl",[...bt.encode(s)])]),$v=s=>X("vtta",[...bt.encode(s)]),Av=s=>{const e=[],t=s.format._options.metadataFormat??"auto",i=s.output._metadataTags;if(t==="mdir"||t==="auto"&&!s.isQuickTime){const n=Pv(i);n&&e.push(n)}else if(t==="mdta"){const n=zv(i);n&&e.push(n)}else(t==="udta"||t==="auto"&&s.isQuickTime)&&Ev(e,s.output._metadataTags);return e.length===0?null:X("udta",void 0,e)},Ev=(s,e)=>{for(const{key:t,value:i}of Zl(e))switch(t){case"title":s.push(rs("©nam",i));break;case"description":s.push(rs("©des",i));break;case"artist":s.push(rs("©ART",i));break;case"album":s.push(rs("©alb",i));break;case"albumArtist":s.push(rs("albr",i));break;case"genre":s.push(rs("©gen",i));break;case"date":s.push(rs("©day",i.toISOString().slice(0,10)));break;case"comment":s.push(rs("©cmt",i));break;case"lyrics":s.push(rs("©lyr",i));break;case"raw":break;case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"beatsPerMinute":case"images":break;default:Gt(t)}if(e.raw)for(const t in e.raw){const i=e.raw[t];i==null||t.length!==4||s.some(n=>n.type===t)||(typeof i=="string"?s.push(rs(t,i)):i instanceof Uint8Array&&s.push(X(t,Array.from(i))))}},rs=(s,e)=>{const t=bt.encode(e);return X(s,[K(t.length),K(wf("und")),Array.from(t)])},Ed={"image/jpeg":13,"image/png":14,"image/bmp":27},mf=(s,e)=>{const t=[];for(const{key:i,value:n}of Zl(s))switch(i){case"title":t.push({key:e?"title":"©nam",value:Xt(n)});break;case"description":t.push({key:e?"description":"©des",value:Xt(n)});break;case"artist":t.push({key:e?"artist":"©ART",value:Xt(n)});break;case"album":t.push({key:e?"album":"©alb",value:Xt(n)});break;case"albumArtist":t.push({key:e?"album_artist":"aART",value:Xt(n)});break;case"comment":t.push({key:e?"comment":"©cmt",value:Xt(n)});break;case"genre":t.push({key:e?"genre":"©gen",value:Xt(n)});break;case"beatsPerMinute":e||t.push({key:"tmpo",value:X("data",[R(21),R(0),K(n)])});break;case"lyrics":t.push({key:e?"lyrics":"©lyr",value:Xt(n)});break;case"date":t.push({key:e?"date":"©day",value:Xt(n.toISOString().slice(0,10))});break;case"images":for(const r of n)r.kind==="coverFront"&&t.push({key:"covr",value:X("data",[R(Ed[r.mimeType]??0),R(0),Array.from(r.data)])});break;case"trackNumber":if(e){const r=s.tracksTotal!==void 0?`${n}/${s.tracksTotal}`:n.toString();t.push({key:"track",value:Xt(r)})}else t.push({key:"trkn",value:X("data",[R(0),R(0),K(0),K(n),K(s.tracksTotal??0),K(0)])});break;case"discNumber":e||t.push({key:"disc",value:X("data",[R(0),R(0),K(0),K(n),K(s.discsTotal??0),K(0)])});break;case"tracksTotal":case"discsTotal":break;case"raw":break;default:Gt(i)}if(s.raw)for(const i in s.raw){const n=s.raw[i];n==null||!e&&i.length!==4||t.some(r=>r.key===i)||(typeof n=="string"?t.push({key:i,value:Xt(n)}):n instanceof Uint8Array?t.push({key:i,value:X("data",[R(0),R(0),Array.from(n)])}):n instanceof L0&&t.push({key:i,value:X("data",[R(Ed[n.mimeType]??0),R(0),Array.from(n.data)])}))}return t},Pv=s=>{const e=mf(s,!1);return e.length===0?null:Ce("meta",0,0,void 0,[sc(!1,"mdir","","appl"),X("ilst",void 0,e.map(t=>X(t.key,void 0,[t.value])))])},zv=s=>{const e=mf(s,!0);return e.length===0?null:X("meta",void 0,[sc(!1,"mdta",""),Ce("keys",0,0,[R(e.length)],e.map(t=>X("mdta",[...bt.encode(t.key)]))),X("ilst",void 0,e.map((t,i)=>{const n=String.fromCharCode(...R(i+1));return X(n,void 0,[t.value])}))])},Xt=s=>X("data",[R(1),R(0),...bt.encode(s)]),Lv=(s,e)=>{switch(s){case"avc":return e.startsWith("avc3")?"avc3":"avc1";case"hevc":return"hvc1";case"vp8":return"vp08";case"vp9":return"vp09";case"av1":return"av01";case"prores":return e}},Rv={avc:Yb,hevc:Qb,vp8:$d,vp9:$d,av1:Kb,prores:null},gf=(s,e,t)=>{switch(s){case"aac":return"mp4a";case"mp3":return"mp4a";case"opus":return"Opus";case"vorbis":return"mp4a";case"flac":return"fLaC";case"ulaw":return"ulaw";case"alaw":return"alaw";case"pcm-u8":return"raw ";case"pcm-s8":return"sowt";case"ac3":return"ac-3";case"eac3":return"ec-3";case"dts":return e}if(t)switch(s){case"pcm-s16":return"sowt";case"pcm-s16be":return"twos";case"pcm-s24":return"in24";case"pcm-s24be":return"in24";case"pcm-s32":return"in32";case"pcm-s32be":return"in32";case"pcm-f32":return"fl32";case"pcm-f32be":return"fl32";case"pcm-f64":return"fl64";case"pcm-f64be":return"fl64"}else switch(s){case"pcm-s16":return"ipcm";case"pcm-s16be":return"ipcm";case"pcm-s24":return"ipcm";case"pcm-s24be":return"ipcm";case"pcm-s32":return"ipcm";case"pcm-s32be":return"ipcm";case"pcm-f32":return"fpcm";case"pcm-f32be":return"fpcm";case"pcm-f64":return"fpcm";case"pcm-f64be":return"fpcm"}},Bv=(s,e)=>{switch(s){case"aac":return Ta;case"mp3":return Ta;case"opus":return sv;case"vorbis":return Ta;case"flac":return iv;case"ac3":return nv;case"eac3":return rv;case"dts":return ov}if(e)switch(s){case"pcm-s24":return _s;case"pcm-s24be":return _s;case"pcm-s32":return _s;case"pcm-s32be":return _s;case"pcm-f32":return _s;case"pcm-f32be":return _s;case"pcm-f64":return _s;case"pcm-f64be":return _s}else switch(s){case"pcm-s16":return ns;case"pcm-s16be":return ns;case"pcm-s24":return ns;case"pcm-s24be":return ns;case"pcm-s32":return ns;case"pcm-s32be":return ns;case"pcm-f32":return ns;case"pcm-f32be":return ns;case"pcm-f64":return ns;case"pcm-f64be":return ns}return null},Fv={webvtt:"wvtt"},Ov={webvtt:lv},wf=s=>{S(s.length===3);let e=0;for(let t=0;t<3;t++)e<<=5,e+=s.charCodeAt(t)-96;return e};class xl{constructor(e,t){if(this.finalized=!1,this.started=!1,this.pos=0,this.trackedWrites=null,this.trackedStart=-1,this.trackedEnd=-1,e._writerAcquired)throw new Error("Can't have multiple Writers for the same Target.");this.target=e,e._setMonotonicity(t),e._writerAcquired=!0}start(){S(!this.started),this.target._start(),this.started=!0}write(e){S(this.started&&!this.finalized),this.maybeTrackWrites(e),this.target._write(e,this.pos),this.pos+=e.byteLength}seek(e){this.pos=e}getPos(){return this.pos}async flush(){return S(this.started&&!this.finalized),this.target._flush()}async finalize(){S(this.started&&!this.finalized),await this.target._finalize(),this.finalized=!0}maybeTrackWrites(e){if(!this.trackedWrites)return;let t=this.getPos();if(t<this.trackedStart){if(t+e.byteLength<=this.trackedStart)return;e=e.subarray(this.trackedStart-t),t=0}const i=t+e.byteLength-this.trackedStart;let n=this.trackedWrites.byteLength;for(;n<i;)n*=2;if(n!==this.trackedWrites.byteLength){const r=new Uint8Array(n);r.set(this.trackedWrites,0),this.trackedWrites=r}this.trackedWrites.set(e,t-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,t+e.byteLength)}startTrackingWrites(){this.trackedWrites=new Uint8Array(2**10),this.trackedStart=this.getPos(),this.trackedEnd=this.trackedStart}stopTrackingWrites(){if(!this.trackedWrites)throw new Error("Internal error: Can't get tracked writes since nothing was tracked.");const t={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,t}}class us extends Ql{constructor(){super(...arguments),this._writerAcquired=!1,this._monotonicity=null,this.onwrite=null}_setMonotonicity(e){this._monotonicity!==!1&&(this._monotonicity=e)}_dispatchWrite(e,t){this.onwrite?.(e,t),this._emit("write",{start:e,end:t})}slice(e){if(!Number.isInteger(e)||e<0)throw new TypeError("offset must be a non-negative integer.");return new Iv(this,e)}}const _a=2**16,Sa=2**32;class Or extends us{constructor(e={}){if(super(),this.buffer=null,this._maxPos=0,!e||typeof e!="object")throw new TypeError("BufferTarget options, when provided, must be an object.");if(e.onFinalize!==void 0&&typeof e.onFinalize!="function")throw new TypeError("options.onFinalize, when provided, must be a function.");if(this._options=e,this._supportsResize="resize"in new ArrayBuffer(0),this._supportsResize)try{this._buffer=new ArrayBuffer(_a,{maxByteLength:Sa})}catch{this._buffer=new ArrayBuffer(_a),this._supportsResize=!1}else this._buffer=new ArrayBuffer(_a);this._bytes=new Uint8Array(this._buffer)}_ensureSize(e){S(this._buffer),S(this._bytes);let t=this._buffer.byteLength;for(;t<e;)t*=2;if(t!==this._buffer.byteLength){if(t>Sa)throw new Error(`ArrayBuffer exceeded maximum size of ${Sa} bytes. Please consider using another target.`);if(this._supportsResize)this._buffer.resize(t);else{const i=new ArrayBuffer(t),n=new Uint8Array(i);n.set(this._bytes,0),this._buffer=i,this._bytes=n}}}_start(){}_write(e,t){S(this._bytes),this._ensureSize(t+e.byteLength),this._bytes.set(e,t),this._maxPos=Math.max(this._maxPos,t+e.byteLength),this._dispatchWrite(t,t+e.byteLength)}async _flush(){}async _finalize(){S(this._buffer),"transferToFixedLength"in this._buffer?this.buffer=this._buffer.transferToFixedLength(this._maxPos):this.buffer=this._buffer.slice(0,this._maxPos),this._buffer=null,this._bytes=null,this._options.onFinalize&&await this._options.onFinalize(this.buffer),this._emit("finalized")}async _close(){}_getSlice(e,t){return S(this._bytes),this._bytes.slice(e,t)}}class Iv extends us{constructor(e,t){super(),this._baseTarget=e,this._offset=t}_start(){}_write(e,t){this._baseTarget._write(e,this._offset+t),this._dispatchWrite(t,t+e.byteLength)}_flush(){return this._baseTarget._flush()}async _finalize(){this._emit("finalized")}async _close(){}_setMonotonicity(e){super._setMonotonicity(e),this._baseTarget._setMonotonicity(e)}}class $a{constructor(e,t){if(this.rootPath=e,this.getTarget=t,typeof e!="string")throw new TypeError("rootPath must be a string.");if(typeof t!="function")throw new TypeError("getTarget must be a function.")}}const Et=57600,Dv=2082844800,Vv=s=>{const e={},t=s.track;return t.metadata.name!==void 0&&(e.name=t.metadata.name),e},ze=(s,e,t=!0)=>{const i=s*e;return t?Math.round(i):i},Wi=s=>{if(s.samples.length===0)return 0;let e=1/0,t=-1/0;for(let i=0;i<s.samples.length;i++){const n=s.samples[i];n.timestamp<e&&(e=n.timestamp),n.timestamp+n.duration>t&&(t=n.timestamp+n.duration)}return e===1/0?0:t-e};class Nv extends lf{constructor(e,t){super(e),this.writer=null,this.boxWriter=null,this.initWriter=null,this.initBoxWriter=null,this.auxTarget=new Or,this.auxWriter=new xl(this.auxTarget,!1),this.auxBoxWriter=new Mr(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=Gn(),this.creationTime=Math.floor(Date.now()/1e3)+Dv,this.finalizedChunks=[],this.wroteFragmentedHeader=!1,this.nextFragmentNumber=1,this.maxWrittenTimestamp=-1/0,this.minWrittenTimestamp=1/0,this.maxWrittenEndTimestamp=-1/0,this.segmentHeaderSize=null,this.format=t,this.formatOptions={...t._options},this.isQuickTime=t instanceof Mf,this.isCmaf=t instanceof Ld,this.minimumFragmentDuration=this.formatOptions.minimumFragmentDuration??(t instanceof Ld?1/0:1),this.auxWriter.start()}async start(){const e=await this.mutex.acquire();if(this.isCmaf?(this.fastStart="fragmented",this.isFragmented=!0):(this.writer=await this.output._getRootWriter(i=>this.formatOptions.fastStart!==void 0?this.formatOptions.fastStart==="fragmented":i instanceof Or),this.boxWriter=new Mr(this.writer),this.fastStart=this.formatOptions.fastStart??(this.writer.target instanceof Or?"in-memory":!1),this.isFragmented=this.fastStart==="fragmented"),this.isCmaf){if(!this.output._hasInitTarget())throw new Error("CMAF outputs require the initTarget field in OutputOptions to be set; the init segment will be written to it.");const i=await this.output._getInitTarget(),n=new xl(i,!0);n.start(),this.initWriter=n,this.initBoxWriter=new Mr(n)}const t=this.output.tracks.some(i=>i.isVideoTrack()&&i.source._codec==="avc");{const i=this.initBoxWriter??this.boxWriter;if(S(i),this.formatOptions.onFtyp&&i.writer.startTrackingWrites(),i.writeBox(Sb({isQuickTime:this.isQuickTime,holdsAvc:t,fragmented:this.isFragmented,cmaf:this.isCmaf})),this.formatOptions.onFtyp){const{data:n,start:r}=i.writer.stopTrackingWrites();this.formatOptions.onFtyp(n,r)}this.ftypSize=i.writer.getPos(),this.isCmaf&&await this.initWriter.flush()}if(this.fastStart!=="in-memory")if(this.fastStart==="reserve"){for(const i of this.output.tracks)if(i.metadata.maximumPacketCount===void 0)throw new Error("All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.")}else this.isFragmented||(S(this.writer),S(this.boxWriter),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=kr(!0),this.boxWriter.writeBox(this.mdat));await this.writer?.flush();for(const i of this.output.tracks)i.isVideoTrack()&&i.metadata.decoderConfig?this.getVideoTrackData(i,i.metadata.primingPacket??null,{decoderConfig:i.metadata.decoderConfig}):i.isAudioTrack()&&i.metadata.decoderConfig&&this.getAudioTrackData(i,i.metadata.primingPacket??null,{decoderConfig:i.metadata.decoderConfig});e()}allTracksAreKnown(){for(const e of this.output.tracks)if(!e.source._closed&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;const e=this.trackDatas.map(t=>t.type==="video"||t.type==="audio"?t.info.decoderConfig.codec:{webvtt:"wvtt"}[t.track.source._codec]);return Kw({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(t=>t.type==="video"),hasAudio:this.trackDatas.some(t=>t.type==="audio"),codecStrings:e})}getVideoTrackData(e,t,i){const n=this.trackDatas.find(f=>f.track===e);if(n)return n;Jl(i,e.source._codec),S(i),S(i.decoderConfig);const r={...i.decoderConfig};S(r.codedWidth!==void 0),S(r.codedHeight!==void 0);let o=!1;if(e.source._codec==="avc"&&!r.description){if(!t)throw new Error("No AVC description provided; you must therefore provide a priming packet.");const f=I0(t.data);if(!f)throw new Error("Couldn't extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in AVCC format.");r.description=D0(f),o=!0}else if(e.source._codec==="hevc"&&!r.description){if(!t)throw new Error("No HEVC description provided; you must therefore provide a priming packet.");const f=N0(t.data);if(!f)throw new Error("Couldn't extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in HEVC format.");r.description=dw(f),o=!0}const a=P5(1/(e.metadata.frameRate??Et),1e6).den,l=r.displayAspectWidth,c=r.displayAspectHeight,h=l===void 0||c===void 0?{num:1,den:1}:Xl({num:l*r.codedHeight,den:c*r.codedWidth}),d=r.codec==="ap4h"||r.codec==="ap4x",u={muxer:this,track:e,type:"video",info:{width:r.codedWidth,height:r.codedHeight,pixelAspectRatio:h,decoderConfig:r,requiresAnnexBTransformation:o,hasAlphaChannel:d},timescale:a,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,avgBitrate:e.source._nominalBitrate??e.metadata.averageBitrate??0,maxBitrate:e.source._nominalBitrate??e.metadata.bitrate??0};return this.trackDatas.push(u),this.trackDatas.sort((f,p)=>f.track.id-p.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),u}getAudioTrackData(e,t,i){const n=this.trackDatas.find(l=>l.track===e);if(n)return n;ec(i,e.source._codec),S(i),S(i.decoderConfig);const r={...i.decoderConfig};let o=!1;if(e.source._codec==="aac"&&!r.description){if(!t)throw new Error("No AAC description provided; you must therefore provide a priming packet.");const l=ro(Ws.tempFromBytes(t.data));if(!l)throw new Error("Couldn't parse ADTS header from the AAC packet. Make sure the packets are in ADTS format (as specified in ISO 13818-7) when not providing a description, or provide a description (must be an AudioSpecificConfig as specified in ISO 14496-3) and ensure the packets are raw AAC data.");const c=Ni[l.samplingFrequencyIndex],h=wo[l.channelConfiguration];if(c===void 0||h===void 0)throw new Error("Invalid ADTS frame header.");r.description=Kl({objectType:l.objectType,outputSampleRate:c,outputNumberOfChannels:h}),o=!0}if(!t){if(e.source._codec==="ac3"||e.source._codec==="eac3")throw new Error("AC-3/E-AC-3 require a priming packet.");if(e.source._codec==="dts")throw new Error("DTS requires a priming packet.")}const a={muxer:this,track:e,type:"audio",info:{numberOfChannels:i.decoderConfig.numberOfChannels,sampleRate:i.decoderConfig.sampleRate,decoderConfig:r,requiresPcmTransformation:!this.isFragmented&&Lt.includes(e.source._codec),expectedNextPcmPacketTimestamp:null,requiresAdtsStripping:o,primingPacket:t,preroll:{packetCount:0,accumulatedAudioSamples:0,audioSampleDurationHistory:[]}},timescale:r.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,avgBitrate:e.source._nominalBitrate??e.metadata.averageBitrate??0,maxBitrate:e.source._nominalBitrate??e.metadata.bitrate??0};return this.trackDatas.push(a),this.trackDatas.sort((l,c)=>l.track.id-c.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),a}getSubtitleTrackData(e,t){const i=this.trackDatas.find(r=>r.track===e);if(i)return i;Z0(t),S(t),S(t.config);const n={muxer:this,track:e,type:"subtitle",info:{config:t.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,avgBitrate:e.source._nominalBitrate??e.metadata.averageBitrate??0,maxBitrate:e.source._nominalBitrate??e.metadata.bitrate??0,lastCueEndTimestamp:null,cueQueue:[],nextSourceId:0,cueToSourceId:new WeakMap};return this.trackDatas.push(n),this.trackDatas.sort((r,o)=>r.track.id-o.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),n}async addEncodedVideoPacket(e,t,i){const n=await this.mutex.acquire();try{const r=this.getVideoTrackData(e,t,i);let o=t.data;if(r.info.requiresAnnexBTransformation){const l=[...Zn(o)].map(c=>o.subarray(c.offset,c.offset+c.length));if(l.length===0)throw new Error("Failed to transform packet data. Make sure all packets are provided in Annex B format, as specified in ITU-T-REC-H.264 and ITU-T-REC-H.265.");o=ew(l,4)}this.validateTimestamp(r.track,t.timestamp,t.type==="key");const a=this.createSampleForTrack(r,o,t.timestamp,t.duration,t.type,0);await this.registerSample(r,a)}finally{n()}}async addEncodedAudioPacket(e,t,i){const n=await this.mutex.acquire();try{const r=this.getAudioTrackData(e,t,i);let o=t.data;if(r.info.requiresAdtsStripping){const u=ro(Ws.tempFromBytes(o));if(!u)throw new Error("Expected ADTS frame, didn't get one.");const f=u.crcCheck===null?no:Y0;o=o.subarray(f)}this.validateTimestamp(r.track,t.timestamp,t.type==="key");let a=t.timestamp,l=t.duration;if(r.info.requiresPcmTransformation){const f=Ns(r.info.decoderConfig.codec).sampleSize*r.info.numberOfChannels;if(l=o.byteLength/f/r.info.sampleRate,r.info.expectedNextPcmPacketTimestamp!==null){const p=a-r.info.expectedNextPcmPacketTimestamp;if(p<.01)a=r.info.expectedNextPcmPacketTimestamp;else{const m=await this.padWithSilence(r,r.info.expectedNextPcmPacketTimestamp,p);a=r.info.expectedNextPcmPacketTimestamp+m}}r.info.expectedNextPcmPacketTimestamp=a+l}const{preroll:c}=r.info;let h=0;if(e.source._codec==="aac"||e.source._codec==="vorbis")h=-Math.min(1,c.packetCount);else if(e.source._codec==="mp3")h=-Math.min(2,c.packetCount);else if(e.source._codec==="opus"){const u=.08*j0;h=-c.audioSampleDurationHistory.length;const f=ww(o);for(c.accumulatedAudioSamples+=f.durationInSamples,c.audioSampleDurationHistory.push(f.durationInSamples);c.accumulatedAudioSamples-c.audioSampleDurationHistory[0]>=u;)c.accumulatedAudioSamples-=c.audioSampleDurationHistory.shift(),S(c.audioSampleDurationHistory.length>0)}c.packetCount++;const d=this.createSampleForTrack(r,o,a,l,t.type,h);await this.registerSample(r,d)}finally{n()}}async padWithSilence(e,t,i){const n=ze(i,e.timescale);if(i=n/e.timescale,n>0){const{sampleSize:r,silentValue:o}=Ns(e.info.decoderConfig.codec),a=n*e.info.numberOfChannels,l=new Uint8Array(r*a).fill(o),c=this.createSampleForTrack(e,new Uint8Array(l.buffer),t,i,"key",0);await this.registerSample(e,c)}return i}async addSubtitleCue(e,t,i){const n=await this.mutex.acquire();try{const r=this.getSubtitleTrackData(e,i);this.validateTimestamp(r.track,t.timestamp,!0),e.source._codec==="webvtt"&&(r.cueQueue.push(t),await this.processWebVTTCues(r,t.timestamp))}finally{n()}}async processWebVTTCues(e,t){for(;e.cueQueue.length>0;){e.lastCueEndTimestamp??=Math.min(0,e.cueQueue[0].timestamp);const i=new Set([]);for(const c of e.cueQueue)S(c.timestamp<=t),S(e.lastCueEndTimestamp<=c.timestamp+c.duration),i.add(Math.max(c.timestamp,e.lastCueEndTimestamp)),i.add(c.timestamp+c.duration);const n=[...i].sort((c,h)=>c-h),r=n[0],o=n[1]??r;if(t<o)break;if(e.lastCueEndTimestamp<r){this.auxWriter.seek(0);const c=_v();this.auxBoxWriter.writeBox(c);const h=this.auxTarget._getSlice(0,this.auxWriter.getPos()),d=this.createSampleForTrack(e,h,e.lastCueEndTimestamp,r-e.lastCueEndTimestamp,"key",0);await this.registerSample(e,d),e.lastCueEndTimestamp=r}this.auxWriter.seek(0);for(let c=0;c<e.cueQueue.length;c++){const h=e.cueQueue[c];if(h.timestamp>=o)break;oo.lastIndex=0;const d=oo.test(h.text),u=h.timestamp+h.duration;let f=e.cueToSourceId.get(h);if(f===void 0&&o<u&&(f=e.nextSourceId++,e.cueToSourceId.set(h,f)),h.notes){const m=$v(h.notes);this.auxBoxWriter.writeBox(m)}const p=Sv(h.text,d?r:null,h.identifier??null,h.settings??null,f??null);this.auxBoxWriter.writeBox(p),u===o&&e.cueQueue.splice(c--,1)}const a=this.auxTarget._getSlice(0,this.auxWriter.getPos()),l=this.createSampleForTrack(e,a,r,o-r,"key",0);await this.registerSample(e,l),e.lastCueEndTimestamp=o}}createSampleForTrack(e,t,i,n,r,o){return{timestamp:i,decodeTimestamp:i,duration:n,data:t,size:t.byteLength,type:r,timescaleUnitsToNextSample:ze(n,e.timescale),prerollSamples:o}}processTimestamps(e,t){if(e.timestampProcessingQueue.length===0)return;if(e.type==="audio"&&e.info.requiresPcmTransformation){S(!this.isFragmented),e.startTimestampOffset??=e.timestampProcessingQueue[0].timestamp;let n=0;for(let r=0;r<e.timestampProcessingQueue.length;r++){const o=e.timestampProcessingQueue[r],a=ze(o.duration,e.timescale);n+=a}if(e.timeToSampleTable.length===0)e.timeToSampleTable.push({sampleCount:n,sampleDelta:1});else{const r=kt(e.timeToSampleTable);r.sampleCount+=n}e.timestampProcessingQueue.length=0;return}const i=e.timestampProcessingQueue.map(n=>n.timestamp).sort((n,r)=>n-r);this.isFragmented?e.startTimestampOffset??=Math.min(i[0],0):e.startTimestampOffset??=i[0];for(let n=0;n<e.timestampProcessingQueue.length;n++){const r=e.timestampProcessingQueue[n];r.decodeTimestamp=i[n];const o=ze(r.timestamp-r.decodeTimestamp,e.timescale),a=ze(r.duration,e.timescale);if(e.lastTimescaleUnits!==null){S(e.lastSample);const l=ze(r.decodeTimestamp,e.timescale,!1),c=Math.round(l-e.lastTimescaleUnits);if(S(c>=0),e.lastTimescaleUnits+=c,e.lastSample.timescaleUnitsToNextSample=c,!this.isFragmented){let h=kt(e.timeToSampleTable);if(S(h),h.sampleCount===1){h.sampleDelta=c;const u=e.timeToSampleTable[e.timeToSampleTable.length-2];u&&u.sampleDelta===c&&(u.sampleCount++,e.timeToSampleTable.pop(),h=u)}else h.sampleDelta!==c&&(h.sampleCount--,e.timeToSampleTable.push(h={sampleCount:1,sampleDelta:c}));h.sampleDelta===a?h.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:a});const d=kt(e.compositionTimeOffsetTable);S(d),d.sampleCompositionTimeOffset===o?d.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:o})}}else e.lastTimescaleUnits=ze(r.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:a}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:o}));e.lastSample=r}if(e.timestampProcessingQueue.length=0,S(e.lastSample),S(e.lastTimescaleUnits!==null),t!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){S(t.type==="key");const n=ze(t.timestamp,e.timescale,!1),r=Math.round(n-e.lastTimescaleUnits);e.lastSample.timescaleUnitsToNextSample=r}}async registerSample(e,t){t.type==="key"&&this.processTimestamps(e,t),e.timestampProcessingQueue.push(t),this.isFragmented?(e.sampleQueue.push(t),await this.interleaveSamples()):this.fastStart==="reserve"?await this.registerSampleFastStartReserve(e,t):await this.addSampleToTrack(e,t)}async addSampleToTrack(e,t){if(!this.isFragmented&&(e.samples.push(t),this.fastStart==="reserve")){const n=e.track.metadata.maximumPacketCount;if(S(n!==void 0),e.samples.length>n)throw new Error(`Track #${e.track.id} has already reached the maximum packet count (${n}). Either add less packets or increase the maximum packet count.`)}let i=!1;if(!e.currentChunk)i=!0;else{e.currentChunk.startTimestamp=Math.min(e.currentChunk.startTimestamp,t.timestamp);const n=t.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){const r=this.trackDatas.every(o=>{if(e===o)return t.type==="key";const a=o.sampleQueue[0];return a?a.type==="key":o.closed});n>=this.minimumFragmentDuration&&r&&t.timestamp>this.maxWrittenTimestamp&&(i=!0,await this.finalizeFragment())}else i=n>=.5}i&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:t.timestamp,samples:[],offset:null,moofOffset:null,trafIndex:null}),S(e.currentChunk),e.currentChunk.samples.push(t),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,t.timestamp),this.maxWrittenEndTimestamp=Math.max(this.maxWrittenEndTimestamp,t.timestamp+t.duration),this.minWrittenTimestamp=Math.min(this.minWrittenTimestamp,t.timestamp))}async finalizeCurrentChunk(e){if(S(!this.isFragmented),S(this.writer),!e.currentChunk)return;e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk);let t=e.currentChunk.samples.length;if(e.type==="audio"&&e.info.requiresPcmTransformation&&(t=e.currentChunk.samples.reduce((i,n)=>i+ze(n.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||kt(e.compactlyCodedChunkTable).samplesPerChunk!==t)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:t}),this.fastStart==="in-memory"){e.currentChunk.offset=0;return}e.currentChunk.offset=this.writer.getPos();for(const i of e.currentChunk.samples)S(i.data),this.writer.write(i.data),i.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(S(this.isFragmented),!(!e&&!this.allTracksAreKnown()))e:for(;;){let t=null,i=1/0;for(const r of this.trackDatas){if(!e&&r.sampleQueue.length===0&&!r.closed)break e;r.sampleQueue.length>0&&r.sampleQueue[0].timestamp<i&&(t=r,i=r.sampleQueue[0].timestamp)}if(!t)break;const n=t.sampleQueue.shift();await this.addSampleToTrack(t,n)}}async finalizeFragment(e=!this.isCmaf){if(S(this.isFragmented),!this.wroteFragmentedHeader){this.wroteFragmentedHeader=!0;const f=this.initBoxWriter??this.boxWriter;S(f),this.formatOptions.onMoov&&f.writer.startTrackingWrites(),this.ensureOneEnabledTrack();const p=dn(this);if(f.writeBox(p),this.formatOptions.onMoov){const{data:m,start:g}=f.writer.stopTrackingWrites();this.formatOptions.onMoov(m,g)}if(this.isCmaf){S(this.initWriter),await this.initWriter.flush(),await this.initWriter.finalize(),this.writer=await this.output._getRootWriter(!0),this.boxWriter=new Mr(this.writer);const m=this.boxWriter.measureBox(_d()),g=this.boxWriter.measureBox(Sd(this,0));this.segmentHeaderSize=m+g,this.writer.seek(this.segmentHeaderSize)}}S(this.writer),S(this.boxWriter);const t=this.trackDatas.filter(f=>f.currentChunk);if(t.length===0){e&&await this.writer.flush();return}const i=this.nextFragmentNumber++,n=Ad(i,t),r=this.writer.getPos(),o=r+this.boxWriter.measureBox(n);let a=o+va,l=1/0;for(let f=0;f<t.length;f++){const p=t[f];S(p.currentChunk),S(p.startTimestampOffset!==null),p.currentChunk.offset=a,p.currentChunk.moofOffset=r,p.currentChunk.trafIndex=f,p.currentChunk.startTimestamp-=p.startTimestampOffset;for(const m of p.currentChunk.samples)a+=m.size,m.timestamp-=p.startTimestampOffset,m.decodeTimestamp-=p.startTimestampOffset;l=Math.min(l,p.currentChunk.startTimestamp)}const c=a-o,h=c>=2**32;if(h)for(const f of t)f.currentChunk.offset+=ld-va;this.formatOptions.onMoof&&this.writer.startTrackingWrites();const d=Ad(i,t);if(this.boxWriter.writeBox(d),this.formatOptions.onMoof){const{data:f,start:p}=this.writer.stopTrackingWrites();this.formatOptions.onMoof(f,p,l)}S(this.writer.getPos()===o),this.formatOptions.onMdat&&this.writer.startTrackingWrites();const u=kr(h);u.size=c,this.boxWriter.writeBox(u),this.writer.seek(o+(h?ld:va));for(const f of t)for(const p of f.currentChunk.samples)this.writer.write(p.data),p.data=null;if(this.formatOptions.onMdat){const{data:f,start:p}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(f,p)}for(const f of t)f.finalizedChunks.push(f.currentChunk),this.finalizedChunks.push(f.currentChunk),f.currentChunk=null;e&&await this.writer.flush()}async registerSampleFastStartReserve(e,t){this.allTracksAreKnown()?(this.mdat||await this.createFastStartReserveMdat(),await this.addSampleToTrack(e,t)):e.sampleQueue.push(t)}async createFastStartReserveMdat(){S(this.writer),S(this.boxWriter),this.ensureOneEnabledTrack();const e=dn(this),i=this.boxWriter.measureBox(e)+this.computeSampleTableSizeUpperBound()+4096;S(this.ftypSize!==null),this.writer.seek(this.ftypSize+i),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=kr(!0),this.boxWriter.writeBox(this.mdat);for(const n of this.trackDatas){for(const r of n.sampleQueue)await this.addSampleToTrack(n,r);n.sampleQueue.length=0}}computeSampleTableSizeUpperBound(){S(this.fastStart==="reserve");let e=0;for(const t of this.trackDatas){const i=t.track.metadata.maximumPacketCount;S(i!==void 0),e+=8*Math.ceil(2/3*i),e+=4*i,e+=8*Math.ceil(2/3*i),e+=12*Math.ceil(2/3*i),e+=4*i,e+=8*i}return e}async onTrackClose(e){const t=await this.mutex.acquire(),i=this.trackDatas.find(n=>n.track===e);i&&(i.closed=!0,i.type==="subtitle"&&e.source._codec==="webvtt"&&await this.processWebVTTCues(i,1/0),this.processTimestamps(i)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),t()}ensureOneEnabledTrack(){for(const e of["video","audio","subtitle"]){const t=this.trackDatas.filter(n=>n.type===e);if(t.length===0)continue;if(!t.some(n=>n.track.metadata.disposition?.default!==!1)){const n=t[0];n.track.metadata.disposition={...n.track.metadata.disposition,default:!0}}}}async forceFragmentFinalization(){S(this.isFragmented);const e=await this.mutex.acquire();try{for(const t of this.trackDatas)t.type==="subtitle"&&t.track.source._codec==="webvtt"&&await this.processWebVTTCues(t,1/0),this.processTimestamps(t);await this.interleaveSamples(!0),await this.finalizeFragment()}finally{e()}}async finalize(){const e=await this.mutex.acquire();this.allTracksKnown.resolve(),this.ensureOneEnabledTrack(),!this.mdat&&this.fastStart==="reserve"&&await this.createFastStartReserveMdat();for(const t of this.trackDatas)t.closed=!0,t.type==="subtitle"&&t.track.source._codec==="webvtt"&&await this.processWebVTTCues(t,1/0),this.processTimestamps(t);if(this.isFragmented)await this.interleaveSamples(!0),await this.finalizeFragment(!1);else for(const t of this.trackDatas){await this.finalizeCurrentChunk(t);const i=Wi(t);if(i>0){let a=0;for(const l of t.samples)a+=l.size;t.avgBitrate=Math.round(8*a/i)}else t.avgBitrate=0;let n=0,r=0,o=0;for(let a=0;a<t.samples.length;a++){const l=t.samples[a];for(r+=l.size;l.decodeTimestamp-t.samples[n].decodeTimestamp>=1;)r-=t.samples[n].size,n++;o=Math.max(o,r)}if(t.maxBitrate=8*o,t.startTimestampOffset!==null)for(let a=0;a<t.samples.length;a++){const l=t.samples[a];l.timestamp-=t.startTimestampOffset,l.decodeTimestamp-=t.startTimestampOffset}}if(S(this.writer),S(this.boxWriter),this.fastStart==="in-memory"){this.mdat=kr(!1);let t;for(let n=0;n<2;n++){const r=dn(this),o=this.boxWriter.measureBox(r);t=this.boxWriter.measureBox(this.mdat);let a=this.writer.getPos()+o+t;for(const l of this.finalizedChunks){l.offset=a;for(const{data:c}of l.samples)S(c),a+=c.byteLength,t+=c.byteLength}if(a<2**32)break;t>=2**32&&(this.mdat.largeSize=!0)}this.formatOptions.onMoov&&this.writer.startTrackingWrites();const i=dn(this);if(this.boxWriter.writeBox(i),this.formatOptions.onMoov){const{data:n,start:r}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(n,r)}this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=t,this.boxWriter.writeBox(this.mdat);for(const n of this.finalizedChunks)for(const r of n.samples)S(r.data),this.writer.write(r.data),r.data=null;if(this.formatOptions.onMdat){const{data:n,start:r}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(n,r)}}else if(this.isFragmented)if(this.isCmaf){const t=this.segmentHeaderSize!==null?this.writer.getPos()-this.segmentHeaderSize:0;this.writer.seek(0),this.boxWriter.writeBox(_d()),this.boxWriter.writeBox(Sd(this,t))}else{const t=this.writer.getPos(),i=Mv(this.trackDatas);this.boxWriter.writeBox(i);const n=this.writer.getPos()-t;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(n)}else{S(this.mdat);const t=this.boxWriter.offsets.get(this.mdat);S(t!==void 0);const i=this.writer.getPos()-t;if(this.mdat.size=i,this.mdat.largeSize=i>=2**32,this.boxWriter.patchBox(this.mdat),this.formatOptions.onMdat){const{data:r,start:o}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(r,o)}const n=dn(this);if(this.fastStart==="reserve"){S(this.ftypSize!==null),this.writer.seek(this.ftypSize),this.formatOptions.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(n);const r=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox($b(r))}else this.formatOptions.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(n);if(this.formatOptions.onMoov){const{data:r,start:o}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(r,o)}}e()}}const Wv=-32768,Hv=2**15-1,Pd=6,Uv=5,jv={video:1,audio:2,subtitle:17};class qv extends lf{constructor(e,t){super(e),this.trackDatas=[],this.allTracksKnown=Gn(),this.segment=null,this.segmentInfo=null,this.seekHead=null,this.tracksElement=null,this.tagsElement=null,this.attachmentsElement=null,this.segmentDuration=null,this.cues=null,this.currentClusterBlocks=[],this.currentClusterStartMsTimestamp=null,this.currentClusterMaxMsTimestamp=null,this.startTimestamp=1/0,this.endTimestamp=-1/0,this.warnedAboutTooNegativeTimestamp=!1,this.format=t}async start(){const e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!!this.format._options.appendOnly),this.ebmlWriter=new tb(this.writer),this.writeEBMLHeader(),this.createSegmentInfo(),this.createCues(),await this.writer.flush();for(const t of this.output.tracks)t.isVideoTrack()&&t.metadata.decoderConfig?this.getVideoTrackData(t,t.metadata.primingPacket??null,{decoderConfig:t.metadata.decoderConfig}):t.isAudioTrack()&&t.metadata.decoderConfig&&this.getAudioTrackData(t,t.metadata.primingPacket??null,{decoderConfig:t.metadata.decoderConfig});e()}writeEBMLHeader(){this.format._options.onEbmlHeader&&this.writer.startTrackingWrites();const e={id:E.EBML,data:[{id:E.EBMLVersion,data:1},{id:E.EBMLReadVersion,data:1},{id:E.EBMLMaxIDLength,data:4},{id:E.EBMLMaxSizeLength,data:8},{id:E.DocType,data:this.format instanceof Ir?"webm":"matroska"},{id:E.DocTypeVersion,data:4},{id:E.DocTypeReadVersion,data:2}]};if(this.ebmlWriter.writeEBML(e),this.format._options.onEbmlHeader){const{data:t,start:i}=this.writer.stopTrackingWrites();this.format._options.onEbmlHeader(t,i)}}maybeCreateSeekHead(e){if(this.format._options.appendOnly)return;const t=new Uint8Array([28,83,187,107]),i=new Uint8Array([21,73,169,102]),n=new Uint8Array([22,84,174,107]),r=new Uint8Array([25,65,164,105]),o=new Uint8Array([18,84,195,103]),a={id:E.SeekHead,data:[{id:E.Seek,data:[{id:E.SeekID,data:i},{id:E.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.segmentInfo)-this.segmentDataOffset:0}]},{id:E.Seek,data:[{id:E.SeekID,data:n},{id:E.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.tracksElement)-this.segmentDataOffset:0}]},this.attachmentsElement?{id:E.Seek,data:[{id:E.SeekID,data:r},{id:E.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.attachmentsElement)-this.segmentDataOffset:0}]}:null,this.tagsElement?{id:E.Seek,data:[{id:E.SeekID,data:o},{id:E.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.tagsElement)-this.segmentDataOffset:0}]}:null,{id:E.Seek,data:[{id:E.SeekID,data:t},{id:E.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.cues)-this.segmentDataOffset:0}]}]};this.seekHead=a}createSegmentInfo(){const e={id:E.Duration,data:new bl(0)};this.segmentDuration=e;const t={id:E.Info,data:[{id:E.TimestampScale,data:1e6},{id:E.MuxingApp,data:kn},{id:E.WritingApp,data:kn},this.format._options.appendOnly?null:e]};this.segmentInfo=t}createTracks(){const e={id:E.Tracks,data:[]};this.tracksElement=e;for(const t of this.trackDatas){let i=sb[t.track.source._codec];S(i),t.type==="audio"&&t.track.source._codec==="dts"&&(t.info.decoderConfig.codec==="dtse"?i="A_DTS/EXPRESS":t.info.decoderConfig.codec==="dtsl"&&(i="A_DTS/LOSSLESS"));let n=0;if(t.type==="audio"){const r=Uw(t.track.source._codec,t.info.decoderConfig);n=Math.round(1e9*r)}e.data.push({id:E.TrackEntry,data:[{id:E.TrackNumber,data:t.track.id},{id:E.TrackUID,data:t.track.id},{id:E.TrackType,data:jv[t.type]},t.track.metadata.disposition?.default===!1?{id:E.FlagDefault,data:0}:null,t.track.metadata.disposition?.forced?{id:E.FlagForced,data:1}:null,t.track.metadata.disposition?.hearingImpaired?{id:E.FlagHearingImpaired,data:1}:null,t.track.metadata.disposition?.visuallyImpaired?{id:E.FlagVisualImpaired,data:1}:null,t.track.metadata.disposition?.original?{id:E.FlagOriginal,data:1}:null,t.track.metadata.disposition?.commentary?{id:E.FlagCommentary,data:1}:null,{id:E.FlagLacing,data:0},{id:E.Language,data:t.track.metadata.languageCode??S0},{id:E.CodecID,data:i},t.codecPrivate?{id:E.CodecPrivate,data:Ke(t.codecPrivate)}:null,t.type==="audio"&&t.info.codecDelay?{id:E.CodecDelay,data:Math.round(1e9*t.info.codecDelay)}:null,n>0?{id:E.SeekPreRoll,data:n}:null,t.track.metadata.name!==void 0?{id:E.Name,data:new As(t.track.metadata.name)}:null,t.type==="video"?this.videoSpecificTrackInfo(t):null,t.type==="audio"?this.audioSpecificTrackInfo(t):null,t.type==="subtitle"?this.subtitleSpecificTrackInfo(t):null]})}}videoSpecificTrackInfo(e){const{frameRate:t,transformationMatrix:i}=e.track.metadata,n=[t?{id:E.DefaultDuration,data:1e9/t}:null];let r,o,a;if(i){r=b5(i);const p=to(k0(-r),i);o=Math.sign(p[0]),a=Math.sign(p[4]),a===-1&&(a=1,o=-o,r=eo(r+180))}else r=e.track.metadata.rotation??0,o=e.track.metadata.flip?-1:1,a=1;const l=r?eo(o===-1?r:-r):0,c=Math.round(Math.acos(o)*fl),h=Math.round(Math.acos(a)*fl),d=!!e.info.aspectRatio&&e.info.aspectRatio.num*e.info.height!==e.info.aspectRatio.den*e.info.width,u=e.info.decoderConfig.colorSpace,f={id:E.Video,data:[{id:E.PixelWidth,data:e.info.width},{id:E.PixelHeight,data:e.info.height},d?{id:E.DisplayWidth,data:e.info.aspectRatio.num}:null,d?{id:E.DisplayHeight,data:e.info.aspectRatio.den}:null,d?{id:E.DisplayUnit,data:3}:null,e.info.alphaMode?{id:E.AlphaMode,data:1}:null,T0(u)?null:{id:E.Colour,data:[{id:E.MatrixCoefficients,data:u?.matrix!=null?fi[u.matrix]:2},{id:E.TransferCharacteristics,data:u?.transfer!=null?ui[u.transfer]:2},{id:E.Primaries,data:u?.primaries!=null?di[u.primaries]:2},{id:E.Range,data:u?.fullRange!=null?u.fullRange?2:1:0}]},l||c||h?{id:E.Projection,data:[{id:E.ProjectionType,data:0},c?{id:E.ProjectionPoseYaw,data:new yn(c)}:null,h?{id:E.ProjectionPosePitch,data:new yn(h)}:null,l?{id:E.ProjectionPoseRoll,data:new yn((l+180)%360-180)}:null]}:null]};return n.push(f),n}audioSpecificTrackInfo(e){const t=Lt.includes(e.track.source._codec)?Ns(e.track.source._codec):null;return[{id:E.Audio,data:[{id:E.SamplingFrequency,data:new yn(e.info.sampleRate)},{id:E.Channels,data:e.info.numberOfChannels},t?{id:E.BitDepth,data:8*t.sampleSize}:null]}]}subtitleSpecificTrackInfo(e){return[]}maybeCreateTags(){const e=[],t=(r,o)=>{e.push({id:E.SimpleTag,data:[{id:E.TagName,data:new As(r)},typeof o=="string"?{id:E.TagString,data:new As(o)}:{id:E.TagBinary,data:o}]})},i=this.output._metadataTags,n=new Set;for(const{key:r,value:o}of Zl(i))switch(r){case"title":t("TITLE",o),n.add("TITLE");break;case"description":t("DESCRIPTION",o),n.add("DESCRIPTION");break;case"artist":t("ARTIST",o),n.add("ARTIST");break;case"album":t("ALBUM",o),n.add("ALBUM");break;case"albumArtist":t("ALBUM_ARTIST",o),n.add("ALBUM_ARTIST");break;case"genre":t("GENRE",o),n.add("GENRE");break;case"beatsPerMinute":t("BPM",o.toString()),n.add("BPM");break;case"comment":t("COMMENT",o),n.add("COMMENT");break;case"lyrics":t("LYRICS",o),n.add("LYRICS");break;case"date":t("DATE",o.toISOString().slice(0,10)),n.add("DATE");break;case"trackNumber":{const a=i.tracksTotal!==void 0?`${o}/${i.tracksTotal}`:o.toString();t("PART_NUMBER",a),n.add("PART_NUMBER")}break;case"discNumber":{const a=i.discsTotal!==void 0?`${o}/${i.discsTotal}`:o.toString();t("DISC",a),n.add("DISC")}break;case"tracksTotal":case"discsTotal":break;case"images":case"raw":break;default:Gt(r)}if(i.raw)for(const r in i.raw){const o=i.raw[r];o==null||n.has(r)||(typeof o=="string"||o instanceof Uint8Array)&&t(r,o)}e.length!==0&&(this.tagsElement={id:E.Tags,data:[{id:E.Tag,data:[{id:E.Targets,data:[{id:E.TargetTypeValue,data:50},{id:E.TargetType,data:"MOVIE"}]},...e]}]})}maybeCreateAttachments(){const e=this.output._metadataTags,t=[],i=new Set,n=e.images??[];for(const r of n){let o=r.name;o===void 0&&(o=(r.kind==="coverFront"?"cover":r.kind==="coverBack"?"back":"image")+(F5(r.mimeType)??""));let a;for(;;){a=0n;for(let l=0;l<8;l++)a<<=8n,a|=BigInt(Math.floor(Math.random()*256));if(a!==0n&&!i.has(a))break}i.add(a),t.push({id:E.AttachedFile,data:[r.description!==void 0?{id:E.FileDescription,data:new As(r.description)}:null,{id:E.FileName,data:new As(o)},{id:E.FileMediaType,data:r.mimeType},{id:E.FileData,data:r.data},{id:E.FileUID,data:a}]})}for(const[r,o]of Object.entries(e.raw??{}))!(o instanceof R0)||!/^\d+$/.test(r)||n.find(l=>l.mimeType===o.mimeType&&O5(l.data,o.data))||t.push({id:E.AttachedFile,data:[o.description!==void 0?{id:E.FileDescription,data:new As(o.description)}:null,{id:E.FileName,data:new As(o.name??"")},{id:E.FileMediaType,data:o.mimeType??""},{id:E.FileData,data:o.data},{id:E.FileUID,data:BigInt(r)}]});t.length!==0&&(this.attachmentsElement={id:E.Attachments,data:t})}createSegment(){this.createTracks(),this.maybeCreateTags(),this.maybeCreateAttachments(),this.maybeCreateSeekHead(!1);const e={id:E.Segment,size:this.format._options.appendOnly?-1:Pd,data:[this.seekHead,this.segmentInfo,this.tracksElement,this.attachmentsElement,this.tagsElement]};if(this.segment=e,this.format._options.onSegmentHeader&&this.writer.startTrackingWrites(),this.ebmlWriter.writeEBML(e),this.format._options.onSegmentHeader){const{data:t,start:i}=this.writer.stopTrackingWrites();this.format._options.onSegmentHeader(t,i)}}createCues(){this.cues={id:E.Cues,data:[]}}get segmentDataOffset(){return S(this.segment),this.ebmlWriter.dataOffsets.get(this.segment)}allTracksAreKnown(){for(const e of this.output.tracks)if(!e.source._closed&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;const e=this.trackDatas.map(t=>t.type==="video"||t.type==="audio"?t.info.decoderConfig.codec:{webvtt:"wvtt"}[t.track.source._codec]);return ib({isWebM:this.format instanceof Ir,hasVideo:this.trackDatas.some(t=>t.type==="video"),hasAudio:this.trackDatas.some(t=>t.type==="audio"),codecStrings:e})}getVideoTrackData(e,t,i){const n=this.trackDatas.find(c=>c.track===e);if(n)return n;Jl(i,e.source._codec),S(i),S(i.decoderConfig),S(i.decoderConfig.codedWidth!==void 0),S(i.decoderConfig.codedHeight!==void 0);const r=i.decoderConfig.displayAspectWidth,o=i.decoderConfig.displayAspectHeight,a=r===void 0||o===void 0?null:Xl({num:r,den:o}),l={track:e,type:"video",info:{width:i.decoderConfig.codedWidth,height:i.decoderConfig.codedHeight,aspectRatio:a,decoderConfig:i.decoderConfig,alphaMode:e.metadata.canBeTransparent||(t?!!t.sideData.alpha:null)},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:i.decoderConfig.description??null,closed:!1};return e.source._codec==="vp9"?l.codecPrivate=new Uint8Array(Nw(l.info.decoderConfig.codec)):e.source._codec==="av1"?l.codecPrivate=new Uint8Array(U0(l.info.decoderConfig.codec)):e.source._codec==="prores"&&(l.codecPrivate=bt.encode(i.decoderConfig.codec)),this.trackDatas.push(l),this.trackDatas.sort((c,h)=>c.track.id-h.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),l}getAudioTrackData(e,t,i){const n=this.trackDatas.find(l=>l.track===e);if(n)return n;ec(i,e.source._codec),S(i),S(i.decoderConfig);const r={...i.decoderConfig};let o=!1;if(e.source._codec==="aac"&&!r.description){if(!t)throw new Error("No AAC description provided; you must therefore provide a priming packet.");const l=ro(Ws.tempFromBytes(t.data));if(!l)throw new Error("Couldn't parse ADTS header from the AAC packet. Make sure the packets are in ADTS format (as specified in ISO 13818-7) when not providing a description, or provide a description (must be an AudioSpecificConfig as specified in ISO 14496-3) and ensure the packets are raw AAC data.");const c=Ni[l.samplingFrequencyIndex],h=wo[l.channelConfiguration];if(c===void 0||h===void 0)throw new Error("Invalid ADTS frame header.");r.description=Kl({objectType:l.objectType,outputSampleRate:c,outputNumberOfChannels:h}),o=!0}const a={track:e,type:"audio",info:{numberOfChannels:i.decoderConfig.numberOfChannels,sampleRate:i.decoderConfig.sampleRate,decoderConfig:r,requiresAdtsStripping:o,codecDelay:null},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:r.description??null,closed:!1};return this.trackDatas.push(a),this.trackDatas.sort((l,c)=>l.track.id-c.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),a}getSubtitleTrackData(e,t){const i=this.trackDatas.find(r=>r.track===e);if(i)return i;Z0(t),S(t),S(t.config);const n={track:e,type:"subtitle",info:{config:t.config},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:bt.encode(t.config.description),closed:!1};return this.trackDatas.push(n),this.trackDatas.sort((r,o)=>r.track.id-o.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),n}async addEncodedVideoPacket(e,t,i){const n=await this.mutex.acquire();try{const r=this.getVideoTrackData(e,t,i);r.info.alphaMode??=!!t.sideData.alpha;let o=t.data;if(e.source._codec==="prores"){if(o.byteLength<8)throw new Error("ProRes packet too small, expected at least 8 bytes.");o=o.subarray(8)}const a=t.type==="key";this.validateTimestamp(r.track,t.timestamp,a);let l=t.timestamp,c=t.duration;e.metadata.frameRate!==void 0&&(l=so(l,e.metadata.frameRate),c=so(c,e.metadata.frameRate));const h=r.info.alphaMode?t.sideData.alpha??null:null,d=this.createInternalChunk(o,l,c,t.type,h);e.source._codec==="vp9"&&this.fixVP9ColorSpace(r,d),r.chunkQueue.push(d),await this.interleaveChunks()}finally{n()}}async addEncodedAudioPacket(e,t,i){const n=await this.mutex.acquire();try{const r=this.getAudioTrackData(e,t,i);let o=t.data;if(r.info.requiresAdtsStripping){const c=ro(Ws.tempFromBytes(o));if(!c)throw new Error("Expected ADTS frame, didn't get one.");const h=c.crcCheck===null?no:Y0;o=o.subarray(h)}const a=t.type==="key";this.validateTimestamp(r.track,t.timestamp,a),r.info.codecDelay??=Math.max(-t.timestamp,0);const l=this.createInternalChunk(o,t.timestamp+r.info.codecDelay,t.duration,t.type);r.chunkQueue.push(l),await this.interleaveChunks()}finally{n()}}async addSubtitleCue(e,t,i){const n=await this.mutex.acquire();try{const r=this.getSubtitleTrackData(e,i);this.validateTimestamp(r.track,t.timestamp,!0);let o=t.text;const a=Math.round(t.timestamp*1e3);oo.lastIndex=0,o=o.replace(oo,d=>{const f=_b(d.slice(1,-1))-a;return`<${cf(f)}>`});const l=bt.encode(o),c=`${t.settings??""}
|
|
2199
|
-
${t.identifier??""}
|
|
2200
|
-
${t.notes??""}`,h=this.createInternalChunk(l,t.timestamp,t.duration,"key",c.trim()?bt.encode(c):null);r.chunkQueue.push(h),await this.interleaveChunks()}finally{n()}}async interleaveChunks(e=!1){if(!(!e&&!this.allTracksAreKnown())){e:for(;;){let t=null,i=1/0;for(const r of this.trackDatas){if(!e&&r.chunkQueue.length===0&&!r.closed)break e;r.chunkQueue.length>0&&r.chunkQueue[0].timestamp<i&&(t=r,i=r.chunkQueue[0].timestamp)}if(!t)break;const n=t.chunkQueue.shift();this.addBlock(t,n)}e||await this.writer.flush()}}fixVP9ColorSpace(e,t){if(t.type!=="key"||!e.info.decoderConfig.colorSpace||!e.info.decoderConfig.colorSpace.matrix)return;const i=new je(t.data);i.skipBits(2);const n=i.readBits(1),o=(i.readBits(1)<<1)+n;if(o===3&&i.skipBits(1),i.readBits(1)||i.readBits(1)!==0||(i.skipBits(2),i.readBits(24)!==4817730))return;o>=2&&i.skipBits(1);const h={rgb:7,bt709:2,bt470bg:1,smpte170m:3}[e.info.decoderConfig.colorSpace.matrix];M5(t.data,i.pos,i.pos+3,h)}createInternalChunk(e,t,i,n,r=null){return{data:e,type:n,timestamp:t,duration:i,additions:r}}addBlock(e,t){this.segment||this.createSegment();const i=Math.round(1e3*t.timestamp),n=this.trackDatas.every(a=>{if(e===a)return t.type==="key";const l=a.chunkQueue[0];return l?l.type==="key":a.closed});let r=!1;if(this.currentClusterStartMsTimestamp===null)r=!0;else{S(this.currentClusterMaxMsTimestamp!==null);const a=i-this.currentClusterStartMsTimestamp;r=n&&i>this.currentClusterMaxMsTimestamp&&a>=1e3*(this.format._options.minimumClusterDuration??1)||a>Hv}if(r&&this.startNewCluster(i),i-this.currentClusterStartMsTimestamp<Wv){if(!this.warnedAboutTooNegativeTimestamp){const a=this.format instanceof Ir?"WebM":"Matroska";Re._warn(`Packets had to be discarded because their timestamp is too negative to represent in ${a}.`),this.warnedAboutTooNegativeTimestamp=!0}return}this.currentClusterBlocks.push({trackData:e,chunk:t,msTimestamp:i,previousMsTimestamp:e.lastWrittenMsTimestamp}),this.startTimestamp=Math.min(this.startTimestamp,i),this.endTimestamp=Math.max(this.endTimestamp,i+Math.round(1e3*t.duration)),e.lastWrittenMsTimestamp=i,this.currentClusterMaxMsTimestamp=Math.max(this.currentClusterMaxMsTimestamp,i)}startNewCluster(e){this.currentClusterStartMsTimestamp!==null&&this.writeCurrentCluster();const t=Math.max(0,e);this.currentClusterStartMsTimestamp=t,this.currentClusterMaxMsTimestamp=t}writeCurrentCluster(){S(this.currentClusterStartMsTimestamp!==null);const e=this.currentClusterStartMsTimestamp,t=new Map,i=new Map;for(const h of this.currentClusterBlocks)h.chunk.type==="key"&&!t.has(h.trackData)&&t.set(h.trackData,h),i.set(h.trackData,h);const n=new Map;for(const h of this.currentClusterBlocks)n.set(h,this.createBlockElement(h,e,i.get(h.trackData)===h));const r={id:E.Cluster,size:this.format._options.appendOnly?-1:Uv,data:[{id:E.Timestamp,data:e},...n.values()]};if(this.format._options.onCluster&&this.writer.startTrackingWrites(),this.ebmlWriter.writeEBML(r),this.currentClusterBlocks=[],this.format._options.onCluster){const{data:h,start:d}=this.writer.stopTrackingWrites();this.format._options.onCluster(h,d,e/1e3)}const o=this.ebmlWriter.offsets.get(r)-this.segmentDataOffset,a=this.ebmlWriter.dataOffsets.get(r),l=new Map;for(const h of t.values())l.has(h.msTimestamp)||l.set(h.msTimestamp,[]),l.get(h.msTimestamp).push(h);const c=[...l.entries()].sort((h,d)=>h[0]-d[0]);for(const[h,d]of c)S(this.cues),this.cues.data.push({id:E.CuePoint,data:[{id:E.CueTime,data:Math.max(0,h)},...d.map(u=>{const f=this.ebmlWriter.offsets.get(n.get(u));return{id:E.CueTrackPositions,data:[{id:E.CueTrack,data:u.trackData.track.id},{id:E.CueClusterPosition,data:o},{id:E.CueRelativePosition,data:f-a}]}})]})}createBlockElement(e,t,i){const{trackData:n,chunk:r,msTimestamp:o}=e,a=new Uint8Array(4),l=new DataView(a.buffer);l.setUint8(0,128|n.track.id),l.setInt16(1,o-t,!1);const c=Math.round(1e3*r.duration);return!!r.additions||n.type==="subtitle"||i&&c>0?{id:E.BlockGroup,data:[{id:E.Block,data:[a,r.data]},r.type==="delta"?{id:E.ReferenceBlock,data:new X0(e.previousMsTimestamp-o)}:null,r.additions?{id:E.BlockAdditions,data:[{id:E.BlockMore,data:[{id:E.BlockAddID,data:1},{id:E.BlockAdditional,data:r.additions}]}]}:null,c>0?{id:E.BlockDuration,data:c}:null]}:(l.setUint8(3,+(r.type==="key")<<7),{id:E.SimpleBlock,data:[a,r.data]})}async onTrackClose(e){const t=await this.mutex.acquire(),i=this.trackDatas.find(n=>n.track===e);i&&(i.closed=!0),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleaveChunks(),t()}async finalize(){const e=await this.mutex.acquire();this.allTracksKnown.resolve();for(const t of this.trackDatas)t.closed=!0;if(this.segment||this.createSegment(),await this.interleaveChunks(!0),this.currentClusterStartMsTimestamp!==null&&this.writeCurrentCluster(),S(this.cues),this.ebmlWriter.writeEBML(this.cues),!this.format._options.appendOnly){const t=this.writer.getPos()-this.segmentDataOffset;this.writer.seek(this.ebmlWriter.offsets.get(this.segment)+4),this.ebmlWriter.writeVarInt(t,Pd);const i=this.startTimestamp===1/0?0:this.endTimestamp;this.segmentDuration.data=new bl(i),this.writer.seek(this.ebmlWriter.offsets.get(this.segmentDuration)),this.ebmlWriter.writeEBML(this.segmentDuration),S(this.seekHead),this.writer.seek(this.ebmlWriter.offsets.get(this.seekHead)),this.maybeCreateSeekHead(!0),this.ebmlWriter.writeEBML(this.seekHead)}e()}}class Gv{constructor(e){this.sourceSampleRate=null,this.sourceNumberOfChannels=null,this.startTime=null,this.bufferStartFrame=0,this.maxWrittenFrame=null,this.targetSampleRate=e.targetSampleRate,this.targetNumberOfChannels=e.targetNumberOfChannels,this.onSample=e.onSample,this.bufferSizeInFrames=Math.floor(this.targetSampleRate*5),this.bufferSizeInSamples=this.bufferSizeInFrames*this.targetNumberOfChannels}doChannelMixerSetup(){S(this.sourceNumberOfChannels!==null);const e=this.sourceNumberOfChannels,t=this.targetNumberOfChannels;e===1&&t===2?this.channelMixer=(i,n)=>i[n*e]:e===1&&t===4?this.channelMixer=(i,n,r)=>i[n*e]*+(r<2):e===1&&t===6?this.channelMixer=(i,n,r)=>i[n*e]*+(r===2):e===2&&t===1?this.channelMixer=(i,n)=>{const r=n*e;return .5*(i[r]+i[r+1])}:e===2&&t===4?this.channelMixer=(i,n,r)=>r<2?i[n*e+r]:0:e===2&&t===6?this.channelMixer=(i,n,r)=>r<2?i[n*e+r]:0:e===4&&t===1?this.channelMixer=(i,n)=>{const r=n*e;return .25*(i[r]+i[r+1]+i[r+2]+i[r+3])}:e===4&&t===2?this.channelMixer=(i,n,r)=>{const o=n*e;return .5*(i[o+r]+i[o+r+2])}:e===4&&t===6?this.channelMixer=(i,n,r)=>{const o=n*e;return r<2?i[o+r]:r===2||r===3?0:i[o+r-2]}:e===6&&t===1?this.channelMixer=(i,n)=>{const r=n*e;return Math.SQRT1_2*(i[r]+i[r+1])+i[r+2]+.5*(i[r+4]+i[r+5])}:e===6&&t===2?this.channelMixer=(i,n,r)=>{const o=n*e;return i[o+r]+Math.SQRT1_2*(i[o+2]+i[o+r+4])}:e===6&&t===4?this.channelMixer=(i,n,r)=>{const o=n*e;return r<2?i[o+r]+Math.SQRT1_2*i[o+2]:i[o+r+2]}:this.channelMixer=(i,n,r)=>r<e?i[n*e+r]:0}ensureTempBufferSize(e){let t=this.tempSourceBuffer.length;for(;t<e;)t*=2;if(t!==this.tempSourceBuffer.length){const i=new Float32Array(t);i.set(this.tempSourceBuffer),this.tempSourceBuffer=i}}async add(e){if(this.sourceSampleRate===null){this.sourceSampleRate=e.sampleRate,this.sourceNumberOfChannels=e.numberOfChannels,this.startTime=e.timestamp;const c=Math.ceil(this.targetSampleRate/this.sourceSampleRate);this.bufferCapacityInFrames=this.bufferSizeInFrames+c,this.outputBuffer=new Float32Array(this.bufferCapacityInFrames*this.targetNumberOfChannels),this.tempSourceBuffer=new Float32Array(this.sourceSampleRate*this.sourceNumberOfChannels),this.doChannelMixerSetup()}S(this.startTime!==null);const t=e.numberOfFrames*e.numberOfChannels;this.ensureTempBufferSize(t);const i=e.allocationSize({planeIndex:0,format:"f32"}),n=new Float32Array(this.tempSourceBuffer.buffer,0,i/4);e.copyTo(n,{planeIndex:0,format:"f32"});const r=Math.round((e.timestamp-this.startTime)*this.sourceSampleRate),o=r+e.numberOfFrames,a=Math.floor((r-1)*this.targetSampleRate/this.sourceSampleRate)+1,l=Math.ceil(o*this.targetSampleRate/this.sourceSampleRate);for(let c=a;c<l;c++){if(c<this.bufferStartFrame)continue;for(;c>=this.bufferStartFrame+this.bufferCapacityInFrames;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames;const h=c-this.bufferStartFrame;S(h<this.bufferCapacityInFrames);const d=c*this.sourceSampleRate/this.targetSampleRate-r,u=Math.floor(d),f=Math.ceil(d),p=d-u;for(let m=0;m<this.targetNumberOfChannels;m++){let g=0,w=0;u>=0&&u<e.numberOfFrames&&(g=this.channelMixer(n,u,m)),f>=0&&f<e.numberOfFrames&&(w=this.channelMixer(n,f,m));const b=g+p*(w-g),y=h*this.targetNumberOfChannels+m;this.outputBuffer[y]+=b}this.maxWrittenFrame===null?this.maxWrittenFrame=h:this.maxWrittenFrame=Math.max(this.maxWrittenFrame,h)}}async finalizeCurrentBuffer(){if(this.maxWrittenFrame===null)return;S(this.startTime!==null);const e=Math.min(this.maxWrittenFrame+1,this.bufferSizeInFrames)*this.targetNumberOfChannels,t=new Float32Array(e);t.set(this.outputBuffer.subarray(0,e));const i=new Mt({format:"f32",sampleRate:this.targetSampleRate,numberOfChannels:this.targetNumberOfChannels,timestamp:this.startTime+this.bufferStartFrame/this.targetSampleRate,data:t});await this.onSample(i),this.outputBuffer.copyWithin(0,this.bufferSizeInSamples),this.outputBuffer.fill(0,this.outputBuffer.length-this.bufferSizeInSamples),this.maxWrittenFrame=this.maxWrittenFrame>=this.bufferSizeInFrames?this.maxWrittenFrame-this.bufferSizeInFrames:null}async finalize(){for(;this.maxWrittenFrame!==null;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames}}var Zv=function(s,e,t){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var i,n;if(t){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");i=e[Symbol.asyncDispose]}if(i===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");i=e[Symbol.dispose],t&&(n=i)}if(typeof i!="function")throw new TypeError("Object not disposable.");n&&(i=function(){try{n.call(this)}catch(r){return Promise.reject(r)}}),s.stack.push({value:e,dispose:i,async:t})}else t&&s.stack.push({async:!0});return e},Xv=(function(s){return function(e){function t(o){e.error=e.hasError?new s(o,e.error,"An error was suppressed during disposal."):o,e.hasError=!0}var i,n=0;function r(){for(;i=e.stack.pop();)try{if(!i.async&&n===1)return n=0,e.stack.push(i),Promise.resolve().then(r);if(i.dispose){var o=i.dispose.call(i.value);if(i.async)return n|=2,Promise.resolve(o).then(r,function(a){return t(a),r()})}else n|=1}catch(a){t(a)}if(n===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return r()}})(typeof SuppressedError=="function"?SuppressedError:function(s,e,t){var i=new Error(t);return i.name="SuppressedError",i.error=s,i.suppressed=e,i});class nc{constructor(){this._connectedTrack=null,this._closingPromise=null,this._closed=!1,this._nominalBitrate=null}_ensureValidAdd(){if(!this._connectedTrack)throw new Error("Source is not connected to an output track.");if(this._connectedTrack.output.state==="canceled")throw new Error("Output has been canceled.");if(this._connectedTrack.output.state==="finalizing"||this._connectedTrack.output.state==="finalized")throw new Error("Output has been finalized.");if(this._connectedTrack.output.state==="pending")throw new Error("Output has not started.");if(this._closed)throw new Error("Source is closed.")}async _start(){}async _flushAndClose(e){}close(){if(this._closingPromise)return;const e=this._connectedTrack;if(!e)throw new Error("Cannot call close without connecting the source to an output track.");if(e.output.state==="pending")throw new Error("Cannot call close before output has been started.");this._closingPromise=(async()=>{await this._flushAndClose(!1),this._closed=!0,!(e.output.state==="finalizing"||e.output.state==="finalized")&&e.output._muxer.onTrackClose(e)})()}async _flushOrWaitForOngoingClose(e){return this._closingPromise??=(async()=>{await this._flushAndClose(e),this._closed=!0})()}}class bf extends nc{constructor(e){if(super(),!ss.includes(e))throw new TypeError(`Invalid video codec '${e}'. Must be one of: ${ss.join(", ")}.`);this._codec=e}}const zd=(s,e)=>{if(s.metadata.hasOnlyKeyPackets&&e.type!=="key")throw new Error("Cannot add non-key packets to a hasOnlyKeyPackets video track.")};class Yv{setError(e){this.errorSet||(this.error=e,this.errorSet=!0)}constructor(e,t){this.source=e,this.encodingConfig=t,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.encoderConfig=null,this.encodersReclaimed=!1,this.muxer=null,this.lastMultipleOfKeyFrameInterval=-1,this.emittedEncoderPackets=0,this.chunkTimestampsAreShiftedByDuration=!1,this.codedWidth=null,this.codedHeight=null,this.outputWidth=null,this.outputHeight=null,this.frameRateLastSample=null,this.frameRateLastTimestamp=null,this.frameRateLastEndTimestamp=null,this.preciseTimings=[],this.customEncoder=null,this.customEncoderCallSerializer=new $0,this.customEncoderQueueSize=0,this.defaultEncodeOptions={},this.alphaEncoder=null,this.splitter=null,this.splitterCreationFailed=!1,this.alphaFrameQueue=[],this.error=null,this.errorSet=!1,this.lastMuxerPromise=Promise.resolve(),this.closed=!1}async add(e,t,i){const n=e;try{this.checkForEncoderError(),this.source._ensureValidAdd();const r=this.encodingConfig,o=r.sizeChangeBehavior??"deny";let a=!1;if(this.codedWidth!==null&&this.codedHeight!==null){if((e.codedWidth!==this.codedWidth||e.codedHeight!==this.codedHeight)&&(a=!0,o==="deny"))throw new Error(`Video sample size must remain constant. Expected ${this.codedWidth}x${this.codedHeight}, got ${e.codedWidth}x${e.codedHeight}. To allow the sample size to change over time, set \`sizeChangeBehavior\` to a value other than 'deny' in the encoding options.`)}else this.codedWidth=e.codedWidth,this.codedHeight=e.codedHeight;if(r.transform?.width!==void 0||r.transform?.height!==void 0||r.transform?.rotate!==void 0||r.transform?.flip!==void 0||r.transform?.crop!==void 0||r.transform?.force===!0||a&&o!=="passThrough"){let d=r.transform?.width,u=r.transform?.height,f=r.transform?.fit??"fill";a&&o!=="passThrough"&&(S(this.outputWidth),S(this.outputHeight),S(o!=="deny"),d=this.outputWidth,u=this.outputHeight,f=o);const p=await e.transform({width:d,height:u,roundDimensionsTo:2,crop:r.transform?.crop,rotate:r.transform?.rotate,flip:r.transform?.flip,fit:f,alpha:r.alpha});(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=p.displayWidth,this.outputHeight=p.displayHeight),t&&e.close(),e=p,t=!0}else(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=e.codedWidth,this.outputHeight=e.codedHeight);const h=r.transform?.frameRate;if(h!==void 0){const d=e.timestamp+e.duration,u=jh(e.timestamp,h);if(this.frameRateLastSample!==null)if(u<=this.frameRateLastTimestamp){this.frameRateLastSample.close(),this.frameRateLastSample=e.clone(),this.frameRateLastEndTimestamp=d;return}else await this.padFrameRate(u,i);e===n&&(e=e.clone(),t=!0),e.setTimestamp(u),e.setDuration(1/h),this.frameRateLastSample?.close(),this.frameRateLastSample=e.clone(),this.frameRateLastTimestamp=u,this.frameRateLastEndTimestamp=d}await this.processAndEncode(e,i)}finally{t&&e.close()}}async processAndEncode(e,t){const i=this.encodingConfig;let n;if(i.transform?.process){let r=i.transform.process(e);if(Is(r)&&(r=await r),r===null)return;Array.isArray(r)||(r=[r]);const o=[];try{for(const a of r)a instanceof St?o.push(a):typeof VideoFrame<"u"&&a instanceof VideoFrame?o.push(new St(a)):o.push(new St(a,{timestamp:e.timestamp,duration:e.duration}))}catch(a){for(const l of o)l!==e&&l.close();for(const l of r)(l instanceof St&&l!==e||typeof VideoFrame<"u"&&l instanceof VideoFrame)&&l.close();throw a}n=o}else n=[e];try{for(const r of n){if(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(r),this.encoderInitialized||await this.ensureEncoderPromise),S(this.encoderInitialized),this.closed)break;this.encodersReclaimed&&this.recreateWebCodecsEncoders();const o=this.encodingConfig.keyFrameInterval??2,a=Math.floor(r.timestamp/o),l={...this.defaultEncodeOptions,...r.encodeOptions,...t},c={...l,keyFrame:l.keyFrame!==void 0?l.keyFrame:o===0||a!==this.lastMultipleOfKeyFrameInterval};if(this.lastMultipleOfKeyFrameInterval=a,this.encodingConfig.onEncodedSample?.(r),this.customEncoder){this.customEncoderQueueSize++;const h=r.clone(),d=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(h,c)).catch(u=>this.setError(u)).finally(()=>{this.customEncoderQueueSize--,h.close()});this.customEncoderQueueSize>=4&&await d}else{S(this.encoder);const h=r.toVideoFrame(),d=Uh(this.preciseTimings,h.timestamp,f=>f.microsecondTimestamp),u=d!==-1?this.preciseTimings[d]:null;if(u&&u.microsecondTimestamp===h.timestamp?(u.timestamp!==r.timestamp&&(u.timestampIsValid=!1),u.duration!==r.duration&&(u.durationIsValid=!1)):(this.preciseTimings.splice(d+1,0,{microsecondTimestamp:h.timestamp,timestamp:r.timestamp,duration:r.duration,timestampIsValid:!0,durationIsValid:!0}),this.preciseTimings.length>128&&this.preciseTimings.shift()),this.alphaEncoder)if(!!h.format&&!h.format.includes("A")||this.splitterCreationFailed){this.alphaFrameQueue.push(null);try{this.encoder.encode(h,c)}finally{h.close()}}else{this.splitter||(this.splitter=new Jv);const{colorFrame:p,alphaFrame:m}=await this.splitter.split(h);this.alphaFrameQueue.push(m);try{this.encoder.encode(p,c)}finally{p.close()}}else try{this.encoder.encode(h,c)}finally{h.close()}this.encoder.encodeQueueSize>=4&&await new Promise(f=>this.encoder.addEventListener("dequeue",f,{once:!0}))}await this.lastMuxerPromise}}finally{for(const r of n)r!==e&&r.close()}}async padFrameRate(e,t){const i=this.encodingConfig.transform.frameRate;S(this.frameRateLastSample);const n=Math.round((e-this.frameRateLastTimestamp)*i);for(let r=1;r<n;r++){const o={stack:[],error:void 0,hasError:!1};try{const a=Zv(o,this.frameRateLastSample.clone(),!1);a.setTimestamp(this.frameRateLastTimestamp+r/i),a.setDuration(1/i),await this.processAndEncode(a,t)}catch(a){o.error=a,o.hasError=!0}finally{Xv(o)}}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{const t=xo(this.encodingConfig.quality,this.encodingConfig.bitrate);S(t!==void 0);const i=ef({...this.encodingConfig,quality:t,width:e.codedWidth,height:e.codedHeight,squarePixelWidth:e.squarePixelWidth,squarePixelHeight:e.squarePixelHeight,framerate:this.source._connectedTrack?.metadata.frameRate});let n=null,r;for(const a of i){const l=a.config;if(this.encodingConfig.onEncoderConfig?.(l),r=rf.find(h=>h.supports(this.encodingConfig.codec,l)),r){n=a;break}if(typeof VideoEncoder>"u")continue;if(l.alpha="discard",this.encodingConfig.alpha==="keep"&&(l.latencyMode="quality"),(l.width%2===1||l.height%2===1)&&(this.encodingConfig.codec==="avc"||this.encodingConfig.codec==="hevc"))throw new Error(`The dimensions ${l.width}x${l.height} are not supported for codec '${this.encodingConfig.codec}'; both width and height must be even numbers. Make sure to round your dimensions to the nearest even number.`);try{if((await VideoEncoder.isConfigSupported(l)).supported){n=a;break}}catch{}}if(!n){if(typeof VideoEncoder>"u")throw new Error(A0("VideoEncoder"));const a=i[0].config,l=i.map(({config:c,quantizer:h})=>h!==null?`quantizer ${h}`:`${c.bitrate} bps`);throw new Error(`This specific encoder configuration (${a.codec}, ${l.join(" / ")}, ${a.width}x${a.height}, hardware acceleration: ${a.hardwareAcceleration??"no-preference"}) is not supported in this environment. Consider using another codec or changing your video parameters.`)}const o=n.config;n.quantizer!==null?this.defaultEncodeOptions=nf(this.encodingConfig.codec,n.quantizer):this.source._nominalBitrate=o.bitrate??null,r?(this.customEncoder=new r,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=o,this.customEncoder.onPacket=(a,l)=>{if(!(a instanceof ls))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(l!==void 0&&(!l||typeof l!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");zd(this.source._connectedTrack,a),this.encodingConfig.onEncodedPacket?.(a,l),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,a,l).catch(c=>{this.setError(c)})},this.customEncoder.onError=a=>{this.setError(a)},await this.customEncoder.init()):(this.encoderConfig=o,this.encodingConfig.codec==="avc"&&En()&&(this.chunkTimestampsAreShiftedByDuration=await Kv()),this.createWebCodecsEncoders()),S(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}createWebCodecsEncoders(){const e=this.encoderConfig;S(e);const t=[],i=[];let n=0,r=0;const o=(l,c)=>{if(R5(l)){this.encodersReclaimed=!0;return}l.stack=c,this.setError(l)},a=new Error("Encoding error").stack;if(this.encoder=new VideoEncoder({output:(l,c)=>{if(!this.alphaEncoder){this.addPacket(l,null,c);return}const h=this.alphaFrameQueue.shift();S(h!==void 0),h?(this.alphaEncoder.encode(h,{...this.defaultEncodeOptions,keyFrame:l.type==="key"}),r++,h.close(),t.push({chunk:l,meta:c})):r===0?this.addPacket(l,null,c):(i.push(n+r),t.push({chunk:l,meta:c}))},error:l=>o(l,a)}),this.encoder.configure(e),this.encodingConfig.alpha==="keep"){const l=new Error("Encoding error").stack;this.alphaEncoder=new VideoEncoder({output:(c,h)=>{r--;const d=t.shift();for(S(d!==void 0),this.addPacket(d.chunk,c,d.meta),n++;i.length>0&&i[0]===n;){i.shift();const u=t.shift();S(u!==void 0),this.addPacket(u.chunk,null,u.meta)}},error:c=>o(c,l)}),this.alphaEncoder.configure(e)}}addPacket(e,t,i){const n={};if(t){const d=new Uint8Array(t.byteLength);t.copyTo(d),n.alpha=d}let r=ls.fromEncodedChunk(e,n);const o=this.encoderConfig;if(S(o),i?.decoderConfig&&(i.decoderConfig.codec=Ww({width:o.width,height:o.height,codec:this.encodingConfig.codec,codecDescription:i.decoderConfig.description?Ke(i.decoderConfig.description):null,colorSpace:i.decoderConfig.colorSpace??null,avcType:o.codec.includes("avc1.")?1:o.codec.includes("avc3.")?3:null,avcCodecInfo:this.encodingConfig.codec==="avc"&&!i.decoderConfig.description?I0(r.data):null,hevcCodecInfo:this.encodingConfig.codec==="hevc"&&!i.decoderConfig.description?N0(r.data):null,vp9CodecInfo:this.encodingConfig.codec==="vp9"?fw(r.data):null,av1CodecInfo:this.encodingConfig.codec==="av1"?pw(r.data):null,proresFormat:null}),this.encodingConfig.codec==="avc"&&i.decoderConfig.description&&En())){const d=tw(Ke(i.decoderConfig.description));let u=d?.sequenceParameterSets[0];if(u&&u[0]===u[1]){S(d),u=u.subarray(1);let f=d.pictureParameterSets[0];f&&(f=f.subarray(1));const p=D0({...d,sequenceParameterSets:[u],pictureParameterSets:f?[f]:[]});i.decoderConfig.description=p}}let a=e.timestamp;this.chunkTimestampsAreShiftedByDuration&&(a-=e.duration??0,r=r.clone({timestamp:a/1e6}));const l=Uh(this.preciseTimings,a,d=>d.microsecondTimestamp),c=l!==-1?this.preciseTimings[l]:null;let h=null;this.emittedEncoderPackets===0&&r.type==="delta"&&i?.decoderConfig&&(h=bw(this.encodingConfig.codec,i.decoderConfig,r.data)),(c&&c.microsecondTimestamp===a||h!==null)&&(r=r.clone({timestamp:c?.timestampIsValid?c.timestamp:void 0,duration:c?.durationIsValid?c.duration:void 0,type:h??void 0})),zd(this.source._connectedTrack,r),this.encodingConfig.onEncodedPacket?.(r,i),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,r,i).catch(d=>{this.setError(d)}),this.emittedEncoderPackets++}recreateWebCodecsEncoders(){S(this.encoder),this.encoder.state!=="closed"&&this.encoder.close(),this.alphaEncoder&&this.alphaEncoder.state!=="closed"&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(e=>e?.close()),this.alphaFrameQueue.length=0,this.encodersReclaimed=!1,this.lastMultipleOfKeyFrameInterval=-1,this.createWebCodecsEncoders()}async flushAndClose(e){try{if(!e&&(this.checkForEncoderError(),this.frameRateLastSample)){const t=this.encodingConfig.transform.frameRate,i=jh(this.frameRateLastEndTimestamp,t);await this.padFrameRate(i)}this.closed=!0,e||(this.customEncoder?this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()):this.encoder&&!this.encodersReclaimed&&(await this.encoder.flush(),await this.alphaEncoder?.flush(),await U5(25)))}finally{this.closed=!0,this.frameRateLastSample?.close(),this.frameRateLastSample=null,this.customEncoder?await this.customEncoderCallSerializer.call(()=>this.customEncoder.close()).catch(t=>this.setError(t)):this.encoder&&(this.encoder.state!=="closed"&&this.encoder.close(),this.alphaEncoder&&this.alphaEncoder.state!=="closed"&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(t=>t?.close()),this.alphaFrameQueue.length=0,this.splitter?.close())}e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.errorSet)throw this.error}}let Qv=null;const Kv=()=>Qv??=(async()=>{let s=null;const e=new VideoEncoder({output:t=>{s??=t.timestamp},error:()=>{}});try{e.configure({codec:"avc1.64001f",width:1280,height:720});const t=new VideoFrame(new Uint8Array(1280*720*1.5),{format:"I420",codedWidth:1280,codedHeight:720,timestamp:0,duration:500});e.encode(t,{keyFrame:!0}),t.close(),await e.flush()}catch{return!1}finally{e.state!=="closed"&&e.close()}return s===500})();let Aa=null;class Jv{constructor(){this.worker=null,this.pendingRequests=new Map,this.nextRequestId=0}split(e){if(!this.worker){if(!Aa){const n=new Blob([`(${ey.toString()})()`],{type:"application/javascript"});Aa=URL.createObjectURL(n)}this.worker=new Worker(Aa),this.worker.addEventListener("message",n=>{const r=n.data,o=this.pendingRequests.get(r.id);o&&(this.pendingRequests.delete(r.id),"error"in r?o.reject(new Error(r.error)):o.resolve({colorFrame:r.colorFrame,alphaFrame:r.alphaFrame}))}),this.worker.addEventListener("error",n=>{const r=new Error(n.message||"Color/alpha splitter worker error.");for(const o of this.pendingRequests.values())o.reject(r);this.pendingRequests.clear()})}const t=this.nextRequestId++,i=Gn();return this.pendingRequests.set(t,i),this.worker.postMessage({id:t,sourceFrame:e},{transfer:[e]}),i.promise}close(){this.worker?.terminate(),this.worker=null;const e=new Error("Color/alpha splitter closed.");for(const t of this.pendingRequests.values())t.reject(e);this.pendingRequests.clear()}}const ey=()=>{let s=null,e=Promise.resolve();self.addEventListener("message",r=>{const{id:o,sourceFrame:a}=r.data;e=e.then(async()=>{try{const{colorFrame:l,alphaFrame:c}=await t(a);self.postMessage({id:o,colorFrame:l,alphaFrame:c},{transfer:[l,c]})}catch(l){self.postMessage({id:o,error:l.message})}finally{a.close()}})});const t=async r=>{const o=r.format;if(!o)throw new Error("CPU color/alpha splitting requires a known VideoFrame format.");const a=r.allocationSize();if((!s||s.byteLength!==a)&&(s=new Uint8Array(a)),await r.copyTo(s),o==="RGBA"||o==="BGRA")return i(s,o,r);if(o==="I420A"||o==="I420AP10"||o==="I420AP12"||o==="I422A"||o==="I422AP10"||o==="I422AP12"||o==="I444A"||o==="I444AP10"||o==="I444AP12")return n(s,o,r);throw new Error(`CPU color/alpha splitting does not support format '${o}'.`)},i=(r,o,a)=>{const l=a.visibleRect?.width??a.codedWidth,c=a.visibleRect?.height??a.codedHeight,h=l*c,d=Math.ceil(l/2),u=Math.ceil(c/2),f=h+d*u*2,p=new Uint8Array(f);for(let b=0,y=3;b<h;b++,y+=4)p[b]=r[y];p.fill(128,h);const m=new VideoFrame(r,{format:o==="RGBA"?"RGBX":"BGRX",codedWidth:l,codedHeight:c,timestamp:a.timestamp,duration:a.duration??void 0}),g={format:"I420",codedWidth:l,codedHeight:c,timestamp:a.timestamp,duration:a.duration??void 0,colorSpace:{fullRange:!0,matrix:"bt709",primaries:"bt709",transfer:"bt709"},transfer:[p.buffer]},w=new VideoFrame(p,g);return{colorFrame:m,alphaFrame:w}},n=(r,o,a)=>{const l=a.visibleRect?.width??a.codedWidth,c=a.visibleRect?.height??a.codedHeight,h=o.includes("P10"),d=o.includes("P12"),u=h||d?2:1;let f,p;o.startsWith("I420")?(f=Math.ceil(l/2),p=Math.ceil(c/2)):o.startsWith("I422")?(f=Math.ceil(l/2),p=c):(f=l,p=c);const m=l*c,g=f*p,w=m*u,b=g*u,y=m*u,C=w+b*2,_=o.replace("A",""),x=Math.ceil(l/2),T=Math.ceil(c/2),M=x*T,k=M*u,A=y+2*k,P=new Uint8Array(A),$=C;P.set(r.subarray($,$+y),0);const H=y,q=h?512:d?2048:128;u===1?P.fill(q,H):new Uint16Array(P.buffer,H,2*M).fill(q);const Y=h?"I420P10":d?"I420P12":"I420",G=new VideoFrame(r.subarray(0,C),{format:_,codedWidth:l,codedHeight:c,timestamp:a.timestamp,duration:a.duration??void 0}),ee={format:Y,codedWidth:l,codedHeight:c,timestamp:a.timestamp,duration:a.duration??void 0,colorSpace:{fullRange:!0,matrix:"bt709",primaries:"bt709",transfer:"bt709"},transfer:[P.buffer]},se=new VideoFrame(P,ee);return{colorFrame:G,alphaFrame:se}}};class ty extends bf{get errorPromise(){return this._errorPromiseAccessed=!0,this._promiseWithResolvers.promise}get paused(){return this._paused}constructor(e,t,i={}){if(!(e instanceof MediaStreamTrack)||e.kind!=="video")throw new TypeError("track must be a video MediaStreamTrack.");if(gb(t),typeof i!="object"||!i)throw new TypeError("options must be an object.");if(i.frameRate!=null&&(typeof i.frameRate!="number"||i.frameRate<=0))throw new TypeError("options.frameRate, when provided, must be either a positive number or null.");if(i.timestampBase!==void 0&&i.timestampBase!=="synced-zero"&&i.timestampBase!=="zero"&&i.timestampBase!=="unix")throw new TypeError("options.timestampBase, when provided, must be one of 'synced-zero', 'zero', or 'unix'.");t={...t,latencyMode:"realtime"},super(t.codec),this._abortController=null,this._workerTrackId=null,this._workerListener=null,this._promiseWithResolvers=Gn(),this._errorPromiseAccessed=!1,this._paused=!1,this._lastVideoFrame=null,this._timerHandle=null,this._videoElement=null,this._options=i,this._encoder=new Yv(this,t),this._track=e}async _start(){this._errorPromiseAccessed||Re._warn("Make sure not to ignore the `errorPromise` field on MediaStreamVideoTrackSource, so that any internal errors get bubbled up properly.");const e=this._options.frameRate!==void 0?this._options.frameRate:this._track.getSettings().frameRate??null;this._abortController=new AbortController;let t=null,i=null,n=0,r=!1,o=null,a=0;const l=()=>{if(S(e!==null),!this._lastVideoFrame)return;S(i!==null),S(t!==null);const d=performance.now();for(;d-i>1e3/e;){i+=1e3/e;const u=t+n/e,f=new VideoFrame(this._videoElement??this._lastVideoFrame,{timestamp:1e6*u,duration:1e6/e});h(f,d)}};e!==null&&(this._timerHandle=W5(l,4));const c=d=>{if(e===null)h(d);else{const u=performance.now();this._lastVideoFrame?(l(),this._lastVideoFrame?.close(),this._lastVideoFrame=d):(h(d.clone(),u),i=u,this._lastVideoFrame=d)}},h=(d,u=performance.now())=>{if(r){d.close();return}n++;const f=d.timestamp/1e6;if(this._paused){if(t!==null){if(o!==null&&this._options.timestampBase!=="unix"){const g=f-o;a-=g}o=f}d.close();return}if(t===null){t=f;let m;const g=this._options.timestampBase??"synced-zero";if(g==="unix")m=Date.now()/1e3;else if(g==="zero")m=0;else{const w=this._connectedTrack.output;w._firstMediaStreamTimestamp===null?(w._firstMediaStreamTimestamp=u/1e3,m=0):m=u/1e3-w._firstMediaStreamTimestamp}a=m-t}if(o=f,this._encoder.getQueueSize()>=8){d.close();return}const p=new St(d,{timestamp:f+a});this._encoder.add(p,!0).catch(m=>{r=!0,this._abortController?.abort(),this._promiseWithResolvers.reject(m),this._workerTrackId!==null&&za({type:"stopTrack",trackId:this._workerTrackId})})};if(typeof MediaStreamTrackProcessor<"u"){const d=new MediaStreamTrackProcessor({track:this._track}),u=new WritableStream({write:c});d.readable.pipeTo(u,{signal:this._abortController.signal}).catch(f=>{f instanceof DOMException&&f.name==="AbortError"||this._promiseWithResolvers.reject(f)})}else if(await ly())this._workerTrackId=oy++,za({type:"videoTrack",trackId:this._workerTrackId,track:this._track}),this._workerListener=u=>{const f=u.data;f.type==="videoFrame"&&f.trackId===this._workerTrackId?c(f.videoFrame):f.type==="error"&&f.trackId===this._workerTrackId&&this._promiseWithResolvers.reject(f.error)},Jt.addEventListener("message",this._workerListener);else if(e!==null){const u=document.createElement("video");u.style.position="fixed",u.style.left="-10000px",u.style.top="-10000px",u.style.width="1px",u.style.height="1px",u.style.opacity="0",u.style.pointerEvents="none",u.muted=!0,u.srcObject=new MediaStream([this._track]),document.body.appendChild(u),this._videoElement=u,u.addEventListener("loadeddata",()=>{if(r||!this._videoElement)return;const f=new VideoFrame(u,{timestamp:1e3*performance.now()});c(f),f.close()},{once:!0}),u.play().catch(f=>{r=!0,this._promiseWithResolvers.reject(f)})}else throw new Error("When no explicit frame rate is set, MediaStreamTrackProcessor is required; but it's not available in this environment.")}pause(){this._paused=!0}resume(){this._paused=!1}async _flushAndClose(e){try{this._abortController&&(this._abortController.abort(),this._abortController=null),this._timerHandle&&H5(this._timerHandle),this._lastVideoFrame?.close(),this._videoElement&&(this._videoElement.srcObject=null,this._videoElement.remove(),this._videoElement=null),this._workerTrackId!==null&&(S(this._workerListener),za({type:"stopTrack",trackId:this._workerTrackId}),await new Promise(t=>{const i=n=>{const r=n.data;r.type==="trackStopped"&&r.trackId===this._workerTrackId&&(S(this._workerListener),Jt.removeEventListener("message",this._workerListener),Jt.removeEventListener("message",i),t())};Jt.addEventListener("message",i)}))}finally{await this._encoder.flushAndClose(e)}}}class vf extends nc{constructor(e){if(super(),!Vs.includes(e))throw new TypeError(`Invalid audio codec '${e}'. Must be one of: ${Vs.join(", ")}.`);this._codec=e}}class sy{setError(e){this.errorSet||(this.error=e,this.errorSet=!0)}constructor(e,t){this.source=e,this.encodingConfig=t,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastNumberOfChannels=null,this.lastSampleRate=null,this.isPcmEncoder=!1,this.outputSampleSize=null,this.writeOutputValue=null,this.customEncoder=null,this.customEncoderCallSerializer=new $0,this.customEncoderQueueSize=0,this.lastEndSampleIndex=null,this.resampler=null,this.error=null,this.errorSet=!1,this.lastMuxerPromise=Promise.resolve(),this.closed=!1}async add(e,t){try{if(this.checkForEncoderError(),this.source._ensureValidAdd(),this.lastNumberOfChannels!==null&&this.lastSampleRate!==null){if(e.numberOfChannels!==this.lastNumberOfChannels||e.sampleRate!==this.lastSampleRate)throw new Error(`Audio parameters must remain constant. Expected ${this.lastNumberOfChannels} channels at ${this.lastSampleRate} Hz, got ${e.numberOfChannels} channels at ${e.sampleRate} Hz.`)}else this.lastNumberOfChannels=e.numberOfChannels,this.lastSampleRate=e.sampleRate;const i=this.encodingConfig;i.transform?.numberOfChannels!==void 0||i.transform?.sampleRate!==void 0?(this.resampler||(this.resampler=new Gv({targetNumberOfChannels:i.transform.numberOfChannels??e.numberOfChannels,targetSampleRate:i.transform.sampleRate??e.sampleRate,onSample:async r=>{await this.processAndEncode(r,!0)}})),await this.resampler.add(e)):await this.processAndEncode(e,t)}finally{t&&e.close()}}async processAndEncode(e,t){const i=this.encodingConfig;if(i.transform?.sampleFormat!==void 0&&fb(e.format)!==i.transform.sampleFormat){const n=mb(e,i.transform.sampleFormat);t&&e.close(),e=n,t=!0}if(i.transform?.process)try{let n=i.transform.process(e);if(Is(n)&&(n=await n),n===null)return;Array.isArray(n)||(n=[n]);try{for(const r of n)if(!(r instanceof Mt))throw new TypeError("The audio process function must return an AudioSample, null, or an array of AudioSamples.");for(const r of n)await this.encodeSample(r,!0)}finally{for(const r of n)r instanceof Mt&&r.close()}}finally{t&&e.close()}else await this.encodeSample(e,t)}async encodeSample(e,t){try{if(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),S(this.encoderInitialized),this.closed)return;{const i=Math.round(e.timestamp*e.sampleRate),n=Math.round((e.timestamp+e.duration)*e.sampleRate);if(this.lastEndSampleIndex===null)this.lastEndSampleIndex=n;else{const r=i-this.lastEndSampleIndex;if(r>=64){const o=new Mt({data:new Float32Array(r*e.numberOfChannels),format:"f32-planar",sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels,numberOfFrames:r,timestamp:this.lastEndSampleIndex/e.sampleRate});await this.encodeSample(o,!0)}this.lastEndSampleIndex+=e.numberOfFrames}}if(this.encodingConfig.onEncodedSample?.(e),this.customEncoder){this.customEncoderQueueSize++;const i=e.clone(),n=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(i)).catch(r=>this.setError(r)).finally(()=>{this.customEncoderQueueSize--,i.close()});this.customEncoderQueueSize>=4&&await n,await this.lastMuxerPromise}else if(this.isPcmEncoder)await this.doPcmEncoding(e,t);else{S(this.encoder);const i=e.toAudioData();this.encoder.encode(i),i.close(),t&&e.close(),this.encoder.encodeQueueSize>=4&&await new Promise(n=>this.encoder.addEventListener("dequeue",n,{once:!0})),await this.lastMuxerPromise}}finally{t&&e.close()}}async doPcmEncoding(e,t){S(this.outputSampleSize),S(this.writeOutputValue);const{numberOfChannels:i,numberOfFrames:n,sampleRate:r,timestamp:o}=e,a=2048,l=[];for(let m=0;m<n;m+=a){const g=Math.min(a,e.numberOfFrames-m),w=g*i*this.outputSampleSize,b=new ArrayBuffer(w),y=new DataView(b);l.push({frameCount:g,view:y})}const c=e.format==="s32"||e.format==="s32-planar",h=c?"s32-planar":"f32-planar",d=c?1/2147483648:1,u=e.allocationSize({planeIndex:0,format:h}),f=c?new Int32Array(u/4):new Float32Array(u/4);for(let m=0;m<i;m++){e.copyTo(f,{planeIndex:m,format:h});for(let g=0;g<l.length;g++){const{frameCount:w,view:b}=l[g];for(let y=0;y<w;y++)this.writeOutputValue(b,(y*i+m)*this.outputSampleSize,f[g*a+y]*d)}}t&&e.close();const p={decoderConfig:{codec:this.encodingConfig.codec,numberOfChannels:i,sampleRate:r}};for(let m=0;m<l.length;m++){const{frameCount:g,view:w}=l[m],b=w.buffer,y=m*a,C=new ls(new Uint8Array(b),"key",o+y/r,g/r);this.encodingConfig.onEncodedPacket?.(C,p),await this.muxer.addEncodedAudioPacket(this.source._connectedTrack,C,p)}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{const{numberOfChannels:t,sampleRate:i,timestamp:n}=e,r=xo(this.encodingConfig.quality,this.encodingConfig.bitrate),o=sf({numberOfChannels:t,sampleRate:i,...this.encodingConfig,quality:r});this.encodingConfig.onEncoderConfig?.(o),this.source._nominalBitrate=o.bitrate??null;const a=of.find(l=>l.supports(this.encodingConfig.codec,o));if(a)this.customEncoder=new a,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=o,this.customEncoder.onPacket=(l,c)=>{if(!(l instanceof ls))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(c!==void 0&&(!c||typeof c!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");this.encodingConfig.onEncodedPacket?.(l,c),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,l,c).catch(h=>{this.setError(h)})},this.customEncoder.onError=l=>{this.setError(l)},await this.customEncoder.init();else if(Lt.includes(this.encodingConfig.codec))this.initPcmEncoder();else{if(typeof AudioEncoder>"u")throw new Error(A0("AudioEncoder"));let l;try{l=(await AudioEncoder.isConfigSupported(o)).supported??!1}catch{l=!1}if(!l)throw new Error(`This specific encoder configuration (${o.codec}, ${o.bitrate} bps, ${o.numberOfChannels} channels, ${o.sampleRate} Hz) is not supported in this environment. Consider using another codec or changing your audio parameters.`);const h=await iy(this.encodingConfig.codec,o.codec)/o.sampleRate;let d=0;const u=new Error("Encoding error").stack;this.encoder=new AudioEncoder({output:(f,p)=>{if(p?.decoderConfig&&(Cf(this.encodingConfig.codec,o,p.decoderConfig),this.encodingConfig.codec==="opus"&&p.decoderConfig.description)){const g=Ke(p.decoderConfig.description);d=H0(g).preSkip/j0}let m=ls.fromEncodedChunk(f);m=m.clone({timestamp:so(m.timestamp-h-d,o.sampleRate),duration:f.duration!=null?so(m.duration,o.sampleRate):void 0}),En()&&(d=0),this.encodingConfig.onEncodedPacket?.(m,p),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,m,p).catch(g=>{this.setError(g)})},error:f=>{f.stack=u,this.setError(f)}}),this.encoder.configure(o),this.encodingConfig.codec==="aac"&&go()&&yf(this.encoder,t,i,n)}S(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}initPcmEncoder(){this.isPcmEncoder=!0;const e=this.encodingConfig.codec,{dataType:t,sampleSize:i,littleEndian:n}=Ns(e);switch(this.outputSampleSize=i,i){case 1:t==="unsigned"?this.writeOutputValue=(r,o,a)=>r.setUint8(o,ct(Math.round(a*128)+128,0,255)):t==="signed"?this.writeOutputValue=(r,o,a)=>{r.setInt8(o,ct(Math.round(a*128),-128,127))}:t==="ulaw"?this.writeOutputValue=(r,o,a)=>{const l=ct(Math.round(a*32768),-32768,32767);r.setUint8(o,xb(l))}:t==="alaw"?this.writeOutputValue=(r,o,a)=>{const l=ct(Math.round(a*32768),-32768,32767);r.setUint8(o,Mb(l))}:S(!1);break;case 2:t==="unsigned"?this.writeOutputValue=(r,o,a)=>r.setUint16(o,ct(Math.round(a*32768)+32768,0,65535),n):t==="signed"?this.writeOutputValue=(r,o,a)=>r.setInt16(o,ct(Math.round(a*32768),-32768,32767),n):S(!1);break;case 3:t==="unsigned"?this.writeOutputValue=(r,o,a)=>Gl(r,o,ct(Math.round(a*8388608)+8388608,0,16777215),n):t==="signed"?this.writeOutputValue=(r,o,a)=>_5(r,o,ct(Math.round(a*8388608),-8388608,8388607),n):S(!1);break;case 4:t==="unsigned"?this.writeOutputValue=(r,o,a)=>r.setUint32(o,ct(Math.round(a*2147483648)+2147483648,0,4294967295),n):t==="signed"?this.writeOutputValue=(r,o,a)=>r.setInt32(o,ct(Math.round(a*2147483648),-2147483648,2147483647),n):t==="float"?this.writeOutputValue=(r,o,a)=>r.setFloat32(o,a,n):S(!1);break;case 8:t==="float"?this.writeOutputValue=(r,o,a)=>r.setFloat64(o,a,n):S(!1);break;default:Gt(i),S(!1)}}async flushAndClose(e){try{e||(this.checkForEncoderError(),this.resampler&&await this.resampler.finalize()),this.closed=!0,e||(this.customEncoder?this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()):this.encoder&&await this.encoder.flush())}finally{this.closed=!0,this.resampler=null,this.customEncoder?await this.customEncoderCallSerializer.call(()=>this.customEncoder.close()).catch(t=>this.setError(t)):this.encoder&&this.encoder.state!=="closed"&&this.encoder.close()}e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.isPcmEncoder?0:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.errorSet)throw this.error}}const Ea=new Map,iy=(s,e)=>{let t=Ea.get(e);return t||(t=(async()=>{const r={codec:e,numberOfChannels:1,sampleRate:48e3,...G0(s)},o=4096,a=2*o,l=[];let c=null,h=null,d=-1/0,u=0,f=null;const p=new AudioEncoder({output:(w,b)=>{b?.decoderConfig&&(c??=b.decoderConfig),l.push(w)},error:w=>{f??=w}}),m=new AudioDecoder({output:w=>{const b=new Float32Array(w.numberOfFrames);w.copyTo(b,{planeIndex:0,format:"f32-planar"}),w.close();for(let y=0;y<b.length;y++)b[y]>d&&(d=b[y],h=u+y);u+=b.length},error:w=>{f??=w}});try{p.configure(r),s==="aac"&&go()&&yf(p,1,48e3,0);const w=new Float32Array(1*a);w[o]=1;const b=new AudioData({data:w,format:"f32-planar",numberOfChannels:1,numberOfFrames:a,sampleRate:48e3,timestamp:0});p.encode(b),b.close(),await p.flush(),S(c),Cf(s,r,c),m.configure(c);for(const y of l)m.decode(y);await m.flush()}catch(w){throw f??w}finally{p.state!=="closed"&&p.close(),m.state!=="closed"&&m.close()}S(h!==null);const g=Math.round(l[0].timestamp/1e6*48e3);return h-o+g})(),Ea.set(e,t),t.catch(()=>Ea.delete(e)),t)},yf=(s,e,t,i)=>{const r=new AudioData({data:new Float32Array(e*1024),format:"f32-planar",numberOfChannels:e,numberOfFrames:1024,sampleRate:t,timestamp:Math.round(1e6*(i-1024/t))});s.encode(r),r.close()},Cf=(s,e,t)=>{if(s==="aac"){if(t.description&&t.description.byteLength>0&&Ke(t.description)[0]===3){const{decoderSpecificInfo:n}=Jw(Ws.tempFromBytes(Ke(t.description)));t.description=n??void 0}let i=!1;if(!t.description||t.description.byteLength<2?i=!0:i=B0(Ke(t.description)).objectType===0,i){const n=Number(kt(e.codec.split(".")));t.description=Kl({objectType:n,outputNumberOfChannels:t.numberOfChannels,outputSampleRate:t.sampleRate})}}};class ny extends vf{get errorPromise(){return this._errorPromiseAccessed=!0,this._promiseWithResolvers.promise}get paused(){return this._paused}constructor(e,t,i={}){if(!(e instanceof MediaStreamTrack)||e.kind!=="audio")throw new TypeError("track must be an audio MediaStreamTrack.");if(wb(t),typeof i!="object"||!i)throw new TypeError("options must be an object.");if(i.timestampBase!==void 0&&i.timestampBase!=="synced-zero"&&i.timestampBase!=="zero"&&i.timestampBase!=="unix")throw new TypeError("options.timestampBase, when provided, must be one of 'synced-zero', 'zero', or 'unix'.");super(t.codec),this._abortController=null,this._audioContext=null,this._scriptProcessorNode=null,this._promiseWithResolvers=Gn(),this._errorPromiseAccessed=!1,this._paused=!1,this._options=i,this._encoder=new sy(this,t),this._track=e}async _start(){this._errorPromiseAccessed||Re._warn("Make sure not to ignore the `errorPromise` field on MediaStreamAudioTrackSource, so that any internal errors get bubbled up properly."),this._abortController=new AbortController;let e=null,t=!1,i=null,n=0;const r=o=>{if(t){o.close();return}const a=o.timestamp;if(this._paused){if(e!==null){if(i!==null&&this._options.timestampBase!=="unix"){const c=a-i;n-=c}i=a}o.close();return}if(e===null){e=o.timestamp;let l;const c=this._options.timestampBase??"synced-zero";if(c==="unix")l=Date.now()/1e3;else if(c==="zero")l=0;else{const h=this._connectedTrack.output;h._firstMediaStreamTimestamp===null?(h._firstMediaStreamTimestamp=performance.now()/1e3,l=0):l=performance.now()/1e3-h._firstMediaStreamTimestamp}n=l-e}if(i=a,this._encoder.getQueueSize()>=8){o.close();return}o.setTimestamp(a+n),this._encoder.add(o,!0).catch(l=>{t=!0,this._abortController?.abort(),this._promiseWithResolvers.reject(l),this._audioContext?.suspend()})};if(typeof MediaStreamTrackProcessor<"u"){const o=new MediaStreamTrackProcessor({track:this._track}),a=new WritableStream({write:l=>r(new Mt(l))});o.readable.pipeTo(a,{signal:this._abortController.signal}).catch(l=>{l instanceof DOMException&&l.name==="AbortError"||this._promiseWithResolvers.reject(l)})}else{const o=window.AudioContext||window.webkitAudioContext;this._audioContext=new o({sampleRate:this._track.getSettings().sampleRate});const a=this._audioContext.createMediaStreamSource(new MediaStream([this._track]));this._scriptProcessorNode=this._audioContext.createScriptProcessor(4096),this._audioContext.state==="suspended"&&await this._audioContext.resume(),a.connect(this._scriptProcessorNode),this._scriptProcessorNode.connect(this._audioContext.destination);let l=0;this._scriptProcessorNode.onaudioprocess=c=>{const h=Mt._fromAudioBuffer(c.inputBuffer,l);l+=c.inputBuffer.duration;for(const d of h)r(d)}}}pause(){this._paused=!0}resume(){this._paused=!1}async _flushAndClose(e){try{this._abortController&&(this._abortController.abort(),this._abortController=null),this._audioContext&&(S(this._scriptProcessorNode),this._scriptProcessorNode.disconnect(),await this._audioContext.suspend())}finally{await this._encoder.flushAndClose(e)}}}const ry=()=>{const s=(i,n)=>{n?self.postMessage(i,{transfer:n}):self.postMessage(i)};s({type:"support",supported:typeof MediaStreamTrackProcessor<"u"});const e=new Map,t=new Map;self.addEventListener("message",i=>{const n=i.data;switch(n.type){case"videoTrack":{t.set(n.trackId,n.track);const r=new MediaStreamTrackProcessor({track:n.track}),o=new WritableStream({write:l=>{if(!t.has(n.trackId)){l.close();return}s({type:"videoFrame",trackId:n.trackId,videoFrame:l},[l])}}),a=new AbortController;e.set(n.trackId,a),r.readable.pipeTo(o,{signal:a.signal}).catch(l=>{l instanceof DOMException&&l.name==="AbortError"||s({type:"error",trackId:n.trackId,error:l})})}break;case"stopTrack":{const r=e.get(n.trackId);r&&(r.abort(),e.delete(n.trackId)),t.get(n.trackId)?.stop(),t.delete(n.trackId),s({type:"trackStopped",trackId:n.trackId})}break;default:Gt(n)}})};let oy=0,Jt=null;const ay=()=>{const s=new Blob([`(${ry.toString()})()`],{type:"application/javascript"}),e=URL.createObjectURL(s);Jt=new Worker(e)};let Pa=null;const ly=async()=>Pa!==null?Pa:(Jt||ay(),new Promise(s=>{S(Jt);const e=t=>{const i=t.data;i.type==="support"&&(Pa=i.supported,Jt.removeEventListener("message",e),s(i.supported))};Jt.addEventListener("message",e)})),za=(s,e)=>{S(Jt),Jt.postMessage(s)};class cy extends nc{constructor(e){if(super(),!ci.includes(e))throw new TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${ci.join(", ")}.`);this._codec=e}}class rc{get supportsVideoRotationMetadata(){return this.supportsVideoTransformationMetadata}getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>ss.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>Vs.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>ci.includes(e))}_codecUnsupportedHint(e){return""}_isFragmentedIsobmff(){return!1}}class oc extends rc{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.fastStart!==void 0&&![!1,"in-memory","reserve","fragmented"].includes(e.fastStart))throw new TypeError("options.fastStart, when provided, must be false, 'in-memory', 'reserve', or 'fragmented'.");if(e.minimumFragmentDuration!==void 0&&(!E0(e.minimumFragmentDuration)||e.minimumFragmentDuration<0))throw new TypeError("options.minimumFragmentDuration, when provided, must be a non-negative number.");if(e.onFtyp!==void 0&&typeof e.onFtyp!="function")throw new TypeError("options.onFtyp, when provided, must be a function.");if(e.onMoov!==void 0&&typeof e.onMoov!="function")throw new TypeError("options.onMoov, when provided, must be a function.");if(e.onMdat!==void 0&&typeof e.onMdat!="function")throw new TypeError("options.onMdat, when provided, must be a function.");if(e.onMoof!==void 0&&typeof e.onMoof!="function")throw new TypeError("options.onMoof, when provided, must be a function.");if(e.metadataFormat!==void 0&&!["mdir","mdta","udta","auto"].includes(e.metadataFormat))throw new TypeError("options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.");super(),this._options=e}getSupportedTrackCounts(){return{video:{min:0,max:4294967295},audio:{min:0,max:4294967295},subtitle:{min:0,max:4294967295},total:{min:0,max:4294967295}}}get supportsVideoTransformationMetadata(){return!0}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return"full"}_createMuxer(e){return new Nv(e,this)}_isFragmentedIsobmff(){return this._options.fastStart==="fragmented"}}class xf extends oc{constructor(e){super(e)}get _name(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...ss,...vo,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...ci]}_codecUnsupportedHint(e){return new Mf().getSupportedCodecs().includes(e)?" Switching to MOV will grant support for this codec.":""}}class Ld extends oc{constructor(e){super(e)}get _name(){return"CMAF"}get fileExtension(){return".m4s"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...ss,...vo,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...ci]}}class Mf extends oc{constructor(e){super(e)}get _name(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...ss,...Vs]}_codecUnsupportedHint(e){return new xf().getSupportedCodecs().includes(e)?" Switching to MP4 will grant support for this codec.":""}}class Rd extends rc{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.appendOnly!==void 0&&typeof e.appendOnly!="boolean")throw new TypeError("options.appendOnly, when provided, must be a boolean.");if(e.minimumClusterDuration!==void 0&&(!E0(e.minimumClusterDuration)||e.minimumClusterDuration<0))throw new TypeError("options.minimumClusterDuration, when provided, must be a non-negative number.");if(e.onEbmlHeader!==void 0&&typeof e.onEbmlHeader!="function")throw new TypeError("options.onEbmlHeader, when provided, must be a function.");if(e.onSegmentHeader!==void 0&&typeof e.onSegmentHeader!="function")throw new TypeError("options.onHeader, when provided, must be a function.");if(e.onCluster!==void 0&&typeof e.onCluster!="function")throw new TypeError("options.onCluster, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new qv(e,this)}get _name(){return"Matroska"}getSupportedTrackCounts(){return{video:{min:0,max:127},audio:{min:0,max:127},subtitle:{min:0,max:127},total:{min:0,max:127}}}get fileExtension(){return".mkv"}get mimeType(){return"video/x-matroska"}getSupportedCodecs(){return[...ss,...vo,...Lt.filter(e=>!["pcm-s8","pcm-f32be","pcm-f64be","ulaw","alaw"].includes(e)),...ci]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return"prefer-non-negative"}}class Ir extends Rd{constructor(e){super(e)}getSupportedCodecs(){return[...ss.filter(e=>["vp8","vp9","av1"].includes(e)),...Vs.filter(e=>["opus","vorbis"].includes(e)),...ci]}get _name(){return"WebM"}get fileExtension(){return".webm"}get mimeType(){return"video/webm"}_codecUnsupportedHint(e){return new Rd().getSupportedCodecs().includes(e)?" Switching to MKV will grant support for this codec.":""}}const Bd=["video","audio","subtitle"];class Xn{constructor(e,t,i,n,r){this.id=e,this.output=t,this.type=i,this.source=n,this.metadata=r}isVideoTrack(){return this.type==="video"}isAudioTrack(){return this.type==="audio"}isSubtitleTrack(){return this.type==="subtitle"}canBePairedWith(e){if(!(e instanceof Xn))throw new TypeError("other must be an OutputTrack.");if(this===e)return!1;const t=Gh(this.metadata.group),i=Gh(e.metadata.group);for(const n of t)if(this.type!==e.type&&i.some(a=>n===a)||i.some(a=>n._pairedGroups.has(a)))return!0;return!1}}class hy extends Xn{constructor(e,t,i,n){super(e,t,"video",i,n)}}class dy extends Xn{constructor(e,t,i,n){super(e,t,"audio",i,n)}}class uy extends Xn{constructor(e,t,i,n){super(e,t,"subtitle",i,n)}}class zn{constructor(){this._pairedGroups=new Set}pairWith(e){if(!(e instanceof zn))throw new TypeError("other must be an OutputTrackGroup.");if(this===e)throw new TypeError("Cannot pair a group with itself.");this._pairedGroups.add(e),e._pairedGroups.add(this)}}const La=s=>{if(!s||typeof s!="object")throw new TypeError("metadata must be an object.");if(s.languageCode!==void 0&&!E5(s.languageCode))throw new TypeError("metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.");if(s.name!==void 0&&typeof s.name!="string")throw new TypeError("metadata.name, when provided, must be a string.");if(s.disposition!==void 0&&G5(s.disposition),s.maximumPacketCount!==void 0&&(!Number.isInteger(s.maximumPacketCount)||s.maximumPacketCount<0))throw new TypeError("metadata.maximumPacketCount, when provided, must be a non-negative integer.");if(s.bitrate!==void 0&&(!Number.isFinite(s.bitrate)||s.bitrate<0))throw new TypeError("metadata.bitrate, when provided, must be a non-negative number.");if(s.averageBitrate!==void 0&&(!Number.isFinite(s.averageBitrate)||s.averageBitrate<0))throw new TypeError("metadata.averageBitrate, when provided, must be a non-negative number.");if(s.group!==void 0&&!(s.group instanceof zn)&&(!Array.isArray(s.group)||s.group.some(e=>!(e instanceof zn))))throw new TypeError("metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.")};class fy extends Ql{get target(){const e="Output.target cannot be used when using PathedTarget with an async callback. Use the 'target' event instead.";if(this._rootTargetPromise)throw new TypeError(e);const t=this._getRootTarget();if(Is(t))throw new TypeError(e);return t}constructor(e){if(super(),this.state="pending",this.defaultTrackGroup=new zn,this.tracks=[],this._onFinalize=null,this._unfinalizedTargets=new Set,this._rootWriterPromise=null,this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new _0,this._metadataTags={},this._rootTarget=null,this._rootTargetPromise=null,this._firstMediaStreamTimestamp=null,!e||typeof e!="object")throw new TypeError("options must be an object.");if(!(e.format instanceof rc))throw new TypeError("options.format must be an OutputFormat.");if(!(e.target instanceof us||e.target instanceof $a))throw new TypeError("options.target must be a Target or a PathedTarget.");if(e.target instanceof us&&this._rememberTarget(e.target),e.initTarget!==void 0&&!(e.initTarget instanceof us)&&typeof e.initTarget!="function")throw new Error("options.initTarget, when provided, must be a Target or a function that returns or resolves to a Target.");if(e.onFinalize!==void 0&&typeof e.onFinalize!="function")throw new TypeError("options.onFinalize, when provided, must be a function.");this.format=e.format,this._target=e.target,this._onFinalize=e.onFinalize??null,this._initTarget=e.initTarget??null,this._initTarget instanceof us&&this._rememberTarget(this._initTarget),this._muxer=e.format._createMuxer(this)}_getTargetValidated(e){S(this._target instanceof $a);const t=this._target.getTarget(e),i=n=>{if(!(n instanceof us))throw new TypeError("getTarget must return a Target.");return n};return Is(t)?t.then(i):i(t)}async _getTarget(e){S(this._target instanceof $a);const t=await this._getTargetValidated(e);return this._emit("target",{target:t,request:e,isRoot:e.isRoot}),this.state==="canceled"?await t._close():this._rememberTarget(t),t}_rememberTarget(e){this._unfinalizedTargets.add(e),e.on("finalized",()=>this._unfinalizedTargets.delete(e),{once:!0})}async _getInitTarget(){if(S(this._initTarget!==null),this._initTarget instanceof us)return this._initTarget;const e=await this._initTarget();return this.state==="canceled"?await e._close():this._rememberTarget(e),e}_hasInitTarget(){return this._initTarget!==null}_getRootTarget(){if(this._rootTarget)return this._rootTarget;if(this._rootTargetPromise)return this._rootTargetPromise;if(this._target instanceof us)return this._emit("target",{target:this._target,request:null,isRoot:!0}),this._rootTarget=this._target,this._target;const e={path:this._target.rootPath,isRoot:!0,mimeType:this.format.mimeType},t=this._getTargetValidated(e),i=n=>(this.state==="canceled"?n._close():this._rememberTarget(n),this._emit("target",{target:n,request:e,isRoot:!0}),this._rootTarget=n,n);return Is(t)?this._rootTargetPromise=t.then(i):i(t)}_getRootWriter(e){return this._rootWriterPromise??=(async()=>{const t=await this._getRootTarget(),i=new xl(t,typeof e=="boolean"?e:e(t));return i.start(),i})()}addVideoTrack(e,t={}){if(!(e instanceof bf))throw new TypeError("source must be a VideoSource.");if(La(t),t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError(`Invalid video rotation: ${t.rotation}. Has to be 0, 90, 180 or 270.`);if(t.flip!==void 0&&typeof t.flip!="boolean")throw new TypeError("metadata.flip, when provided, must be a boolean.");if(t.transformationMatrix!==void 0&&(!Array.isArray(t.transformationMatrix)||t.transformationMatrix.length!==9||!t.transformationMatrix.every(n=>Number.isFinite(n))))throw new TypeError("metadata.transformationMatrix, when provided, must be an array of 9 finite numbers.");if(t.frameRate!==void 0&&(!Number.isFinite(t.frameRate)||t.frameRate<=0))throw new TypeError(`Invalid video frame rate: ${t.frameRate}. Must be a positive number.`);if(t.hasOnlyKeyPackets!==void 0&&typeof t.hasOnlyKeyPackets!="boolean")throw new TypeError("metadata.hasOnlyKeyPackets, when provided, must be a boolean.");if(t.canBeTransparent!==void 0&&typeof t.canBeTransparent!="boolean")throw new TypeError("metadata.canBeTransparent, when provided, must be a boolean.");if(t.decoderConfig!==void 0&&Jl({decoderConfig:t.decoderConfig},e._codec),t.primingPacket!==void 0){if(!(t.primingPacket instanceof ls))throw new TypeError("metadata.primingPacket, when provided, must be an EncodedPacket.");if(t.decoderConfig===void 0)throw new TypeError("metadata.primingPacket can only be provided alongside metadata.decoderConfig.")}const i={...t};return i.group??=this.defaultTrackGroup,this._addTrack(new hy(this.tracks.length+1,this,e,i))}addAudioTrack(e,t={}){if(!(e instanceof vf))throw new TypeError("source must be an AudioSource.");if(La(t),t.decoderConfig!==void 0&&ec({decoderConfig:t.decoderConfig},e._codec),t.primingPacket!==void 0){if(!(t.primingPacket instanceof ls))throw new TypeError("metadata.primingPacket, when provided, must be an EncodedPacket.");if(t.decoderConfig===void 0)throw new TypeError("metadata.primingPacket can only be provided alongside metadata.decoderConfig.")}const i={...t};return i.group??=this.defaultTrackGroup,this._addTrack(new dy(this.tracks.length+1,this,e,i))}addSubtitleTrack(e,t={}){if(!(e instanceof cy))throw new TypeError("source must be a SubtitleSource.");La(t);const i={...t};return i.group??=this.defaultTrackGroup,this._addTrack(new uy(this.tracks.length+1,this,e,i))}setMetadataTags(e){if(q5(e),this.state!=="pending")throw new Error("Cannot set metadata tags after output has been started or canceled.");this._metadataTags=e}_addTrack(e){if(this.state!=="pending")throw new Error("Cannot add track after output has been started or canceled.");if(e.source._connectedTrack)throw new Error("Source is already used for a track.");const t=this.format.getSupportedTrackCounts(),i=this.tracks.reduce((o,a)=>o+(a.type===e.type?1:0),0),n=t[e.type].max;if(i===n)throw new Error(n===0?`${this.format._name} does not support ${e.type} tracks.`:`${this.format._name} does not support more than ${n} ${e.type} track${n===1?"":"s"}.`);const r=t.total.max;if(this.tracks.length===r)throw new Error(`${this.format._name} does not support more than ${r} tracks${r===1?"":"s"} in total.`);if(e.isVideoTrack()){const o=this.format.getSupportedVideoCodecs();if(o.length===0)throw new Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!o.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${o.map(a=>`'${a}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isAudioTrack()){const o=this.format.getSupportedAudioCodecs();if(o.length===0)throw new Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!o.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${o.map(a=>`'${a}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isSubtitleTrack()){const o=this.format.getSupportedSubtitleCodecs();if(o.length===0)throw new Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!o.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${o.map(a=>`'${a}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}return this.tracks.push(e),e.source._connectedTrack=e,e}hasEnoughTracks(){const e=this.format.getSupportedTrackCounts();for(const i of Bd){const n=this.tracks.reduce((o,a)=>o+(a.type===i?1:0),0),r=e[i].min;if(n<r)return!1}const t=e.total.min;return!(this.tracks.length<t)}async start(){const e=this.format.getSupportedTrackCounts();for(const i of Bd){const n=this.tracks.reduce((o,a)=>o+(a.type===i?1:0),0),r=e[i].min;if(n<r)throw new Error(r===e[i].max?`${this.format._name} requires exactly ${r} ${i} track${r===1?"":"s"}.`:`${this.format._name} requires at least ${r} ${i} track${r===1?"":"s"}.`)}const t=e.total.min;if(this.tracks.length<t)throw new Error(t===e.total.max?`${this.format._name} requires exactly ${t} track${t===1?"":"s"}.`:`${this.format._name} requires at least ${t} track${t===1?"":"s"}.`);if(this.state==="canceled")throw new Error("Output has been canceled.");return this._startPromise?(Re._warn("Output has already been started."),this._startPromise):this._startPromise=(async()=>{this.state="started";const i=this._mutex.acquire();try{await this._muxer.start();const n=this.tracks.map(r=>r.source._start());await Promise.all(n)}finally{(await i)()}})()}getMimeType(){return this._muxer.getMimeType()}async cancel(){if(this.state==="canceled")return this._cancelPromise??void 0;if(this.state==="finalizing"||this.state==="finalized"){this.state==="finalized"&&Re._warn("Output has already been finalized.");return}return this._cancelPromise=(async()=>{this.state="canceled";const e=await this._mutex.acquire();try{const t=this.tracks.map(i=>i.source._flushOrWaitForOngoingClose(!0));await Promise.all(t),await Promise.all([...this._unfinalizedTargets].map(i=>i._close())),this._unfinalizedTargets.clear()}finally{e()}})()}async finalize(){if(this.state==="pending")throw new Error("Cannot finalize before starting.");if(this.state==="canceled")throw new Error("Cannot finalize after canceling.");return this._finalizePromise?(Re._warn("Output has already been finalized."),this._finalizePromise):this._finalizePromise=(async()=>{this.state="finalizing";const e=await this._mutex.acquire();try{const t=this.tracks.map(i=>i.source._flushOrWaitForOngoingClose(!1));if(await Promise.all(t),await this._muxer.finalize(),this._rootWriterPromise){const i=await this._rootWriterPromise;i.finalized||(await i.flush(),await i.finalize())}this._onFinalize&&await this._onFinalize(),this.state="finalized"}catch(t){throw this.state="canceled",t}finally{await Promise.all([...this._unfinalizedTargets].map(t=>t._close().catch(()=>{}))),this._unfinalizedTargets.clear(),e()}})()}}const Fd=30,py=300;function my(s,e,t=3840){const i=Math.min(1,t/Math.max(s,e)),n=r=>Math.max(2,Math.floor(r*i/2)*2);return{width:n(s),height:n(e)}}function gy(s){const e=Math.max(0,Math.floor(s));return`${Math.floor(e/60)}:${String(e%60).padStart(2,"0")}`}async function wy(s,e){const t=await kd(["avc"],{width:s,height:e,bitrate:Cl});if(t)return{format:new xf({fastStart:"in-memory"}),video:t,audio:["aac","opus"]};const i=await kd(["vp9","vp8"],{width:s,height:e,bitrate:Cl});return i?{format:new Ir,video:i,audio:["opus","vorbis"]}:null}function by(s){let e=null;function t({copy:i,stream:n,sound:r}){s.drawHooks.delete(i);for(const o of n.getTracks())o.stop();r?.release()}return{get recording(){return!!e},get seconds(){return e?(performance.now()-e.started)/1e3:0},async start(i=null){const n=s.canvas,{width:r,height:o}=my(n.width,n.height),a=await wy(r,o);if(!a)throw i?.release(),new Error("This browser cannot encode video");const l=document.createElement("canvas");l.width=r,l.height=o;const c=l.getContext("2d"),h=()=>c.drawImage(n,0,0,r,o);s.renderFrame(),h(),s.drawHooks.add(h);const d=l.captureStream(),u={copy:h,stream:d,sound:i};try{const f=new fy({format:a.format,target:new Or});f.addVideoTrack(new ty(d.getVideoTracks()[0],{codec:a.video,bitrate:Cl},{frameRate:Fd}),{frameRate:Fd});const p=i?await Cb(a.audio,{bitrate:Md}):null;p&&f.addAudioTrack(new ny(i.track,{codec:p,bitrate:Md})),await f.start(),e={...u,output:f,format:a.format,started:performance.now()}}catch(f){throw t(u),f}},async stop(){const i=e;e=null;try{await i.output.finalize()}finally{t(i)}return{blob:new Blob([i.output.target.buffer],{type:i.format.mimeType}),extension:i.format.fileExtension.replace(/^\./,"")}}}}const vy="/assets/aldargon-B_VubjBf.svg",yy="/assets/arrakesh-BW9Bb56U.svg",Cy="/assets/atoll-mfMgWjQE.svg",xy="/assets/autumn-Cvk8t_-3.svg",My="/assets/bamboo-KEAHdFas.svg",ky="/assets/basalt-g767Blh3.svg",Ty="/assets/beach-q2rexblq.svg",_y="/assets/callisto-bug4x0L8.svg",Sy="/assets/cancri-BOebEtMP.svg",$y="/assets/canyon-FF3hqLaT.svg",Ay="/assets/ceres-BeB8pWjM.svg",Ey="/assets/challenger-Bg9wWAtc.svg",Py="/assets/crystal-bk_pmXWn.svg",zy="/assets/dagmora-Co5gg-3x.svg",Ly="/assets/deadstar-x-dSincY.svg",Ry="/assets/desert-Bkozg-2y.svg",By="/assets/dragonnest-DExsIn2w.svg",Fy="/assets/draugr-ChEwvDI7.svg",Oy="/assets/enceladus-BlSNfFYi.svg",Iy="/assets/endral-DQ-u4-N6.svg",Dy="/assets/europa-Cgids_PV.svg",Vy="/assets/fjord-rGF4e-MG.svg",Ny="/assets/forest-BVWgbcSU.svg",Wy="/assets/frozenlake-B8282a2Z.svg",Hy="/assets/ganymede-Dg4iJbs2.svg",Uy="/assets/garden-TQmDzzU5.svg",jy="/assets/glimmer-BIK9hzb3.svg",qy="/assets/halley-B32BiHtn.svg",Gy="/assets/hd189733b-E4qM1zIs.svg",Zy="/assets/hollow-DKKw0GKy.svg",Xy="/assets/horth-DPuhph1g.svg",Yy="/assets/iapetus-CMxb57ov.svg",Qy="/assets/io-C7TKKMjC.svg",Ky="/assets/j1407b-Dx2Qblb7.svg",Jy="/assets/jakhara-BLl7oBmq.svg",e6="/assets/jupiter-8ezAafsg.svg",t6="/assets/kaladorn-CkaAJJ7a.svg",s6="/assets/kashiwa-_WrMlYhf.svg",i6="/assets/kepler16b-CdRP9SpW.svg",n6="/assets/kepler186f-Bosuwusi.svg",r6="/assets/lanternnight-Bde4tTOv.svg",o6="/assets/lt2230-CtZQ_E_7.svg",a6="/assets/lt4260-BfDP2hby.svg",l6="/assets/mars-MRN7bCwO.svg",c6="/assets/mercury-Dxhy2buH.svg",h6="/assets/middangard-TZnEvlji.svg",d6="/assets/milners-Bbcl_qzx.svg",u6="/assets/miranda-DeKynADL.svg",f6="/assets/moon-trBMXXaP.svg",p6="/assets/moors-h4HR2QJC.svg",m6="/assets/muspel-CbnFgpIq.svg",g6="/assets/nabora-C_M0gUvC.svg",w6="/assets/north-CCQ_abLA.svg",b6="/assets/ocean-xTY8Tv7N.svg",v6="/assets/oz-ClTxqgDh.svg",y6="/assets/pandora-vc20uhuY.svg",C6="/assets/phobos-DKRMWpmg.svg",x6="/assets/pluto-Bv-I3Adh.svg",M6="/assets/proxima-CJWGm2yh.svg",k6="/assets/qubitron-B9yy8CKB.svg",T6="/assets/redspot-CV5z9nSH.svg",_6="/assets/ring-CWw9HQNl.svg",S6="/assets/sakura-BaPBQo7U.svg",$6="/assets/saturnrings-C0bWB6Nk.svg",A6="/assets/savanna-3fK5T_wl.svg",E6="/assets/sky-B_jCrmWW.svg",P6="/assets/sugarvale-CNIezmWw.svg",z6="/assets/tatawin-B4kGS6XH.svg",L6="/assets/terra-BpxwvhON.svg",R6="/assets/titan-DRcbXkdn.svg",B6="/assets/titanic-D6TQMoe4.svg",F6="/assets/trappist-DegjcuQ8.svg",O6="/assets/triton-DXbtxCV7.svg",I6="/assets/tundra-D7lIxFPP.svg",D6="/assets/undersea-rehq9Wmh.svg",V6="/assets/valley-DVlve4ea.svg",N6="/assets/venus-OIZfT1Sa.svg",W6="/assets/vespera-CXGN-RGx.svg",H6="/assets/worldtree-wqKc2Sb_.svg",U6="/assets/yavora4-D1u-Riyb.svg",kf={challenger:{id:"challenger",name:"Challenger Deep",blurb:"The floor of the Mariana Trench, eleven kilometers down: soft gray ooze, sea cucumbers and xenophyophores, marine snow drifting down, and sparks of living light in the dark.",sky:{top:0},ground:{high:7104092}},titanic:{id:"titanic",name:"RMS Titanic",blurb:"The bow of the Titanic on the floor of the North Atlantic, 3,800 meters down: rust hanging in drapes, the railing at the prow, a field of debris, and the lights of the submersibles.",sky:{top:0},ground:{high:7235162}},ceres:{id:"ceres",name:"Ceres",blurb:"A dark, cratered dwarf planet in the asteroid belt, with bright salt spots.",sky:{top:131587},ground:{high:5723996}},io:{id:"io",name:"Io",blurb:"Sulfur plains, lava lakes, glowing rifts, towering plumes, and Jupiter filling the sky.",sky:{top:263174},ground:{high:14993504}},europa:{id:"europa",name:"Europa",blurb:"A shell of ice scored with rust-red cracks, and Jupiter low on the horizon.",sky:{top:197640},ground:{high:15920870}},ganymede:{id:"ganymede",name:"Ganymede",blurb:"Dark old ice and bright grooved bands, under a half-lit Jupiter.",sky:{top:197381},ground:{high:9734780}},callisto:{id:"callisto",name:"Callisto",blurb:"The most cratered ground in the solar system, dark and dusted with frost.",sky:{top:197380},ground:{high:6182476}},aldargon:{id:"aldargon",name:"Aldargon",blurb:"What is left of Aldargon after the Dead Star fired: the colony on one broken piece of its grasslands, among shards of the planet still glowing where they split, with the Dead Star hanging in the sky.",sky:{top:65795},ground:{high:9090138}},arrakesh:{id:"arrakesh",name:"Arrakesh",blurb:"Bleached dunes to every horizon, rock walls, and two moons by day.",sky:{top:8824518},ground:{high:15519384}},dagmora:{id:"dagmora",name:"Dagmora",blurb:"Still black water, twisted trees, and mist that never lifts.",sky:{top:4872776},ground:{high:4871215}},endral:{id:"endral",name:"Endral",blurb:"A clearing in a forest of giant trees, with a gas giant overhead.",sky:{top:5932724},ground:{high:4542508}},horth:{id:"horth",name:"Horth",blurb:"Endless snowfields, rounded snow massifs, and wind that never stops.",sky:{top:9089232},ground:{high:16317439}},lt4260:{id:"lt4260",name:"LT-4260",blurb:"Blue-black rock, jagged ridges on every side, and a storm that never lifts.",sky:{top:1317930},ground:{high:2764862}},pandora:{id:"pandora",name:"Pandora",blurb:"A rainforest that glows after dark, floating rock, and a banded giant overhead.",sky:{top:2779824},ground:{high:4160074}},phobos:{id:"phobos",name:"Phobos",blurb:"A grooved, dusty little moon with Mars filling half the sky.",sky:{top:131586},ground:{high:7234136}},enceladus:{id:"enceladus",name:"Enceladus",blurb:"Blinding white ice, deep blue tiger-stripe rifts, geysers taller than mountains, and Saturn overhead.",sky:{top:131846},ground:{high:16448767}},titan:{id:"titan",name:"Titan",blurb:"Thick orange haze, methane drizzle, and dark hydrocarbon lakes.",sky:{top:9067050},ground:{high:9071172}},iapetus:{id:"iapetus",name:"Iapetus",blurb:"Half the ground coal-black, half snow-white, a vast ridge, and ringed Saturn.",sky:{top:131587},ground:{high:15262940}},miranda:{id:"miranda",name:"Miranda",blurb:"A patchwork moon, the tallest cliff in the solar system, and pale Uranus.",sky:{top:131844},ground:{high:10263712}},triton:{id:"triton",name:"Triton",blurb:"Pink nitrogen ice, dark geyser plumes, and deep-blue Neptune.",sky:{top:131846},ground:{high:15524058}},jupiter:{id:"jupiter",name:"Jupiter's clouds",blurb:"A station adrift on the ammonia cloud deck, the Great Red Spot turning on the horizon, lightning in the storms below, and the Galilean moons overhead.",sky:{top:1454174},ground:{high:9341586}},redspot:{id:"redspot",name:"Jupiter's Great Red Spot",blurb:"A station riding the edge of a storm wider than Earth: brick-red clouds wheel below while storm clouds stream past the base on winds of hundreds of miles an hour.",sky:{top:1716320},ground:{high:9341586}},saturnrings:{id:"saturnrings",name:"Saturn's rings",blurb:"Daphnis, a moonlet a few miles wide, riding the Keeler Gap: ring ice streams past on both sides, while the rings sweep away to Saturn, bright B ring, dark Cassini Division, and all.",sky:{top:65794},ground:{high:13157564}},draugr:{id:"draugr",name:"Draugr",blurb:"A frozen rock in endless night around a dead star: the pulsar's twin beams sweep the sky and flash as they pass, while aurora burns in its wind.",sky:{top:65795},ground:{high:4607064}},hd189733b:{id:"hd189733b",name:"HD 189733 b",blurb:"A hot Jupiter the color of cobalt: the colony rides a rock in the haze, an orange star swollen huge and fixed in the sky, and glass rains sideways on winds of five thousand miles an hour.",sky:{top:663146},ground:{high:4473422}},j1407b:{id:"j1407b",name:"J1407b",blurb:"An ice moon with a cracked crust under the rings of J1407b, a system two hundred times wider than Saturn's, crossing the face of its young orange star.",sky:{top:65795},ground:{high:13161180}},proxima:{id:"proxima",name:"Proxima b",blurb:"Frozen rock in endless twilight, under a red sun that never sets.",sky:{top:1314332},ground:{high:6967368}},trappist:{id:"trappist",name:"TRAPPIST-1e",blurb:"A rust-red shore under a dim red sun, with sister planets hanging in the sky.",sky:{top:3811898},ground:{high:9069640}},kepler16b:{id:"kepler16b",name:"Kepler-16b",blurb:"An icy moon of the gas giant Kepler-16b, where two suns rise and set together.",sky:{top:2240586},ground:{high:12896464}},kepler186f:{id:"kepler186f",name:"Kepler-186f",blurb:"An Earth-sized world under an orange-red sun, where the plants grow dark red.",sky:{top:4872842},ground:{high:5909028}},cancri:{id:"cancri",name:"55 Cancri e",blurb:"A lava world so close to its star that the sun fills a quarter of the sky.",sky:{top:1705990},ground:{high:3811876}},vespera:{id:"vespera",name:"Vespera",blurb:"A piece of a sky city, floating among drifting sunset clouds.",sky:{top:4873408},ground:{high:14736856}},kaladorn:{id:"kaladorn",name:"Kaladorn",blurb:"Green clifftops over a cold, gray-green sea, under rain and rolling cloud.",sky:{top:5399148},ground:{high:7113804}},middangard:{id:"middangard",name:"Middangard",blurb:"Rolling green hills, ringed by a watch hill, dark woods, a lone mountain, misty peaks, golden woods, a hall on the plains, a white city and its beacons, a land of fire, and a black tower.",sky:{top:3964108},ground:{high:8829010}},glimmer:{id:"glimmer",name:"Glimmer",blurb:"A twilight forest of giant mushrooms, with caps and moss that glow in the dark.",sky:{top:1709632},ground:{high:3428426}},undersea:{id:"undersea",name:"Undersea dome",blurb:"The colony under a glass dome on the sea floor, among kelp forests and coral, with light shafts and rising bubbles.",sky:{top:666170},ground:{high:12104852}},garden:{id:"garden",name:"Giant's garden",blurb:"Bots no bigger than beetles among towering daisies, tulips, and blades of grass, with dewdrops the size of boulders.",sky:{top:3835608},ground:{high:6986298}},crystal:{id:"crystal",name:"Crystal caverns",blurb:"A cavern hung with stalactites, giant glowing crystals, and still pools lit from below.",sky:{top:394252},ground:{high:4076616}},dragonnest:{id:"dragonnest",name:"Dragon's nest",blurb:"A mountaintop nest of giant dragon eggs among heaps of gold, some cracking, some already hatched and empty, and a dragon circling the peaks.",sky:{top:3811914},ground:{high:6969936}},worldtree:{id:"worldtree",name:"World tree",blurb:"The colony on one branch of a tree so vast its trunk vanishes into the clouds above and below.",sky:{top:3832520},ground:{high:7231554}},sugarvale:{id:"sugarvale",name:"Sugarvale",blurb:"Pink sugar hills, candy-cane groves, lollipop trees, gumdrops, chocolate rivers, and sprinkles on the breeze.",sky:{top:8040688},ground:{high:16765156}},lanternnight:{id:"lanternnight",name:"Lantern night",blurb:"A still lake under a full moon, and thousands of paper lanterns drifting up into the night.",sky:{top:395802},ground:{high:4872762}},kashiwa:{id:"kashiwa",name:"Kashiwa",blurb:"A clearing among colossal trees, lakes in the hollows, and a humid haze.",sky:{top:4881064},ground:{high:5138990}},lt2230:{id:"lt2230",name:"LT-2230",blurb:"Black volcanic rock and moss under low cloud, rain, and a ringed giant.",sky:{top:4872810},ground:{high:4869696}},milners:{id:"milners",name:"Milner's world",blurb:"An ankle-deep ocean to every horizon, Gargaros glowing through the storm, and a wave the size of a mountain.",sky:{top:3424074},ground:{high:6977138}},muspel:{id:"muspel",name:"Muspel",blurb:"Rivers of lava between black spires, erupting volcanoes on every side, and lightning in the ash.",sky:{top:1967620},ground:{high:3813420}},tatawin:{id:"tatawin",name:"Tatawin",blurb:"Sand dunes, sandstone mesas, and two suns in a pale sky.",sky:{top:6989020},ground:{high:15256728}},halley:{id:"halley",name:"Halley's Comet",blurb:"A dark, crumbling nucleus of dust and ice, jets of gas streaming away from the sun, and a tail across the sky.",sky:{top:65793},ground:{high:6445648}},nabora:{id:"nabora",name:"Nabora",blurb:"Rolling forest meeting a vast lake, with the warm lights of a city under the water glowing up from the deep.",sky:{top:3834064},ground:{high:8829010}},jakhara:{id:"jakhara",name:"Jakhara",blurb:"Golden dunes, wind-scoured mesas, scrap half-buried in the sand, and a giant downed starship.",sky:{top:9089232},ground:{high:15254666}},qubitron:{id:"qubitron",name:"Qubitron",blurb:"A world of metal plates and glowing seams, jagged steel outcrops, and conduits arching out of the ground.",sky:{top:1709104},ground:{high:8817816}},ring:{id:"ring",name:"Ring",blurb:"Green hills, pines, and gray rock, under the ring itself arching up from the horizon across the sky.",sky:{top:3830980},ground:{high:8038474}},deadstar:{id:"deadstar",name:"Dead Star",blurb:"Gray plating to the horizon, a trench beside the colony, gun towers, and Yavora with its moon peeking around the edge.",sky:{top:65794},ground:{high:9080468}},yavora4:{id:"yavora4",name:"Yavora IV",blurb:"Dense jungle under towering trees, mist in the canopy, and the orange gas giant Yavora overhead.",sky:{top:6983856},ground:{high:4876846}},north:{id:"north",name:"The North",blurb:"A wall of ice towering across the land, the frozen forest and snowy north beyond it, and pines and white-barked trees on the near side.",sky:{top:5929632},ground:{high:8034906}},oz:{id:"oz",name:"Oz",blurb:"A yellow brick road winding through the countryside and fields of poppies toward the Emerald City, under a rainbow.",sky:{top:3836640},ground:{high:9097290}}},Od={agents:null,quiet:["idle","sleeping"],wanted:["asking","done"]},j6={working:"Nobody is building right now",delegating:"Nobody is waiting on agents right now",asking:"Nobody needs you right now",done:"Nothing is done and ready for you",wanted:"Nothing wants you right now",error:"Nothing has hit an error lately",celebrating:"Nothing has shipped lately",quiet:"Nobody is idle right now",agents:"No bots on the surface"},q6=1e4;function ac(s){return Object.hasOwn(Od,s)?Od[s]:[s]}function G6(s,e){const t=ac(e),i=r=>r.thread?.lastActivityAt||0,n=r=>e==="wanted"?t.indexOf(r.status):0;return s.filter(r=>!t||t.includes(r.status)).sort((r,o)=>n(r)-n(o)||i(o)-i(r)||r.id.localeCompare(o.id))}function Z6(){let s=null,e=0,t=-1/0;return(i,n,r)=>{const o=G6(i,n);return(n!==s||r-t>q6)&&(e=0),s=n,t=r,o.length?o[e++%o.length]:null}}const lc=[["sky","sky"],["bodies","sky"],["far","horizon"],["bed","ground"],["sea","water"],["ground","ground"],["island","island"],["water","water"],["scatter","scatter"],["grass","grass"],["near","horizon"],["lights","shaders"],["air","landing"]];Object.fromEntries(lc);let X6=0;const Le=(s,e,t)=>Math.min(t,Math.max(e,s)),j=s=>Math.round(s*100)/100;function v(s,...e){let t=s[0];for(let i=0;i<e.length;i++)t+=(typeof e[i]=="number"?j(e[i]):e[i])+s[i+1];return t}function Hi(s,e="#808080"){return typeof s=="number"&&Number.isFinite(s)?[s>>16&255,s>>8&255,s&255]:typeof s=="string"&&/^#[0-9a-f]{6}$/i.test(s)?[1,3,5].map(t=>parseInt(s.slice(t,t+2),16)):Hi(e)}const Tf=s=>`#${s.map(e=>Le(Math.round(e),0,255).toString(16).padStart(2,"0")).join("")}`;function D(s,e){return Tf(Hi(s,e))}function J(s,e,t){const i=Hi(s),n=Hi(e);return Tf(i.map((r,o)=>r+(n[o]-r)*t))}const ve=(s,e)=>J(s,"#ffffff",e),ne=(s,e)=>J(s,"#000000",e);function Ui(s){const[e,t,i]=Hi(s);return(.2126*e+.7152*t+.0722*i)/255}function _f(s){const[e,t,i]=Hi(s);return t>e*1.05&&t>i*1.05}function Ge(s){let e=2166136261;for(let i=0;i<s.length;i++)e=Math.imul(e^s.charCodeAt(i),16777619);let t=e>>>0;return()=>{t=t+1831565813>>>0;let i=t;return i=Math.imul(i^i>>>15,i|1),i^=i+Math.imul(i^i>>>7,i|61),((i^i>>>14)>>>0)/4294967296}}const z=(s,e,t)=>e+(t-e)*s(),Ln=(s,e)=>e[Math.floor(s()*e.length)%e.length];function Y6(s){return String(s).replace(/[&<>"]/g,e=>({"&":"&","<":"<",">":">",'"':"""})[e])}function Q6(){const s=`wi${(++X6).toString(36)}`,e={prefix:s,defs:[],count:0,halos:new Map,layers:Object.fromEntries(lc.map(([t])=>[t,[]])),id:t=>`${s}-${t}${(e.count++).toString(36)}`,add(t,i){i&&e.layers[t].push(i)},under(t,i){i&&e.layers[t].unshift(i)}};return e}function Sf(s){return s.map(([e,t,i=1])=>`<stop offset="${j(e)}" stop-color="${t}"${i<1?` stop-opacity="${j(i)}"`:""}/>`).join("")}function ge(s,e,[t,i,n,r]=[0,0,0,1],o=!1){const a=s.id("l");return s.defs.push(`<linearGradient id="${a}" x1="${j(t)}" y1="${j(i)}" x2="${j(n)}" y2="${j(r)}"${o?' gradientUnits="userSpaceOnUse"':""}>${Sf(e)}</linearGradient>`),`url(#${a})`}function pi(s,e,{cx:t=.5,cy:i=.5,r:n=.5,fx:r=t,fy:o=i}={}){const a=s.id("r");return s.defs.push(`<radialGradient id="${a}" cx="${j(t)}" cy="${j(i)}" r="${j(n)}" fx="${j(r)}" fy="${j(o)}">${Sf(e)}</radialGradient>`),`url(#${a})`}function Ml(s,e,t=.6){const i=`${e}${t}`;return s.halos.has(i)||s.halos.set(i,pi(s,[[0,e,t],[.4,e,t*.42],[1,e,0]])),s.halos.get(i)}function ko(s,e){const t=s.id("c");return s.defs.push(`<clipPath id="${t}">${e}</clipPath>`),`url(#${t})`}const _e=(s,e,t,i,n,r=.7)=>v`<circle cx="${e}" cy="${t}" r="${i}" fill="${Ml(s,n,r)}"/>`;function Dr(s,e="M"){let t=v`${e}${s[0][0]} ${s[0][1]}`;for(let i=0;i<s.length-1;i++){const n=s[i-1]??s[i],r=s[i],o=s[i+1],a=s[i+2]??o;t+=v` C${r[0]+(o[0]-n[0])/6} ${r[1]+(o[1]-n[1])/6} ${o[0]-(a[0]-r[0])/6} ${o[1]-(a[1]-r[1])/6} ${o[0]} ${o[1]}`}return t}const Ra=s=>s.map(([e,t])=>`${j(e)},${j(t)}`).join(" ");function K6(s){const t=(s.sun??{}).fixed??.5,i=(s.aurora??0)>0,n=t>=.86||i,r=!n&&t>=.66,o=!!s.seafloor||(s.fog?.sky??0)>=.5;let a=D(s.sky?.top,"#2c5c9c"),l=D(s.sky?.bottom,"#a8c8e4");i&&t<.86&&(a=J(a,"#030918",.85),l=J(l,"#183450",.74));const c=s.atmosphere??1,h={low:D(s.ground?.low,"#4a5a3a"),high:D(s.ground?.high,"#7a9a5a")};h.tint=D(s.ground?.tint,ve(h.high,.2));const d=s.water?{shallow:D(s.water.shallow,"#52c8d8"),deep:D(s.water.deep,"#1c6fba"),foam:D(s.water.foam,"#ffffff"),lava:!!s.water.glow,frozen:!!s.water.ice||Ui(D(s.water.shallow,"#52c8d8"))>.72&&(s.water.waveHeight??.1)<.03,low:(s.water.level??-1)<-8,opacity:s.water.opacity??.9}:null,u={planet:s,id:String(s.id??s.name??"world"),time:t,night:n,dusk:r,aurora:i,enclosed:o,shape:s.shape??"plain",H:62,skyTop:a,skyBottom:l,starry:!o&&(n||c<.3||Ui(a)<.1),atmosphere:c,ground:h,rock:D(s.rock,ne(h.low,.1)),shore:D(s.shore?.color,ve(h.high,.3)),haze:D(s.fog?.color??s.horizon,l),glow:s.glow!=null?D(s.glow):null,water:d,skip:new Set,scatterScale:1,bodies:[],sun:null};return u.bodies=s8(t8(s.companions??[],u)),s.comet&&(u.sunSide=-1,u.groundShape="nucleus"),s.plating&&(u.groundShape="metal"),u.sun=$f(s,u),s.comet&&u.sun&&Object.assign(u.sun,{x:18,y:u.H-14,r:Math.min(u.sun.r,2.6)}),u}const To=s=>!!(s.blackHole||s.hole||/gargaros/i.test(s.name??""));function J6(s){if(To(s))return 7;let e=Math.min(44,2.5+4.2*(s.size??.52)**.6);return s.rings&&(e=Math.min(e,38/(s.rings.outer??2.2))),e}function e8(s){for(const e of s){const t=e.body.peek,i=t&&s.find(o=>o!==e&&o.body.name===t.of);if(!i)continue;const n=(t.side??150)*Math.PI/180;t.scale&&(e.r=Math.max(e.body.star?3:2.2,i.r*t.scale));const r=i.r+e.r*(2*(t.shown??.5)-1)+(t.gap??0)*.9;e.x=i.x+Math.cos(n)*r,e.y=i.y-Math.sin(n)*r,e.behind=!0,e.faint=!1}for(const e of s){const t=e.body.on,i=t&&s.find(o=>o!==e&&o.body.name===t.of);if(!i)continue;const n=(t.lat??0)*Math.PI/180,r=(t.lon??0)*Math.PI/180;t.scale&&(e.r=Math.max(e.body.star?3:2.2,i.r*t.scale)),e.x=i.x+Math.cos(n)*Math.sin(r)*i.r,e.y=i.y-Math.sin(n)*i.r,e.faint=!1}return s}function t8(s,e){const t=!e.starry&&Ui(e.skyTop)>.22,i=e.shape==="sky";return s.filter(n=>n&&!(t&&/^moon$/i.test(n.name??"")&&(n.size??.52)<1)).slice(0,4).map(n=>{const r=J6(n);if(n.peek||n.on)return{body:n,x:50,y:30,r,faint:!1};const[o,a]=n.at??[-12,8];let l=50+o*1.05,c;return a<0?c=e.H-a*1.5:r>12?c=e.H-Math.max(a*1.8,r*.5):c=Le(e.H-8-a*2.6,r+7,e.H-r-3),n.rings&&(c=Math.min(c,e.H-r*.45)),i&&(c=Math.min(c,r+12)),r<12&&(l=Le(l,14+r,86-r)),{body:n,x:l,y:c,r,faint:t&&r<12&&!To(n)}}).sort((n,r)=>r.r-n.r)}function s8(s){return e8(s).sort((e,t)=>(t.behind?1:0)-(e.behind?1:0)||t.r-e.r)}function Id(s=1){return Le(4.5*s**.8,1.6,24)}function $f(s,e){const t=s.sun;if(!t||e.night||e.enclosed)return null;const i=e.bodies[0],n=e.sunSide??(i&&i.r>7&&i.x>=47?-1:1),r=Id(t.disc),o=50+n*(r>12?17:25),a=e.dusk?e.H-r*(t.second?1.6:.45)-2:Le(24,r+8,e.H-r-8),l={x:o,y:a,r,side:n,color:D(t.color,"#fff4e0"),hidden:!!t.hidden};if(t.second){const c=Id(t.second.disc),h=(t.second.offset??.02)>=0?1:-1;l.second={x:o-n*h*(r+c)*1.35,y:e.dusk?a+r*.9:a+r*.8+1.5,r:c,color:D(t.second.color,"#ffc078")}}return l}function i8(s,e){const t=e.shape==="sky"?100:e.H+2,i=ge(s,[[0,e.skyTop],[.58,J(e.skyTop,e.skyBottom,.6)],[1,e.skyBottom]],[0,0,0,t],!0);if(s.add("sky",`<rect width="100" height="100" fill="${i}"/>`),e.starry&&n8(s,e),e.aurora&&r8(s),!e.enclosed&&e.atmosphere>.3&&e.shape!=="sky"){const r=e.sun?e.sun.x:50;s.add("sky",v`<ellipse cx="${r}" cy="${e.H}" rx="70" ry="${e.dusk?24:14}" fill="${Ml(s,ve(e.skyBottom,.3),e.dusk?.7:.3)}"/>`)}const n=e.sun;n?.hidden?s.add("sky",v`<ellipse cx="${n.x}" cy="${n.y+4}" rx="34" ry="26" fill="${Ml(s,ve(n.color,.2),.5)}"/>`):n&&(s.add("sky",_e(s,n.x,n.y,Math.max(n.r*3.6,13),n.color,e.starry?.35:.6)),n.second&&s.add("sky",_e(s,n.second.x,n.second.y,Math.max(n.second.r*3.2,10),n.second.color,.45))),o8(s,e)}function n8(s,e){const t=Ge(`${e.id}-stars`),i=Ui(e.skyBottom)<.2?34:18,n=e.shape==="sky"?96:e.H-4;let r="";for(let o=0;o<i;o++){const a=z(t,3,97),l=z(t,3,n),c=t()<.16?z(t,.55,.9):z(t,.22,.48);r+=v`<circle cx="${a}" cy="${l}" r="${c}" fill-opacity="${z(t,.35,1)}"/>`}for(let o=0;o<2;o++){const a=z(t,12,88),l=z(t,8,n*.6),c=z(t,1.6,2.4);r+=v`<path d="M${a} ${l-c}L${a+c*.2} ${l-c*.2}L${a+c} ${l}L${a+c*.2} ${l+c*.2}L${a} ${l+c}L${a-c*.2} ${l+c*.2}L${a-c} ${l}L${a-c*.2} ${l-c*.2}Z"/>`}s.add("sky",`<g fill="#fff">${r}</g>`)}function r8(s,e){const t=[{color:"#46f0a2",top:"#7a5cff",opacity:.8,points:[[-4,30],[22,20],[48,27],[72,15],[104,22]],height:15},{color:"#3ad8d0",top:"#5a7cff",opacity:.55,points:[[-4,18],[30,10],[58,16],[84,6],[104,10]],height:11}];for(const i of t){const n=ge(s,[[0,i.top,0],[.45,i.top,i.opacity*.22],[.82,i.color,i.opacity*.75],[1,i.color,0]]),r=i.points.map(([o,a],l)=>[o+(l%2?2:-2),a+i.height+(l%2?3:0)]).reverse();s.add("sky",`<path d="${Dr(i.points.map(([o,a])=>[o,a-i.height*.6]))}${Dr(r,"L")}Z" fill="${n}"/>`),s.add("sky",`<path d="${Dr(i.points.map(([o,a])=>[o,a+i.height*.55]))}" fill="none" stroke="${i.color}" stroke-opacity="${j(i.opacity*.5)}" stroke-width=".7"/>`)}}function ao(s,e,t,i,n,r=1){return v`<g fill-opacity="${r}"><ellipse cx="${s}" cy="${e}" rx="${t*.5}" ry="${t*.15}" fill="${n}"/><circle cx="${s-t*.21}" cy="${e-t*.08}" r="${t*.17}" fill="${i}"/><circle cx="${s+t*.04}" cy="${e-t*.16}" r="${t*.23}" fill="${i}"/><circle cx="${s+t*.27}" cy="${e-t*.05}" r="${t*.14}" fill="${i}"/></g>`}function o8(s,e){const t=e.planet.clouds,i=t?.amount??0;if(i<.12||e.enclosed||e.skip.has("clouds"))return;const n=Ge(`${e.id}-clouds`),r=D(t.color,"#ffffff"),o=e.night?J(r,e.skyTop,.6):e.dusk?J(r,"#ffb890",.25):r,a=J(o,e.skyTop,.28);let l="";if(i>=.78){const c=ge(s,[[0,J(o,e.skyTop,.35)],[1,o,.4]]);l+=`<path d="M-2 -2H102V${j(18+i*6)}C80 ${j(24+i*4)} 64 ${j(16+i*6)} 44 ${j(22+i*5)}S12 ${j(16+i*5)} -2 ${j(22+i*4)}Z" fill="${c}"/>`;for(let h=-4;h<106;h+=13)l+=v`<ellipse cx="${h+z(n,-2,2)}" cy="${z(n,16,26)}" rx="${z(n,8,12)}" ry="${z(n,2.4,3.6)}" fill="${J(o,e.skyTop,.15)}" fill-opacity=".7"/>`}else{const c=[...e.bodies,...e.sun?[{x:e.sun.x,y:e.sun.y,r:e.sun.r+4}]:[]],h=i>.4?3:i>.25?2:1;let d=0;for(let u=0;u<24&&d<h;u++){const f=z(n,12,18),p=z(n,14,86),m=z(n,14,e.H-20);c.some(g=>Math.abs(g.x-p)<g.r+f*.55&&Math.abs(g.y-m)<g.r+f*.3)||(l+=ao(p,m,f,o,a,.9),d++)}}s.add("sky",l)}function Dd(s,e){const t=pi(s,[[0,"#ffffff"],[.55,ve(e.color,.6)],[1,e.color]]);let i=v`<circle cx="${e.x}" cy="${e.y}" r="${e.r}" fill="${t}"/>`;if(e.r<2.8){const n=e.r*5;i+=v`<path d="M${e.x-n} ${e.y}H${e.x+n}M${e.x} ${e.y-n}V${e.y+n}" stroke="${ve(e.color,.5)}" stroke-width=".42" stroke-linecap="round" stroke-opacity=".85"/>`}return i}function a8(s,e){const t=e.sun;if(!t||t.hidden)return;let i=Dd(s,t);t.second&&(i+=Dd(s,t.second)),s.under("bodies",i)}function l8(s,e,t,i){const n=s.bands.map(h=>D(h)),r=Le(Math.round((s.banding??6)*1.4),5,14),o=2*i/r,a=i*.3,l=o*.22;let c="";for(let h=0;h<r;h++){const d=t-i+o*h+o*.2,u=o*(.5+h*7%3*.14);c+=v`<path d="M${e-i*1.2} ${d}q${a} ${-l} ${2*a} 0t${2*a} 0t${2*a} 0t${2*a} 0v${u}q${-a} ${l} ${-2*a} 0t${-2*a} 0t${-2*a} 0t${-2*a} 0Z" fill="${n[h%n.length]}" fill-opacity=".9"/>`}return c}function Vd(s,e,t,i,n,r){const{inner:o=1.3,outer:a=2.2,color:l,opacity:c=.8}=e.rings,[h=12,d=6]=e.pole??[],u=Le(.16+d/70,.14,.42),f=a-o,p=n*a*1.15,m=ko(s,r==="front"?v`<rect x="${-p}" y="0" width="${p*2}" height="${p}"/>`:v`<rect x="${-p}" y="${-p}" width="${p*2}" height="${p}"/>`),g=[[.1,.18,.4],[.4,.44,.95],[.84,.24,.72]].map(([w,b,y])=>v`<circle r="${n*(o+f*w)}" stroke-width="${n*f*b}" stroke-opacity="${y*c}"/>`).join("");return v`<g transform="translate(${t} ${i}) rotate(${-h*.9}) scale(1 ${u})"><g clip-path="${m}" fill="none" stroke="${D(l,"#d8ccb0")}">${g}</g></g>`}function c8(s,e,t,i,n){const r=J(D(n.hole?.color??n.rings?.color??n.glow,"#ffd8a0"),"#fff0d0",.35),o=ge(s,[[0,r,0],[.2,r,.8],[.5,"#ffffff"],[.8,r,.8],[1,r,0]],[0,0,1,0]);return _e(s,e,t,i*2.6,r,.38)+v`<ellipse cx="${e}" cy="${t}" rx="${i*1.32}" ry="${i*1.24}" fill="none" stroke="${r}" stroke-width="${i*.32}" stroke-opacity=".85"/>`+v`<ellipse cx="${e}" cy="${t}" rx="${i*1.12}" ry="${i*1.06}" fill="none" stroke="#fff6e0" stroke-width="${i*.08}"/>`+v`<circle cx="${e}" cy="${t}" r="${i}" fill="#010101"/>`+v`<path d="M${e-i*2.5} ${t+i*.05}Q${e} ${t-i*.5} ${e+i*2.5} ${t+i*.05}Q${e} ${t+i*.38} ${e-i*2.5} ${t+i*.05}Z" fill="${o}"/>`}function h8(s,e,{body:t,x:i,y:n,r,faint:o,haze:a=0}){if(To(t))return c8(s,i,n,r,t);if(t.star){const x=J(D(t.color,"#ffffff"),"#58ff78",.35);return _e(s,i,n,r*1.6,x,.6)+v`<path d="M${i-r} ${n}H${i+r}M${i} ${n-r}V${n+r}" stroke="${x}" stroke-width=".5" stroke-linecap="round"/><circle cx="${i}" cy="${n}" r=".75" fill="#ffffff"/>`}const l=D(t.color,"#d8d4cc"),c=e.sun&&Math.sign(e.sun.x-i)||1,h=v`<circle cx="${i}" cy="${n}" r="${r}"/>`,d=ko(s,h),u=pi(s,[[0,ve(l,.2)],[.7,l],[1,ne(l,.22)]],{cx:.5+c*.16,cy:.4,r:.72}),f=Ge(`${e.id}-${t.name??"body"}`);let p="";const m=-(t.pole?.[0]??0)*.8;let g="";if(t.bands?.length&&(g+=l8(t,i,n,r)),t.storm){const{lat:x=0,lon:T=0,size:M=.1}=t.storm;g+=v`<ellipse cx="${i+T/90*r*.85}" cy="${n-x/90*r*.95}" rx="${M*r*1.5}" ry="${M*r*.95}" fill="${D(t.storm.color,ne(l,.3))}"/>`}if(g&&(p+=`<g transform="rotate(${j(m)} ${j(i)} ${j(n)})">${g}</g>`),t.mottle){const x=D(t.mottle.color,ne(l,.25));for(let T=0;T<8;T++){const M=f()*Math.PI*2,k=Math.sqrt(f())*r*.8,A=r*z(f,.08,.24);p+=v`<ellipse cx="${i+Math.cos(M)*k}" cy="${n+Math.sin(M)*k}" rx="${A}" ry="${A*z(f,.45,.8)}" fill="${x}" fill-opacity="${Le((t.mottle.amount??.3)*1.2,.2,.5)}" transform="rotate(${z(f,-30,30)} ${i} ${n})"/>`}}if(t.clouds)for(let x=0;x<4;x++){const T=n-r*.6+x*r*.4,M=i+z(f,-.5,.3)*r;p+=v`<path d="M${M-r*.45} ${T}q${r*.25} ${-r*.18} ${r*.5} 0t${r*.45} ${r*.04}" fill="none" stroke="${D(t.clouds.color,"#ffffff")}" stroke-width="${r*.1}" stroke-linecap="round" stroke-opacity="${Le((t.clouds.amount??.4)*1.6,.3,.85)}"/>`}if((t.metal||t.station)&&(p+=v`<path d="M${i-r} ${n+r*.04}H${i+r}" stroke="${ne(l,.4)}" stroke-width="${r*.09}"/>`),t.mark&&(p+=v`<ellipse cx="${i-r*.25}" cy="${n+r*.1}" rx="${r*.32}" ry="${r*.22}" fill="${D(t.mark.color,ne(l,.4))}" fill-opacity=".7"/>`),!t.metal&&!t.station&&(t.craters||!t.bands&&r>4&&(t.mottle||/moon/i.test(t.name??""))))for(let x=0;x<3;x++){const T=f()*Math.PI*2,M=Math.sqrt(f())*r*.65,k=r*z(f,.08,.16),A=i+Math.cos(T)*M,P=n+Math.sin(T)*M;p+=v`<circle cx="${A}" cy="${P}" r="${k}" fill="${ne(l,.22)}"/><path d="M${A-k} ${P}A${k} ${k} 0 0 0 ${A+k} ${P}" fill="none" stroke="${ve(l,.3)}" stroke-width="${k*.35}"/>`}const w=e.starry?.82:.32,b=ge(s,c>0?[[0,"#000",w],[.5,"#000",w*.3],[.78,"#000",0]]:[[.22,"#000",0],[.5,"#000",w*.3],[1,"#000",w]],[0,0,1,0]);p+=v`<rect x="${i-r}" y="${n-r}" width="${r*2}" height="${r*2}" fill="${b}"/>`;const y=t.glow!=null?D(t.glow):ve(l,.3);let C="";(r>10||e.starry)&&(C+=_e(s,i,n,r*1.35,y,e.starry?.32:.22)),t.rings&&(C+=Vd(s,t,i,n,r,"back")),C+=v`<circle cx="${i}" cy="${n}" r="${r}" fill="${u}"/><g clip-path="${d}">${p}</g>`,C+=v`<circle cx="${i}" cy="${n}" r="${r-.3}" fill="none" stroke="${y}" stroke-opacity=".35" stroke-width=".6"/>`,t.rings&&(C+=Vd(s,t,i,n,r,"front"));const _=o?.6:1-a;return _<1?v`<g opacity="${_}">${C}</g>`:C}function d8(s,e){for(const t of e.bodies)s.add("bodies",h8(s,e,t));a8(s,e)}function cc(s){return Le((s.height??30)*.2,4,26)}function Af(s,e,t){return J(D(e,"#5a5e68"),s.haze,Le(t*.75,0,.7))}function Ef(s,e,t,i){const n=[[-3,e+2]];if(s==="domes"||s==="hills"){for(let h=0;h<=4;h++)n.push([-3+106*h/4+z(i,-4,4),e-t*(h%2?z(i,.65,1):z(i,.25,.5))]);return{d:Dr(n.slice(1),"M").replace(/^M/,`M-3 ${j(e+2)}L`)+v`L103 ${e+2}Z`}}if(s==="treeline"){let c=v`M-3 ${e+2}V${e-t*.3}`;for(let h=-3;h<104;h+=z(i,2.2,3.4)){const d=t*z(i,.55,1);c+=v`L${h+.8} ${e-t*.3}L${h+1.6} ${e-d}L${h+2.4} ${e-t*.3}`}return{d:c+v`L103 ${e-t*.3}V${e+2}Z`}}if(s==="buttes"||s==="mesas"){const c=s==="mesas";let h=v`M-3 ${e+2}`,d=-3+z(i,2,10);const u=[];for(;d<100;){const f=c?z(i,18,30):z(i,7,14),p=t*z(i,c?.45:.6,1);h+=v`L${d-2.5} ${e+2}L${d} ${e-p*.3}L${d+.6} ${e-p}L${d+f-.6} ${e-p}L${d+f} ${e-p*.3}L${d+f+2.5} ${e+2}`;for(let m=1;m<3;m++)u.push(v`M${d+.3} ${e-p+p*m/3}H${d+f-.3}`);d+=f+z(i,c?8:6,c?20:16)}return{d:h+v`L103 ${e+2}Z`,strata:u.join("")}}if(s==="wall"){for(let c=-3;c<=103;c+=6)n.push([c,e-t*z(i,.75,1)]);return n.push([103,e+2]),{d:`M${Ra(n)}Z`}}if(s==="cliff")return n.push([40,e-t*.12],[52,e-t*.18],[53.5,e-t],[70,e-t*1.04],[103,e-t*.92],[103,e+2]),{d:`M${Ra(n)}Z`,face:v`M52 ${e-t*.18}L53.5 ${e-t}L57 ${e-t*.98}L55 ${e-t*.16}Z`};const r=s==="crags",o=r?9:6,a=106/o,l=[];for(let c=0;c<o;c++){const h=-3+a*c,d=h+a*z(i,.35,.65),u=t*z(i,r?.45:.55,1);n.push([d-a*.28,e-u*z(i,.3,.55)],[d,e-u],[d+a*.24,e-u*z(i,.45,.7)],[h+a,e-t*z(i,.08,.3)]),l.push([d,e-u,u,a])}return n.push([103,e+2]),{d:`M${Ra(n)}Z`,apexes:l}}function u8(s,e,t,i="far"){const n=Ge(`${e.id}-ridge`),r=e.H,o=cc(t),a=Le(t.layers??1,1,3);for(let l=a-1;l>=0;l--){const c=o*(1-l*.22),h=Af(e,t.color,(t.haze??.3)+l*.25),d=Ef(t.kind,r+l*-1.5,c,n);let u=`<path d="${d.d}" fill="${h}"/>`;if(d.face&&(u+=`<path d="${d.face}" fill="${ve(h,.18)}"/>`),d.strata&&(u+=`<path d="${d.strata}" fill="none" stroke="${ne(h,.18)}" stroke-width=".5" stroke-opacity=".7"/>`),l===0&&d.apexes&&t.snow){const f=D(t.snow.color,"#f4f6fa"),p=t.snow.line??.5;let m="";for(const[w,b,y,C]of d.apexes){if(y<c*p*.9)continue;const _=y*(1-p)*.9+1.2,x=C*.26*(_/y)*1.6+.8;m+=v`<path d="M${w} ${b}L${w+x} ${b+_}L${w+x*.35} ${b+_*.72}L${w} ${b+_*.95}L${w-x*.4} ${b+_*.7}L${w-x} ${b+_}Z"/>`}const g=ko(s,`<path d="${d.d}"/>`);u+=`<g clip-path="${g}" fill="${f}" fill-opacity=".92">${m}</g>`}s.add(i,u)}}function f8(s,e,t){const i=e.H,n=Math.max(cc(t),24),r=D(t.color,"#16404c"),o=D(t.snow?.color,"#e4f0f2"),a=ge(s,[[0,ve(r,.18)],[.6,r],[1,ne(r,.25)]]),l=v`M-3 ${i+2}V${i-n*.7}C8 ${i-n*.98} 24 ${i-n*1.08} 40 ${i-n*.98}C48 ${i-n*.93} 52 ${i-n*.82} 50 ${i-n*.72}C58 ${i-n*.62} 70 ${i-n*.4} 82 ${i-n*.22}C90 ${i-n*.12} 98 ${i-n*.08} 103 ${i-n*.06}V${i+2}Z`;s.add("far",`<path d="${l}" fill="${a}"/>`),s.add("far",v`<path d="M-3 ${i-n*.7}C8 ${i-n*.98} 24 ${i-n*1.08} 40 ${i-n*.98}C48 ${i-n*.93} 52 ${i-n*.82} 50 ${i-n*.72}" fill="none" stroke="${o}" stroke-width="1.6" stroke-linecap="round" stroke-opacity=".9"/>`),s.add("far",v`<path d="M50 ${i-n*.72}C58 ${i-n*.62} 70 ${i-n*.4} 82 ${i-n*.22}" fill="none" stroke="${o}" stroke-width=".8" stroke-opacity=".55"/>`),s.add("far",v`<path d="M2 ${i-n*.55}C14 ${i-n*.66} 26 ${i-n*.7} 38 ${i-n*.66}M4 ${i-n*.3}C18 ${i-n*.38} 34 ${i-n*.4} 48 ${i-n*.34}" fill="none" stroke="${ve(r,.35)}" stroke-width=".6" stroke-opacity=".5"/>`)}function p8(s){const i=n=>((n-225)%360+540)%360-180;return s.map(n=>({realm:n,x:50+i(n.at)/110*46,w:(n.span??20)/110*46})).filter(({x:n,w:r})=>n+r/2>-4&&n-r/2<104)}function m8(s,e,t,i,n,r,o,a=3){const l=t-n;let c=v`<path d="M${e-i/2} ${t}L${e-i*.11} ${l}Q${e} ${l+1} ${e+i*.11} ${l}L${e+i/2} ${t}Z" fill="${r}"/>`;c+=v`<path d="M${e+i*.11} ${l}L${e+i/2} ${t}L${e+i*.18} ${t}Z" fill="${ne(r,.25)}"/>`;for(let h=0;h<Math.min(a,4);h++){const d=h%2?1:-1,u=(.18+h*.07)*i;c+=v`<path d="M${e+d*i*.05} ${l+.5}Q${e+d*u*.6} ${l+n*.4} ${e+d*u} ${t-.5}" fill="none" stroke="${o}" stroke-width=".7" stroke-linecap="round"/>`}return c+=v`<ellipse cx="${e}" cy="${l+.4}" rx="${i*.12}" ry=".9" fill="${ve(o,.35)}"/>`,c}function g8(s,e,t){const i=e.H,n=cc(t),r=D(t.glow,"#ff4a12"),o=Ge(`${e.id}-realms`),a=p8(t.realms),l=[...a.filter(h=>!h.realm.feature).sort((h,d)=>d.w-h.w),...a.filter(h=>h.realm.feature)],c=[];for(const{realm:h,x:d,w:u}of l){const f=Af(e,h.color,t.haze??.2),p=n*(h.height??1)*(h.shape==="plains"?.25:1),m={plains:"domes",forest:"treeline",hills:"domes"}[h.shape]??h.shape,g=Ef(m,i,p,o);let b=`<g clip-path="${ko(s,v`<rect x="${d-u/2}" y="0" width="${u}" height="100"/>`)}"><path d="${g.d}" fill="${f}"/>`;if(h.snow&&g.apexes){const C=D(h.snow.color,"#f4f6fa");for(const[_,x,T,M]of g.apexes){const k=T*(1-(h.snow.line??.5))*.9+1;b+=v`<path d="M${_} ${x}L${_+M*.2} ${x+k}L${_} ${x+k*.8}L${_-M*.2} ${x+k}Z" fill="${C}" fill-opacity=".9"/>`}}b+="</g>";const y=h.feature;if(y){const C=50+((((y.at??h.at)-225)%360+540)%360-180)/110*46,_=Math.max(2.4,(y.span??6)/110*46),x=D(y.color,"#2a201c"),T=D(y.glow,r);if(y.kind==="volcano"){const M=n*(y.height??.8)*1.45;b+=m8(s,C,i+1,Math.max(_*1.3,M*1.5),M,x,T,y.streams),c.push(_e(s,C,i+1-M,5,T,.7))}else if(y.kind==="tower"){const M=n*(y.height??.9)*1.6,k=Math.max(2.6,_);b+=v`<path d="M${C-k*.7} ${i+1}L${C-k*.38} ${i-M*.55}L${C-k*.5} ${i-M*.9}L${C-k*.2} ${i-M}L${C-k*.08} ${i-M*.93}L${C+k*.08} ${i-M*.93}L${C+k*.2} ${i-M}L${C+k*.5} ${i-M*.9}L${C+k*.38} ${i-M*.55}L${C+k*.7} ${i+1}Z" fill="${x}"/>`,b+=v`<ellipse cx="${C}" cy="${i-M*.95}" rx="${k*.42}" ry="${k*.22}" fill="${T}"/><ellipse cx="${C}" cy="${i-M*.95}" rx="${k*.07}" ry="${k*.2}" fill="#2a0800"/>`,c.push(_e(s,C,i-M*.95,5.5,T,.85))}else if(y.kind==="spires")b+=rC(s,e,C,y);else if(y.kind==="city"){const M=Le(y.tiers??5,3,7),k=n*(y.height??.4)*1.6,A=Math.max(_*1.6,7),P=D(y.color,"#f4f1ea");for(let $=0;$<M;$++){const H=i+1-($+1)*k/M,q=A*(1-$/(M+1));b+=v`<rect x="${C-q/2}" y="${H}" width="${q}" height="${k/M+.2}" fill="${$%2?ne(P,.08):P}"/>`}b+=v`<path d="M${C-.35} ${i+1-k}L${C} ${i-k-3}L${C+.35} ${i+1-k}Z" fill="${P}"/>`}}for(const C of h.beacons??[]){const _=50+(((C-225)%360+540)%360-180)/110*46;c.push(_e(s,_,i-p*.8,1.6,"#ffb040",.95))}s.add("far",b)}for(const h of t.smoke?.at??[]){const d=50+(((h[0]-225)%360+540)%360-180)/110*46;if(d<-5||d>105)continue;const u=i-n*1.2;s.add("far",v`<path d="M${d-1} ${u}C${d-3} ${u-8} ${d+6} ${u-12} ${d+4} ${u-22}C${d+12} ${u-18} ${d+10} ${u-8} ${d+3} ${u}Z" fill="${D(t.smoke.jets?.[0]?.color,"#2a2220")}" fill-opacity=".75"/>`)}for(const h of c)s.add("lights",h)}function w8(s,e,t){const i=D(t.rock,e.rock),n=D(t.top,e.ground.high),r=D(t.peak,ve(i,.15)),o=[[12,30,.85],[86,22,1],[70,42,.5],[27,47,.45],[52,14,.38]];for(const[a,l,c]of o.sort((h,d)=>h[2]-d[2])){const h=(1-c)*.55,d=J(i,e.haze,h),u=J(n,e.haze,h);let f=v`<path d="M${a-8*c} ${l}L${a-6*c} ${l+4*c}L${a-3*c} ${l+9*c}L${a+.5*c} ${l+15*c}L${a+3*c} ${l+8*c}L${a+6.5*c} ${l+4*c}L${a+8*c} ${l}Z" fill="${d}"/>`;f+=v`<path d="M${a+.5*c} ${l+15*c}L${a+3*c} ${l+8*c}L${a+6.5*c} ${l+4*c}L${a+8*c} ${l}L${a+2*c} ${l+2*c}Z" fill="${ne(d,.2)}"/>`,t.mountains&&(f+=v`<path d="M${a-6*c} ${l}L${a-1.5*c} ${l-9*c}L${a+.5*c} ${l-7*c}L${a+2.5*c} ${l-11*c}L${a+7*c} ${l}Z" fill="${J(r,e.haze,h)}"/>`,f+=v`<path d="M${a+2.5*c} ${l-11*c}L${a+7*c} ${l}L${a+3*c} ${l}Z" fill="${ne(J(r,e.haze,h),.18)}"/>`,f+=v`<path d="M${a+2.5*c} ${l-11*c}L${a+3.6*c} ${l-8*c}L${a+1.6*c} ${l-8.5*c}Z" fill="#fff" fill-opacity=".85"/>`),f+=v`<ellipse cx="${a}" cy="${l}" rx="${8.2*c}" ry="${1.8*c}" fill="${u}"/>`,f+=v`<path d="M${a-5*c} ${l+1}v${4*c}M${a+4*c} ${l+1}v${5.5*c}" stroke="${ne(u,.2)}" stroke-width="${.5*c}" stroke-linecap="round" fill="none"/>`,s.add("far",f)}}function b8(s,e,t){const i=Ge(`${e.id}-belt`),n=D(t.belt?.color??t.color,"#8a8a90");let r="";for(let a=0;a<70;a++){const l=i(),c=-4+l*108,h=44-l*30+z(i,-3,3)*(1+Math.sin(l*9));r+=v`<circle cx="${c}" cy="${h}" r="${z(i,.18,.5)}" fill="${n}" fill-opacity="${z(i,.4,.9)}"/>`}const o=D(t.color,"#5a5a60");for(const[a,l,c]of[[22,30,1.6],[70,18,2.3],[84,34,1.1]])r+=v`<path d="M${a-c} ${l}L${a-c*.4} ${l-c*.9}L${a+c*.8} ${l-c*.6}L${a+c} ${l+c*.3}L${a+c*.1} ${l+c*.9}L${a-c*.8} ${l+c*.6}Z" fill="${o}"/><path d="M${a-c*.4} ${l-c*.9}L${a+c*.8} ${l-c*.6}L${a+c*.2} ${l-c*.1}Z" fill="${ve(o,.35)}"/>`;s.add("far",r)}function v8(s,e,t){const i=e.H,n=Ge(`${e.id}-jets`);for(const r of t){const o=D(r.color,"#e8e0d0"),a=D(r.core,"#ffffff");if(r.fall||r.fixed||r.flat)continue;const l=Le((r.height??20)*.17,3,34),c=r.glow?[z(n,20,34),z(n,62,80)]:r.canopy?[z(n,66,74)]:[z(n,16,30),z(n,58,70),z(n,78,88)].slice(0,r.every>1?2:3);for(const h of c)if(r.canopy){const d=ge(s,[[0,o,.85],[1,o,.15]]);s.add("far",v`<path d="M${h-1.2} ${i}C${h-1} ${i-l*.6} ${h-2} ${i-l*.9} ${h-9} ${i-l*.78}C${h-6} ${i-l*1.08} ${h+6} ${i-l*1.08} ${h+9} ${i-l*.78}C${h+2} ${i-l*.9} ${h+1} ${i-l*.6} ${h+1.2} ${i}Z" fill="${d}"/>`)}else if(r.glow)s.add("far",v`<path d="M${h-1} ${i+1}Q${h} ${i-l*1.6} ${h+1} ${i+1}Z" fill="${o}"/>`),s.add("lights",_e(s,h,i-l*.4,l*1.2+2,o,.8));else{const d=ge(s,[[0,a,0],[.4,o,.55],[1,a,.9]]);s.add("far",v`<path d="M${h-.5} ${i}L${h-l*.16} ${i-l}Q${h} ${i-l*1.08} ${h+l*.16} ${i-l}L${h+.5} ${i}Z" fill="${d}"/>`)}}}function y8(s,e,t,i){const n=e.H;for(const[r,o]of[[30,1.6],[62,1.1]]){const a=ge(s,[[0,"#ffffff",.95],[1,"#dcecf0",.7]]);s.add("ground",v`<path d="M${r-o/2} ${i}C${r-o/2+.3} ${i+6} ${r-o} ${n-2} ${r-o} ${n+3}H${r+o}C${r+o} ${n-2} ${r+o/2+.3} ${i+6} ${r+o/2} ${i}Z" fill="${a}"/>`),s.add("water",v`<ellipse cx="${r}" cy="${n+3.4}" rx="${o*2.6}" ry="1.1" fill="#ffffff" fill-opacity=".6"/>`)}}function Pf(s,e,t,i,n=null){const r=Ge(`${e.id}-sea-of-clouds`),o=J(t,e.skyTop,.3);let a=v`<rect x="0" y="86" width="100" height="16" fill="${J(t,e.skyBottom,.25)}"/>`;for(let l=0;l<3;l++)for(let c=-8+l*6;c<110;c+=13){const h=n?Ln(r,n):J(t,e.skyBottom,.3-l*.12);a+=ao(c+z(r,-2,2),78+l*8,z(r,14,20),h,n?ne(h,.12):o,.95)}s.add(i,a)}function C8(s,e,t){const i=e.H,n=D(t.color,"#9ae8ff"),r=D(t.frame,"#d8f4ff"),o=pi(s,[[0,n,.05],[.75,n,.12],[1,n,.32]],{cx:.5,cy:1,r:1}),a=50,l=i+14,c=33;s.add("near",v`<path d="M${a-c} ${l}A${c} ${c*.95} 0 0 1 ${a+c} ${l}Z" fill="${o}"/>`);let h="";for(const d of[.33,.7])h+=v`<path d="M${a-c*d} ${l}A${c*d} ${c*.95} 0 0 1 ${a+c*d} ${l}"/>`;h+=v`<path d="M${a-c*.9} ${l-c*.42}Q${a} ${l-c*.52} ${a+c*.9} ${l-c*.42}M${a-c*.62} ${l-c*.76}Q${a} ${l-c*.84} ${a+c*.62} ${l-c*.76}"/>`,s.add("near",`<g fill="none" stroke="${r}" stroke-opacity=".38" stroke-width=".5">${h}</g>`),s.add("near",v`<path d="M${a-c} ${l}A${c} ${c*.95} 0 0 1 ${a+c} ${l}" fill="none" stroke="${r}" stroke-opacity=".8" stroke-width=".9"/>`),s.add("near",v`<path d="M${a-c*.72} ${l-c*.5}A${c*.8} ${c*.8} 0 0 1 ${a-c*.18} ${l-c*.86}" fill="none" stroke="#fff" stroke-opacity=".6" stroke-width="1.2" stroke-linecap="round"/>`),s.add("near",v`<ellipse cx="${a}" cy="${l}" rx="${c}" ry="2" fill="${r}" fill-opacity=".35"/>`)}function x8(s,e,t){const i=D(t.jets?.[0]?.color,"#7ae8f0"),n=ge(s,[[0,i,.42],[1,i,0]]);let r="";for(const[o,a,l]of[[18,7,10],[40,10,12],[62,6,9],[80,9,12]])r+=v`<path d="M${o} -2L${o+a} -2L${o+a+l} ${e.H+8}L${o+l-a*.4} ${e.H+8}Z"/>`;s.add("sky",`<g fill="${n}">${r}</g>`)}function M8(s,e){const t=Ge(`${e.id}-lanterns`),i=["#ffb050","#ffc870","#ff9440"];let n="";for(let r=0;r<16;r++){const o=z(t,6,e.H-8),l=.5+(o-4)/e.H*.9,c=z(t,8,92),h=Ln(t,i);n+=v`<rect x="${c-l*.7}" y="${o-l}" width="${l*1.4}" height="${l*1.9}" rx="${l*.4}" fill="${h}"/><rect x="${c-l*.5}" y="${o+l*.7}" width="${l}" height="${l*.25}" fill="${ne(h,.4)}"/>`,s.add("lights",_e(s,c,o,l*3.4,h,.5))}s.add("far",n)}function k8(s,e,t){const i=D(t.color,"#2a2234"),n=D(t.crystal,"#9a6aff");let r="M-2 -2H102V12";const o=Ge(`${e.id}-ceiling`);for(let l=100;l>-4;l-=z(o,4,8))r+=v`L${l} ${z(o,10,16)}L${l-1.6} ${z(o,18,30)}L${l-3} ${z(o,10,15)}`;r+="L-2 12Z",s.add("far",`<path d="${r}" fill="${i}"/>`);let a="";for(const[l,c,h]of[[22,14,1.2],[58,12,1.5],[80,15,1]])a+=v`<path d="M${l-1.2*h} ${c}L${l} ${c+6*h}L${l+1.2*h} ${c}Z" fill="${n}"/><path d="M${l} ${c}L${l} ${c+6*h}L${l+1.2*h} ${c}Z" fill="${ve(n,.35)}"/>`,s.add("lights",_e(s,l,c+3*h,5*h,n,.6));s.add("far",a)}function T8(s,e){const t="#5a4632",i=ge(s,[[0,ve(t,.12)],[.6,t],[1,ne(t,.3)]],[0,0,1,0]);s.add("far",v`<path d="M-4 -2H22C20 20 18 40 20 60C21 72 24 86 28 102H-4Z" fill="${i}"/>`),s.add("far",`<path d="M4 4C3 24 6 50 5 92M12 0C11 30 13 62 15 100M18 10C16 30 15 46 17 62" fill="none" stroke="${ne(t,.35)}" stroke-width=".7" stroke-opacity=".7"/>`),s.add("far",v`<path d="M18 20C30 14 46 12 60 6" fill="none" stroke="${t}" stroke-width="3.4" stroke-linecap="round"/>`);const n=["#3a6a2a","#4a7a34","#2e5a26"];let r="";for(const[o,a,l,c]of[[36,4,9,0],[54,2,8,1],[14,-2,12,2],[66,8,6,0]])r+=v`<circle cx="${o}" cy="${a}" r="${l}" fill="${n[c]}"/>`;s.add("far",r)}function _8(s,e,t){const i=t.skyline;i&&(i.kind==="wave"?f8(s,e,i):i.realms?g8(s,e,i):i.kind&&u8(s,e,i),i.floaters&&w8(s,e,i.floaters),i.asteroids&&b8(s,e,i.asteroids),i.jets&&!i.realms&&v8(s,e,i.jets),i.clouds&&Pf(s,e,"#ffb070","far",(i.clouds.colors??[]).map(n=>D(n)).filter(Boolean)),i.dome&&C8(s,e,i.dome),i.rays&&(e.enclosed?x8:pC)(s,e,i.rays),i.lanterns&&M8(s,e),i.ceiling&&k8(s,e,i.ceiling),i.worldTree&&T8(s),i.nest&&K8(s,e),i.dragon&&J8(s,e))}function js(s,e){const{low:t,high:i}=e.ground;return ge(s,[[0,i],[.5,J(i,t,.45)],[1,t]])}const S8=s=>[{x:9,y:s+4,s:.46,far:!0},{x:22,y:s+3.5,s:.42,far:!0},{x:79,y:s+3.5,s:.44,far:!0},{x:91,y:s+4.5,s:.42,far:!0},{x:13,y:s+12,s:.72},{x:30,y:s+11,s:.64},{x:70,y:s+11.5,s:.66},{x:87,y:s+12.5,s:.74},{x:21,y:s+24,s:1.3,front:!0},{x:79,y:s+23,s:1.25,front:!0}];function hc(s,e){const{H:t,ground:i}=e;s.add("ground",v`<path d="M-2 ${t}H102V${t+12}H-2Z" fill="${J(i.low,e.haze,.5)}"/>`),s.add("ground",v`<path d="M-2 ${t+3}C18 ${t-1.5} 34 ${t+1} 52 ${t+2.5}S84 ${t-1} 102 ${t+2}V102H-2Z" fill="${J(J(i.low,i.high,.4),e.haze,.25)}"/>`);const n=v`M-2 ${t+11}C16 ${t+5} 40 ${t+6.5} 58 ${t+9.5}S88 ${t+6} 102 ${t+8}`;return s.add("ground",`<path d="${n}V102H-2Z" fill="${js(s,e)}"/>`),s.add("ground",`<path d="${n}" fill="none" stroke="${i.tint}" stroke-opacity=".5" stroke-width=".9"/>`),S8(t)}function $8(s,e){const{H:t,ground:i}=e;return s.add("ground",v`<path d="M-2 ${t}H102V${t+8}H-2Z" fill="${J(i.low,e.haze,.45)}"/>`),[[t+1,3,.35],[t+7,4.5,.25],[t+15,6,.12],[t+26,8,0]].forEach(([r,o,a],l)=>{const c=l%2?14:-6,h=v`M-2 ${r+o*.4}C${10+c} ${r-o} ${26+c} ${r-o*.9} ${38+c} ${r+o*.2}S${70+c} ${r-o*1.2} ${102} ${r+o*.1}`,d=ge(s,[[0,J(ve(i.tint,.05),e.haze,a)],[.35,J(i.high,e.haze,a)],[1,J(i.low,e.haze,a)]]);s.add("ground",`<path d="${h}V102H-2Z" fill="${d}"/>`),s.add("ground",`<path d="${h}" fill="none" stroke="${ve(i.tint,.3)}" stroke-opacity=".55" stroke-width=".7"/>`)}),[{x:14,y:t+12,s:.55},{x:84,y:t+10,s:.5},{x:26,y:t+30,s:.85},{x:80,y:t+31,s:.9}]}function A8(s,e,t){const{H:i,ground:n}=e;s.add("bed",v`<rect x="0" y="${i}" width="100" height="40" fill="${J(e.shore,e.water?.deep??"#1c6fba",.55)}"/>`);const r=i+21;s.add("ground",v`<ellipse cx="50" cy="${r}" rx="31" ry="9.6" fill="${e.shore}"/>`),s.add("ground",v`<ellipse cx="50" cy="${r+1.4}" rx="31" ry="8.4" fill="${ne(e.shore,.12)}" fill-opacity=".5"/>`),s.add("ground",v`<path d="M24 ${r-1}C26 ${r-8} 40 ${r-9.5} 52 ${r-9}C66 ${r-8.6} 76 ${r-6} 76 ${r-1.5}C70 ${r+3} 30 ${r+3.5} 24 ${r-1}Z" fill="${js(s,e)}"/>`);const o=[{x:35,y:r-1.5,s:.72},{x:46,y:r-4.6,s:.86},{x:57,y:r-4.4,s:.8},{x:67,y:r-1.6,s:.7}];if(t.reef){const a=v`M6 ${i+9}C6 ${i+2} 94 ${i+2} 94 ${i+9}`;s.add("ground",`<path d="${a}" fill="none" stroke="${e.shore}" stroke-width="1.6" stroke-dasharray="9 3 14 2"/>`);for(const[l,c]of[[14,i+5.5],[33,i+3.4],[70,i+3.5],[88,i+5.6]])s.add("ground",v`<ellipse cx="${l}" cy="${c}" rx="3.4" ry="1" fill="${n.high}"/>`),o.push({x:l,y:c-.3,s:.3,far:!0})}else if(!e.water?.frozen)for(const[a,l]of[[16,9],[33,5],[83,11]])s.add("ground",v`<path d="M${a-l/2} ${i+1.6}Q${a} ${i-2.2} ${a+l/2} ${i+1.6}Z" fill="${J(n.high,e.haze,.35)}"/>`),o.push({x:a+.5,y:i+.4,s:.26,far:!0});return o}function E8(s,e){const{H:t,ground:i}=e;s.add("bed",v`<rect x="0" y="${t}" width="100" height="40" fill="${J(e.shore,e.water?.deep??"#1c6fba",.5)}"/>`);const n=v`M40 102C44 ${t+22} 50 ${t+9} 62 ${t+4}S88 ${t+1} 102 ${t+1.5}`;s.add("ground",`<path d="${n}V102Z" fill="${e.shore}"/>`);const r=v`M47 102C50 ${t+23} 56 ${t+11} 66 ${t+6}S90 ${t+3} 102 ${t+3}V102Z`;return s.add("ground",`<path d="${r}" fill="${js(s,e)}"/>`),[{x:78,y:t+6,s:.42,far:!0},{x:92,y:t+6,s:.42,far:!0},{x:70,y:t+14,s:.62},{x:88,y:t+15,s:.66},{x:66,y:t+30,s:.95}]}function P8(s,e,t){const{H:i,ground:n}=e,r=D(t.cliffs?.color,e.rock),o=D(t.cliffs?.moss,n.low);s.add("bed",v`<rect x="0" y="${i}" width="100" height="40" fill="${ne(r,.4)}"/>`);const a=v`M-2 ${i-11}L10 ${i-13}L26 ${i-11.5}L44 ${i-14}L64 ${i-12}L82 ${i-13.5}L102 ${i-12}`,l=ge(s,[[0,J(r,e.haze,.15)],[1,ne(J(r,e.haze,.3),.2)]]);s.add("ground",`<path d="${a}V${j(i+3)}H-2Z" fill="${l}"/>`),s.add("ground",`<path d="${a}V${j(i-9.6)}L82 ${j(i-11.4)}L64 ${j(i-10.2)}L44 ${j(i-12)}L26 ${j(i-9.8)}L10 ${j(i-11.2)}L-2 ${j(i-9.4)}Z" fill="${J(o,e.haze,.25)}"/>`),s.add("ground",`<path d="M6 ${j(i-10)}v12M18 ${j(i-11)}v13M36 ${j(i-11.5)}v14M54 ${j(i-12)}v14M74 ${j(i-11.5)}v14M92 ${j(i-11)}v13" stroke="${ne(r,.3)}" stroke-width=".5" stroke-opacity=".55"/>`);const c=v`M-2 ${i+20}C14 ${i+17} 30 ${i+19} 46 ${i+22}S80 ${i+18} 102 ${i+16}`;return s.add("ground",`<path d="${c}V102H-2Z" fill="${js(s,e)}"/>`),s.add("ground",`<path d="${c}" fill="none" stroke="${n.tint}" stroke-opacity=".5" stroke-width=".9"/>`),t.skyline?.falls&&y8(s,e,t.skyline.falls,i-11.5),[{x:14,y:i+30,s:.9},{x:86,y:i+28,s:.95},{x:72,y:i+22,s:.6},{x:26,y:i+23,s:.55},{x:40,y:i-12.6,s:.3,far:!0},{x:76,y:i-12.4,s:.3,far:!0}]}function z8(s,e,t){const{H:i,ground:n}=e,r=D(t.cliffs?.color,e.rock);s.add("bed",v`<rect x="0" y="${i}" width="100" height="40" fill="${ne(e.water?.deep??"#1a3a40",.2)}"/>`),s.add("ground",v`<path d="M-2 ${i+1}L8 ${i-3}L20 ${i-3.5}L26 ${i+1}Z" fill="${J(n.low,e.haze,.45)}"/>`),s.add("ground",v`<path d="M28 102L33 ${i+14}L40 ${i+10}L46 ${i+26}L40 102Z" fill="${r}"/>`),s.add("ground",v`<path d="M33 ${i+14}L40 ${i+10}L43 ${i+18}L37 ${i+22}Z" fill="${ve(r,.15)}"/>`);const o=v`M33 ${i+14}C40 ${i+9} 56 ${i+6} 74 ${i+5}S96 ${i+4} 102 ${i+4}`;return s.add("ground",`<path d="${o}V102H40L46 ${j(i+26)}L40 ${j(i+10)}Z" fill="${js(s,e)}"/>`),s.add("ground",`<path d="${o}" fill="none" stroke="${n.tint}" stroke-opacity=".5" stroke-width=".9"/>`),s.add("water",v`<path d="M24 101C28 ${i+30} 30 ${i+20} 34 ${i+16}" fill="none" stroke="#fff" stroke-opacity=".6" stroke-width="1.1" stroke-dasharray="3 2"/>`),[{x:64,y:i+12,s:.55},{x:84,y:i+11,s:.6},{x:58,y:i+28,s:.9},{x:90,y:i+28,s:.95}]}function L8(s,e){const{H:t,ground:i}=e;return s.add("ground",v`<rect x="0" y="${t}" width="100" height="40" fill="${js(s,e)}"/>`),[{x:18,y:t+18,s:.5},{x:80,y:t+24,s:.6},{x:34,y:t+31,s:.75}]}function R8(s,e){const t=hc(s,e),{H:i}=e,n=ne(e.rock,.1);return s.add("ground",v`<path d="M-2 102V${i+6}L4 ${i-6}L8 ${i+2}L12 ${i-12}L17 ${i+4}L22 ${i+12}L28 102Z" fill="${n}"/>`),s.add("ground",v`<path d="M102 102V${i+4}L96 ${i-10}L91 ${i+1}L87 ${i-4}L82 ${i+10}L76 102Z" fill="${n}"/>`),s.add("ground",v`<path d="M12 ${i-12}L17 ${i+4}L13 ${i+2}Z M96 ${i-10}L91 ${i+1}L95 ${i}Z" fill="${ve(n,.2)}"/>`),t.filter(r=>r.x>26&&r.x<78)}function zf(s,e,t,i){const n=e.H,r=D(i.rock,e.rock),o=D(i.soil,"#7a5a3c"),a=D(i.vine,"#4f8f3a"),l=v`M16 ${n+1}C20 ${n-6.5} 80 ${n-6.5} 84 ${n+1}`,c=v`M16 ${n+1}C28 ${n+5} 72 ${n+5} 84 ${n+1}L79 ${n+8}L71 ${n+13}L63 ${n+22}L55 ${n+32}L50 ${n+38}L45 ${n+28}L37 ${n+19}L28 ${n+12}L21 ${n+6}Z`,h=ge(s,[[0,ve(r,.1)],[1,ne(r,.35)]]);return s.add("island",`<path d="${c}" fill="${h}"/>`),s.add("island",v`<path d="M50 ${n+38}L55 ${n+32}L63 ${n+22}L71 ${n+13}L79 ${n+8}L84 ${n+1}L60 ${n+6}Z" fill="${ne(r,.22)}" fill-opacity=".7"/>`),s.add("island",v`<path d="M16 ${n+1}C28 ${n+5} 72 ${n+5} 84 ${n+1}L82 ${n+3.5}C70 ${n+7} 30 ${n+7} 18 ${n+3.5}Z" fill="${o}"/>`),i.vines!==!1&&s.add("island",`<path d="M24 ${j(n+4)}q1 4 -.5 8M36 ${j(n+5)}q1 5 0 11M66 ${j(n+5)}q-1 4 .5 9M76 ${j(n+3.5)}q1 3 0 6" fill="none" stroke="${a}" stroke-width=".8" stroke-linecap="round"/>`),s.add("ground",`<path d="${l}C72 ${j(n+5)} 28 ${j(n+5)} 16 ${j(n+1)}Z" fill="${js(s,e)}"/>`),s.add("ground",`<path d="${l}" fill="none" stroke="${e.ground.tint}" stroke-opacity=".55" stroke-width=".8"/>`),[{x:32,y:n+.5,s:.46},{x:43,y:n-1.5,s:.56},{x:58,y:n-1.2,s:.52},{x:69,y:n+.8,s:.42}]}function B8(s,e,t,i){const n=e.H,r=D(i.hull,"#e0dbd6"),o=D(i.deck,"#b8b4bc"),a=D(i.lights,"#ffd890"),l=ge(s,[[0,r],[1,ne(r,.45)]]);s.add("island",v`<path d="M18 ${n}C22 ${n+13} 78 ${n+13} 82 ${n}Z" fill="${l}"/>`),s.add("island",v`<path d="M46 ${n+9}L47.5 ${n+30}L52.5 ${n+30}L54 ${n+9}Z" fill="${ne(r,.3)}"/><ellipse cx="50" cy="${n+31}" rx="4.5" ry="2.4" fill="${ne(r,.15)}"/><path d="M44 ${n+18}h12M45 ${n+24}h10" stroke="${ne(r,.45)}" stroke-width=".6"/>`),s.add("ground",v`<ellipse cx="50" cy="${n}" rx="32" ry="6.6" fill="${o}"/><ellipse cx="50" cy="${n+.6}" rx="32" ry="6.2" fill="none" stroke="${r}" stroke-width="1"/>`);let c="";for(const[d,u,f]of[[38,4,6],[44,3.4,10],[50,5,15],[56.5,3.6,9],[62,4,5.5],[30,3,3.5],[70,3,3.5]]){const p=ge(s,[[0,ve(r,.15)],[1,ne(r,.25)]],[0,0,1,0]);c+=v`<path d="M${d-u/2} ${n+1}V${n-f+u*.4}Q${d} ${n-f-u*.2} ${d+u/2} ${n-f+u*.4}V${n+1}Z" fill="${p}"/>`}s.add("scatter",c);let h="";for(let d=0;d<9;d++)h+=v`<circle cx="${23+d*6.8}" cy="${n+3.6+Math.sin(d/8*Math.PI)*2.4}" r=".45"/>`;return s.add("lights",`<g fill="${a}">${h}</g>`),s.add("lights",_e(s,50,n+4,14,a,.25)),[]}function F8(s,e,t,i){const n=e.H,r=D(i.bark,"#5a4632"),o=D(i.moss,"#4a6a2e"),a=ge(s,[[0,ve(r,.1)],[1,ne(r,.35)]]);return s.add("island",v`<path d="M10 ${n-6}C34 ${n-4} 64 ${n-2} 96 ${n+1}C97 ${n+4} 96 ${n+7} 92 ${n+8}C64 ${n+8} 36 ${n+16} 12 ${n+22}Z" fill="${a}"/>`),s.add("island",`<path d="M24 ${j(n+2)}C40 ${j(n+3)} 60 ${j(n+4)} 84 ${j(n+4)}M30 ${j(n+9)}C46 ${j(n+8)} 62 ${j(n+7)} 78 ${j(n+6)}" fill="none" stroke="${ne(r,.35)}" stroke-width=".6"/>`),s.add("ground",v`<path d="M12 ${n-7}C36 ${n-9} 66 ${n-6} 95 ${n+.5}C66 ${n-2} 36 ${n-3.5} 12 ${n-4}Z" fill="${o}"/>`),s.add("ground",v`<path d="M26 ${n-6.2}C40 ${n-10} 62 ${n-9} 76 ${n-3.6}C62 ${n-4.6} 40 ${n-5} 26 ${n-6.2}Z" fill="${js(s,e)}"/>`),[{x:38,y:n-6.4,s:.42},{x:52,y:n-6.6,s:.48},{x:66,y:n-5.2,s:.4}]}const O8={rock:zf,city:B8,branch:F8};function I8(s,e,t){const i=t.skyIsland??{};return!t.skyline?.clouds&&!t.openSky&&Pf(s,e,D(i.cloud,"#ffffff"),"sky"),(O8[i.style]??zf)(s,e,t,i)}const Lf={plain:hc,dunes:$8,island:A8,coast:E8,fjord:P8,headland:z8,shallows:L8,crags:R8,sky:I8};function D8(s,e,t){const{H:i,ground:n}=e;if(!["plain","dunes","crags","shallows"].includes(e.groundShape??e.shape))return;const o=Ge(`${e.id}-marks`);let a="";t.split&&!t.wall&&(a+=v`<path d="M-2 ${i}H44L30 102H-2Z" fill="${D(t.split.color,"#2a1c16")}"/>`);for(const c of t.patches??[]){const h=D(c.color,n.low);for(let d=0;d<4;d++){const u=z(o,i+9,98),f=(u-i)/40;a+=v`<ellipse cx="${z(o,6,94)}" cy="${u}" rx="${z(o,3,8)*(.4+f)}" ry="${z(o,.6,1.6)*(.4+f)}" fill="${h}" fill-opacity="${Le((c.amount??.4)*1.1,.25,.85)}"/>`}}if(t.streaks){const c=D(t.streaks.color,ne(n.low,.2));let h="";for(let d=0;d<5;d++){const u=z(o,i+9,96),f=z(o,0,70);h+=v`M${f} ${u}q${z(o,6,12)} ${z(o,-2,2)} ${z(o,14,26)} ${z(o,-1,3)}`}a+=`<path d="${h}" fill="none" stroke="${c}" stroke-width=".5" stroke-opacity="${j(Le(t.streaks.amount??.5,.3,.75))}" stroke-linecap="round"/>`}const l=Le(Math.round((t.craters??0)/7),0,6);for(let c=0;c<l;c++){const h=z(o,i+10,97),d=.4+(h-i)/40,u=z(o,6,94),f=z(o,2.4,5.2)*d;a+=v`<ellipse cx="${u}" cy="${h}" rx="${f}" ry="${f*.32}" fill="${ne(n.low,.22)}"/><path d="M${u-f} ${h}A${f} ${f*.32} 0 0 0 ${u+f} ${h}" fill="none" stroke="${ve(n.high,.25)}" stroke-width="${.35*d}"/>`}if(t.fissures){const c=t.fissures;if(c.parallel&&(c.width??0)>=20){const h=D(t.cliffs?.color,c.color),d=D(t.cliffs?.band,ve(h,.2));a+=v`<path d="M30 102L46 ${i+4}L54 ${i+4}L74 102Z" fill="${ne(h,.25)}"/>`,a+=v`<path d="M30 102L46 ${i+4}L48 ${i+4}L40 102Z" fill="${h}"/>`;let u="";for(let f=1;f<6;f++){const p=i+4+f*6.6,m=(p-i-4)/(102-i-4);u+=v`M${46-m*16} ${p}L${48-m*8} ${p}M${54+m*20} ${p}L${52+m*12} ${p}`}a+=`<path d="${u}" stroke="${d}" stroke-width=".9" stroke-opacity=".8"/>`}else{const h=e.water?.lava,d=h?D(t.water.shallow,"#ff8a20"):D(c.color,ne(n.low,.4));let u="";for(let f=0;f<Math.min(c.count??2,4);f++){let p=z(o,10,90),m=i+z(o,8,14);u+=v`M${p} ${m}`;for(let g=0;g<4;g++)p+=z(o,-6,6),m+=z(o,5,9),u+=v`L${p} ${m}`}a+=`<path d="${u}" fill="none" stroke="${d}" stroke-width="${h?1.1:.8}" stroke-linejoin="round" stroke-linecap="round"/>`,h&&s.add("lights",`<path d="${u}" fill="none" stroke="${D(t.water.foam,"#ffe08a")}" stroke-width=".4" stroke-linejoin="round"/>`)}}if(t.monument?.shape==="standingStone"){let c="";for(let h=0;h<11;h++){const d=h/11*Math.PI*2+.3,u=62+Math.cos(d)*17,f=i+13+Math.sin(d)*4.4,p=(Math.sin(d)+1)/2,m=4.6+p*2.6,g=1.8+p*.9;c+=v`<rect x="${u-g/2}" y="${f-m}" width="${g}" height="${m}" rx=".5" fill="${J("#8a8a84",e.haze,.25-p*.2)}"/><rect x="${u+g*.1}" y="${f-m}" width="${g*.4}" height="${m}" rx=".3" fill="#5e5e5a" fill-opacity=".6"/>`}a+=c}if(t.glints){const c=D(t.glints.color,"#ff6a2a");for(let h=0;h<6;h++)s.add("lights",_e(s,z(o,8,92),z(o,i+8,96),1.6,c,.9))}if(t.outcrops){const c=D(t.outcrops.color,ne(e.rock,.3));for(const[h,d,u]of[[20,i+9,1],[74,i+8,.8]])a+=v`<path d="M${h-6*u} ${d+1}L${h-3*u} ${d-3*u}L${h+u} ${d-4*u}L${h+5*u} ${d-1.5*u}L${h+7*u} ${d+1}Z" fill="${c}"/>`}s.add("ground",a)}function Rf(s,e,t,i,n,r,o,a=.58){const l=e.water,c=ge(s,[[0,ve(l.shallow,.3)],[1,J(l.shallow,l.deep,.3)]]);let h=`<path d="${o}" fill="${c}" fill-opacity="${j(a)}"/>`;return h+=v`<path d="M${t+n*.1} ${i+r*.3}l${n*.12} ${r*.1}l${n*.08} ${-r*.05}l${n*.1} ${r*.12}M${t+n*.55} ${i+r*.55}l${n*.1} ${-r*.12}l${n*.14} ${r*.06}" fill="none" stroke="#ffffff" stroke-opacity=".75" stroke-width=".5"/>`,h}function V8(s,e){const t=e.water,i=e.H;if(t.lava){const a=ge(s,[[0,ve(t.shallow,.2)],[1,t.deep]]),l=v`M8 102C14 ${i+26} 30 ${i+22} 36 ${i+14}C40 ${i+9} 48 ${i+8} 56 ${i+7}C50 ${i+11} 46 ${i+16} 44 ${i+22}C40 ${i+32} 34 ${i+36} 30 102Z`;return s.add("water",`<path d="${l}" fill="${a}"/>`),s.add("water",v`<path d="M20 100C26 ${i+28} 36 ${i+22} 42 ${i+13}" fill="none" stroke="${t.foam}" stroke-width=".7" stroke-opacity=".9"/>`),s.add("lights",_e(s,34,i+22,22,t.shallow,.55)),{x:34,w:14,top:i+6,bottom:102}}if(t.low&&!e.planet.fissures?.parallel)return null;if(t.low)return s.add("water",v`<path d="M49.5 ${i+5}C50 ${i+12} 47 ${i+20} 50 ${i+28}C52 ${i+34} 49 ${i+38} 52 102L54 102C52 ${i+38} 55 ${i+34} 53 ${i+28}C51 ${i+20} 52.5 ${i+12} 50.5 ${i+5}Z" fill="${t.shallow}"/>`),null;const n=50,r=i+18,o=v`M${n-22} ${r}C${n-20} ${r-5.5} ${n+16} ${r-6.5} ${n+22} ${r-1}C${n+24} ${r+4.5} ${n-14} ${r+7.5} ${n-22} ${r}Z`;if(t.frozen)s.add("water",Rf(s,e,n-22,r-6.5,44,13,o));else{const a=ge(s,[[0,J(t.shallow,e.skyBottom,.35)],[1,t.deep]]);s.add("water",`<path d="${o}" fill="${a}" fill-opacity="${j(Le(t.opacity,.7,1))}"/>`),s.add("water",v`<path d="M${n-22} ${r}C${n-20} ${r-5.5} ${n+16} ${r-6.5} ${n+22} ${r-1}" fill="none" stroke="${t.foam}" stroke-opacity=".45" stroke-width=".6"/>`),s.add("lights",v`<path d="M${n-10} ${r-1}h7M${n+4} ${r+1.5}h9M${n-4} ${r+3.6}h5" stroke="#fff" stroke-opacity=".7" stroke-width=".5" stroke-linecap="round"/>`)}return{x:n,w:24,top:r-7,bottom:r+8}}function N8(s,e,t){const i=e.water,n=e.H,r=e.groundShape??e.shape;if(i.frozen){s.add("sea",v`<rect x="0" y="${n}" width="100" height="40" fill="${ne(i.deep,.15)}"/>`),s.add("sea",Rf(s,e,0,n,100,40,v`M0 ${n}H100V102H0Z`,.42));return}const o=ge(s,[[0,J(i.shallow,e.skyBottom,.5)],[.3,i.deep],[1,ne(i.deep,.18)]],[0,n,0,100],!0),a=r==="fjord"?n-6:n;s.add("sea",v`<rect x="0" y="${a}" width="100" height="${102-a}" fill="${o}" fill-opacity="${Le(i.opacity,.75,1)}"/>`),r==="island"&&s.add("sea",v`<ellipse cx="50" cy="${n+21.5}" rx="41" ry="13.5" fill="${i.shallow}" fill-opacity=".85"/><ellipse cx="50" cy="${n+21.5}" rx="34" ry="11" fill="none" stroke="${i.foam}" stroke-opacity=".7" stroke-width=".7"/>`),r==="coast"&&s.add("sea",v`<path d="M34 102C38 ${n+22} 44 ${n+9} 56 ${n+3.5}S86 ${n} 102 ${n+.5}V102Z" fill="${i.shallow}" fill-opacity=".8"/>`);let l="";const c=Ge(`${e.id}-waves`);for(let h=0;h<6;h++){const d=n+3+h*5.5,u=z(c,2,40);l+=v`M${u} ${d}q2 -.8 4 0t4 0`}s.add("lights",`<path d="${l}" fill="none" stroke="${i.foam}" stroke-opacity=".5" stroke-width=".45" stroke-linecap="round"/>`)}function W8(s,e){const t=e.water,i=e.H,n=ge(s,[[0,J(e.skyBottom,t.shallow,.35)],[1,J(t.shallow,e.skyTop,.35)]]);s.add("water",v`<rect x="0" y="${i}" width="100" height="40" fill="${n}" fill-opacity="${Le(t.opacity,.6,.95)}"/>`);let r="";const o=Ge(`${e.id}-ripples`);for(let a=0;a<9;a++){const l=i+2+a*4.2,c=z(o,-4,70);r+=v`M${c} ${l}h${z(o,8,26)}`}s.add("water",`<path d="${r}" stroke="${t.foam}" stroke-opacity=".5" stroke-width=".4" stroke-linecap="round"/>`)}function H8(s,e,t){if(!e.water||e.skip.has("water"))return null;const i=e.groundShape??e.shape;return["island","coast","fjord","headland"].includes(i)?(N8(s,e),null):i==="shallows"?(W8(s,e),null):i==="sky"?null:V8(s,e)}const Nd={flora:["round","round","bush","round","rock"],rocks:["rock"],desert:["cactus","rock","cactus","spire"],beach:["palm","round","palm","bush"],ocean:["palm"],tundra:["snowpine","snowpine","snowpine","rock"],frozenlake:["snowpine","snowpine","rock"],woodland:["round","pine","round","bush"],forest:["pine","pine","round","pine","fern"],kaladorn:["pine","rock","bush"],middangard:["round","bush","round","round"],glimmer:["mushroom","mushroom","fern"],hollow:["round","round","round","bush"],savanna:["acacia","baobab","acacia","bush"],valley:["pine","pine","flowers"],canyon:["pine","spire","rock"],fjord:["pine","pine","rock"],bamboo:["bamboo","bamboo","lantern"],moors:["heather","stone","heather"],undersea:["kelp","coral","kelp"],garden:["daisy","tulip","dew","daisy"],crystal:["crystal","crystal","spire"],roost:["spire","deadtree","rock"],sugarvale:["lollipop","cane","gumdrop"],lanternnight:["round","round","lantern"],sakura:["round"],lava:["spire","rock"],proxima:["rock","ice","deadtree"],trappist:["bush","rock"],kepler186f:["jungle","round","bush"],kashiwa:["redwood","jungle"],lt2230:["spire","rock"],pluto:["ice","rock"],arrakesh:["spire","rock"],horth:["shard","ice"],lt4260:["spire","spire","rock"],endral:["redwood","pine"],dagmora:["swamp","swamp","fern"],pandora:["alien","jungle","alien"],deadstar:["turret","greeble","turret"],qubitron:["steel","conduit","steel"],jakhara:["scrap","rock","scrap"],north:["pine","whitebark","snowpine"],oz:["poppies","round","poppies"],challenger:["ooze","cucumber","seapen","ooze"],titanic:["debris","cucumber","debris","rock"],yavora:["jungle","redwood","jungle","fern"]},U8={sakura:"#f2a6c6",lanternnight:"#e8a0c0",hollow:"#e0782e",kepler186f:"#7a2626",pandora:"#2f8a6a",trappist:"#8a4a30",savanna:"#6e7c34",dagmora:"#6a7a44",endral:"#2e5a34",kashiwa:"#3a6a2e"};function j8(s,e){return Nd[s.scatter]?Nd[s.scatter]:Ui(e.ground.high)>.82?["snowpine","ice","rock"]:_f(e.ground.high)?["round","pine","bush"]:["rock","spire"]}function q8(s,e){const t=U8[s.scatter]??(_f(e.ground.high)?J(e.ground.high,"#2f6a32",.55):"#4f7a3a");return{leaf:t,leafDark:ne(t,.3),leafLight:ve(t,.25),pine:"#264a32",pineLight:"#3a6a46",trunk:"#6b4a33",rock:e.rock,rockLight:ve(e.rock,.3),rockDark:ne(e.rock,.3),glow:e.glow??"#7ae8ff",sand:e.ground.high,autumn:s.scatter==="hollow",blossom:s.scatter==="sakura"||s.scatter==="lanternnight"}}const kl={round(s,e,t,i){let n=v`<rect x="${s-.8*t}" y="${e-6.5*t}" width="${1.6*t}" height="${6.5*t}" rx="${.5*t}" fill="${i.trunk}"/><circle cx="${s}" cy="${e-9.5*t}" r="${5.2*t}" fill="${i.leafDark}"/><circle cx="${s-1.1*t}" cy="${e-10.6*t}" r="${4.2*t}" fill="${i.leaf}"/><circle cx="${s-2.1*t}" cy="${e-12*t}" r="${1.9*t}" fill="${i.leafLight}"/>`;return i.blossom&&(n+=v`<g fill="#fff" fill-opacity=".8"><circle cx="${s+2*t}" cy="${e-11*t}" r="${.6*t}"/><circle cx="${s-3*t}" cy="${e-8.6*t}" r="${.5*t}"/><circle cx="${s+.4*t}" cy="${e-7*t}" r="${.55*t}"/></g>`),i.autumn&&(n+=v`<circle cx="${s+2.6*t}" cy="${e-8*t}" r="${2.2*t}" fill="#c84a24"/>`),{shape:n}},bush(s,e,t,i){return{shape:v`<circle cx="${s-1.6*t}" cy="${e-1.8*t}" r="${2.2*t}" fill="${i.leafDark}"/><circle cx="${s+1.2*t}" cy="${e-2.2*t}" r="${2.6*t}" fill="${i.leaf}"/>`}},pine(s,e,t,i){const n=[[2.6,9,5.2],[6.2,12.6,4.2],[9.8,16,3]];let r=v`<rect x="${s-.6*t}" y="${e-3*t}" width="${1.2*t}" height="${3*t}" fill="${i.trunk}"/>`;for(const[o,a,l]of n)r+=v`<path d="M${s-l*t} ${e-o*t}L${s} ${e-a*t}L${s+l*t} ${e-o*t}Z" fill="${i.pine}"/><path d="M${s} ${e-a*t}L${s+l*t} ${e-o*t}L${s} ${e-o*t}Z" fill="${i.pineLight}"/>`;return{shape:r}},snowpine(s,e,t,i){let{shape:n}=kl.pine(s,e,t,i);for(const[r,o,a]of[[2.6,9,5.2],[6.2,12.6,4.2],[9.8,16,3]]){const l=(o-r)*t,c=e-o*t,h=a*t;n+=v`<path d="M${s} ${c}L${s+h*.55} ${c+l*.5}L${s+h*.22} ${c+l*.4}L${s} ${c+l*.55}L${s-h*.25} ${c+l*.4}L${s-h*.55} ${c+l*.5}Z" fill="#f4f8fc"/>`}return{shape:n}},palm(s,e,t){const i=s+2.6*t,n=e-13*t;let r=v`<path d="M${s} ${e}Q${s+1.4*t} ${e-7*t} ${i} ${n}" fill="none" stroke="#8a6a44" stroke-width="${1.1*t}" stroke-linecap="round"/>`,o="";for(const[a,l]of[[-5.5,3],[-3,-2],[3,-2.5],[6,2.5],[1,4]])o+=v`M${i} ${n}q${a*.5*t} ${(l-3)*t} ${a*t} ${l*t}`;return r+=`<path d="${o}" fill="none" stroke="#3f8a3c" stroke-width="${j(.95*t)}" stroke-linecap="round"/>`,{shape:r}},cactus(s,e,t){return{shape:v`<path d="M${s} ${e}V${e-11*t}M${s-.2*t} ${e-5*t}H${s-2.6*t}V${e-8.6*t}M${s+.2*t} ${e-6.5*t}H${s+2.6*t}V${e-9.6*t}" fill="none" stroke="${"#5a8a46"}" stroke-width="${2*t}" stroke-linecap="round" stroke-linejoin="round"/><path d="M${s-.4*t} ${e-1}V${e-10.6*t}" stroke="#7aaa5a" stroke-width="${.5*t}" stroke-linecap="round"/>`}},acacia(s,e,t,i){return{shape:v`<path d="M${s} ${e}V${e-5*t}L${s-2.5*t} ${e-8.5*t}M${s} ${e-5*t}L${s+2.8*t} ${e-8.8*t}" fill="none" stroke="#5a4030" stroke-width="${.8*t}" stroke-linecap="round"/><ellipse cx="${s}" cy="${e-9.6*t}" rx="${7*t}" ry="${1.9*t}" fill="${i.leaf}"/><ellipse cx="${s-.6*t}" cy="${e-10.2*t}" rx="${5*t}" ry="${1.1*t}" fill="${i.leafLight}"/>`}},baobab(s,e,t,i){return{shape:v`<path d="M${s-2.4*t} ${e}C${s-2*t} ${e-5*t} ${s-1.6*t} ${e-8*t} ${s-1.3*t} ${e-9*t}L${s+1.3*t} ${e-9*t}C${s+1.6*t} ${e-8*t} ${s+2*t} ${e-5*t} ${s+2.4*t} ${e}Z" fill="#8a7058"/><path d="M${s-1*t} ${e-9*t}l${-2*t} ${-2*t}M${s} ${e-9*t}v${-2.4*t}M${s+1*t} ${e-9*t}l${2*t} ${-1.8*t}" stroke="#8a7058" stroke-width="${.6*t}" stroke-linecap="round"/><g fill="${i.leaf}"><circle cx="${s-3*t}" cy="${e-11.4*t}" r="${1.3*t}"/><circle cx="${s}" cy="${e-12*t}" r="${1.4*t}"/><circle cx="${s+3*t}" cy="${e-11.2*t}" r="${1.2*t}"/></g>`}},bamboo(s,e,t){let i="";for(const[n,r,o,a]of[[-2.6,17,-1.2,"#6e9a44"],[-.8,22,-.2,"#86b052"],[1,19,.7,"#7aa64a"],[2.8,15,1.4,"#6a9440"]]){const l=e-r*t,c=s+(n+o)*t;i+=v`<path d="M${s+n*t} ${e}L${c} ${l}" stroke="${a}" stroke-width="${1.05*t}" stroke-linecap="round"/>`;let h="";for(let d=1;d<4;d++){const u=d/4,f=s+(n+o*u)*t;h+=v`M${f-.55*t} ${e-r*t*u}h${1.1*t}`}i+=`<path d="${h}" stroke="#4e7a34" stroke-width="${j(.3*t)}"/>`,i+=v`<path d="M${c} ${l+1.4*t}q${2.4*t} ${-.4*t} ${3.4*t} ${1.6*t}M${c} ${l+3*t}q${-2.4*t} ${-.2*t} ${-3.2*t} ${1.8*t}" fill="none" stroke="#4f8a3a" stroke-width="${.75*t}" stroke-linecap="round"/>`}return{shape:i}},mushroom(s,e,t,i,n){const r=J(i.glow,"#6a4aa8",.45);return{shape:v`<path d="M${s-1.2*t} ${e}L${s-.9*t} ${e-9*t}H${s+.9*t}L${s+1.2*t} ${e}Z" fill="#e4dccc"/><path d="M${s-6*t} ${e-8.6*t}Q${s} ${e-17*t} ${s+6*t} ${e-8.6*t}Q${s} ${e-7.2*t} ${s-6*t} ${e-8.6*t}Z" fill="${r}"/><g fill="${ve(i.glow,.5)}"><circle cx="${s-2.4*t}" cy="${e-11*t}" r="${.8*t}"/><circle cx="${s+1.4*t}" cy="${e-12.4*t}" r="${.7*t}"/><circle cx="${s+3.4*t}" cy="${e-10*t}" r="${.5*t}"/></g>`,light:v`<ellipse cx="${s}" cy="${e-8.4*t}" rx="${5.4*t}" ry="${.9*t}" fill="${ve(i.glow,.3)}"/>`+_e(n,s,e-9*t,8*t,i.glow,.45)}},redwood(s,e,t,i){const n=Math.max(-4,e-40*t);return{shape:v`<path d="M${s-4.2*t} ${e}C${s-3*t} ${e-3*t} ${s-2.8*t} ${e-6*t} ${s-2.8*t} ${e-9*t}L${s-2.4*t} ${n}H${s+2.4*t}L${s+2.8*t} ${e-9*t}C${s+2.8*t} ${e-6*t} ${s+3*t} ${e-3*t} ${s+4.2*t} ${e}Z" fill="#7a4a32"/><path d="M${s-.8*t} ${e}L${s-.6*t} ${n}M${s+1*t} ${e}L${s+.8*t} ${n}" stroke="#5a3424" stroke-width="${.4*t}"/><ellipse cx="${s}" cy="${n+2}" rx="${6*t}" ry="${4*t}" fill="${i.leaf}"/>`}},swamp(s,e,t,i){return{shape:v`<path d="M${s-4*t} ${e}C${s-2*t} ${e-1*t} ${s-1.4*t} ${e-4*t} ${s-1.8*t} ${e-7*t}C${s-2.6*t} ${e-9*t} ${s-.6*t} ${e-11*t} ${s} ${e-13*t}C${s+1*t} ${e-10*t} ${s+2*t} ${e-8*t} ${s+1.4*t} ${e-5*t}C${s+1.2*t} ${e-2*t} ${s+2.6*t} ${e-1*t} ${s+4.4*t} ${e}Z" fill="#5e5444"/><path d="M${s} ${e-11*t}L${s-5*t} ${e-13*t}M${s+.6*t} ${e-10*t}L${s+5.4*t} ${e-12.4*t}" stroke="#5e5444" stroke-width="${.8*t}" stroke-linecap="round"/><ellipse cx="${s-4*t}" cy="${e-13.6*t}" rx="${4*t}" ry="${1.8*t}" fill="${i.leafDark}"/><ellipse cx="${s+4.6*t}" cy="${e-13*t}" rx="${4.4*t}" ry="${2*t}" fill="${i.leaf}"/><ellipse cx="${s+.4*t}" cy="${e-14.8*t}" rx="${3.6*t}" ry="${1.8*t}" fill="${i.leafLight}"/><path d="M${s-6*t} ${e-13*t}v${4*t}M${s-2.6*t} ${e-12.6*t}v${5*t}M${s+3*t} ${e-12*t}v${4.4*t}M${s+7*t} ${e-12.4*t}v${3.2*t}" stroke="#9aaa76" stroke-width="${.35*t}" stroke-opacity=".8"/>`}},kelp(s,e,t){let i="";for(const n of[-1.6,.4,2])i+=v`M${s+n*t} ${e}C${s+(n-2)*t} ${e-5*t} ${s+(n+2)*t} ${e-9*t} ${s+n*t} ${e-15*t}`;return{shape:`<path d="${i}" fill="none" stroke="#5a8a3a" stroke-width="${j(.9*t)}" stroke-linecap="round"/>`}},coral(s,e,t){return{shape:v`<path d="M${s} ${e}V${e-4*t}L${s-2.2*t} ${e-7*t}M${s} ${e-4*t}L${s+2.2*t} ${e-8*t}L${s+3*t} ${e-10*t}M${s-2.2*t} ${e-7*t}L${s-2.6*t} ${e-9*t}" fill="none" stroke="#f07a8a" stroke-width="${1.1*t}" stroke-linecap="round"/><path d="M${s+3*t} ${e}A${3*t} ${3*t} 0 0 1 ${s+9*t} ${e}Z" fill="#e8a050"/>`}},daisy(s,e,t){const i=e-16*t;let n="";for(let r=0;r<8;r++)n+=v`<ellipse cx="${s}" cy="${i-2.2*t}" rx="${.9*t}" ry="${2*t}" transform="rotate(${r*45} ${s} ${i})"/>`;return{shape:v`<path d="M${s} ${e}Q${s+1.2*t} ${e-8*t} ${s} ${i}" fill="none" stroke="#4a8a3a" stroke-width="${.9*t}"/><g fill="#ffffff">${n}</g><circle cx="${s}" cy="${i}" r="${1.4*t}" fill="#f2c230"/>`}},tulip(s,e,t){const i=e-15*t;return{shape:v`<path d="M${s} ${e}V${i}" stroke="#4a8a3a" stroke-width="${.9*t}"/><path d="M${s-2.4*t} ${i}Q${s-2.6*t} ${i-4.4*t} ${s-1*t} ${i-4.8*t}L${s} ${i-3.2*t}L${s+1*t} ${i-4.8*t}Q${s+2.6*t} ${i-4.4*t} ${s+2.4*t} ${i}Q${s} ${i+1.6*t} ${s-2.4*t} ${i}Z" fill="#e8506a"/>`}},dew(s,e,t,i,n){return{shape:v`<circle cx="${s}" cy="${e-2.2*t}" r="${2.2*t}" fill="${pi(n,[[0,"#ffffff"],[.5,"#cfeefa"],[1,"#7ab8d8"]],{cx:.35,cy:.3})}" fill-opacity=".9"/>`}},lollipop(s,e,t){return{shape:v`<path d="M${s} ${e}V${e-9*t}" stroke="#ffffff" stroke-width="${.6*t}"/><circle cx="${s}" cy="${e-11.5*t}" r="${3.2*t}" fill="#ff7ab0"/><path d="M${s} ${e-11.5*t}m${-1.6*t} 0a${1.6*t} ${1.6*t} 0 1 1 ${2.4*t} ${1.2*t}" fill="none" stroke="#fff" stroke-width="${.6*t}"/>`}},cane(s,e,t){const i=v`M${s} ${e}V${e-10*t}A${2*t} ${2*t} 0 0 0 ${s-4*t} ${e-10*t}`;return{shape:`<path d="${i}" fill="none" stroke="#ffffff" stroke-width="${j(1.3*t)}" stroke-linecap="round"/><path d="${i}" fill="none" stroke="#e8304a" stroke-width="${j(1.3*t)}" stroke-dasharray="${j(1.2*t)} ${j(1.2*t)}"/>`}},gumdrop(s,e,t,i,n,r){const o=Ln(r,["#7ad0a0","#ffb04a","#a07aff","#ff6a8a"]);return{shape:v`<path d="M${s-2.6*t} ${e}Q${s-2.6*t} ${e-4.6*t} ${s} ${e-4.8*t}Q${s+2.6*t} ${e-4.6*t} ${s+2.6*t} ${e}Z" fill="${o}"/><path d="M${s-1.2*t} ${e-3.4*t}q.8 -.8 1.8 -.9" fill="none" stroke="#fff" stroke-opacity=".7" stroke-width="${.4*t}"/>`}},crystal(s,e,t,i,n){const r=ge(n,[[0,ve(i.glow,.5)],[1,i.glow]]);return{shape:v`<g fill="${r}"><path d="M${s-2.2*t} ${e}L${s-2.8*t} ${e-6*t}L${s-1.6*t} ${e-9*t}L${s-.6*t} ${e-5*t}L${s-.6*t} ${e}Z"/><path d="M${s-.8*t} ${e}L${s-.6*t} ${e-9*t}L${s+.6*t} ${e-13*t}L${s+1.6*t} ${e-9*t}L${s+1.4*t} ${e}Z"/><path d="M${s+1.2*t} ${e}L${s+2*t} ${e-5*t}L${s+3.6*t} ${e-6.6*t}L${s+3.2*t} ${e}Z"/></g><path d="M${s+.6*t} ${e-13*t}L${s+1.6*t} ${e-9*t}L${s+1.4*t} ${e}L${s+.5*t} ${e}Z" fill="#fff" fill-opacity=".3"/>`,light:_e(n,s,e-6*t,9*t,i.glow,.5)}},rock(s,e,t,i){return{shape:v`<path d="M${s-3.2*t} ${e}L${s-2.6*t} ${e-2.4*t}L${s-.8*t} ${e-3.6*t}L${s+1.6*t} ${e-3.2*t}L${s+3.2*t} ${e-1.4*t}L${s+3.4*t} ${e}Z" fill="${i.rock}"/><path d="M${s-2.6*t} ${e-2.4*t}L${s-.8*t} ${e-3.6*t}L${s+.6*t} ${e-2}L${s-1.6*t} ${e-1.2*t}Z" fill="${i.rockLight}"/>`}},spire(s,e,t,i){return{shape:v`<path d="M${s-2.6*t} ${e}L${s-1.4*t} ${e-6*t}L${s-.9*t} ${e-11*t}L${s-.2*t} ${e-14*t}L${s+.6*t} ${e-10*t}L${s+1.6*t} ${e-6.5*t}L${s+2.6*t} ${e}Z" fill="${i.rockDark}"/><path d="M${s-.2*t} ${e-14*t}L${s+.6*t} ${e-10*t}L${s+1.6*t} ${e-6.5*t}L${s+2.6*t} ${e}L${s+.6*t} ${e}Z" fill="${i.rock}"/>`}},ice(s,e,t){return{shape:v`<path d="M${s} ${e-6*t}L${s+3*t} ${e-4.6*t}L${s} ${e-3.2*t}L${s-3*t} ${e-4.6*t}Z" fill="#eef8ff"/><path d="M${s-3*t} ${e-4.6*t}L${s} ${e-3.2*t}V${e}L${s-3*t} ${e-1.4*t}Z" fill="#bfe2f2"/><path d="M${s+3*t} ${e-4.6*t}L${s} ${e-3.2*t}V${e}L${s+3*t} ${e-1.4*t}Z" fill="#94c4de"/>`}},shard(s,e,t){return{shape:v`<path d="M${s-2.4*t} ${e}L${s-.6*t} ${e-12*t}L${s+1.4*t} ${e}Z" fill="#cfeaf8"/><path d="M${s-.6*t} ${e-12*t}L${s+1.4*t} ${e}L${s+.2*t} ${e}Z" fill="#9ccae2"/><path d="M${s+1*t} ${e}L${s+2.4*t} ${e-6*t}L${s+3.6*t} ${e}Z" fill="#b8dcf0"/>`}},heather(s,e,t){return{shape:v`<g><circle cx="${s-2.4*t}" cy="${e-.6*t}" r="${1.8*t}" fill="#7a3a7a"/><circle cx="${s}" cy="${e-1.2*t}" r="${2.2*t}" fill="#9a4a8a"/><circle cx="${s+2.4*t}" cy="${e-.6*t}" r="${1.6*t}" fill="#8a4280"/></g>`}},stone(s,e,t){return{shape:v`<rect x="${s-1.2*t}" y="${e-6.5*t}" width="${2.4*t}" height="${6.5*t}" rx="${.9*t}" fill="#8a8a84"/><rect x="${s+.2*t}" y="${e-6.2*t}" width="${1*t}" height="${6.2*t}" rx="${.5*t}" fill="#6e6e6a"/>`}},lantern(s,e,t,i,n){return{shape:v`<rect x="${s-.5*t}" y="${e-4*t}" width="${1*t}" height="${4*t}" fill="#8a8a84"/><rect x="${s-1.3*t}" y="${e-6.2*t}" width="${2.6*t}" height="${2.4*t}" fill="#ffd27a"/><path d="M${s-2.4*t} ${e-6.2*t}L${s} ${e-8*t}L${s+2.4*t} ${e-6.2*t}Z" fill="#6e6e6a"/>`,light:_e(n,s,e-5*t,5*t,"#ffc870",.7)}},jungle(s,e,t,i){return{shape:v`<path d="M${s} ${e}V${e-10*t}" stroke="#5a4030" stroke-width="${1.2*t}"/><ellipse cx="${s}" cy="${e-11*t}" rx="${6.4*t}" ry="${3*t}" fill="${i.leafDark}"/><ellipse cx="${s-1*t}" cy="${e-12.6*t}" rx="${4.6*t}" ry="${2.4*t}" fill="${i.leaf}"/><ellipse cx="${s-2*t}" cy="${e-13.6*t}" rx="${2*t}" ry="${1*t}" fill="${i.leafLight}"/>`}},deadtree(s,e,t){return{shape:v`<path d="M${s} ${e}V${e-9*t}M${s} ${e-5*t}L${s-3*t} ${e-8.4*t}M${s} ${e-6.5*t}L${s+2.6*t} ${e-10*t}M${s-1.6*t} ${e-6.8*t}L${s-2.4*t} ${e-10*t}" fill="none" stroke="#4a3e36" stroke-width="${.7*t}" stroke-linecap="round"/>`}},alien(s,e,t,i,n){return{shape:v`<path d="M${s} ${e}C${s-1*t} ${e-6*t} ${s+1*t} ${e-10*t} ${s} ${e-15*t}" fill="none" stroke="#3a4a3a" stroke-width="${1*t}"/><path d="M${s} ${e-15*t}q${-4*t} ${-1*t} ${-6*t} ${3*t}M${s} ${e-15*t}q${4*t} ${-1*t} ${6*t} ${3.4*t}M${s} ${e-15*t}q${-2*t} ${1*t} ${-3*t} ${4.6*t}M${s} ${e-15*t}q${2*t} ${1*t} ${3.4*t} ${4.4*t}" fill="none" stroke="${i.leaf}" stroke-width="${1.1*t}" stroke-linecap="round"/>`,light:[[-6,-12],[6,-11.6],[-3,-10.4],[3.4,-10.6]].map(([r,o])=>_e(n,s+r*t,e+o*t,1.6*t,i.glow,.9)).join("")}},fern(s,e,t,i){return{shape:v`<path d="M${s} ${e}q${-3*t} ${-2*t} ${-4.6*t} ${-1*t}M${s} ${e}q${-1.6*t} ${-3.4*t} ${-2.6*t} ${-4.6*t}M${s} ${e}q${.4*t} ${-3.8*t} ${.6*t} ${-5.2*t}M${s} ${e}q${2*t} ${-3*t} ${3.4*t} ${-3.8*t}M${s} ${e}q${3*t} ${-1.4*t} ${4.6*t} ${-.6*t}" fill="none" stroke="${i.leaf}" stroke-width="${.8*t}" stroke-linecap="round"/>`}},whitebark(s,e,t){return{shape:v`<path d="M${s-1.4*t} ${e}C${s-1*t} ${e-4*t} ${s-1.6*t} ${e-7*t} ${s-.6*t} ${e-10*t}H${s+.8*t}C${s+1.4*t} ${e-7*t} ${s+1*t} ${e-4*t} ${s+1.6*t} ${e}Z" fill="#ece6dc"/><circle cx="${s-2.4*t}" cy="${e-11*t}" r="${3.2*t}" fill="#9a1e22"/><circle cx="${s+1.6*t}" cy="${e-12*t}" r="${3.6*t}" fill="#c8302e"/><circle cx="${s-.2*t}" cy="${e-14.2*t}" r="${2.4*t}" fill="#e04a3a"/><path d="M${s-.5*t} ${e-6*t}q.4 .5 .9 0" fill="none" stroke="#7a2a22" stroke-width="${.3*t}"/>`}},turret(s,e,t,i){return{shape:v`<path d="M${s-2.6*t} ${e}V${e-7*t}H${s+2.6*t}V${e}Z" fill="${i.rock}"/><path d="M${s+.6*t} ${e}V${e-7*t}H${s+2.6*t}V${e}Z" fill="${i.rockDark}"/><rect x="${s-3.4*t}" y="${e-8.6*t}" width="${6.8*t}" height="${1.8*t}" fill="${i.rockLight}"/><path d="M${s-1*t} ${e-8.6*t}V${e-10.6*t}H${s+1*t}V${e-8.6*t}Z" fill="${i.rock}"/><path d="M${s+.6*t} ${e-9.8*t}L${s+5*t} ${e-12*t}" stroke="${i.rockDark}" stroke-width="${.6*t}" stroke-linecap="round"/><path d="M${s-.6*t} ${e-9.8*t}L${s+4*t} ${e-12.8*t}" stroke="${i.rockDark}" stroke-width="${.5*t}" stroke-linecap="round"/>`}},greeble(s,e,t,i){return{shape:v`<rect x="${s-3*t}" y="${e-2.4*t}" width="${6*t}" height="${2.4*t}" fill="${i.rockLight}"/><rect x="${s-1.6*t}" y="${e-4*t}" width="${2.6*t}" height="${1.6*t}" fill="${i.rock}"/><rect x="${s+1.4*t}" y="${e-3.2*t}" width="${1.2*t}" height="${.8*t}" fill="${i.rockDark}"/>`}},ooze(s,e,t){return{shape:v`<path d="M${s-3.4*t} ${e}C${s-3.6*t} ${e-2.6*t} ${s-1*t} ${e-3.8*t} ${s+.4*t} ${e-3*t}C${s+2.6*t} ${e-3.6*t} ${s+3.8*t} ${e-1.6*t} ${s+3.4*t} ${e}Z" fill="#b8ae98"/><path d="M${s-2*t} ${e-1.4*t}Q${s} ${e-2.6*t} ${s+2*t} ${e-1.2*t}" fill="none" stroke="#8a826e" stroke-width="${.4*t}"/>`}},cucumber(s,e,t,i,n){return{shape:v`<ellipse cx="${s}" cy="${e-1.2*t}" rx="${3.4*t}" ry="${1.3*t}" fill="#c87aa8" fill-opacity=".85"/><path d="M${s-1.6*t} ${e-2.3*t}Q${s} ${e-4.2*t} ${s+1.4*t} ${e-2.3*t}" fill="#e0a8cc" fill-opacity=".8"/>`,light:_e(n,s,e-1.4*t,4*t,"#d080ff",.35)}},seapen(s,e,t,i,n){return{shape:v`<path d="M${s} ${e}V${e-5*t}" stroke="#6a8a9a" stroke-width="${.5*t}"/><path d="M${s} ${e-4*t}C${s-1.8*t} ${e-6*t} ${s-1.2*t} ${e-9*t} ${s} ${e-10*t}C${s+1.2*t} ${e-9*t} ${s+1.8*t} ${e-6*t} ${s} ${e-4*t}Z" fill="#5ae8d8"/>`,light:_e(n,s,e-7*t,6*t,"#5ae8ff",.55)}},debris(s,e,t){return{shape:v`<path d="M${s-3.6*t} ${e}L${s-2.4*t} ${e-4.6*t}L${s+1.8*t} ${e-5.4*t}L${s+3.4*t} ${e-2*t}L${s+3*t} ${e}Z" fill="#6a3e24"/><path d="M${s-2.4*t} ${e-4.6*t}L${s+1.8*t} ${e-5.4*t}L${s+1.4*t} ${e-4.2*t}L${s-2*t} ${e-3.4*t}Z" fill="#a0582a"/><path d="M${s-1.2*t} ${e-4.8*t}V${e-3*t}M${s+.8*t} ${e-5.2*t}V${e-3.6*t}" stroke="#c0703a" stroke-width="${.3*t}"/>`}},scrap(s,e,t,i){return{shape:v`<path d="M${s-4.6*t} ${e}L${s-3.6*t} ${e-4.4*t}L${s+1.6*t} ${e-6*t}L${s+4*t} ${e-2.6*t}L${s+4.4*t} ${e}Z" fill="#8a847a"/><path d="M${s-3.6*t} ${e-4.4*t}L${s+1.6*t} ${e-6*t}L${s+1.2*t} ${e-4.6*t}L${s-3*t} ${e-3.2*t}Z" fill="#b4aea2"/><path d="M${s-2*t} ${e-4.6*t}V${e}M${s+.6*t} ${e-5.4*t}V${e}" stroke="#5a564e" stroke-width="${.35*t}"/><path d="M${s-5.4*t} ${e}Q${s} ${e-1.6*t} ${s+5.6*t} ${e}Z" fill="${i.sand}"/>`}},steel(s,e,t,i){return{shape:v`<path d="M${s-3*t} ${e}L${s-1.4*t} ${e-9*t}L${s+.4*t} ${e-12*t}L${s+2.6*t} ${e-6*t}L${s+3.2*t} ${e}Z" fill="#6e7684"/><path d="M${s+.4*t} ${e-12*t}L${s+2.6*t} ${e-6*t}L${s+3.2*t} ${e}L${s+.8*t} ${e}Z" fill="#9aa2ae"/><path d="M${s+.4*t} ${e-12*t}L${s+.8*t} ${e}" stroke="${i.glow}" stroke-width="${.35*t}" stroke-opacity=".9"/>`}},conduit(s,e,t,i,n){return{shape:v`<path d="M${s-5*t} ${e}C${s-5*t} ${e-9*t} ${s+5*t} ${e-9*t} ${s+5*t} ${e}" fill="none" stroke="#5a6270" stroke-width="${1.6*t}"/><path d="M${s-5*t} ${e}C${s-5*t} ${e-9*t} ${s+5*t} ${e-9*t} ${s+5*t} ${e}" fill="none" stroke="${i.glow}" stroke-width="${.45*t}"/>`,light:_e(n,s,e-6*t,5*t,i.glow,.45)}},poppies(s,e,t,i,n,r){let o="";for(let a=0;a<9;a++){const l=s+z(r,-6,6)*t,c=e-z(r,0,2.6)*t;o+=v`<path d="M${l} ${c+1.2*t}V${c}" stroke="#3a7a2a" stroke-width="${.25*t}"/><circle cx="${l}" cy="${c}" r="${.75*t}" fill="#e8302a"/><circle cx="${l}" cy="${c}" r="${.25*t}" fill="#2a0a08"/>`}return{shape:o}},flowers(s,e,t,i,n,r){let o="";for(let a=0;a<7;a++)o+=v`<circle cx="${s+z(r,-5,5)*t}" cy="${e-z(r,0,2)*t}" r="${.6*t}" fill="${Ln(r,["#f2e070","#c08ae0","#f07a7a","#ffffff"])}"/>`;return{shape:o}}};function G8(s,e,t,i,n){const r=e.scatterKinds??j8(t,e),o=q8(t,e),a=Ge(`${e.id}-scatter`),l=i.filter(c=>!n||Math.abs(c.x-n.x)>n.w||c.y<n.top||c.y>n.bottom).sort((c,h)=>c.y-h.y);for(const c of l){const h=c.kind??(c.front?r[0]:r[Math.floor(a()*r.length)%r.length]),d=(kl[h]??kl.rock)(c.x,c.y,c.s*e.scatterScale,o,s,a);s.add("scatter",c.far?`<g opacity=".82">${d.shape}</g>`:d.shape),d.light&&s.add("lights",d.light)}}function Z8(s,e,t){const i=t.grass,n=D(i.root,e.ground.low),r=D(i.tip,e.ground.tint),o=ge(s,[[0,r],[1,n]]),a=Ge(`${e.id}-grass`),l=e.groundShape??e.shape;if(l==="sky"||l==="island")return;const c=Le((i.height?.[1]??.6)/.6*6,4,13);let h="";for(let u=4;u<97;u+=z(a,1.6,3)){const f=Math.abs(u-50)/50,p=c*z(a,.55,1)*(.55+f*.6),m=z(a,-1.6,1.6);h+=v`M${u} 101Q${u+m*.4} ${101-p*.6} ${u+m} ${101-p}Q${u+m*.3+.7} ${101-p*.5} ${u+1.5} 101Z`}s.add("grass",`<path d="${h}" fill="${o}"/>`);let d="";for(let u=0;u<6;u++){const f=z(a,8,92),p=z(a,e.H+10,e.H+22);d+=v`M${f-1} ${p}l.4 -2l.6 2l.5 -2.4l.5 2.4`}s.add("grass",`<path d="${d}" fill="none" stroke="${r}" stroke-width=".4" stroke-opacity=".8"/>`)}function X8(s,e,t){const i=e.H;if(t.mist&&!e.skip.has("mist")){const n=D(t.mist.color,"#ffffff"),r=Le((t.mist.amount??.3)*1.4,.2,.5),o=ge(s,[[0,n,0],[.45,n,r],[1,n,0]]);s.add("near",v`<rect x="0" y="${i-4}" width="100" height="18" fill="${o}"/>`)}if(!e.enclosed&&t.fog&&e.atmosphere>.3&&(e.groundShape??e.shape)!=="sky"){const n=Le(1.1-(t.fog.near??100)/160,.2,.8),r=ge(s,[[0,e.haze,0],[.55,e.haze,n*.7],[1,e.haze,0]]);s.add("far",v`<rect x="0" y="${i-6}" width="100" height="10" fill="${r}"/>`)}}const Y8={snow:{color:"#ffffff",size:[.3,.75],count:16},blizzard:{color:"#ffffff",streak:[-2.4,.8],count:14},rain:{color:"#c8d8e8",streak:[-.8,2.6],count:14},pollen:{color:"#fff2a0",size:[.2,.42],count:7},fireflies:{color:"#e8ff7a",glow:!0,count:6,dark:!0},petals:{color:"#ffc4dc",petal:!0,count:10},leaves:{color:"#e0782e",petal:!0,count:8},embers:{color:"#ff8a3a",glow:!0,count:10},ash:{color:"#9a9490",size:[.25,.5],count:12},bubbles:{color:"#c8f4ff",bubble:!0,count:9},spores:{glow:!0,count:9},sand:{color:"#f0d8a8",streak:[-2,.3],count:10},dust:{color:"#d8b090",size:[.2,.4],count:8},grit:{color:"#5a6a7a",streak:[-1.6,.6],count:10},spray:{color:"#ffffff",size:[.2,.45],count:8,low:!0},darkplume:{color:"#3a2e2a",plume:!0,count:3},geyser:{color:"#e8f4ff",plume:!0,count:2},sprinkles:{sprinkle:!0,count:12},fireworks:{fireworks:!0}};function Q8(s,e,t){const i=Ge(`${e.id}-weather`),n=e.night||e.starry||Ui(e.skyTop)<.2||e.dusk;let r="";for(const o of t.weather??[]){const a=Y8[o.kind];if(!a||a.dark&&!n)continue;if(a.fireworks){for(const[h,d,u]of[[30,16,"#ffd24a"],[18,28,"#7ad8ff"]]){let f="";for(let p=0;p<10;p++){const m=p/10*Math.PI*2;f+=v`M${h+Math.cos(m)*1.4} ${d+Math.sin(m)*1.4}L${h+Math.cos(m)*4} ${d+Math.sin(m)*4}`}r+=`<path d="${f}" stroke="${u}" stroke-width=".5" stroke-linecap="round"/>`}continue}const l=Math.round(a.count*Le(o.rate??1,.4,1.4)),c=a.color??e.glow??"#9af0ff";for(let h=0;h<l;h++){const d=z(i,6,94),u=a.low?z(i,e.H-6,96):z(i,6,96);if(a.glow)s.add("air",_e(s,d,u,2.2,c,.85)),r+=v`<circle cx="${d}" cy="${u}" r=".38" fill="#ffffff"/>`;else if(a.streak)r+=v`<path d="M${d} ${u}l${a.streak[0]} ${a.streak[1]}" stroke="${c}" stroke-opacity=".7" stroke-width=".35" stroke-linecap="round"/>`;else if(a.petal)r+=v`<ellipse cx="${d}" cy="${u}" rx=".9" ry=".45" fill="${c}" transform="rotate(${z(i,0,180)} ${d} ${u})"/>`;else if(a.bubble)r+=v`<circle cx="${d}" cy="${u}" r="${z(i,.5,1.2)}" fill="none" stroke="${c}" stroke-opacity=".75" stroke-width=".3"/>`;else if(a.plume){const f=z(i,14,86);r+=v`<path d="M${f-.5} ${e.H+1}Q${f-1} ${e.H-9} ${f+3} ${e.H-16}Q${f+1} ${e.H-8} ${f+.5} ${e.H+1}Z" fill="${c}" fill-opacity=".7"/>`}else a.sprinkle?r+=v`<path d="M${d} ${u}l1 .5" stroke="${Ln(i,["#ff6a9a","#7ad8ff","#ffe066","#9aff8a","#ffffff"])}" stroke-width=".55" stroke-linecap="round"/>`:r+=v`<circle cx="${d}" cy="${u}" r="${z(i,a.size[0],a.size[1])}" fill="${c}" fill-opacity=".85"/>`}}if(t.lightning){const o=e.sun?.x>50?30:70,a=v`M${o} 8L${o-3} 18L${o+1} 19L${o-4} ${e.H-6}L${o+3} 22L${o-1} 21L${o+2} 8Z`;s.add("air",_e(s,o-1,20,14,"#cfe0ff",.45)),r+=`<path d="${a}" fill="#f4f8ff"/>`}s.add("air",r)}const Wd=[["#120e10","#7e2418"],["#142a1c","#8a7a3c"],["#a89c84","#d2b06a"],["#22180e","#9a6a32"],["#1a1e22","#6e7a84"]];function K8(s,e){const t=e.H,i=ge(s,[[0,"#ffe080"],[.5,"#e8b844"],[1,"#9a6a14"]]);s.add("scatter",v`<path d="M50 ${t+17}Q61 ${t+7} 72 ${t+17}Z" fill="${i}"/><g fill="#fff6c8"><circle cx="58" cy="${t+12}" r=".7"/><circle cx="65" cy="${t+11}" r=".6"/></g>`),s.add("lights",_e(s,61,t+13,12,"#ffd060",.3));let n="";for(let a=0;a<30;a++){const l=-2+a*3.6,c=t+27+Math.sin(a*1.7)*1.4;n+=v`M${l} ${c}l${5+a%3} ${(a%2?-1:1)*1.6}`}s.add("near",v`<path d="M-4 ${t+34}Q50 ${t+18} 104 ${t+34}V104H-4Z" fill="#2e241c"/><path d="${n}" stroke="#4a3626" stroke-width="1.1" stroke-linecap="round"/>`);const r=[{x:18,kind:"whole"},{x:31,kind:"cracked"},{x:46,kind:"hatched"},{x:61,kind:"whole"},{x:76,kind:"cracked"},{x:89,kind:"hatched"}];let o="";r.forEach(({x:a,kind:l},c)=>{const[h,d]=Wd[c%Wd.length],u=ge(s,[[0,d],[1,h]],[0,0,1,1]),f=t+26-Math.sin(a/100*Math.PI)*3;if(l==="hatched"){o+=v`<path d="M${a-4.6} ${f-4}C${a-4.6} ${f+1.6} ${a+4.6} ${f+1.6} ${a+4.6} ${f-4}L${a+3} ${f-5.6}L${a+1.6} ${f-3.8}L${a} ${f-5.8}L${a-1.6} ${f-3.8}L${a-3} ${f-5.6}Z" fill="${u}"/>`,o+=v`<path d="M${a-3.6} ${f-4.4}L${a-3} ${f-5.2}L${a-1.6} ${f-3.6}L${a} ${f-5.4}L${a+1.6} ${f-3.6}L${a+3} ${f-5.2}L${a+3.6} ${f-4.4}Q${a} ${f-2.4} ${a-3.6} ${f-4.4}Z" fill="#9e8c70"/>`,o+=v`<path d="M${a+6} ${f+.6}l2.4 -1.4l.8 1.8ZM${a-8} ${f+.4}l2 -1.6l1 1.4Z" fill="${h}"/>`;return}let p="";for(let m=0;m<5;m++){const g=f-9.2+m*2.2,w=4.4*Math.sin((m+.8)/6*Math.PI);for(let b=a-w+m%2*.8;b<a+w-.4;b+=1.6)p+=v`M${b} ${g}q.8 1.3 1.6 0`}if(o+=v`<ellipse cx="${a}" cy="${f-5}" rx="4.4" ry="6.2" fill="${u}"/><path d="${p}" fill="none" stroke="${d}" stroke-opacity=".55" stroke-width=".45"/>`,l==="cracked"){const m=v`M${a-3.6} ${f-6}l1.6 1l1 -1.6l1.4 1.2l1.2 -1.4l1.6 1.4`;s.add("lights",v`<path d="${m}" fill="none" stroke="#ff7a24" stroke-width="1.6" stroke-opacity=".5" stroke-linejoin="round"/>`),o+=v`<path d="${m}" fill="none" stroke="#ffb060" stroke-width=".7" stroke-linejoin="round"/>`}}),s.add("near",o)}function J8(s,e){const t=e.H,i=J("#0c0a10",e.haze,.3);s.add("far",v`<g transform="translate(66 ${t-22})" fill="${i}"><path d="M10.2 -2.82Q9.9 -3 9.48 -3.09L8.58 -3.3L8.16 -3.45Q7.38 -4.14 6.78 -4.62L7.62 -3.48Q7.08 -3.87 6.54 -3.96L7.08 -3.27Q6.6 -3.18 6 -2.97Q4.92 -2.67 3.9 -2.1Q3.12 -1.86 2.4 -1.68L1.86 -1.68Q1.77 -1.98 1.56 -2.1L1.32 -1.59Q0.66 -1.5 0 -1.44Q-0.15 -1.74 -0.3 -1.86L-0.6 -1.38Q-1.26 -1.35 -1.92 -1.32Q-2.04 -1.56 -2.16 -1.68L-2.46 -1.26Q-3 -1.2 -3.6 -1.14Q-5.4 -0.96 -7.2 -0.72Q-9 -0.66 -10.8 -0.96Q-12 -1.2 -12.9 -1.5L-14.1 -1.68L-12.78 -1.23Q-11.7 -0.78 -10.5 -0.57Q-8.7 -0.33 -7.2 -0.36Q-5.7 -0.36 -4.5 -0.45L-3.6 -0.33Q-3.24 0 -3.18 0.36Q-3.72 0.78 -4.08 1.02L-4.92 1.2L-4.74 1.38Q-4.26 1.38 -3.78 1.29Q-3.3 1.08 -2.82 0.66Q-2.46 0.24 -2.22 -0.15Q-0.84 -0.06 0.6 -0.18L1.26 -0.12Q1.44 0.18 1.44 0.42L1.08 0.96L1.38 1.14Q1.74 1.02 2.04 0.72Q2.22 0.36 2.22 -0.18Q2.88 -0.54 3.72 -1.08Q4.8 -1.68 5.82 -2.16Q6.72 -2.34 7.62 -2.37Q8.64 -2.46 9.54 -2.64Z"/><path d="M1.56 -1.68Q2.74 -3.89 1.81 -6.22Q1.19 -5.31 0.25 -4.88Q-0.7 -4.1 -1.73 -3.57Q-2.94 -2.72 -3.9 -1.93Q-2.41 -1.75 -0.88 -1.75ZM1.81 -6.22Q2.43 -8.85 2.38 -11.54Q1.2 -10.55 0.4 -9.99Q-0.17 -10.6 -0.95 -11.53Q-1.68 -10.57 -1.89 -9.69Q-2.92 -9.82 -4.01 -10.35Q-3.46 -9.11 -3.27 -8.48Q-4.25 -8.16 -5.08 -7.91Q-3.73 -6.99 -2.29 -6.17Q-1.08 -5.61 0.16 -5.16Z"/></g>`)}function Hd(s,e,t,i,n,r={}){s.bodies.push({body:e,x:t,y:i,r:n,faint:!1,...r}),s.bodies.sort((o,a)=>(a.behind?1:0)-(o.behind?1:0)||a.r-o.r)}function eC(s,e){return s.bodies.some(t=>e.test(t.body.name??""))}const tC={basalt:{paint(s,e){const t=e.H,i=Ge(`${e.id}-columns`);let n="";for(let r=0;r<6;r++){const o=t+7+r*r*.9+r*3,a=2.2+r*.85,l=30-r*5,c=62-r*1.5;for(let h=l+r%2*a*.5;h<c;h+=a){const d=(h-l)/(c-l),u=Math.max(.4,(d*5+z(i,-.6,1.6))*(.6+r*.16)),f=o-u,p=z(i,.85,1.15),m=ne(J("#3c3b40","#1c1e22",1-d),1-p*.8),g=J(ve("#4a494e",.12*p),"#1e2226",(1-d)*.6);n+=v`<path d="M${h-a/2} ${f}V${o}H${h+a/2}V${f}Z" fill="${m}"/>`,n+=v`<path d="M${h-a/2} ${f}L${h-a/4} ${f-a*.2}H${h+a/4}L${h+a/2} ${f}L${h+a/4} ${f+a*.2}H${h-a/4}Z" fill="${g}" stroke="#141518" stroke-width=".25"/>`}}s.add("scatter",n),s.add("water",v`<path d="M10 ${t+9}q3 -1 6 0t6 0M4 ${t+18}q4 -1.2 8 0t8 0M14 ${t+30}q4 -1.4 8 0t8 0" fill="none" stroke="#f2f6f6" stroke-opacity=".55" stroke-width=".7" stroke-linecap="round"/>`)}},jupiter:{paint(s,e){const t=e.H,i=["#f0e6d2","#c89a6a","#e8dcc0","#b07a50","#f4ecdc","#d4ae80"];let n="",r=t-3;for(let a=0;r<104;a++){const l=(r-t+3)/40,c=1.2+l*l*14;n+=v`<path d="M-2 ${r}C30 ${r+c*.2} 70 ${r-c*.15} 102 ${r+c*.1}V${r+c+.6}H-2Z" fill="${J(i[a%i.length],e.haze,.35*(1-l))}"/>`,r+=c}s.add("far",n);const o=ge(s,[[0,"#d8784a"],[.5,"#b04a2c"],[1,"#8a3220"]],[0,0,1,1]);s.add("far",v`<ellipse cx="27" cy="${t+6}" rx="11" ry="3.4" fill="#ead8c0" fill-opacity=".8"/><ellipse cx="27" cy="${t+6}" rx="9" ry="2.6" fill="${o}"/><path d="M20 ${t+6}q7 -2.4 14 0M22 ${t+7}q5 1.4 10 -.2" fill="none" stroke="#e6a07a" stroke-opacity=".6" stroke-width=".5"/>`),s.add("far",ao(78,t-4,14,"#f4ecdc","#c8b090",.95)+ao(10,t-3,10,"#ece0c8","#c0a888",.9))}},redspot:{paint(s,e){const t=e.H;s.add("far",v`<path d="M-2 ${t-2}H102V104H-2Z" fill="${J("#d6b090",e.haze,.3)}"/>`);const i=pi(s,[[0,"#6e2216"],[.35,"#9a3a24"],[.7,"#c05a36"],[.88,"#d88a62"],[1,"#ead2b6"]]),n=t+24;s.add("far",v`<ellipse cx="54" cy="${n}" rx="76" ry="25" fill="#efe0ca"/><ellipse cx="54" cy="${n}" rx="68" ry="21" fill="${i}"/>`);let r="";for(let l=1;l<=6;l++){const c=l/7;r+=v`<ellipse cx="${54+(1-c)*3}" cy="${n-(1-c)*1.5}" rx="${68*c}" ry="${21*c}" fill="none" stroke="${l%2?"#e09a76":"#6e2216"}" stroke-opacity="${.42-l*.04}" stroke-width="${.5+l*.08}" stroke-dasharray="${10+l*6} ${5+l*2}" transform="rotate(${l-4} 54 ${n})"/>`}s.add("far",r);const o=Ge(`${e.id}-stream`);let a="";for(let l=0;l<7;l++){const c=z(o,-6,96),h=z(o,t-22,t+4),d=z(o,12,22);a+=v`<ellipse cx="${c}" cy="${h}" rx="${d*.55}" ry="${d*.09}" fill="#f0dcc6" fill-opacity=".55"/><ellipse cx="${c+d*.1}" cy="${h+d*.05}" rx="${d*.4}" ry="${d*.05}" fill="#a8604a" fill-opacity=".35"/>`}s.add("far",a)}},saturnrings:{paint(s,e){const i=e.bodies.find(l=>/saturn/i.test(l.body.name??""))?.y??42,n=ge(s,[[0,"#f0e6d4",.96],[.25,"#d8ccb8",.95],[1,"#9a8e7c",.9]]),r=v`M-2 ${i+13}C8 ${i+12} 14 ${i+15} 22 ${i+13.4}S36 ${i+12} 44 ${i+13}S62 ${i+14.6} 72 ${i+13}S90 ${i+12.4} 102 ${i+13.2}`;s.add("bodies",v`<path d="M-2 ${i}H102V${i+12}H-2Z" fill="${n}"/>`),s.add("bodies",`<path d="${r}V${j(i+11.5)}H-2Z" fill="#a69a86" fill-opacity=".92"/>`),s.add("bodies",v`<path d="M-2 ${i+1.2}H102M-2 ${i+2.6}H102M-2 ${i+4.8}H102" stroke="#7a6e60" stroke-opacity=".55" stroke-width=".35"/><path d="M-2 ${i+8.4}H102" stroke="#5a5048" stroke-opacity=".4" stroke-width=".5"/>`),s.add("bodies",`<path d="${r}" fill="none" stroke="#fff6e4" stroke-opacity=".8" stroke-width=".6"/>`);let o="";const a=Ge(`${e.id}-ring-ice`);for(let l=0;l<26;l++)o+=v`<circle cx="${z(a,0,100)}" cy="${i+z(a,11.5,15.5)}" r="${z(a,.25,.6)}"/>`;s.add("bodies",`<g fill="#e8dcc8">${o}</g>`),s.add("near",v`<path d="M-2 104V${e.H+34}C14 ${e.H+32.5} 24 ${e.H+35} 36 ${e.H+33.6}S60 ${e.H+32} 74 ${e.H+33.8}S92 ${e.H+33} 102 ${e.H+33.6}V104Z" fill="${n}"/>`)}},draugr:{paint(s,e){const t=e.bodies.find(a=>a.body.pulsar);if(!t)return;const{x:i,y:n}=t,r=ge(s,[[0,"#d8e4ff",.85],[.45,"#a8c4ff",.35],[1,"#a8c4ff",0]],[0,0,1,0]),o=ge(s,[[0,"#a8c4ff",0],[.55,"#a8c4ff",.35],[1,"#d8e4ff",.85]],[0,0,1,0]);s.add("bodies",v`<g transform="translate(${i} ${n}) rotate(-28)"><path d="M0 -.5L64 -5L64 5L0 .5Z" fill="${r}"/><path d="M0 -.5L-64 -5L-64 5L0 .5Z" fill="${o}"/></g>`),s.add("bodies",_e(s,i,n,9,"#b8ccff",.7))}},hd189733b:{paint(s){const e=Ge("hd189733b-glass");let t="";for(let i=0;i<22;i++){const n=z(e,-4,100),r=z(e,4,96),o=z(e,3,7);t+=v`M${n} ${r}l${o} ${o*.12}`}s.add("lights",`<path d="${t}" stroke="#e4f0ff" stroke-opacity=".6" stroke-width=".45" stroke-linecap="round"/>`)}},titan:{adjust(s){eC(s,/saturn/i)||Hd(s,{name:"Saturn",color:14206106,bands:[15391924,13809802,14865066,13019260],banding:6,rings:{inner:1.24,outer:2.27,color:14208176,opacity:.85},pole:[14,8],glow:15786176},36,28,13,{haze:.5})}},tatawin:{adjust(s,e){if(s.dusk=!0,s.sunSide=1,s.sun=$f(e,s),s.sun?.second){const{sun:t}=s;t.r*=1.5,t.y=s.H-t.r*1.3-3,t.second.r*=1.5,t.second.x=t.x-(t.r+t.second.r)*1.25,t.second.y=t.y+t.r*.7}s.skyBottom=J(s.skyBottom,"#ffb878",.5)}},milners:{adjust(s){s.bodies.some(e=>To(e.body))||Hd(s,{name:"Gargaros",hole:{color:16767136}},72,20,7),s.sunSide=-1}},middangard:{adjust(s){s.scatterKinds=["round","bush","round"]}},dragonnest:{adjust(s){s.slotFilter=e=>e.y>s.H+20&&e.x>24}},undersea:{paint(s,e){const t=e.H;let i="";for(const[n,r,o]of[[42,6,5],[50,7,8],[58,5,4.5],[36,4,3]])i+=v`<path d="M${n-r/2} ${t+14}V${t+14-o+r/2}A${r/2} ${r/2} 0 0 1 ${n+r/2} ${t+14-o+r/2}V${t+14}Z" fill="#d8e4e8"/>`;s.add("scatter",i),s.add("lights",`<g fill="#ffd890">${[[42,t+11],[50,t+9],[58,t+11.5],[52,t+12]].map(([n,r])=>v`<rect x="${n-.5}" y="${r}" width="1" height="1"/>`).join("")}</g>`)}},frozenlake:{paint(s,e){const t=e.H;let i="";for(const[n,r,o,a]of[[13,t+13,1.1,1],[87,t+12,1.1,-1],[30,t+4.5,.6,1],[72,t+5,.6,-1],[50,t+34.5,1.1,-1]])i+=v`<g transform="translate(${n} ${r}) scale(${o*a} ${o})"><path d="M-3 0C-1.6 -1.6 1.6 -1.6 3 0C1.6 1.6 -1.6 1.6 -3 0ZM3 0L5 -1.4L5 1.4Z"/></g>`;s.layers.sea.splice(1,0,`<g fill="#0e2232" fill-opacity=".85">${i}</g>`),s.add("lights",`<g fill="#d8f6ff" fill-opacity=".55">${[[13,t+12.3],[87,t+11.3],[50,t+33.8]].map(([n,r])=>v`<ellipse cx="${n}" cy="${r}" rx="2.2" ry=".35"/>`).join("")}</g>`)}},tundra:{adjust(s){s.scatterScale=1.25,s.scatterKinds=["snowpine"]}},lanternnight:{paint(s,e){const t=e.bodies[0];if(!t)return;const i=Le(t.x,34,66);s.add("lights",v`<path d="M${i-5} ${e.H+13.4}h10M${i-3.6} ${e.H+15.4}h7M${i-2.4} ${e.H+17.6}h4.8M${i-1.4} ${e.H+19.8}h2.8" stroke="#fff4d8" stroke-opacity=".75" stroke-width=".6" stroke-linecap="round"/>`)}},garden:{adjust(s){s.scatterScale=1.5}},sky:{paint(s,e){const t=e.H;s.add("island",v`<path d="M80 ${t+3}C81 ${t+12} 80 ${t+22} 81 ${t+34}" fill="none" stroke="#eef8ff" stroke-width="1.2" stroke-opacity=".85"/>`)}},yavora4:{paint(s,e){const t=e.H,i=Ge(`${e.id}-canopy`);let n="";for(let o=-4;o<106;o+=7)n+=v`<circle cx="${o+z(i,-1,1)}" cy="${t+4+z(i,-1.5,1.5)}" r="${z(i,4.2,6)}"/>`;s.add("ground",`<g fill="#2a5a2e">${n}</g>`);let r="";for(let o=0;o<104;o+=9)r+=v`<circle cx="${o+z(i,-2,2)}" cy="${t+2+z(i,-1,1)}" r="${z(i,2,3.2)}"/>`;s.add("ground",`<g fill="#3e7a3a">${r}</g>`)}}};function sC(s,e,t){const i=D(t.land,"#5a8a44"),n=D(t.sea,"#2a5a8a"),r=D(t.wall,"#9aa4b4"),o=e.H,a=ge(s,[[0,J(i,e.skyTop,.4)],[.3,n],[.6,i],[.85,J(n,e.skyBottom,.15)],[1,J(i,e.skyBottom,.3)]],[0,0,0,1]),l=v`M14 ${o+2}C28 ${o*.55} 38 ${o*.25} 43 -4`,c=v`M49 -4C50 ${o*.25} 54 ${o*.55} 64 ${o+2}`;s.add("bodies",`<path d="${l}L49 -4C50 ${j(o*.25)} 54 ${j(o*.55)} 64 ${j(o+2)}Z" fill="${a}" fill-opacity=".92"/>`),s.add("bodies",`<path d="${l}" fill="none" stroke="${ve(r,.3)}" stroke-width="1.2"/><path d="${c}" fill="none" stroke="${r}" stroke-width="1"/>`),s.add("bodies",v`<path d="M30 ${o*.7}C36 ${o*.45} 42 ${o*.3} 46 ${o*.05}M52 ${o*.8}C49 ${o*.6} 47 ${o*.4} 46 ${o*.2}" fill="none" stroke="#ffffff" stroke-opacity=".35" stroke-width=".8" stroke-dasharray="3 2"/>`)}function iC(s,e,t){const i=["#e84a4a","#f29a3a","#f2d84a","#5ac85a","#4a8ae8","#8a5ad8"],n=Le((t.amount??.35)*1.5,.3,.7);let r="";i.forEach((o,a)=>{const l=40-a*2;r+=v`<path d="M${50-l} ${e.H+2}A${l} ${l*.9} 0 0 1 ${50+l} ${e.H+2}" stroke="${o}"/>`}),s.add("sky",v`<g fill="none" stroke-width="2.1" stroke-opacity="${n}">${r}</g>`)}function nC(s,e,t){const i=D(t.color,"#ff3a52"),n=30,r=e.H-15,o=v`<ellipse cx="${n}" cy="${r}" rx="6.6" ry="7.6"/><circle cx="${n}" cy="${r-9.6}" r="5.4"/><circle cx="${n-4.2}" cy="${r-14}" r="2"/><circle cx="${n+4.2}" cy="${r-14}" r="2"/><ellipse cx="${n-6.4}" cy="${r-2}" rx="2.2" ry="3.4"/><ellipse cx="${n+6.4}" cy="${r-2}" rx="2.2" ry="3.4"/><ellipse cx="${n-3.6}" cy="${r+7}" rx="2.8" ry="2.2"/><ellipse cx="${n+3.6}" cy="${r+7}" rx="2.8" ry="2.2"/>`;s.add("bodies",`<g fill="${i}" fill-opacity=".85">${o}</g>`+v`<ellipse cx="${n-2}" cy="${r-12}" rx="1.6" ry="1" fill="#fff" fill-opacity=".55"/><ellipse cx="${n-2.6}" cy="${r-3}" rx="1.4" ry="2.6" fill="#fff" fill-opacity=".3"/>`)}function rC(s,e,t,i){const n=e.H,r=D(i.color,"#2ec870"),o=D(i.light,"#a8ffc8");let a="";for(const[l,c,h]of[[-6,9,2.6],[-2.5,14,2.4],[0,19,3],[3,13,2.4],[6.5,8,2.6],[-9,5,2.4],[9.5,5,2.4]])a+=v`<path d="M${t+l-h/2} ${n+1}V${n-c+h}L${t+l} ${n-c}L${t+l+h/2} ${n-c+h}V${n+1}Z"/>`;return s.add("lights",_e(s,t,n-7,18,o,.5)),`<g fill="${r}">${a}</g>`+v`<path d="M${t} ${n-19}L${t+1.5} ${n-16}V${n+1}H${t}Z" fill="${o}" fill-opacity=".6"/>`}function oC(s,e,t){const i=e.H,n=D(t.color,"#f0c838"),r=D(t.mortar,ne(n,.25));s.add("ground",v`<path d="M38 102C44 ${i+26} 62 ${i+22} 56 ${i+14}C52 ${i+9} 48 ${i+6} 50 ${i+1.5}L51.2 ${i+1.5}C50 ${i+6} 56 ${i+9} 60 ${i+14}C66 ${i+22} 56 ${i+28} 58 102Z" fill="${n}"/>`),s.add("ground",v`<path d="M42 ${i+34}h14M46 ${i+27}h12M52 ${i+21}h8M54 ${i+16}h5M51 ${i+10}h4" stroke="${r}" stroke-width=".5"/>`)}function aC(s,e,t){const i=e.H,n=Le((t.height??24)*.95,14,28),r=ge(s,[[0,"#f2fbff"],[.5,"#bfe2f4"],[1,"#8ec0dc"]]),o=v`M-2 ${i-n}L14 ${i-n-1}L30 ${i-n+.4}L48 ${i-n-1.4}L66 ${i-n}L84 ${i-n-1.2}L102 ${i-n}`;s.add("far",v`<path d="M8 ${i-n}L20 ${i-n-8}L30 ${i-n}ZM56 ${i-n}L70 ${i-n-10}L84 ${i-n}Z" fill="${J("#e8eef4",e.haze,.35)}"/>`),s.add("far",`<path d="${o}V${j(i+2)}H-2Z" fill="${r}"/>`);let a="";for(let l=3;l<100;l+=5.5)a+=v`M${l} ${i-n+1}L${l+.6} ${i+1}`;s.add("far",`<path d="${a}" stroke="#7aaccc" stroke-width=".5" stroke-opacity=".55"/>`),s.add("far",`<path d="${o}V${j(i-n+1.6)}H-2Z" fill="#ffffff"/>`),s.add("lights",_e(s,50,i-n/2,40,"#cfefff",.18))}function lC(s,e){const t=e.H,i=ge(s,[[0,"#b0aa9e"],[.5,"#8a8478"],[1,"#5a564e"]]);s.add("far",v`<g transform="rotate(-18 50 ${t})"><path d="M16 ${t+6}L22 ${t-6}L80 ${t-10}C88 ${t-10} 92 ${t-4} 92 ${t+2}L86 ${t+6}Z" fill="${i}"/><path d="M28 ${t-6.4}V${t+5}M40 ${t-7.2}V${t+5}M52 ${t-8}V${t+5}M64 ${t-8.8}V${t+5}M76 ${t-9.6}V${t+5}" stroke="#4e4a42" stroke-width=".6"/><path d="M22 ${t-6}L80 ${t-10}L80 ${t-7.6}L23 ${t-3.6}Z" fill="#c8c2b4" fill-opacity=".6"/><g fill="#3e3a34"><rect x="91" y="${t-7}" width="5" height="4" rx="1"/><rect x="91" y="${t-1}" width="5" height="4" rx="1"/></g><path d="M16 ${t+6}L20 ${t-2}L14 ${t-1}L18 ${t-6}L10 ${t-3}Z" fill="#6e6a60"/></g>`),s.add("far",v`<path d="M6 ${t+3}C20 ${t-2} 32 ${t-1} 44 ${t+2}Z" fill="${J(e.ground.high,e.haze,.2)}"/>`)}function cC(s,e){const t=e.H,i=ge(s,[[0,"#3a3430"],[.6,"#221e1b"],[1,"#100e0d"]],[0,0,1,0]);s.add("lights",v`<path d="M-4 -4L14 -4L40 ${t-4}L18 ${t+6}Z" fill="#dce8ff" fill-opacity=".14"/>`),s.add("far",v`<path d="M14 ${t-16}L20 ${t+8}L104 ${t+1}L104 ${t-8}Q62 ${t-9} 14 ${t-16}Z" fill="${i}"/>`),s.add("far",v`<path d="M50 ${t-11}h24v-4h-20Z" fill="#2e2824"/><path d="M36 ${t-13}L64 ${t-19}" stroke="#4a3a2e" stroke-width="1.1"/>`),s.add("far",v`<path d="M14 ${t-16.6}L44 ${t-13.6}" fill="none" stroke="#9a7a58" stroke-width=".5"/><path d="M20 ${t-16}v1.4M26 ${t-15.4}v1.4M32 ${t-14.8}v1.4M38 ${t-14.2}v1.4" stroke="#9a7a58" stroke-width=".35"/>`);let n="";for(let o=30;o<102;o+=4.5)n+=v`<circle cx="${o}" cy="${t-5+(o-30)*.03}" r=".55"/><circle cx="${o+2}" cy="${t-1.4+(o-30)*.02}" r=".5"/>`;s.add("far",`<g fill="#070605">${n}</g>`);let r="";for(let o=18;o<102;o+=3.2)r+=v`M${o} ${t-15.6+(o-14)*.08}v${1.6+o*7%5*.5}`;s.add("far",`<path d="${r}" stroke="#a0582a" stroke-width=".7" stroke-linecap="round"/>`),s.add("far",v`<path d="M10 ${t+9}C26 ${t+2} 60 ${t+2} 104 ${t+1}V${t+6}C70 ${t+7} 30 ${t+11} 10 ${t+9}Z" fill="${J(e.ground.high,"#000000",.25)}"/>`),s.add("far",v`<circle cx="23" cy="${t-7}" r="1.4" fill="#4a3424"/>`)}function hC(s,e){const t=["#4a7a3c","#2a5a8a","#e4eaee","#3e6a34","#4a7a3c","#2a5a8a"],i=[[12,22,7],[84,16,5],[92,52,8],[8,66,6],[70,84,4.5],[30,90,5.5]];let n="";i.forEach(([r,o,a],l)=>{n+=v`<path d="M${r-a} ${o}L${r+a*1.1} ${o-a*.2}L${r+a*.7} ${o+a*.9}L${r-a*.1} ${o+a*1.4}L${r-a*.8} ${o+a*.7}Z" fill="#3a2e2a"/>`,n+=v`<path d="M${r-a*.95} ${o+a*.12}L${r+a*1.02} ${o-a*.08}" stroke="#ff7a2a" stroke-width="${a*.16}" stroke-linecap="round"/>`,n+=v`<path d="M${r-a} ${o}L${r+a*1.1} ${o-a*.2}L${r+a*.9} ${o-a*.55}L${r-a*.7} ${o-a*.4}Z" fill="${t[l%t.length]}"/>`}),s.add("far",`<g>${n}</g>`),s.add("lights",_e(s,50,60,30,"#ff7a2a",.12))}function dC(s,e){const t=e.H;s.add("lights",v`<path d="M70 14L76 12L60 ${t+18}L40 ${t+16}Z" fill="#dce8ff" fill-opacity=".16"/>`),s.add("far",v`<rect x="69" y="9" width="9" height="4" rx=".8" fill="#f2c230"/><rect x="69.4" y="12.6" width="8.2" height="2.4" fill="#2a2e32"/><circle cx="70.6" cy="14.6" r=".9" fill="#fff4d8"/>`)}function uC(s,e,t){const i=e.H,n=(t.colors??["#ffb050"]).map(o=>D(o));((e.groundShape??e.shape)==="coast"?[[18,i+12,5],[32,i+20,6.5],[12,i+24,4],[38,i+9,3.5]]:[[30,i+16,5],[50,i+22,6.5],[70,i+15,4.5]]).forEach(([o,a,l],c)=>{const h=n[c%n.length];s.add("lights",_e(s,o,a,l*2.6,h,.7)),s.add("lights",v`<path d="M${o-l} ${a}A${l} ${l*.7} 0 0 1 ${o+l} ${a}Z" fill="${ve(h,.4)}" fill-opacity=".5"/>`)})}function fC(s,e,t){const i=e.H,n=e.sun?.x??18,r=D(t.dust,"#ffe4b8"),o=D(t.ion,"#5a9aff"),a=ge(s,[[0,"#ffffff",.9],[.45,r,.5],[1,r,0]],[0,1,1,0]);s.add("far",v`<path d="M${n+28} ${i-2}C50 30 70 6 104 -6L104 30C80 32 62 44 ${n+38} ${i-1}Z" fill="${a}"/>`),s.add("far",v`<path d="M${n+30} ${i-3}L104 -2" stroke="${o}" stroke-width="2.2" stroke-opacity=".55" stroke-linecap="round"/><path d="M${n+30} ${i-3}L104 -2" stroke="#d8ecff" stroke-width=".6" stroke-opacity=".8"/>`),s.add("lights",_e(s,n+32,i-2,12,"#cfefff",.6))}function pC(s,e,t){const i=e.H,n=D(t.jets?.[0]?.color,"#dfe6f2"),r=(e.sun?.x??50)<50?1:-1;let o="";for(const[a,l]of[[28,14],[46,20],[66,12],[80,17]])o+=v`<path d="M${a-.6} ${i+1}Q${a} ${i-l*.5} ${a+r*l*.3} ${i-l}Q${a+.8} ${i-l*.5} ${a+.6} ${i+1}Z"/>`;s.add("far",`<g fill="${n}" fill-opacity=".55">${o}</g>`)}function mC(s,e,t){t.skyRing&&sC(s,e,t.skyRing),t.rainbow&&iC(s,e,t.rainbow),t.skyline?.gummyBear&&nC(s,e,t.skyline.gummyBear),t.wall&&aC(s,e,t.wall),t.wreck&&lC(s,e,t.wreck),t.skyline?.shards&&hC(s),t.titanic?cC(s,e):t.skyline?.rovs&&dC(s,e),t.road&&oC(s,e,t.road),t.underglow&&uC(s,e,t.underglow),t.comet&&fC(s,e,t.comet)}function gC(s,e,t){const i=e.H,n=t.plating??{},r=ge(s,[[0,J(e.ground.high,e.haze,.2)],[1,ne(e.ground.low,.25)]]);s.add("ground",v`<rect x="0" y="${i}" width="100" height="40" fill="${r}"/>`);let o="";for(let h=1;h<8;h++)o+=v`M0 ${i+h*h*40/64}H100`;for(let h=-8;h<=8;h++)o+=v`M${50+h*4.5} ${i}L${50+h*28} 102`;s.add("ground",`<path d="${o}" stroke="${ne(e.ground.low,.45)}" stroke-width=".4" stroke-opacity=".85"/>`);const a=Ge(`${e.id}-plates`);let l="";for(let h=0;h<14;h++){const d=z(a,i+3,96),u=(d-i)/40,f=z(a,4,92);Math.abs(f-50)<14*u+3||(l+=v`<rect x="${f}" y="${d}" width="${(2+a()*5)*u+1}" height="${(1+a()*2)*u+.4}" fill="${a()<.5?ve(e.ground.high,.15):ne(e.ground.low,.15)}"/>`)}s.add("ground",l);const c=D(n.glow,"#56e6ff");if((n.conduits??0)>0){let h="";for(let d=0;d<8;d++){const u=1+Math.floor(a()*6),f=i+u*u*40/64,p=Math.floor(z(a,-6,6)),m=(f-i)/40;h+=v`M${50+p*(4.5+23.5*m)} ${f}H${50+(p+1)*(4.5+23.5*m)}`}s.add("lights",`<path d="${h}" stroke="${c}" stroke-width=".7" stroke-linecap="round"/>`),s.add("lights",_e(s,50,i+18,30,c,.16))}if(t.fissures?.box){s.add("ground",v`<path d="M49 ${i}L51 ${i}L66 102L34 102Z" fill="${ne(e.ground.low,.6)}"/><path d="M49 ${i}L34 102L39 102L49.6 ${i}Z" fill="${ve(e.ground.low,.1)}"/><path d="M51 ${i}L66 102L62 102L50.4 ${i}Z" fill="${ne(e.ground.low,.4)}"/>`);let h="";for(let d=0;d<6;d++){const u=(d+1)/7;h+=v`<circle cx="${49.4-u*12}" cy="${i+u*40}" r="${.2+u*.35}"/><circle cx="${50.6+u*13}" cy="${i+u*40}" r="${.2+u*.35}"/>`}s.add("lights",`<g fill="${c}">${h}</g>`)}else if((n.lights??0)>0){let h="";for(let d=0;d<8;d++)h+=v`<circle cx="${z(a,6,94)}" cy="${z(a,i+4,96)}" r=".45"/>`;s.add("lights",`<g fill="${c}">${h}</g>`)}return[{x:14,y:i+12,s:.7},{x:84,y:i+13,s:.75},{x:24,y:i+26,s:1.1,front:!0},{x:78,y:i+25,s:1.05,front:!0}]}function wC(s,e){const t=e.H,i=ge(s,[[0,e.ground.high],[1,ne(e.ground.low,.3)]]);return s.add("ground",v`<path d="M-4 102V${t+10}C14 ${t-2} 36 ${t-4} 58 ${t-2}C78 ${t} 92 ${t+6} 104 ${t+14}V102Z" fill="${i}"/>`),s.add("ground",v`<path d="M-4 ${t+10}C14 ${t-2} 36 ${t-4} 58 ${t-2}C78 ${t} 92 ${t+6} 104 ${t+14}" fill="none" stroke="${ve(e.ground.tint,.2)}" stroke-opacity=".45" stroke-width=".6"/>`),[{x:22,y:t+18,s:.7},{x:76,y:t+22,s:.8},{x:40,y:t+30,s:1}]}Object.assign(Lf,{metal:gC,nucleus:wC});function bC(s){const e=Q6(),t=K6(s),i=tC[s.id];i?.adjust?.(t,s),i8(e,t),d8(e,t),t.skip.has("skyline")||_8(e,t,s);const n=t.groundShape??t.shape,r=(Lf[n]??hc)(e,t,s);D8(e,t,s);const o=H8(e,t);return t.skip.has("scatter")||G8(e,t,s,t.slotFilter?r.filter(t.slotFilter):r,o),s.grass&&!t.skip.has("grass")&&Z8(e,t,s),X8(e,t,s),mC(e,t,s),i?.paint?.(e,t,s),Q8(e,t,s),e}function vC(s={},{label:e=""}={}){const t=bC(s),i=t.id("frame"),n=pi(t,[[.62,"#000",0],[1,"#000",.3]]),r=lc.map(([a])=>t.layers[a].join("")).join("");return`<svg class="world-icon" viewBox="0 0 100 100"${e?` role="img" aria-label="${Y6(e)}"`:' aria-hidden="true"'}><defs><clipPath id="${i}"><circle cx="50" cy="50" r="50"/></clipPath>${t.defs.join("")}</defs><g clip-path="url(#${i})">${r}<rect width="100" height="100" fill="${n}"/></g><circle cx="50" cy="50" r="49.2" fill="none" stroke="#fff" stroke-opacity=".22" stroke-width="1.6"/></svg>`}const yC={minimal:1,low:1,medium:2,high:3,xhigh:4,max:5},CC={minimal:"Minimal",low:"Low",medium:"Medium",high:"High",xhigh:"Extra high",max:"Max"},xC={"claude-code":"CC",codex:"Cx",cursor:"Cu",antigravity:"AG",hermes:"H",opencode:"OC",kilocode:"K"},MC=(s,e)=>xC[s]||String(e||s||"").slice(0,1).toUpperCase();function kC(s){const e=/^(?:[\w.-]+\/)?claude-([a-z]+)-(\d+)(?:-(\d{1,2}))?(?:-\d{8})?(\[.*\])?$/.exec(s||"");if(!e)return s||"";const[,t,i,n]=e;return`${t[0].toUpperCase()}${t.slice(1)} ${n?`${i}.${n}`:i}`}function Bf(s,e=Date.now()){if(!s)return"never";const t=Math.max(0,e-s);if(t<45*1e3)return"just now";const i=Math.round(t/6e4);if(i<60)return`${i}m ago`;const n=Math.round(i/60);return n<24?`${n}h ago`:`${Math.round(n/24)}d ago`}function Ud(s){const e=yC[String(s).toLowerCase()]??0;return`<svg viewBox="0 0 24 24" fill="currentColor">${[1,2,3,4,5].map(i=>`<rect x="${i*4-1.5}" y="${20-i*3.2}" width="2.6" height="${i*3.2}" rx="1.1" class="${i<=e?"bar-on":"bar-off"}"/>`).join("")}</svg>`}const Ff=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="-230 -69 757 162" width="757" height="162" role="img" aria-label="Threadnauts">
|
|
2201
|
-
<title>Threadnauts</title>
|
|
2202
|
-
<defs><linearGradient id="tnh-s" x1="0" y1="-60" x2="0" y2="62" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#ffffff"/><stop offset="1" stop-color="#d9dfe8"/></linearGradient><radialGradient id="tnh-v" cx="-9.7" cy="-17.3" r="55.2" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#2f4466"/><stop offset="0.6" stop-color="#141e33"/><stop offset="1" stop-color="#0b1120"/></radialGradient><linearGradient id="tnh-wingTips" x1="0" y1="-60" x2="0" y2="62" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#d27d60"/><stop offset="1" stop-color="#b1583a"/></linearGradient><linearGradient id="tnh-engineBands" x1="0" y1="-60" x2="0" y2="62" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#d27d60"/><stop offset="1" stop-color="#b1583a"/></linearGradient><linearGradient id="tnh-sideDomes" x1="0" y1="-60" x2="0" y2="62" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#d27d60"/><stop offset="1" stop-color="#b1583a"/></linearGradient><linearGradient id="tnh-faceTrim" x1="0" y1="-60" x2="0" y2="62" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#d27d60"/><stop offset="1" stop-color="#b1583a"/></linearGradient><filter id="tnh-g" x="-1" y="-1" width="3" height="3"><feGaussianBlur stdDeviation="3.2"/></filter><filter id="tnh-h" x="-1" y="-1" width="3" height="3"><feGaussianBlur stdDeviation="5"/></filter></defs>
|
|
2203
|
-
<g transform="translate(-102 18.1) scale(0.7600)"><path d="M6,40 C-22,78 -80,90 -110,68 C-130,52 -120,24 -103,32 C-86,40 -96,70 -122,80" fill="none" stroke="#c96442" stroke-width="5.5" stroke-linecap="round"/><circle cx="-134.3" cy="83.3" r="4.6" fill="#c96442" opacity="0.8"/><circle cx="-145.8" cy="80.8" r="3.7" fill="#c96442" opacity="0.55"/><circle cx="-156.3" cy="77.8" r="2.9" fill="#c96442" opacity="0.3"/><path d="M80.5,56.4C80.8,55.7 81.2,55 81.2,54.3C80.6,45.6 79.6,37 78.7,28.4C78.5,27.1 78.1,25.8 77.9,24.5C76.7,24 75.6,23.5 74.5,23.2C67.8,21.4 61,19.9 54.4,18C52.4,17.4 50.4,16.5 48.4,15.6C46.8,14.9 45.3,14.1 43.8,13.3C44,13.5 44.2,13.7 44.3,14C44.1,14.7 44,15.5 43.6,16.2C43.4,16.5 43,16.9 42.6,17C41.8,17.1 41.1,17.1 40.3,17C39.4,16.8 38.5,16.5 37.5,16.3C41.8,20.8 46,25.4 50.3,29.9C58.1,38.1 66,46.1 73.9,54.2C72.8,52.9 71.7,51.6 70.6,50.3C72.6,52.8 74.5,55.3 76.7,57.6C77.1,57.9 77.6,57.9 78.1,57.9C78.6,57.9 79.2,57.6 79.7,57.5C80,57.1 80.3,56.8 80.5,56.4Z" fill="url(#tnh-s)" stroke="#121319" stroke-width="3" stroke-linejoin="round" paint-order="stroke"/><path d="M80.5,56.4C80.8,55.7 81.2,55 81.2,54.3C81.1,52 80.7,49.8 80.5,47.6C80.3,48.3 80.1,49 79.9,49.7C79.3,50 78.9,50.6 78.3,50.7C77,50.9 75.6,50.9 74.3,50.8C73.1,50.7 71.8,50.5 70.6,50.3C63.7,42.4 57.4,33.9 50.1,26.4C46.4,22.5 41.7,19.7 37.5,16.3C41.8,20.8 46,25.4 50.3,29.9C58.1,38.1 66,46.1 73.9,54.2C72.8,52.9 71.7,51.6 70.6,50.3C72.6,52.8 74.5,55.3 76.7,57.6C77.1,57.9 77.6,57.9 78.1,57.9C78.6,57.9 79.2,57.6 79.7,57.5C80,57.1 80.3,56.8 80.5,56.4Z" fill="url(#tnh-wingTips)"/><path d="M-80.9,55.1C-80.8,55.5 -80.7,56 -80.5,56.4C-80.3,56.8 -80.1,57.2 -79.7,57.5C-79.3,57.8 -78.9,57.9 -78.4,57.9C-77.8,57.9 -77.1,58 -76.7,57.6C-74.4,55.4 -72.6,52.8 -70.6,50.3C-71.7,51.6 -72.8,52.9 -73.9,54.2C-66,46.1 -58.1,38.1 -50.3,29.9C-46,25.4 -41.8,20.8 -37.5,16.3C-38.5,16.5 -39.4,16.8 -40.3,17C-41.1,17.1 -41.8,17.1 -42.6,17C-43,16.9 -43.4,16.5 -43.6,16.2C-44,15.5 -44.1,14.7 -44.3,14C-44.2,13.7 -44,13.5 -43.8,13.3C-45.3,14.1 -46.8,14.9 -48.4,15.6C-50.4,16.5 -52.4,17.4 -54.4,18C-61,19.9 -67.8,21.4 -74.5,23.2C-75.6,23.5 -76.7,24 -77.9,24.5C-78.1,25.8 -78.5,27.1 -78.7,28.4C-79.1,31.6 -79.4,34.9 -79.7,38.1C-80.2,43.5 -80.8,48.9 -81.2,54.3C-81.2,54.6 -81,54.8 -80.9,55.1Z" fill="url(#tnh-s)" stroke="#121319" stroke-width="3" stroke-linejoin="round" paint-order="stroke"/><path d="M-80.9,55.1C-80.8,55.5 -80.7,56 -80.5,56.4C-80.3,56.8 -80.1,57.2 -79.7,57.5C-79.3,57.8 -78.9,57.9 -78.4,57.9C-77.8,57.9 -77.1,58 -76.7,57.6C-74.4,55.4 -72.6,52.8 -70.6,50.3C-71.8,50.5 -73.1,50.7 -74.3,50.8C-75.6,50.9 -77,50.9 -78.3,50.7C-78.9,50.6 -79.3,50 -79.9,49.7C-80.1,49 -80.3,48.3 -80.5,47.6C-80.7,49.8 -81,52 -81.2,54.3C-81.2,54.6 -81,54.8 -80.9,55.1ZM-73.9,54.2C-64.8,44.8 -55.6,35.4 -46.5,26C-43.4,22.8 -40.5,19.5 -37.5,16.3C-41.7,19.7 -46.4,22.5 -50.1,26.4C-58.6,35.2 -66,44.9 -73.9,54.2Z" fill="url(#tnh-wingTips)"/><path d="M99.1,-60.1C98.9,-60.7 98.7,-61.3 98.4,-61.8C98.2,-62.1 98,-62.4 97.7,-62.5C97.2,-62.8 96.7,-62.8 96.2,-62.9C96.7,-62.8 97.2,-62.7 97.7,-62.6C97.2,-62.7 96.7,-62.9 96.2,-62.9C95.8,-62.9 95.4,-62.8 95.1,-62.5C92.1,-60.2 89.4,-57.5 86.5,-55.1C72.2,-43.5 57.9,-32 43.6,-20.5C44.4,-20.8 45.1,-21.1 45.9,-21.2C46.6,-21.3 47.3,-21.4 47.9,-21.2C48.4,-21.1 48.7,-20.8 49,-20.5C49.4,-19.8 49.6,-19 50,-18.2C49.8,-18 49.7,-17.8 49.6,-17.6C53.2,-19.2 56.7,-21 60.4,-22.3C66.6,-24.5 72.9,-25.9 79.1,-27.9C80.3,-28.2 81.7,-28.3 82.6,-29.2C83.8,-30.2 84.4,-31.8 85.1,-33.1C90,-41.8 94.7,-50.6 99.4,-59.3C99.3,-59.6 99.2,-59.8 99.1,-60.1Z" fill="url(#tnh-s)" stroke="#121319" stroke-width="3" stroke-linejoin="round" paint-order="stroke"/><path d="M99.1,-60.1C98.9,-60.7 98.7,-61.3 98.4,-61.8C98.2,-62.1 98,-62.4 97.7,-62.5C97.2,-62.8 96.7,-62.8 96.2,-62.9C96.7,-62.8 97.2,-62.7 97.7,-62.6C97.2,-62.7 96.7,-62.9 96.2,-62.9C95.8,-62.9 95.4,-62.8 95.1,-62.5C92.1,-60.2 89.4,-57.5 86.5,-55.1C72.2,-43.5 57.9,-32 43.6,-20.5C48.5,-23.9 53.6,-26.9 58.3,-30.7C68,-38.5 76.7,-47.3 86.5,-55.1C87.3,-55.7 88.6,-55.5 89.7,-55.6C90.9,-55.7 92.1,-55.8 93.2,-55.6C93.8,-55.5 94.4,-55.1 94.8,-54.6C95.3,-54 95.4,-53.2 95.7,-52.5C96.9,-54.7 98.2,-57 99.4,-59.3C99.3,-59.6 99.2,-59.8 99.1,-60.1Z" fill="url(#tnh-wingTips)"/><path d="M-98.6,-61.4C-98.9,-60.7 -99.1,-60 -99.4,-59.3C-94.7,-50.6 -90,-41.8 -85.1,-33.1C-84.4,-31.8 -83.8,-30.2 -82.6,-29.2C-81.7,-28.3 -80.3,-28.2 -79.1,-27.9C-72.9,-25.9 -66.6,-24.5 -60.4,-22.3C-56.7,-21 -53.2,-19.2 -49.6,-17.6C-49.7,-17.8 -49.8,-18 -50,-18.2C-49.6,-19 -49.4,-19.8 -49,-20.5C-48.7,-20.8 -48.4,-21.1 -47.9,-21.2C-47.3,-21.4 -46.6,-21.3 -45.9,-21.2C-45.1,-21.1 -44.4,-20.8 -43.6,-20.5C-57.9,-32 -72.2,-43.5 -86.5,-55.1C-89.4,-57.5 -92.1,-60.2 -95.1,-62.5C-95.5,-62.9 -96.2,-62.9 -96.7,-62.9C-97.1,-62.9 -97.4,-62.7 -97.7,-62.5C-97.2,-62.7 -96.7,-62.8 -96.2,-62.9C-96.7,-62.8 -97.2,-62.7 -97.7,-62.6C-98,-62.2 -98.3,-61.8 -98.6,-61.4Z" fill="url(#tnh-s)" stroke="#121319" stroke-width="3" stroke-linejoin="round" paint-order="stroke"/><path d="M-98.6,-61.4C-98.9,-60.7 -99.1,-60 -99.4,-59.3C-98.2,-57 -96.9,-54.7 -95.7,-52.5C-95.4,-53.2 -95.3,-54 -94.8,-54.6C-94.4,-55.1 -93.8,-55.5 -93.2,-55.6C-92.1,-55.8 -90.9,-55.7 -89.7,-55.6C-88.6,-55.5 -87.3,-55.7 -86.5,-55.1C-76.7,-47.3 -68,-38.5 -58.3,-30.7C-53.6,-26.9 -48.5,-23.9 -43.6,-20.5C-57.9,-32 -72.2,-43.5 -86.5,-55.1C-89.4,-57.5 -92.1,-60.2 -95.1,-62.5C-95.5,-62.9 -96.2,-62.9 -96.7,-62.9C-97.1,-62.9 -97.4,-62.7 -97.7,-62.5C-97.2,-62.7 -96.7,-62.8 -96.2,-62.9C-96.7,-62.8 -97.2,-62.7 -97.7,-62.6C-98,-62.2 -98.3,-61.8 -98.6,-61.4Z" fill="url(#tnh-wingTips)"/><path d="M28.1,17.9C26.2,17.7 24.3,17.4 22.3,17.4C21.7,17.4 21.1,17.6 20.6,17.7C18.8,18.1 17,18.3 15.3,19C13.6,19.6 12,20.6 10.6,21.7C9.2,22.9 7.9,24.3 6.9,25.8C5.8,27.3 5,29 4.5,30.7C3.9,32.5 3.6,34.3 3.7,36.1C3.7,38.6 3.9,41.1 4.7,43.4C5.5,46 6.7,48.4 8.3,50.5C10,52.7 12,54.7 14.3,56.2C16.5,57.7 19.1,58.7 21.7,59.5C23.7,60.1 25.8,60.3 27.8,60.2C30.3,60 32.8,59.7 35.1,58.8C37.1,58.1 38.9,56.8 40.6,55.5C42,54.4 43.2,53.1 44.2,51.6C45.3,49.9 46.2,48.1 46.7,46.2C47.3,44.3 47.6,42.3 47.5,40.4C47.4,37.8 47,35.3 46.1,33C45.2,30.4 43.7,28.1 42,26C40.8,24.4 39.1,23.2 37.5,21.8C36.9,21.4 36.3,21 35.7,20.7C33.9,19.8 32,19 30.1,18.3C29.5,18 28.8,18 28.1,17.9ZM26.3,42.7C26.6,41.9 26.9,41.2 27.3,40.6C27.8,39.9 28.3,39.3 28.9,38.8C29.5,38.3 30.2,37.9 30.9,37.7C31.7,37.4 32.4,37.2 33.2,37.2C34,37.1 34.7,37.2 35.5,37.4C36.2,37.6 36.8,38 37.5,38.3C36.2,37.2 34.9,36 33.5,35C32.9,34.6 32.2,34.3 31.4,34.1C30.7,33.9 29.9,33.8 29.1,33.9C28.3,33.9 27.5,34.1 26.8,34.4C26,34.7 25.3,35.1 24.7,35.6C24.1,36.1 23.5,36.7 23.1,37.3C22.6,38 22.3,38.8 22,39.5C21.8,40.3 21.7,41.1 21.7,41.9C21.7,42.7 21.8,43.5 22.1,44.2C22.3,45 22.7,45.7 23.2,46.3C23.6,46.9 24.2,47.4 24.8,47.9C26.2,48.9 27.7,49.9 29.1,50.8C28.5,50.3 27.9,49.9 27.5,49.3C27,48.7 26.6,48 26.4,47.3C26.1,46.5 26,45.7 26,45C26,44.2 26.1,43.4 26.3,42.7Z" fill="url(#tnh-s)" stroke="#121319" stroke-width="3" stroke-linejoin="round" paint-order="stroke"/><path d="M42,26C43,27.8 44.4,29.5 45.1,31.5C45.8,33.5 46.2,35.6 46.2,37.8C46.2,39.9 45.9,42.1 45.3,44.2C44.7,46.3 43.8,48.3 42.5,50.1C41.3,52 39.8,53.6 38.1,55C36.4,56.3 34.5,57.4 32.4,58.2C30.4,59 28.3,59.4 26.2,59.5C24.1,59.6 22,59.1 19.9,58.8C20.5,59.1 21.1,59.4 21.7,59.5C23.7,59.8 25.8,60.3 27.8,60.2C29.9,60.1 31.9,59.6 33.9,58.9C35.8,58.1 37.7,57.1 39.4,55.7C41,54.4 42.5,52.8 43.7,51C44.9,49.3 45.8,47.3 46.4,45.3C47,43.3 47.3,41.1 47.2,39C47.2,37 46.9,34.9 46.1,33C45.1,30.5 43.4,28.3 42,26Z" fill="url(#tnh-engineBands)"/><path d="M-20.6,17.7C-21.1,17.6 -21.7,17.4 -22.3,17.4C-24.9,17.5 -27.6,17.7 -30.1,18.3C-32.1,18.8 -33.9,19.8 -35.7,20.7C-36.3,21 -36.9,21.4 -37.5,21.8C-39.1,23.2 -40.8,24.4 -42,26C-43.7,28.1 -45.2,30.4 -46.1,33C-47,35.3 -47.4,37.8 -47.5,40.4C-47.6,42.3 -47.3,44.3 -46.7,46.2C-46.2,48.1 -45.3,50 -44.2,51.6C-43.1,53.2 -41.7,54.7 -40.2,55.9C-38.6,57.1 -36.9,58.2 -35.1,58.8C-32.7,59.6 -30.3,60 -27.8,60.2C-25.8,60.3 -23.7,60.1 -21.7,59.5C-19.1,58.7 -16.5,57.7 -14.3,56.2C-12,54.7 -10,52.7 -8.3,50.5C-6.7,48.4 -5.5,46 -4.7,43.4C-3.9,41.1 -3.7,38.6 -3.7,36.1C-3.6,34.3 -3.9,32.5 -4.5,30.7C-5,29 -5.8,27.3 -6.9,25.8C-7.9,24.3 -9.2,22.9 -10.6,21.7C-12,20.6 -13.6,19.6 -15.3,19C-17,18.3 -18.8,18.1 -20.6,17.7ZM-22,39.5C-22.3,38.8 -22.6,38 -23.1,37.3C-23.5,36.7 -24.1,36.1 -24.7,35.6C-25.3,35.1 -26,34.7 -26.8,34.4C-27.5,34.1 -28.3,33.9 -29.1,33.9C-29.9,33.8 -30.7,33.9 -31.4,34.1C-32.2,34.3 -32.9,34.6 -33.5,35C-34.9,36 -36.2,37.2 -37.5,38.3C-36.8,38 -36.2,37.6 -35.5,37.4C-34.7,37.2 -34,37.1 -33.2,37.2C-32.4,37.2 -31.7,37.4 -30.9,37.7C-30.2,37.9 -29.5,38.3 -28.9,38.8C-28.3,39.3 -27.8,39.9 -27.3,40.6C-26.9,41.2 -26.6,41.9 -26.3,42.7C-26.1,43.4 -26,44.2 -26,45C-26,45.7 -26.1,46.5 -26.4,47.3C-26.6,48 -27,48.7 -27.5,49.3C-27.9,49.9 -28.5,50.3 -29.1,50.8C-27.7,49.9 -26.2,48.9 -24.8,47.9C-24.2,47.4 -23.6,46.9 -23.2,46.3C-22.7,45.7 -22.3,45 -22.1,44.2C-21.8,43.5 -21.7,42.7 -21.7,41.9C-21.7,41.1 -21.8,40.3 -22,39.5Z" fill="url(#tnh-s)" stroke="#121319" stroke-width="3" stroke-linejoin="round" paint-order="stroke"/><path d="M-42,26C-43.4,28.3 -45.1,30.5 -46.1,33C-46.9,34.9 -47.2,37 -47.2,39C-47.3,41.1 -47,43.3 -46.4,45.3C-45.8,47.3 -44.9,49.3 -43.7,51C-42.5,52.8 -41,54.4 -39.4,55.7C-37.7,57.1 -35.8,58.1 -33.9,58.9C-31.9,59.6 -29.9,60.1 -27.8,60.2C-25.8,60.3 -23.7,59.8 -21.7,59.5C-21.1,59.4 -20.5,59.1 -19.9,58.8C-22,59.1 -24.1,59.6 -26.2,59.5C-28.3,59.4 -30.4,59 -32.4,58.2C-34.5,57.4 -36.4,56.3 -38.1,55C-39.8,53.6 -41.3,52 -42.5,50.1C-43.8,48.3 -44.7,46.3 -45.3,44.2C-45.9,42.1 -46.2,39.9 -46.2,37.8C-46.2,35.6 -45.8,33.5 -45.1,31.5C-44.4,29.5 -43,27.8 -42,26Z" fill="url(#tnh-engineBands)"/><path d="M30.1,-17.1C32.4,-17.1 34.7,-17.5 36.9,-18.2C38.7,-18.8 40.4,-19.7 41.9,-20.9C43.4,-22 44.8,-23.4 45.9,-25C47.1,-26.6 48,-28.3 48.6,-30.2C49.2,-32 49.4,-34 49.4,-35.9C49.4,-37.8 49.1,-39.8 48.5,-41.6C47.9,-43.4 47,-45.1 45.9,-46.7C44.8,-48.2 43.3,-49.4 41.9,-50.7C41.6,-51 41.3,-51.3 41,-51.5C39.3,-52.4 37.6,-53.5 35.8,-54.1C33.5,-54.7 31.1,-55.1 28.8,-55C26.9,-55 24.9,-54.6 23.1,-54C21.1,-53.2 19.1,-52.2 17.3,-50.9C15.8,-49.8 14.5,-48.4 13.5,-46.9C12.4,-45.4 11.6,-43.7 11,-41.9C10.5,-40.1 10.2,-38.3 10.2,-36.4C10.2,-34.6 10.5,-32.7 11,-31C11.6,-29.2 12.4,-27.6 13.5,-26.1C14.8,-24.2 16.3,-22.4 18.1,-21.1C20,-19.7 22.1,-18.7 24.4,-17.9C26.2,-17.3 28.1,-17 30.1,-17.1ZM30.3,-38.2C30.7,-38.8 31.2,-39.3 31.8,-39.8C32.3,-40.2 33,-40.5 33.6,-40.8C34.3,-41 35,-41.1 35.7,-41.2C36.4,-41.2 37.1,-41 37.8,-40.9C36.8,-41.2 35.8,-41.7 34.7,-42C34,-42.2 33.3,-42.3 32.6,-42.3C31.8,-42.3 31.1,-42.1 30.4,-41.9C29.7,-41.7 29.1,-41.3 28.5,-40.9C27.9,-40.4 27.4,-39.9 27,-39.3C26.5,-38.7 26.2,-38 26,-37.3C25.8,-36.6 25.7,-35.8 25.7,-35.1C25.7,-34.4 25.8,-33.6 26,-32.9C26.2,-32.2 26.5,-31.6 27,-31C27.4,-30.4 27.9,-29.9 28.5,-29.4C29.1,-29 29.7,-28.7 30.4,-28.4C31.5,-28.1 32.6,-27.9 33.6,-27.7C33,-28 32.3,-28.2 31.8,-28.6C31.2,-29.1 30.7,-29.6 30.3,-30.1C29.9,-30.7 29.5,-31.4 29.3,-32C29.1,-32.7 29,-33.4 29,-34.2C29,-34.9 29.1,-35.6 29.3,-36.3C29.5,-37 29.9,-37.6 30.3,-38.2Z" fill="url(#tnh-s)" stroke="#121319" stroke-width="3" stroke-linejoin="round" paint-order="stroke"/><path d="M30.1,-17.1C32.3,-17.4 34.7,-17.5 36.9,-18.2C38.7,-18.8 40.4,-19.7 41.9,-20.9C43.4,-22 44.8,-23.4 45.9,-25C47,-26.6 47.9,-28.3 48.5,-30.2C49.1,-32 49.4,-34 49.4,-35.9C49.4,-37.8 49.1,-39.8 48.5,-41.6C47.9,-43.4 47.1,-45.2 45.9,-46.7C44.5,-48.5 42.6,-49.9 41,-51.5C42.4,-50.1 44,-49 45.1,-47.4C46.3,-45.8 47.2,-44 47.8,-42.1C48.4,-40.3 48.7,-38.3 48.7,-36.3C48.7,-34.3 48.4,-32.3 47.8,-30.4C47.2,-28.5 46.3,-26.7 45.1,-25C44,-23.4 42.6,-22 41,-20.8C39.4,-19.6 37.6,-18.7 35.8,-18C33.9,-17.4 32,-17.4 30.1,-17.1Z" fill="url(#tnh-engineBands)"/><path d="M-36.9,-18.2C-34.7,-17.5 -32.4,-17.1 -30.1,-17.1C-28.1,-17 -26.2,-17.6 -24.4,-17.9C-23.9,-18 -23.5,-18.3 -23.1,-18.5C-21.4,-19.3 -19.6,-20 -18.1,-21.1C-16.5,-22.2 -15.2,-23.6 -14.1,-25.2C-12.8,-26.9 -11.7,-28.9 -11,-31C-10.4,-32.7 -10.2,-34.6 -10.2,-36.4C-10.2,-38.3 -10.5,-40.1 -11,-41.9C-11.6,-43.7 -12.4,-45.4 -13.5,-46.9C-14.5,-48.4 -15.8,-49.8 -17.3,-50.9C-19.1,-52.2 -21.1,-53.2 -23.1,-54C-24.9,-54.6 -26.9,-55 -28.8,-55C-31.1,-55.1 -33.5,-54.7 -35.8,-54.1C-37.6,-53.5 -39.3,-52.4 -41,-51.5C-41.3,-51.3 -41.6,-51 -41.9,-50.7C-43.3,-49.4 -44.8,-48.2 -45.9,-46.7C-47,-45.1 -47.9,-43.4 -48.5,-41.6C-49.1,-39.6 -49.4,-37.6 -49.4,-35.5C-49.4,-33.7 -49.2,-31.9 -48.6,-30.2C-48,-28.3 -47.1,-26.6 -45.9,-25C-44.8,-23.4 -43.4,-22 -41.9,-20.9C-40.4,-19.7 -38.7,-18.8 -36.9,-18.2ZM-27,-39.3C-27.4,-39.9 -27.9,-40.4 -28.5,-40.9C-29.1,-41.3 -29.7,-41.7 -30.4,-41.9C-31.1,-42.1 -31.8,-42.3 -32.6,-42.3C-33.3,-42.3 -34,-42.2 -34.7,-42C-35.8,-41.7 -36.8,-41.2 -37.8,-40.9C-37.1,-41 -36.4,-41.2 -35.7,-41.2C-35,-41.1 -34.3,-41 -33.6,-40.8C-33,-40.5 -32.3,-40.2 -31.8,-39.8C-31.2,-39.3 -30.7,-38.8 -30.3,-38.2C-29.9,-37.6 -29.5,-37 -29.3,-36.3C-29.1,-35.6 -29,-34.9 -29,-34.2C-29,-33.4 -29.1,-32.7 -29.3,-32C-29.5,-31.4 -29.9,-30.7 -30.3,-30.1C-30.7,-29.6 -31.2,-29.1 -31.8,-28.6C-32.3,-28.2 -33,-28 -33.6,-27.7C-32.6,-27.9 -31.5,-28.1 -30.4,-28.4C-29.7,-28.7 -29.1,-29 -28.5,-29.4C-27.9,-29.9 -27.4,-30.4 -27,-31C-26.5,-31.6 -26.2,-32.2 -26,-32.9C-25.8,-33.6 -25.7,-34.4 -25.7,-35.1C-25.7,-35.8 -25.8,-36.6 -26,-37.3C-26.2,-38 -26.5,-38.7 -27,-39.3Z" fill="url(#tnh-s)" stroke="#121319" stroke-width="3" stroke-linejoin="round" paint-order="stroke"/><path d="M-30.1,-17.1C-32,-17.4 -33.9,-17.4 -35.8,-18C-37.6,-18.7 -39.4,-19.6 -41,-20.8C-42.6,-22 -44,-23.4 -45.1,-25C-46.3,-26.7 -47.2,-28.5 -47.8,-30.4C-48.4,-32.3 -48.7,-34.3 -48.7,-36.3C-48.7,-38.3 -48.4,-40.3 -47.8,-42.1C-47.2,-44 -46.3,-45.8 -45.1,-47.4C-44,-49 -42.4,-50.1 -41,-51.5C-42.6,-49.9 -44.5,-48.5 -45.9,-46.7C-47.1,-45.2 -47.9,-43.4 -48.5,-41.6C-49.1,-39.8 -49.4,-37.8 -49.4,-35.9C-49.4,-34 -49.1,-32 -48.5,-30.2C-47.9,-28.3 -47,-26.6 -45.9,-25C-44.8,-23.4 -43.4,-22 -41.9,-20.9C-40.4,-19.7 -38.7,-18.8 -36.9,-18.2C-34.7,-17.5 -32.3,-17.4 -30.1,-17.1Z" fill="url(#tnh-engineBands)"/><path d="M0.8,-106.2C0.4,-106.2 -0.1,-106.4 -0.6,-106.2C-1.1,-106.1 -1.4,-105.6 -1.8,-105.3C-2,-104.6 -2.2,-103.9 -2.2,-103.2C-2.4,-85.1 -2.3,-67 -2.3,-48.9C-2.2,-49.5 -2.2,-50.1 -2.1,-50.8C-1.9,-51 -1.6,-51.2 -1.4,-51.4C-0.5,-51.4 0.3,-51.4 1.1,-51.4C1.4,-51.2 1.7,-51 1.9,-50.8C2,-68.9 2.1,-87.1 2.1,-105.3C2,-105.7 1.8,-105.9 1.7,-106.2C1.4,-106.2 1.1,-106.2 0.8,-106.2Z" fill="url(#tnh-s)" stroke="#121319" stroke-width="3" stroke-linejoin="round" paint-order="stroke"/><path d="M61.4,22.2C63.2,20.2 65.4,18.5 66.9,16.1C68.5,13.6 69.6,10.7 70.4,7.7C71,5.2 71.1,2.6 71.1,0C71.1,-2.6 71,-5.2 70.4,-7.7C69.6,-10.7 68.5,-13.6 66.9,-16.1C65.4,-18.5 63.2,-20.2 61.4,-22.2C61.7,-21.2 62.1,-20.2 62.3,-19.1C62.6,-17.1 62.9,-15 63,-12.9C63.3,-8.6 63.4,-4.3 63.4,0C63.4,4.3 63.3,8.6 63,12.9C62.9,15 62.6,17.1 62.3,19.1C62.1,20.2 61.7,21.2 61.4,22.2ZM62.8,-21.8C62.6,-23 62.5,-24.2 62.2,-25.4C61.9,-26.7 61.4,-28 61,-29.4C59.4,-30.5 57.7,-31.6 56,-32.7C55.8,-32.8 55.6,-32.9 55.4,-33C55.2,-32.6 54.8,-32.4 54.7,-32C54.3,-30.2 53.8,-28.4 53.6,-26.5C53.1,-21.7 52.8,-16.8 52.5,-12C52.3,-8 52.3,-4 52.3,0C52.3,4 52.3,8 52.5,12C52.8,16.8 53.1,21.7 53.6,26.5C53.8,28.4 54.3,30.2 54.7,32C54.8,32.4 55.2,32.6 55.4,33C57.3,31.8 59.1,30.6 61,29.4C61.4,28 61.9,26.7 62.2,25.4C62.5,24.2 62.6,23 62.8,21.8C63.1,18.5 63.4,15.2 63.5,11.9C63.7,8 63.8,4 63.8,0C63.8,-4 63.7,-8 63.5,-11.9C63.4,-15.2 63.1,-18.5 62.8,-21.8ZM54.1,-19.9C54.2,-21.2 54.5,-22.5 54.9,-23.8C55,-24.1 55.2,-24.3 55.4,-24.5C55.5,-24.4 55.7,-24.3 55.9,-24.3C52.4,-26.5 48.9,-28.7 45.4,-30.9C45.1,-29.9 44.6,-29 44.5,-28C44,-24.1 43.6,-20.3 43.4,-16.4C43.1,-9 43,-1.7 43.1,5.7C43.2,12.1 43.6,18.5 44.1,24.9C44.2,26.7 44.6,28.3 45,30C45,30.3 45.3,30.6 45.4,30.9C48.9,28.7 52.4,26.5 55.9,24.3C55.7,24.3 55.5,24.4 55.4,24.5C55.1,23.8 54.6,23.1 54.5,22.3C54.1,20.5 53.9,18.6 53.7,16.8C53.5,14.2 53.3,11.6 53.2,9C53.1,3 53,-3 53.2,-9C53.3,-12.7 53.6,-16.3 54.1,-19.9Z" fill="url(#tnh-s)" stroke="#121319" stroke-width="3" stroke-linejoin="round" paint-order="stroke"/><path d="M61.4,22.2C63.2,20.2 65.4,18.5 66.9,16.1C68.5,13.6 69.6,10.7 70.4,7.7C71,5.2 71.1,2.6 71.1,0C71.1,-2.6 71,-5.2 70.4,-7.7C69.6,-10.7 68.5,-13.6 66.9,-16.1C65.4,-18.5 63.2,-20.2 61.4,-22.2C61.7,-21.2 62.1,-20.2 62.3,-19.1C62.6,-17.1 62.9,-15 63,-12.9C63.3,-8.6 63.4,-4.3 63.4,0C63.4,4.3 63.3,8.6 63,12.9C62.9,15 62.6,17.1 62.3,19.1C62.1,20.2 61.7,21.2 61.4,22.2Z" fill="url(#tnh-sideDomes)"/><path d="M-61.4,22.2C-61.7,21.2 -62.1,20.2 -62.3,19.1C-62.6,17.1 -62.9,15 -63,12.9C-63.3,8.6 -63.4,4.3 -63.4,0C-63.4,-4.3 -63.3,-8.6 -63,-12.9C-62.9,-15 -62.6,-17.1 -62.3,-19.1C-62.1,-20.2 -61.7,-21.2 -61.4,-22.2C-63.2,-20.2 -65.4,-18.5 -66.9,-16.1C-68.5,-13.6 -69.6,-10.7 -70.4,-7.7C-71,-5.2 -71.1,-2.6 -71.1,0C-71.1,2.6 -71,5.2 -70.4,7.7C-69.6,10.7 -68.5,13.6 -66.9,16.1C-65.4,18.5 -63.2,20.2 -61.4,22.2ZM-62.2,-25.4C-62.9,-20.9 -63.2,-16.4 -63.5,-11.9C-63.8,-8 -63.8,-4 -63.8,0C-63.8,4 -63.7,8 -63.5,11.9C-63.4,15.2 -63.1,18.5 -62.8,21.8C-62.6,23 -62.5,24.2 -62.2,25.4C-61.9,26.7 -61.4,28 -61,29.4C-59.1,30.6 -57.3,31.8 -55.4,33C-55.2,32.6 -54.8,32.4 -54.7,32C-54.3,30.2 -53.8,28.4 -53.6,26.5C-53.1,21.7 -52.8,16.8 -52.5,12C-52.3,8 -52.3,4 -52.3,0C-52.3,-4 -52.3,-8 -52.5,-12C-52.8,-16.8 -53.1,-21.7 -53.6,-26.5C-53.8,-28.4 -54.3,-30.2 -54.7,-32C-54.8,-32.4 -55.2,-32.6 -55.4,-33C-57.3,-31.8 -59.1,-30.6 -61,-29.4C-61.4,-28 -62,-26.8 -62.2,-25.4ZM-54.5,-22.3C-54.1,-20.5 -53.9,-18.6 -53.7,-16.8C-53.5,-14.2 -53.3,-11.6 -53.2,-9C-53.1,-3 -53.1,3 -53.2,9C-53.3,11.6 -53.5,14.2 -53.7,16.8C-53.9,18.6 -54.1,20.5 -54.5,22.3C-54.6,23.1 -55.1,23.8 -55.4,24.5C-55.5,24.4 -55.7,24.3 -55.9,24.3C-52.4,26.5 -48.9,28.7 -45.4,30.9C-45.3,30.6 -45,30.3 -45,30C-44.6,28.3 -44.2,26.7 -44.1,24.9C-43.6,18.5 -43.2,12.1 -43.1,5.7C-43,-1.7 -43.1,-9 -43.4,-16.4C-43.6,-20.3 -44,-24.1 -44.5,-28C-44.6,-29 -45.1,-29.9 -45.4,-30.9C-45.6,-30.8 -45.8,-30.8 -45.9,-30.7C-49.3,-28.5 -52.5,-26.4 -55.9,-24.3C-55.7,-24.3 -55.5,-24.4 -55.4,-24.5C-55.1,-23.8 -54.6,-23.1 -54.5,-22.3Z" fill="url(#tnh-s)" stroke="#121319" stroke-width="3" stroke-linejoin="round" paint-order="stroke"/><path d="M-61.4,22.2C-61.7,21.2 -62.1,20.2 -62.3,19.1C-62.6,17.1 -62.9,15 -63,12.9C-63.3,8.6 -63.4,4.3 -63.4,0C-63.4,-4.3 -63.3,-8.6 -63,-12.9C-62.9,-15 -62.6,-17.1 -62.3,-19.1C-62.1,-20.2 -61.7,-21.2 -61.4,-22.2C-63.2,-20.2 -65.4,-18.5 -66.9,-16.1C-68.5,-13.6 -69.6,-10.7 -70.4,-7.7C-71,-5.2 -71.1,-2.6 -71.1,0C-71.1,2.6 -71,5.2 -70.4,7.7C-69.6,10.7 -68.5,13.6 -66.9,16.1C-65.4,18.5 -63.2,20.2 -61.4,22.2Z" fill="url(#tnh-sideDomes)"/><path d="M47.3,6.2C47.3,-1.8 47.5,-9.8 47.7,-17.7C47.8,-20.8 48.1,-23.9 48.5,-26.9C48.7,-28.8 49.2,-30.6 49.5,-32.5C47.8,-29.1 45.6,-25.9 44.2,-22.4C42.7,-18.9 41.7,-15.2 40.9,-11.5C40.2,-7.7 40,-3.8 40,0C40,3.8 40.2,7.7 40.9,11.5C41.7,15.2 42.7,18.9 44.2,22.4C45.6,25.9 47.8,29.1 49.5,32.5C49,29.2 48.4,26 48.1,22.7C47.6,17.2 47.4,11.7 47.3,6.2ZM23.5,55.7C27.2,54.2 30.8,52.3 34.1,50C37.4,47.8 40.5,45.3 43.3,42.4C46,39.6 48.4,36.4 50.7,33.2C51,32.8 51.2,32.2 51.3,31.7C51.9,27.7 52.5,23.6 52.7,19.6C53.2,13.1 53.3,6.5 53.3,0C53.3,-6.5 53.2,-13.1 52.7,-19.6C52.5,-23.6 51.9,-27.7 51.3,-31.7C51.2,-32.2 50.9,-32.7 50.7,-33.2C50.5,-33.3 50.3,-33.3 50.1,-33.5C47.5,-36.5 45.4,-39.8 42.6,-42.6C39.8,-45.4 36.8,-47.9 33.5,-50.1C30.2,-52.3 26.7,-54.2 23.1,-55.7C19.4,-57.2 15.5,-58 11.8,-59.1C11.6,-58.3 11.4,-57.5 11.2,-56.7C14.8,-55.6 18.5,-54.9 21.9,-53.4C25.4,-52 28.7,-50.3 31.8,-48.2C34.9,-46.1 37.7,-43.8 40.4,-41.1C43,-38.5 45,-35.4 47.4,-32.6C48.5,-32.8 49.6,-33 50.7,-33.2C48.2,-36.3 46,-39.6 43.3,-42.4C40.5,-45.3 37.4,-47.8 34.1,-50C30.8,-52.3 27.2,-54.2 23.5,-55.7C19.8,-57.2 15.8,-58 12,-59.2C11.2,-61.8 10.4,-64.3 9.7,-66.9C6.4,-67.2 3.2,-68 0,-68C-3.2,-68 -6.4,-67.2 -9.7,-66.9C-10.4,-64.3 -11.2,-61.8 -12,-59.2C-15.8,-58 -19.8,-57.2 -23.5,-55.7C-27.2,-54.2 -30.8,-52.3 -34.1,-50C-37.4,-47.8 -40.5,-45.3 -43.3,-42.4C-46,-39.6 -48.2,-36.3 -50.7,-33.2C-49.6,-33 -48.5,-32.8 -47.4,-32.6C-45,-35.4 -43,-38.5 -40.4,-41.1C-37.7,-43.8 -34.9,-46.1 -31.8,-48.2C-28.7,-50.3 -25.4,-52 -21.9,-53.4C-18.5,-54.9 -14.8,-55.6 -11.2,-56.7C-11.1,-56.8 -11.1,-56.9 -11,-57C-11.3,-57.7 -11.5,-58.4 -11.8,-59.1C-15.5,-58 -19.4,-57.2 -23.1,-55.7C-26.7,-54.2 -30.2,-52.3 -33.5,-50.1C-36.8,-47.9 -39.8,-45.4 -42.6,-42.6C-45.4,-39.8 -47.5,-36.5 -50.1,-33.5C-50.3,-33.3 -50.5,-33.3 -50.7,-33.2C-51.1,-31.8 -51.6,-30.3 -51.8,-28.8C-52.3,-25.7 -52.6,-22.7 -52.7,-19.6C-53.1,-13.1 -53.3,-6.5 -53.3,0C-53.3,6.5 -53.2,13.1 -52.7,19.6C-52.5,23.6 -51.9,27.7 -51.3,31.7C-51.2,32.2 -51,32.8 -50.7,33.2C-48.4,36.4 -46,39.6 -43.3,42.4C-40.5,45.3 -37.4,47.8 -34.1,50C-30.8,52.3 -27.2,54.2 -23.5,55.7C-19.8,57.2 -15.9,58.4 -12,59.2C-8.1,60 -4,60.4 0,60.4C4,60.4 8.1,60 12,59.2C15.9,58.4 19.8,57.2 23.5,55.7ZM-47.3,0C-47.3,4 -47.3,8.1 -47.5,12.1C-47.6,15.7 -47.7,19.2 -48.1,22.7C-48.4,26 -49,29.2 -49.5,32.5C-47.8,29.1 -45.6,25.9 -44.2,22.4C-42.7,18.9 -41.9,15.2 -40.9,11.5C-40.7,10.4 -40.6,9.3 -40.5,8.2C-40.3,5.5 -39.9,2.7 -40,0C-40,-3.6 -40.1,-7.2 -40.8,-10.8C-41.5,-14.8 -42.7,-18.7 -44.2,-22.4C-45.6,-26 -47.8,-29.1 -49.5,-32.5C-49,-29.2 -48.4,-26 -48.1,-22.7C-47.7,-19.2 -47.6,-15.7 -47.5,-12.1C-47.3,-8.1 -47.3,-4 -47.3,0Z" fill="url(#tnh-s)" stroke="#121319" stroke-width="3" stroke-linejoin="round" paint-order="stroke"/><path d="M23.5,55.7C27.2,54.2 30.8,52.3 34.1,50C37.4,47.8 40.5,45.3 43.3,42.4C46,39.6 48.6,36.6 50.7,33.2C51.5,31.9 51.6,30.3 51.8,28.8C52.1,27.5 52.2,26.1 52.3,24.7C52.6,21 52.8,17.3 53.1,13.6C50.7,14.9 48.3,16.2 45.9,17.5C44.9,17.3 44,17.1 43,16.9C42.8,21.5 42.5,26.1 42.3,30.6C39.3,32.6 36.5,34.8 33.3,36.4C30,38.1 26.4,39.6 22.8,40.7C19,41.9 15.1,42.8 11.2,43.4C7.5,44 3.7,44.4 0,44.4C-3.7,44.4 -7.5,44 -11.2,43.4C-15.1,42.8 -19,41.9 -22.8,40.7C-26.4,39.6 -30,38.1 -33.3,36.4C-36.5,34.8 -39.3,32.6 -42.3,30.6C-42.5,26.1 -42.8,21.5 -43,16.9C-44,17.1 -44.9,17.3 -45.9,17.5C-48.3,16.2 -50.7,14.9 -53.1,13.6C-52.8,17.3 -52.6,21 -52.3,24.7C-52.2,26.1 -52.1,27.5 -51.8,28.8C-51.6,30.3 -51.5,31.9 -50.7,33.2C-48.6,36.6 -46,39.6 -43.3,42.4C-40.5,45.3 -37.4,47.8 -34.1,50C-30.8,52.3 -27.2,54.2 -23.5,55.7C-19.8,57.2 -15.9,58.4 -12,59.2C-8.1,60 -4,60.4 0,60.4C4,60.4 8.1,60 12,59.2C15.9,58.4 19.8,57.2 23.5,55.7Z" fill="url(#tnh-s)"/><path d="M45.9,-17.5C44.9,-17.3 44,-17.1 43,-16.9C43.1,-8.4 43.2,0.1 43.2,8.6C44.2,8.8 45.1,9.1 46.1,9C47.3,8.9 48.5,8.3 49.7,8C49.7,5.3 49.8,2.7 49.8,0C49.7,-5.2 49.6,-10.4 49.5,-15.5C48.3,-16.2 47.1,-16.9 45.9,-17.5ZM34.1,-40.4C36.9,-38.8 39.5,-36.7 42.2,-34.9C42.1,-35.6 42.1,-36.3 42,-36.9C39.3,-38.9 36.8,-41.1 33.9,-42.7C30.9,-44.5 27.7,-46 24.4,-47.1C21,-48.3 17.6,-49.3 14,-49.8C9.4,-50.5 4.7,-50.8 0,-50.8C-4.7,-50.8 -9.4,-50.5 -14,-49.8C-17.6,-49.3 -21,-48.3 -24.4,-47.1C-27.7,-46 -30.9,-44.5 -33.9,-42.7C-36.8,-41.1 -39.3,-38.9 -42,-36.9C-42.1,-36.3 -42.1,-35.6 -42.2,-34.9C-39.5,-36.7 -36.9,-38.8 -34.1,-40.4C-31,-42 -27.9,-43.4 -24.6,-44.5C-21.2,-45.6 -17.7,-46.6 -14.1,-47.1C-9.4,-47.7 -4.7,-47.9 0,-47.9C4.7,-47.9 9.4,-47.7 14.1,-47.1C17.7,-46.6 21.2,-45.6 24.6,-44.5C27.9,-43.4 31,-42 34.1,-40.4ZM-43.2,-8.6C-43.2,-11.4 -43.1,-14.1 -43,-16.9C-44,-17.1 -44.9,-17.3 -45.9,-17.5C-47.1,-16.9 -48.3,-16.2 -49.5,-15.5C-49.6,-7.7 -49.6,0.1 -49.7,8C-48.5,8.3 -47.3,8.9 -46.1,9C-45.1,9.1 -44.2,8.8 -43.2,8.6C-43.2,2.9 -43.3,-2.9 -43.2,-8.6Z" fill="url(#tnh-faceTrim)"/><path d="M11.1,-62.2C10.6,-63.7 10.1,-65.3 9.7,-66.9C6.4,-67.2 3.2,-68 0,-68C-3.2,-68 -6.4,-67.2 -9.7,-66.9C-10.4,-64.3 -11.3,-61.8 -12,-59.2C-12.2,-58.5 -12.2,-57.7 -12.3,-56.9C-8.2,-57.3 -4.1,-58.1 0,-58.1C4.1,-58.1 8.2,-57.3 12.3,-56.9C12.2,-57.7 12.2,-58.5 12,-59.2C11.8,-60.2 11.4,-61.2 11.1,-62.2Z" fill="#c96442" opacity="0.55" filter="url(#tnh-h)"/><path d="M11.1,-62.2C10.6,-63.7 10.1,-65.3 9.7,-66.9C6.4,-67.2 3.2,-68 0,-68C-3.2,-68 -6.4,-67.2 -9.7,-66.9C-10.4,-64.3 -11.3,-61.8 -12,-59.2C-12.2,-58.5 -12.2,-57.7 -12.3,-56.9C-8.2,-57.3 -4.1,-58.1 0,-58.1C4.1,-58.1 8.2,-57.3 12.3,-56.9C12.2,-57.7 12.2,-58.5 12,-59.2C11.8,-60.2 11.4,-61.2 11.1,-62.2Z" fill="#c96442"/><path d="M33.3,36.4C36.5,34.8 39.3,32.6 42.3,30.6C42.5,26.1 42.9,21.5 43,16.9C43.2,11.2 43.3,5.6 43.3,0C43.3,-5.6 43.2,-11.2 43,-16.9C42.9,-21.5 42.5,-26.1 42.3,-30.6C39.3,-32.6 36.5,-34.8 33.3,-36.4C30,-38.1 26.4,-39.6 22.8,-40.7C19,-41.9 15.1,-42.8 11.2,-43.4C7.5,-44 3.7,-44.4 0,-44.4C-3.7,-44.4 -7.5,-44 -11.2,-43.4C-15.1,-42.8 -19,-41.9 -22.8,-40.7C-26.4,-39.6 -30,-38.1 -33.3,-36.4C-36.5,-34.8 -39.3,-32.6 -42.3,-30.6C-42.5,-26.1 -42.9,-21.5 -43,-16.9C-43.2,-11.2 -43.3,-5.6 -43.3,0C-43.3,5.6 -43.2,11.2 -43,16.9C-42.9,21.5 -42.5,26.1 -42.3,30.6C-39.3,32.6 -36.5,34.8 -33.3,36.4C-30,38.1 -26.4,39.6 -22.8,40.7C-19,41.9 -15.1,42.8 -11.2,43.4C-7.5,44 -3.7,44.4 0,44.4C3.7,44.4 7.5,44 11.2,43.4C15.1,42.8 19,41.9 22.8,40.7C26.4,39.6 30,38.1 33.3,36.4Z" fill="#c3cbd8" stroke="#c3cbd8" stroke-width="7" stroke-linejoin="round"/><path d="M33.3,36.4C36.5,34.8 39.3,32.6 42.3,30.6C42.5,26.1 42.9,21.5 43,16.9C43.2,11.2 43.3,5.6 43.3,0C43.3,-5.6 43.2,-11.2 43,-16.9C42.9,-21.5 42.5,-26.1 42.3,-30.6C39.3,-32.6 36.5,-34.8 33.3,-36.4C30,-38.1 26.4,-39.6 22.8,-40.7C19,-41.9 15.1,-42.8 11.2,-43.4C7.5,-44 3.7,-44.4 0,-44.4C-3.7,-44.4 -7.5,-44 -11.2,-43.4C-15.1,-42.8 -19,-41.9 -22.8,-40.7C-26.4,-39.6 -30,-38.1 -33.3,-36.4C-36.5,-34.8 -39.3,-32.6 -42.3,-30.6C-42.5,-26.1 -42.9,-21.5 -43,-16.9C-43.2,-11.2 -43.3,-5.6 -43.3,0C-43.3,5.6 -43.2,11.2 -43,16.9C-42.9,21.5 -42.5,26.1 -42.3,30.6C-39.3,32.6 -36.5,34.8 -33.3,36.4C-30,38.1 -26.4,39.6 -22.8,40.7C-19,41.9 -15.1,42.8 -11.2,43.4C-7.5,44 -3.7,44.4 0,44.4C3.7,44.4 7.5,44 11.2,43.4C15.1,42.8 19,41.9 22.8,40.7C26.4,39.6 30,38.1 33.3,36.4Z" fill="url(#tnh-v)"/><path d="M-30.4,-15.1 A33.8,34.6 0 0 1 -12.2,-32.3" fill="none" stroke="#fff" stroke-opacity="0.28" stroke-width="4.4" stroke-linecap="round"/><path d="M-21.1,11.5 A7.9,10 0 1 1 -10.5,11.5 A14.2,14.2 0 0 0 -21.1,11.5 ZM10.5,11.5 A7.9,10 0 1 1 21.1,11.5 A14.2,14.2 0 0 0 10.5,11.5 Z" fill="#7fcfff" fill-rule="evenodd" filter="url(#tnh-g)" opacity="0.9"/><path d="M-21.1,11.5 A7.9,10 0 1 1 -10.5,11.5 A14.2,14.2 0 0 0 -21.1,11.5 ZM10.5,11.5 A7.9,10 0 1 1 21.1,11.5 A14.2,14.2 0 0 0 10.5,11.5 Z" fill="#eef8ff" fill-rule="evenodd"/></g>
|
|
2204
|
-
<g fill="none" stroke="#fff" stroke-width="9" stroke-linecap="round" stroke-linejoin="round"><path d="M9,4 V46 A14,14 0 0 0 23,60 M0,20 H24"/><path transform="translate(37 0)" d="M0,0 V60 M0,39 A19,19 0 0 1 38,39 V60"/><path transform="translate(90 0)" d="M0,20 V60 M0,42 A22,22 0 0 1 22,20 H26"/><path transform="translate(127 0)" d="M1,40 H40 A20,20 0 1 0 34.14,54.14"/><path transform="translate(182 0)" d="M40,40 A20,20 0 1 0 0,40 A20,20 0 1 0 40,40 M40,20 V60"/><path transform="translate(237 0)" d="M40,40 A20,20 0 1 0 0,40 A20,20 0 1 0 40,40 M40,0 V60"/><path transform="translate(292 0)" d="M0,20 V60 M0,39 A19,19 0 0 1 38,39 V60"/><path transform="translate(345 0)" d="M40,40 A20,20 0 1 0 0,40 A20,20 0 1 0 40,40 M40,20 V60"/><path transform="translate(400 0)" d="M0,20 V41 A19,19 0 0 0 38,41 M38,20 V60"/><path transform="translate(451 0)" d="M9,4 V46 A14,14 0 0 0 23,60 M0,20 H24"/><path transform="translate(488 0)" d="M24.39,25 A12,10 0 1 0 14,40 A14,10 0 1 1 1.88,55"/></g>
|
|
2205
|
-
</svg>
|
|
2206
|
-
`,TC=Ff.replaceAll("tnh-","tnb-").replace(/<title>[^<]*<\/title>\s*/,""),Of=/Mac/.test(navigator.platform),_C=Object.assign({"./world-icons/aldargon.svg":vy,"./world-icons/arrakesh.svg":yy,"./world-icons/atoll.svg":Cy,"./world-icons/autumn.svg":xy,"./world-icons/bamboo.svg":My,"./world-icons/basalt.svg":ky,"./world-icons/beach.svg":Ty,"./world-icons/callisto.svg":_y,"./world-icons/cancri.svg":Sy,"./world-icons/canyon.svg":$y,"./world-icons/ceres.svg":Ay,"./world-icons/challenger.svg":Ey,"./world-icons/crystal.svg":Py,"./world-icons/dagmora.svg":zy,"./world-icons/deadstar.svg":Ly,"./world-icons/desert.svg":Ry,"./world-icons/dragonnest.svg":By,"./world-icons/draugr.svg":Fy,"./world-icons/enceladus.svg":Oy,"./world-icons/endral.svg":Iy,"./world-icons/europa.svg":Dy,"./world-icons/fjord.svg":Vy,"./world-icons/forest.svg":Ny,"./world-icons/frozenlake.svg":Wy,"./world-icons/ganymede.svg":Hy,"./world-icons/garden.svg":Uy,"./world-icons/glimmer.svg":jy,"./world-icons/halley.svg":qy,"./world-icons/hd189733b.svg":Gy,"./world-icons/hollow.svg":Zy,"./world-icons/horth.svg":Xy,"./world-icons/iapetus.svg":Yy,"./world-icons/io.svg":Qy,"./world-icons/j1407b.svg":Ky,"./world-icons/jakhara.svg":Jy,"./world-icons/jupiter.svg":e6,"./world-icons/kaladorn.svg":t6,"./world-icons/kashiwa.svg":s6,"./world-icons/kepler16b.svg":i6,"./world-icons/kepler186f.svg":n6,"./world-icons/lanternnight.svg":r6,"./world-icons/lt2230.svg":o6,"./world-icons/lt4260.svg":a6,"./world-icons/mars.svg":l6,"./world-icons/mercury.svg":c6,"./world-icons/middangard.svg":h6,"./world-icons/milners.svg":d6,"./world-icons/miranda.svg":u6,"./world-icons/moon.svg":f6,"./world-icons/moors.svg":p6,"./world-icons/muspel.svg":m6,"./world-icons/nabora.svg":g6,"./world-icons/north.svg":w6,"./world-icons/ocean.svg":b6,"./world-icons/oz.svg":v6,"./world-icons/pandora.svg":y6,"./world-icons/phobos.svg":C6,"./world-icons/pluto.svg":x6,"./world-icons/proxima.svg":M6,"./world-icons/qubitron.svg":k6,"./world-icons/redspot.svg":T6,"./world-icons/ring.svg":_6,"./world-icons/sakura.svg":S6,"./world-icons/saturnrings.svg":$6,"./world-icons/savanna.svg":A6,"./world-icons/sky.svg":E6,"./world-icons/sugarvale.svg":P6,"./world-icons/tatawin.svg":z6,"./world-icons/terra.svg":L6,"./world-icons/titan.svg":R6,"./world-icons/titanic.svg":B6,"./world-icons/trappist.svg":F6,"./world-icons/triton.svg":O6,"./world-icons/tundra.svg":I6,"./world-icons/undersea.svg":D6,"./world-icons/valley.svg":V6,"./world-icons/venus.svg":N6,"./world-icons/vespera.svg":W6,"./world-icons/worldtree.svg":H6,"./world-icons/yavora4.svg":U6}),If=/Win/.test(navigator.platform),jd=Of?"Finder":If?"Explorer":"Files",de={settings:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.6a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>',eye:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round"><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7z"/><circle cx="12" cy="12" r="3"/></svg>',eyeOff:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round"><path d="M9.9 4.24A9.1 9.1 0 0 1 12 4c6.5 0 10 7 10 7a18.5 18.5 0 0 1-2.16 3.19M6.6 6.6C4.06 8.2 2 11 2 11s3.5 7 10 7a9.7 9.7 0 0 0 5.4-1.6"/><path d="M14.12 14.12a3 3 0 1 1-4.24-4.24M2 2l20 20"/></svg>',home:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="M3 10.5 12 3l9 7.5"/><path d="M5 9.5V20h14V9.5"/><path d="M9.5 20v-6h5v6"/></svg>',next:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><path d="M12 8v4.5M12 16h.01"/></svg>',sun:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round"><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4"/></svg>',globe:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7"><circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3a15 15 0 0 1 0 18 15 15 0 0 1 0-18z"/></svg>',camera:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linejoin="round"><path d="M3 8.5h3.2l1.5-2h8.6l1.5 2H21v11H3z"/><circle cx="12" cy="14" r="3.4"/></svg>',help:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round"><circle cx="12" cy="12" r="9"/><path d="M9.6 9.2a2.5 2.5 0 1 1 3.4 2.3c-.7.3-1 .8-1 1.6v.4"/><path d="M12 17h.01"/></svg>',open:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M14 4h6v6M20 4l-8.5 8.5"/><path d="M18 14v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V7a1 1 0 0 1 1-1h5"/></svg>',archive:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h18v3H3z"/><path d="M5 9v10h14V9"/><path d="M10 13h4"/></svg>',close:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round"><path d="M6 6l12 12M18 6L6 18"/></svg>',back:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><path d="M14.5 5.5 8 12l6.5 6.5"/></svg>',plus:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M20.5 11.7a8 8 0 0 1-8.5 8 9.3 9.3 0 0 1-2.7-.4L4.5 21l1.4-4.1a7.9 7.9 0 0 1-2.4-5.7A8 8 0 0 1 12 3.6a8 8 0 0 1 8.5 8.1z"/><path d="M12 8.6v5.4M9.3 11.3h5.4"/></svg>',folder:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M3 7.4A1.4 1.4 0 0 1 4.4 6h4.2l2 2.5h7A1.4 1.4 0 0 1 19 9.9v7.7a1.4 1.4 0 0 1-1.4 1.4H4.4A1.4 1.4 0 0 1 3 17.6z"/></svg>',copy:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="11" height="11" rx="2"/><path d="M5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1"/></svg>',locate:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round"><circle cx="12" cy="12" r="3"/><circle cx="12" cy="12" r="7.6"/><path d="M12 1.8v2.6M12 19.6v2.6M1.8 12h2.6M19.6 12h2.6"/></svg>',orbit:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7"><circle cx="12" cy="12" r="4"/><ellipse cx="12" cy="12" rx="10.2" ry="4.6" transform="rotate(-24 12 12)"/><circle cx="21" cy="8.2" r="1.5" fill="currentColor" stroke="none"/></svg>',sound:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="M4 9.5v5h3.5L12 18.5v-13L7.5 9.5z"/><path d="M15.5 9a4 4 0 0 1 0 6"/><path d="M18 6.5a8 8 0 0 1 0 11"/></svg>',record:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7"><circle cx="12" cy="12" r="8.5"/><circle cx="12" cy="12" r="4" fill="currentColor" stroke="none"/></svg>',stop:'<svg viewBox="0 0 24 24"><rect x="7" y="7" width="10" height="10" rx="2" fill="currentColor"/></svg>',lock:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><rect x="5" y="10.5" width="14" height="10" rx="2"/><path d="M8 10.5V7.5a4 4 0 0 1 8 0v3"/></svg>',soundOff:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="M4 9.5v5h3.5L12 18.5v-13L7.5 9.5z"/><path d="M16 9.5l5 5M21 9.5l-5 5"/></svg>',branch:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><circle cx="7" cy="5.5" r="2.2"/><circle cx="7" cy="18.5" r="2.2"/><circle cx="17" cy="7.5" r="2.2"/><path d="M7 7.7v8.6"/><path d="M17 9.7c0 3.4-2.6 4.6-6 5.2-1.9.3-3.3.9-4 1.4"/></svg>',worktree:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><circle cx="6.5" cy="5" r="2.2"/><circle cx="17.5" cy="5" r="2.2"/><circle cx="12" cy="19" r="2.2"/><path d="M6.5 7.2v1.3a3 3 0 0 0 3 3h5a3 3 0 0 0 3-3V7.2"/><path d="M12 11.5v5.3"/></svg>',model:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M11 3.5l1.8 4.9 4.9 1.8-4.9 1.8L11 16.9l-1.8-4.9-4.9-1.8 4.9-1.8z"/><path d="M18 14.5l.8 2 2 .8-2 .8-.8 2-.8-2-2-.8 2-.8z"/></svg>',org:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M4.5 20V5.4A1.4 1.4 0 0 1 5.9 4h6.7A1.4 1.4 0 0 1 14 5.4V20"/><path d="M14 9h4.1a1.4 1.4 0 0 1 1.4 1.4V20"/><path d="M3 20h18"/><path d="M7.5 8h3M7.5 11.5h3M7.5 15h3M16.8 13h.01M16.8 16.5h.01"/></svg>'},Ba=[{key:"asking",label:"Needs you",cls:"asking",title:"Jump to the bots stopped on a question for you"},{key:"working",label:"Working",cls:"working",title:"Jump to the bots that are working"},{key:"delegating",label:"Waiting on agents",cls:"delegating",title:"Jump to the bots waiting for other agents to finish"},{key:"done",label:"Done",cls:"done",title:"Jump to the bots that finished, ready for you to read"},{key:"error",label:"Error",cls:"error",title:"Jump to the bots whose session hit an error"},{key:"celebrating",label:"Shipped",cls:"celebrating",title:"Jump to the bots that shipped"},{key:"quiet",label:"Idle",cls:"quiet",title:"Jump to the idle and dormant bots"},{key:"agents",label:"Bots",one:"Bot",cls:"idle",title:"Jump to every bot"}];class SC{constructor(e,t,i){this.settings=t,this.actions=i,this.visible=!0,this._last={},this.el=document.createElement("div"),this.el.className="hud",this.el.innerHTML=IC,e.appendChild(this.el),this.$=n=>this.el.querySelector(n),this._buildStats(),this._buildSettings(),this._buildAvatar(),this._wire(),this.syncSettings(),this._layoutObserver=new ResizeObserver(()=>this._syncLayout()),this._layoutObserver.observe(this.el),this._layoutObserver.observe(this.$(".side")),this._syncLayout()}_buildStats(){const e=this.$(".stats"),t=this.$("#btn-threadgauge");this.statEls={};for(const i of Ba){const n=document.createElement("button");n.className=`stat ${i.cls}`,n.type="button",n.dataset.key=i.key,n.title=`${i.title}, most recently used first`,n.innerHTML=`<i class="pip"></i><span class="n">0</span><span class="lbl">${i.label}</span>`,n.type="button",n.addEventListener("click",()=>this.actions.focusStatus?.(i.key)),e.insertBefore(n,t),this.statEls[i.key]=n}}_buildSettings(){const e=this.$(".settings .body"),t=this.settings;this.controls=[];const i=Ss("Threadnauts Pro");this.licenseStatus=document.createElement("p"),this.licenseStatus.className="license-status",this.settingsKey=this._licenseForm(!0,u=>u.proThrough?(da(u)||this.toast("Threadnauts Pro is unlocked"),""):Vh(u)),this.getPro=document.createElement("a"),this.getPro.className="license-get",this.getPro.href=x0,this.getPro.target="_blank",this.getPro.rel="noopener",this.getPro.textContent="Get Threadnauts Pro",i.append(this.licenseStatus,this.settingsKey.form,this.settingsKey.message,this.getPro),e.appendChild(i),e.appendChild(Ss("Quality preset",Fa(Object.entries(ps).map(([u,f])=>({id:u,label:f.label,title:f.hint})),()=>t.get("preset"),u=>t.applyPreset(u),this.controls)));const n=Ss("Performance");n.append(this._toggle("HDR + bloom","bloom","Glowing eyes, lamps, and windows. The first thing to drop."),this._toggle("Tilt-shift","tiltShift","A shallow depth of field, which is what makes the colony read as a model."),this._slider("Tilt-shift blur","tiltShiftStrength",0,1,.05,u=>`${Math.round(u*100)}%`,"Aperture: how shallow the focus is, and how far out of it things go."),this._slider("Tilt-shift angle","tiltShiftAngle",-90,90,1,u=>`${u}°`,"Swings the plane of focus, the way tilting a real lens does."),this._select("Shadows","shadows",[["off","Off"],["low","Low"],["high","High"],["ultra","Ultra"]]),this._select("Particles","particles",[["off","Off"],["low","Low"],["full","Full"]]),this._select("Textures","textureQuality",[["low","Low"],["medium","Medium"],["high","High"],["ultra","Ultra"]]),this._select("Ground detail","groundDetail",[["low","Low"],["medium","Medium"],["high","High"]]),this._toggle("Anti-aliasing","antialias","SMAA pass. Cheap, but not free."),this._slider("Render scale","renderScale",.35,2,.05,u=>`${Math.round(u*100)}%`,"100% is your display’s own resolution, retina included."),this._toggle("Adaptive quality","autoQuality","Quietly drops render scale if frames get expensive."),this._slider("Scatter","scatterDensity",0,1,.05,u=>`${Math.round(u*100)}%`),this._slider("Max bots","maxAgents",10,200,10,u=>String(u)),this._toggle("Stars","stars")),e.appendChild(n);const r=Ss("World");this.worldIcons=[];for(const{name:u,planets:f}of kc){const p=document.createElement("h4");p.className="planet-group",p.textContent=u;const m=document.createElement("div");m.className="planets";for(const g of f){const w=Wt[g]??kf[g],b=document.createElement("button");b.type="button",b.className="planet",b.title=w.blurb;const y=$i(w.sky?.top??2907292),C=$i(w.ground.high);b.innerHTML=`<i class="world-icon-slot" style="--slot-sky:${y};--slot-ground:${C}"></i><span>${w.name}</span>`+(hl(g)?`<i class="pro-lock" title="Part of Threadnauts Pro">${de.lock}</i>`:""),this.worldIcons.push({slot:b.firstElementChild,planet:w}),b.addEventListener("click",()=>this._worldOpen(g)?this._chooseWorld(g):this.showUpgrade(w)),m.appendChild(b),this.controls.push({el:b,sync:()=>{b.setAttribute("aria-pressed",String(this.settings.get("planet")===g)),b.classList.toggle("locked",!this._worldOpen(g))}})}r.append(p,m)}const o=document.createElement("h4");o.className="planet-group",o.textContent="Objects in the sky",r.append(o,Fa([{id:"realistic",label:"More realistic",title:"Real sizes, with small moons drawn a little larger so they show up."},{id:"cinematic",label:"More cinematic",title:"Bigger and more detailed, the way films frame them."}],()=>this.settings.get("skyBodies"),u=>this.settings.set("skyBodies",u),this.controls)),e.appendChild(r);const a=Ss("Lighting");a.append(Fa([...Oi.map(u=>({id:u.id,label:u.label})),{id:"live",label:"Live"}],()=>this.settings.get("clockTime")?"live":OC(this.settings.get("timeOfDay")),u=>{this.settings.set("autoTime",!1),this.settings.set("clockTime",u==="live"),u==="live"?this.settings.set("timeOfDay",lm()):this.settings.set("timeOfDay",Oi.find(f=>f.id===u).value)},this.controls),this._slider("Time of day","timeOfDay",0,1,.005,FC,void 0,()=>{this.settings.set("clockTime",!1)}),this._toggle("Cycle day/night","autoTime","Runs the clock forward on its own. Ignored while the sky is following this machine’s clock."),this._slider("Cycle length","dayLength",30,900,30,u=>`${Math.round(u/60)}m`),this._toggle("Environment light","ibl","Image-based lighting taken from this planet’s own sky. Metals get something to reflect."),this._slider("Environment","iblIntensity",0,2,.05,u=>u.toFixed(2)),this._slider("Exposure","exposure",.4,2,.05,u=>u.toFixed(2)),this._slider("Bloom","bloomStrength",0,1.6,.02,u=>u.toFixed(2))),e.appendChild(a);const l=Ss("View");If||l.append(this._select("Open threads in","openIn",[["app","Desktop app"],["terminal","Terminal"]],"Terminal runs the harness’s own CLI in a new window, so the CLI has to be installed. THREADNAUTS_TERMINAL or $TERMINAL picks the emulator.")),l.append(this._toggle("Hide dormant repos","hideDormant","Takes a repo off the map when every thread in it has been quiet for three days. Its threads are untouched, and it comes back to the same ground the moment one wakes up."),this._toggle("Organization districts","districts","Puts the repos of each organization side by side in the base, with a glowing wall and the organization’s name when you point at one. Turning it off brings back the layout you had without districts. Each layout keeps the moves you made in it.")),l.append(this._select("Mouse buttons","leftDrag",[["orbit","Left orbits, right pans"],["pan","Left pans, right orbits"]],"Middle-drag and ⌃ or ⇧ + drag do the same as right-drag."),this._toggle("Follow selected bot","followSelected","Tracks the selected bot until you deselect. You can still pan, orbit, and zoom while it follows."),this._toggle("Return to isometric","autoFrame","Eases the angle back when you stop dragging."),this._slider("Field of view","fov",20,60,1,u=>`${u}°`),this._toggle("Project labels","showLabels"),this._toggle("Reduced motion","reducedMotion","Calms the bobbing and the camera easing."),this._toggle("Show FPS","showFps")),e.appendChild(l);const c=Ss("Look");c.append(this._slider("Ambient occlusion","ambientOcclusion",0,1,.05,u=>u===0?"Off":`${Math.round(u*100)}%`,"Soft shading in creases and where surfaces meet. Try 20–35% for a subtle effect; 0 turns it off."),this._slider("World curve","worldCurve",0,1,.05,u=>`${Math.round(u*100)}%`,"How far the ground bends away toward the horizon. The point under the cursor never moves."),this._toggle("Color grade","colorGrade","Saturation, warmth, lifted shadows, and a soft vignette on the finished frame."),this._slider("Saturation","saturation",.6,1.5,.05,u=>u.toFixed(2)),this._slider("Vignette","vignette",0,1,.05,u=>`${Math.round(u*100)}%`),this._toggle("Clouds","clouds","Cumulus drifting over worlds that have weather."),this._select("Wildlife","fauna",[["off","Off"],["low","Some"],["full","Full"]])),e.appendChild(c);const h=Ss("Sound"),d=u=>`${Math.round(u*100)}%`;h.append(this._toggle("Ambient sound","sound","A bed for each world, things calling out on their own clocks, and work you can hear where it is happening. Louder as you lean in."),this._slider("Master","masterVolume",0,1,.05,d),this._slider("Ambience","ambienceVolume",0,1,.05,d,"Beds, weather, and the shoreline."),this._slider("Wildlife","wildlifeVolume",0,1,.05,d,"Birds, fish, and other animals."),this._slider("Working","workingVolume",0,1,.05,d,"Bots at work on their projects."),this._slider("Drones","dronesVolume",0,1,.05,d,"Their hum in flight, and the parcels they drop."),this._slider("Ship","shipVolume",0,1,.05,d,"The lander’s hum."),this._slider("Bot voices","botVoicesVolume",0,1,.05,d,"Bots answering when you click them, getting annoyed when you keep clicking, confirming your prompts, asking for you when they need you, and reacting to errors."),this._slider("Bot machinery","machineryVolume",0,1,.05,d,"Servos whirring as bots turn their heads, a clunk when they sit down, and powering down to sleep or up as they leave the ship. Louder as you lean in.")),e.appendChild(h)}_licenseForm(e,t){const i=document.createElement("form");i.className="license-form",i.innerHTML=`<input class="license-key" type="text" placeholder="THREADCRUMBS-…" autocomplete="off" spellcheck="false" aria-label="License key"><button class="btn${e?" primary":""}" type="submit">Unlock</button>`;const n=document.createElement("p");n.className="license-message",n.setAttribute("role","status");const r=i.querySelector("input"),o=i.querySelector("button"),a=(l,c=!1)=>{qd(n,l),n.classList.toggle("err",c)};return i.addEventListener("submit",async l=>{if(l.preventDefault(),!o.disabled){o.disabled=!0,a("Checking your key…");try{const c=await this.actions.activateLicense(r.value),h=c.error?ql(c.error):t(c);if(h)return a(h,!0);r.value="",a("")}finally{o.disabled=!1}}}),{form:i,input:r,message:n,note:a}}_orgColor(e){const t=this.actions.orgAccent?.(e);return t===void 0?"":$i(t)}setThreadgauge(e){this._threadgauge!==e&&(this._threadgauge=e,this.$("#btn-threadgauge").hidden=!e,this.$("#btn-context").hidden=!e,e&&(this.$("#btn-threadgauge").href=e))}get hasThreadgauge(){return!!this._threadgauge}setContext(e){const t=e?.limit?Math.min(100,e.used/e.limit*100):null,i=t??0,n=this.$("#btn-context");n.querySelector(".gauge").dataset.level=t==null?"unknown":t>=90?"full":t>=70?"high":"ok",n.querySelector(".gauge-fill").setAttribute("stroke-dasharray",`${i} 100`),n.querySelector(".gauge-needle").style.transform=`rotate(${Vf+Nf*i/100}deg)`,n.querySelector(".ctx-mini-value").textContent=t==null?"—":`${Math.round(t)}%`}openInThreadgauge(){const e=this.selected?.thread?.id;if(!this._threadgauge||!e)return;const t=String(e).split(":errand:")[0];window.open(`${this._threadgauge}#thread=${encodeURIComponent(t)}`,Df)?.focus()}setLicense(e){const t=u5(e),i=!!this.actions.activateLicense;qd(this.licenseStatus,f5(e)),this.settingsKey.form.hidden=!i||!(t||da(e)),this.getPro.hidden=!da(e),this.$(".upgrade-key").hidden=!i,t&&this.settingsKey.note(t,!0)}_row(e,t){const i=document.createElement("div");i.className="row";const n=document.createElement("div");return n.className="label",n.innerHTML=`<span>${e}</span>${t?`<span class="hint">${t}</span>`:""}`,i.appendChild(n),i}_toggle(e,t,i){const n=this._row(e,i),r=document.createElement("button");return r.type="button",r.className="toggle",r.setAttribute("role","switch"),r.setAttribute("aria-label",e),r.addEventListener("click",()=>this.settings.set(t,!this.settings.get(t))),n.appendChild(r),this.controls.push({el:n,sync:()=>{r.setAttribute("aria-checked",String(!!this.settings.get(t))),n.classList.toggle("overridden",this.settings.isOverridden(t))}}),n}_select(e,t,i,n){const r=this._row(e,n),o=document.createElement("select");o.className="select";for(const[a,l]of i){const c=document.createElement("option");c.value=a,c.textContent=l,o.appendChild(c)}return o.addEventListener("change",()=>this.settings.set(t,o.value)),r.appendChild(o),this.controls.push({el:r,sync:()=>{o.value=String(this.settings.get(t)),r.classList.toggle("overridden",this.settings.isOverridden(t))}}),r}_slider(e,t,i,n,r,o,a,l){const c=this._row(e,a),h=document.createElement("div");h.style.cssText="display:flex;align-items:center;gap:8px";const d=document.createElement("input");d.type="range",d.setAttribute("aria-label",e),d.className="slider",d.min=i,d.max=n,d.step=r;const u=document.createElement("span");return u.className="value",d.addEventListener("input",()=>{l?.(),this.settings.set(t,Number(d.value))}),h.append(d,u),c.appendChild(h),this.controls.push({el:c,sync:()=>{const f=Number(this.settings.get(t));document.activeElement!==d&&(d.value=String(f)),u.textContent=o(f),c.classList.toggle("overridden",this.settings.isOverridden(t))}}),c}_buildAvatar(){const e=this.$(".thread-pop .avatar canvas");e.width=108,e.height=108,this.avatarCtx=e.getContext("2d"),this.avatarTmp=document.createElement("canvas"),this.avatarTmp.width=108,this.avatarTmp.height=108,this.avatarTmpCtx=this.avatarTmp.getContext("2d"),this._avatarState={frame:-1,color:""}}_wire(){const e=(l,c,h)=>this.$(l).addEventListener(c,h);e("#btn-settings","click",()=>this.toggleSettings());const t=this.$(".side .toolbar"),i=this.$(".side .grab");let n=null;const r=l=>{!this.isPhone()||l.target.closest(".btn, .brand")||(n=l.clientY)},o=l=>{if(n===null)return;const c=l.clientY-n;n=null,Math.abs(c)>24?this.toggleSheet(c<0):l.target.closest(".btn, .brand")||this.toggleSheet()};for(const l of[t,i])l.addEventListener("pointerdown",r),l.addEventListener("pointerup",o);e("#btn-close-settings","click",()=>this.toggleSettings(!1)),e("#btn-hide","click",()=>this.toggleUi()),e("#btn-help","click",()=>this.toggleHelp()),e("#btn-shot","click",()=>this.actions.screenshot?.()),e("#btn-home","click",()=>this.actions.resetView?.()),e("#btn-next","click",()=>this.actions.focusStatus?.("wanted")),e("#btn-orbit","click",()=>this.setOrbit(this.actions.toggleOrbit?.())),e("#btn-planet","click",()=>this.actions.cyclePlanet?.()),e("#btn-time","click",()=>this.actions.cycleTime?.()),e("#btn-sound","click",()=>this.settings.set("sound",!this.settings.get("sound"))),e("#btn-open","click",()=>this.actions.openThread?.()),e("#btn-viewed","click",()=>this.actions.markViewed?.()),e("#btn-archive","click",()=>this.actions.archiveThread?.()),e("#btn-deselect","click",()=>this.actions.select?.(null)),e("#btn-context","click",()=>this.openInThreadgauge()),e("#btn-follow","click",()=>this.settings.set("followSelected",!this.settings.get("followSelected"))),e("#btn-new-session","click",()=>this.actions.newConversation?.()),e("#btn-reveal","click",()=>this.actions.revealProject?.()),e("#btn-copy-path","click",()=>this.actions.copyProjectPath?.()),e("#btn-hide-project","click",()=>this.actions.hideProject?.()),e("#btn-locate","click",()=>this.actions.focusProject?.(this.project?.name)),e("#btn-close-project","click",()=>this.actions.closeProject?.());const a=this.$(".projects");a.addEventListener("pointerover",l=>{const c=l.target.closest(".repo, .org-row");this.actions.hoverOrg?.(c?.dataset.org??null),this.actions.hoverProject?.(c?.dataset.project??null)}),a.addEventListener("pointerleave",()=>{this.actions.hoverOrg?.(null),this.actions.hoverProject?.(null)}),e(".help","click",l=>{l.target===this.$(".help")&&this.toggleHelp(!1)}),this.$(".help .sheet").addEventListener("click",l=>l.stopPropagation()),e("#btn-help-close","click",()=>this.toggleHelp(!1)),e("#btn-record","click",()=>this.actions.record?.()),e(".upgrade","click",l=>{l.target===this.$(".upgrade")&&this.closeUpgrade()}),this.$(".upgrade .sheet").addEventListener("click",l=>l.stopPropagation()),e("#btn-get-pro","click",()=>this.closeUpgrade()),e("#btn-upgrade-later","click",()=>this.closeUpgrade()),this.upgradeKey=this._licenseForm(!1,l=>{const c=this._upgradePlanet;return this._worldOpen(c.id)?(this.closeUpgrade(),this._chooseWorld(c.id),this.toast("Threadnauts Pro is unlocked"),""):Vh(l)}),this.$(".upgrade-key").append(this.upgradeKey.form,this.upgradeKey.message),this.settings.onChange(()=>this.syncSettings())}syncSettings(){const e=!!this.settings.get("followSelected");this.$("#btn-follow").setAttribute("aria-pressed",String(e)),this.$("#btn-follow").title=e?"Stop following selected bot":"Follow selected bot";for(const r of this.controls)r.sync();const t=this.settings.get("leftDrag")!=="pan";this.$("#help-drag").textContent=t?"Tilt & rotate":"Drag the ground",this.$("#help-right-drag").textContent=t?"Drag the ground":"Tilt & rotate",this.$("#help-nav").textContent=t?"Drag to tilt and rotate, right-drag to move the ground itself, and scroll to zoom in on whatever is under the cursor.":"Navigation works like Google Earth — drag the ground itself, right-drag to tilt, scroll to zoom in on whatever is under the cursor.",this.$(".fps").classList.toggle("on",!!this.settings.get("showFps"));const i=!!this.settings.get("sound"),n=this.$("#btn-sound");n.innerHTML=i?de.sound:de.soundOff,n.setAttribute("aria-pressed",String(i)),n.title=i?"Mute (M)":"Unmute (M)"}setStats(e){for(const t of Ba){const i=ac(t.key),n=i&&i.length>1?i.reduce((o,a)=>o+(e[a]??0),0):e[t.key]??0,r=this.statEls[t.key];this._last["stat:"+t.key]!==n&&(this._last["stat:"+t.key]=n,r.querySelector(".n").textContent=String(n),r.querySelector(".lbl").textContent=n===1&&t.one?t.one:t.label,r.dataset.empty=String(n===0))}}setLegend(e,t=null,i=[]){this._legendArgs=[e,t,i];const{orgs:n,loose:r,grouped:o}=Zg([...e,...i]);this._groupedOrgs=o;const a=e.map(c=>`${c.name}:${c.count}:${c.accent}:${c.urgent?1:0}:${c.org||""}:${c.label||""}`).join("|")+`~${t}~`+i.map(c=>`${c.name}:${c.count}:${c.off}:${c.org||""}:${c.label||""}`).join("|");if(this._last.legend===a)return;this._last.legend=a;const l=this.$(".projects");l.innerHTML="";for(const c of n){const h=c.repos.filter(f=>f.off).length,d=document.createElement("div");d.className=`org-row${h===c.repos.length?" off-map":""}`,d.dataset.org=c.name,d.title=`${c.repos.length} repo${c.repos.length===1?"":"s"} and ${c.count} thread${c.count===1?"":"s"} in ${c.name}`+(h?`, ${h} off the map`:""),d.innerHTML=`<i class="icon org-icon" style="color:${this._orgColor(c.name)}">${de.org}</i><span class="n">${It(c.name)}</span>`+(c.urgent?'<i class="alarm"></i>':"")+`<span class="count">${c.count}</span>`;const u=document.createElement("div");u.className="org-repos";for(const f of c.repos)u.appendChild(this._repoRow(f,!0,t));l.append(d,u)}for(const c of r)l.appendChild(this._repoRow(c,!1,t));this.$(".sec-head .sec-count").textContent=String(e.length+i.length)}_repoRow(e,t,i){const n=It(t&&e.label||e.name);if(e.off){const o=e.off==="quiet",a=document.createElement("div");a.className="repo off-map",a.title=o?`Nothing has happened in ${e.name} for three days, so Hide dormant repos took it off the map`:`You hid ${e.name} from the map. Its threads keep running.`,a.innerHTML=`<i class="icon repo-icon">${de.eyeOff}</i><span class="n">${n}</span><span class="count">${e.count}</span>`;const l=document.createElement("button");return l.type="button",l.className="btn ghost show-repo",l.title=o?"Show quiet repos again (turns off Hide dormant repos)":`Put ${e.name} back on the map`,l.textContent="Show",l.addEventListener("click",()=>{if(!o)return this.actions.unhideProject?.(e.name);this.settings.set("hideDormant",!1),this.toast("Showing quiet repos again")}),a.appendChild(l),a}const r=document.createElement("button");return r.type="button",r.className="repo",r.dataset.project=e.name,r.title=`${e.count} thread${e.count===1?"":"s"} in ${e.name}`,r.setAttribute("aria-pressed",String(e.name===i)),r.innerHTML=`<i class="icon repo-icon" style="color:${$i(e.accent)}">${de.folder}</i><span class="n">${n}</span>`+(e.urgent?'<i class="alarm"></i>':"")+`<span class="count">${e.count}</span>`,r.addEventListener("click",()=>this.actions.pickProject?.(e.name)),r}setProject(e){const t=this.$(".side");if(!e){if(this.project=null,this._last.project===null)return;this._last.project=null,t.classList.remove("drilled"),t.classList.remove("open"),this._syncLayout();return}this.project=e;const i=e.org&&this._groupedOrgs?.has(e.org)?e.org:null,n=this.$("#btn-close-project"),r=i||"All repos";n.dataset.label!==r&&(n.dataset.label=r,n.innerHTML=`${de.back} ${It(r)}`),this.isPhone()&&!this.selected&&!t.classList.contains("open")&&(t.classList.add("open"),this._syncLayout());const o=`${e.name}~${e.label}~${i}~${e.path}~${e.accent}~${e.selectedId}~${Math.floor(Date.now()/6e4)}~`+e.threads.map(u=>`${u.id}:${u.status}:${u.title}:${u.lastActivityAt}`).join("|");if(t.classList.add("drilled"),this._last.project===o)return;this._last.project=o,this.$(".side .who .repo-icon").style.color=$i(e.accent),this.$(".side .name").textContent=i&&e.label||e.name;const a=this.$(".side .path");a.textContent=e.path?BC(e.path):"folder unknown",a.title=e.path||"",this.$("#btn-new-session").disabled=!e.path,this.$("#btn-reveal").disabled=!e.path,this.$("#btn-copy-path").disabled=!e.path;const l=e.threads.length,c=["asking","done","error"].map(u=>[Ba.find(f=>f.key===u),e.threads.filter(f=>f.status===u).length]).filter(([,u])=>u).map(([u,f])=>`<span class="want ${u.cls}">${f} ${u.label.toLowerCase()}</span>`);this.$(".side .threads-head").innerHTML=`<span>${l} thread${l===1?"":"s"}</span>`+(c.length?`<span class="wants">${c.join(" · ")}</span>`:"");const h=this.$(".side .threads"),d=h.scrollTop;h.innerHTML="";for(const u of e.threads){const f=document.createElement("button");if(f.type="button",f.className=`thread ${Oa(u.status)}`,f.setAttribute("aria-pressed",String(u.id===e.selectedId)),f.title=Fh[u.status]||u.status,f.innerHTML=`<i class="pip"></i><span class="t">${It(u.title||"Untitled thread")}</span><span class="when">${Bf(u.lastActivityAt)}</span>`+(u.worktree?`<span class="wt"><i class="icon">${de.worktree}</i>${It(u.worktree)}</span>`:""),f.addEventListener("click",()=>this.actions.focusThread?.(u.id)),h.appendChild(f),u.id===e.selectedId&&this._scrolledTo!==u.id){this._scrolledTo=u.id;const p=f;requestAnimationFrame(()=>{const m=p.offsetTop,g=m+p.offsetHeight;m<h.scrollTop?h.scrollTop=m:g>h.scrollTop+h.clientHeight&&(h.scrollTop=g-h.clientHeight)})}}h.scrollTop=d,e.selectedId||(this._scrolledTo=null)}setSelection(e,t){const i=this.$(".thread-pop");if(this.$("#btn-new-session").classList.toggle("primary",!e||!t),!e||!t){i.classList.remove("on"),this.selected=null;return}this.selected={agent:e,thread:t},i.classList.add("on"),this.isPhone()&&this.toggleSheet(!1);const n=this.$(".thread-pop .title-text");n.textContent=t.title||"Untitled thread",n.title=t.title||"";const r=Fh[e.status]||e.status,o=t.harnessName||"";this.$(".thread-pop .title-harness").innerHTML=zC(t.harness,o),i.dataset.status=Oa(e.status),this.$(".thread-pop .card-status").innerHTML=`<span class="status" data-status="${Oa(e.status)}"><i class="pip"></i>${It(r)}</span>`,this.$(".thread-pop .now").textContent=PC(e.status,t);const a=t.project?this.actions.districtOf?.(t.project):null;this.$(".thread-pop .meta-row").innerHTML=LC(t,a).map(RC).join("");const l=this.$("#btn-open");l.dataset.harness!==o&&(l.dataset.harness=o,l.innerHTML=`${de.open} ${o?`Open ${It(o)}`:"Open"}`,l.title=`Open this thread in ${o||"the harness it came from"} (Enter)`),l.disabled=t.canOpen===!1,this.$("#btn-viewed").hidden=!t.unread,this._cardSize={w:i.offsetWidth,h:i.offsetHeight}}placeCard(e){const t=this.$(".thread-pop");if(!e||!this.selected){this._cardOn&&(this._cardOn=!1,t.classList.remove("on"));return}if(this.isPhone()){this._cardOn||(this._cardOn=!0,t.classList.add("on"));return}const i=this._cardSize||{w:296,h:140},n=12,r=26,o=window.innerWidth-n-(this._sideWidth||0);let a=!1;const l=e.reach??0;let c=e.x+l+r;c+i.w>o&&(c=Math.min(e.x-l-r-i.w,o-i.w),a=!0,c<n&&(c=Math.min(Math.max(n,e.x-i.w/2),o-i.w)));const h=Math.min(Math.max(n,e.y-i.h/2),window.innerHeight-n-i.h);this._cardOn||(this._cardOn=!0,t.classList.add("on"));const d=Math.round(c),u=Math.round(h);(d!==this._cardX||u!==this._cardY)&&(this._cardX=d,this._cardY=u,t.style.transform=`translate3d(${d}px, ${u}px, 0)`),a!==this._cardFlip&&(this._cardFlip=a,t.classList.toggle("flip",a));const f=Math.min(Math.max(14,e.y-u),i.h-14);f!==this._cardNib&&(this._cardNib=f,t.style.setProperty("--nib-y",`${Math.round(f)}px`))}_syncLayout(){const e=this.el.clientWidth,t=this.el.clientHeight,i=this.$(".side");let n=0,r=0,o=0,a=0;if(this.isPhone()){const c=parseFloat(getComputedStyle(this.el).getPropertyValue("--peek"))||0,h=i.offsetTop+(i.classList.contains("open")?0:i.offsetHeight-c);r=Math.max(0,t-h)}else n=Math.max(0,e-i.offsetLeft);const l=this.$(".rail");l.offsetWidth<l.offsetHeight?o=l.offsetLeft+l.offsetWidth:a=l.offsetTop+l.offsetHeight,this._sideWidth=this.visible?n:0,this.el.style.setProperty("--side",`${this._sideWidth}px`),this.actions.viewportChanged?.({width:e,height:t,right:n,bottom:r,left:o,top:a,visible:this.visible})}updateAvatar(e){if(!this.selected||!e)return;const t=this.selected.agent,i=t.faceFrame??B.idle,n=t.eye,r=$C(n);if(this._avatarState.frame===i&&this._avatarState.color===r)return;this._avatarState={frame:i,color:r};const o=108,a=e.width/Kt,l=i%Kt*a,c=Math.floor(i/Kt)*(e.height/Gr),h=this.avatarTmpCtx;h.globalCompositeOperation="source-over",h.clearRect(0,0,o,o),h.drawImage(e,l,c,a,a,0,0,o,o),h.globalCompositeOperation="multiply",h.fillStyle=r,h.fillRect(0,0,o,o),h.globalCompositeOperation="source-over";const d=this.avatarCtx;d.fillStyle="#06070c",d.fillRect(0,0,o,o),d.drawImage(this.avatarTmp,0,0),d.globalAlpha=.2,d.fillStyle="#000";for(let u=0;u<o;u+=3)d.fillRect(0,u,o,1);d.globalAlpha=1}setFps(e,t,i){if(!this.settings.get("showFps"))return;const n=this.$(".fps"),r=Math.round(e.fps);this._last.fps===r&&this._last.calls===e.drawCalls||(this._last.fps=r,this._last.calls=e.drawCalls,n.innerHTML=`<b>${r}</b> fps · ${e.frameMs.toFixed(1)} ms<br>${e.drawCalls} draws · ${(e.triangles/1e3).toFixed(0)}k tris<br>${t.bw}×${t.bh} (${Math.round(t.scale/(window.devicePixelRatio||1)*100)}%)`+(i?`<br>${i}`:""))}hint(e,t=3200){const i=this.$(".hint-pill");i.textContent=e,i.classList.add("on"),clearTimeout(this._hintTimer),this._hintTimer=setTimeout(()=>i.classList.remove("on"),t)}toast(e,t="",i=null){const n=document.createElement("div");if(n.className=`toast panel ${t}`,n.textContent=e,i){const r=document.createElement("button");r.type="button",r.className="btn ghost toast-action",r.textContent=i.label,r.addEventListener("click",()=>{i.run(),n.remove()}),n.classList.add("with-action"),n.appendChild(r)}this.$(".toasts").appendChild(n),setTimeout(()=>{n.classList.add("leaving"),setTimeout(()=>n.remove(),260)},i?7e3:3600)}setOrbit(e){this.$("#btn-orbit").setAttribute("aria-pressed",String(!!e))}isPhone(){return window.matchMedia("(max-width: 600px)").matches}toggleSheet(e){const t=this.$(".side"),i=e??!t.classList.contains("open");return t.classList.toggle("open",i),this._syncLayout(),i}toggleSettings(e){const t=this.$(".settings"),i=e??t.classList.contains("closed");t.classList.toggle("closed",!i),this.$("#btn-settings").setAttribute("aria-pressed",String(i));const n=this.$(".side");n.classList.toggle("covered",i),n.inert=i,t.inert=!i,i&&this._paintWorldIcons(),i?this.$("#btn-close-settings").focus({preventScroll:!0}):t.contains(document.activeElement)&&this.$("#btn-settings").focus({preventScroll:!0})}_paintWorldIcons(){for(const{slot:e,planet:t}of this.worldIcons.splice(0))e.outerHTML=this._iconFor(t)}_iconFor(e){const t=Wt[e.id],i=_C[`./world-icons/${e.id}.svg`];return i?`<img class="world-icon" src="${i}" alt="" draggable="false">`:vC(t??e)}_worldOpen(e){return this.actions.worldOpen?this.actions.worldOpen(e):!0}_chooseWorld(e){this.actions.chooseWorld?this.actions.chooseWorld(e):this.settings.set("planet",e)}showUpgrade(e){const t=kc.flatMap(i=>i.planets).filter(hl).length;this.$(".upgrade .upgrade-world").innerHTML=this._iconFor(e),this.$("#upgrade-title").textContent=`${e.name} is a Pro world`,this.$(".upgrade p.sub").textContent=`Threadnauts Pro unlocks all ${t} Pro worlds, plus every new world as it arrives.`,this._upgradePlanet=e,this.upgradeKey.input.value="",this.upgradeKey.note(""),this.$(".upgrade").classList.add("open"),this.$("#btn-get-pro").focus({preventScroll:!0})}setRecording(e){const t=this.$("#btn-record");t.classList.toggle("recording",e),t.setAttribute("aria-pressed",String(e)),t.innerHTML=e?de.stop:de.record,t.title=e?"Stop recording (R)":"Record video (R)",this.$(".rec-chip").hidden=!e,this._recordTime="",e&&this.setRecordTime(0)}setRecordTime(e){const t=gy(e);t!==this._recordTime&&(this._recordTime=t,this.$(".rec-chip span").textContent=t)}closeUpgrade(){this.$(".upgrade").classList.remove("open")}get upgradeOpen(){return this.$(".upgrade").classList.contains("open")}toggleHelp(e){const t=this.$(".help"),i=e??!t.classList.contains("open");t.classList.toggle("open",i)}toggleUi(e){return this.visible=e??!this.visible,this.el.classList.toggle("hidden",!this.visible),this.$("#btn-hide").innerHTML=this.visible?de.eye:de.eyeOff,this.actions.uiVisibility?.(this.visible),this._syncLayout(),this.visible||this.toggleHelp(!1),this.visible}removeBoot(){const e=document.querySelector(".boot");e&&(e.classList.add("gone"),setTimeout(()=>e.remove(),550))}}function qd(s,e){const[t,...i]=e.split(ha);if(s.textContent=t,!i.length)return;const n=document.createElement("a");n.href=d5,n.target="_blank",n.rel="noopener",n.textContent=ha,s.append(n,i.join(ha))}function Ss(s,e){const t=document.createElement("div");return t.className="group",t.innerHTML=`<h3>${s}</h3>`,e&&t.appendChild(e),t}function Fa(s,e,t,i){const n=document.createElement("div");n.className="chips";const r=[];for(const o of s){const a=document.createElement("button");a.type="button",a.className="chip",a.textContent=o.label,o.title&&(a.title=o.title),a.addEventListener("click",()=>t(o.id)),n.appendChild(a),r.push([o.id,a])}return i.push({el:n,sync:()=>{const o=e();for(const[a,l]of r)l.setAttribute("aria-pressed",String(a===o))}}),n}const $i=s=>"#"+(s>>>0).toString(16).padStart(6,"0").slice(-6);function $C(s){const e=Math.max(s.r,s.g,s.b,1),t=i=>Math.round(Math.pow(Math.min(1,i/e),1/2.2)*255);return`rgb(${t(s.r)},${t(s.g)},${t(s.b)})`}const Df="threadgauge",Gd="M-19.8,19.8 A28,28 0 1 1 19.8,19.8",Vf=135,Nf=270,Wf=s=>`<svg class="gauge gauge-mini" viewBox="-36 -36 72 72" aria-hidden="true" data-level="${s==null?"unknown":"ok"}"><circle class="gauge-dial" r="35"/><path class="gauge-track" d="${Gd}" pathLength="100"/><path class="gauge-fill" d="${Gd}" pathLength="100" stroke-dasharray="${s??0} 100"/><line class="gauge-needle" x1="0" y1="0" x2="21" y2="0" style="transform: rotate(${Vf+Nf*(s??0)/100}deg)"/><circle class="gauge-hub" r="7"/></svg>`,AC=Wf(null),EC=Wf(200/3);function PC(s,e){const t=Bf(e.lastActivityAt);return s==="working"?`Active ${t}`:s==="delegating"?"Waiting on agents":s==="asking"?"Waiting for your answer":s==="done"?`Finished ${t} · your turn`:s==="error"?"Stopped on an error":s==="celebrating"?`Pull request merged · ${t}`:`Last active ${t}`}function zC(s,e){return!s&&!e?"":`<i class="harness-mark" data-harness="${It(s||"")}" title="${It(e||s)}">${It(MC(s,e))}</i>`}function LC(s,e=null){return[e&&{kind:"org",icon:de.org,text:e.org,title:`Organization ${e.org}`,color:$i(e.accent)},s.project&&{kind:"folder",icon:de.folder,text:e?e.label:s.project,title:s.projectPath||s.project},s.worktree&&{kind:"worktree",icon:de.worktree,text:s.worktree,title:`Worktree ${s.worktree}`},s.gitBranch&&{kind:"branch",icon:de.branch,text:s.gitBranch,title:`Branch ${s.gitBranch}`},s.model&&{kind:"model",icon:de.model,text:kC(s.model),title:[s.model,Zd(s.effort)].filter(Boolean).join(" · "),after:s.effort?Ud(s.effort):""},!s.model&&s.effort&&{kind:"effort",icon:Ud(s.effort),text:"",title:Zd(s.effort)}].filter(Boolean)}const Zd=s=>s?`Effort: ${CC[s]||s}`:"",RC=s=>`<span class="meta meta-${s.kind}" title="${It(s.title)}"><i class="icon"${s.color?` style="color:${s.color}"`:""}>${s.icon}</i>`+(s.text?`<span class="meta-text">${It(s.text)}</span>`:"")+(s.after?`<i class="icon">${s.after}</i>`:"")+"</span>";function It(s){return String(s).replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}function Oa(s){return s==="working"?"working":s==="delegating"?"delegating":s==="asking"?"asking":s==="done"?"done":s==="error"?"error":s==="celebrating"?"celebrating":"idle"}function Qs(s){return`<svg viewBox="0 0 24 24"><path d="${v0[s]}"/></svg>`}function BC(s,e=30){const t=s.replace(/^\/Users\/[^/]+/,"~");if(t.length<=e)return t;const i=t.split("/");let n=i.pop()||"";for(;i.length;){const r=i.pop();if(n.length+r.length+3>e)break;n=`${r}/${n}`}return`…/${n}`}function FC(s){const e=s*24*60,t=Math.floor(e/60)%24,i=Math.floor(e%60);return`${String(t).padStart(2,"0")}:${String(i).padStart(2,"0")}`}function OC(s){let e=Oi[0],t=1/0;for(const i of Oi){const n=Math.min(Math.abs(i.value-s),1-Math.abs(i.value-s));n<t&&(t=n,e=i)}return t<.03?e.id:null}const IC=`
|
|
2207
|
-
<div class="rec-chip" hidden><i></i><span>0:00</span></div>
|
|
2208
|
-
<aside class="side panel">
|
|
2209
|
-
<div class="grab"></div>
|
|
2210
|
-
<a class="brand" href="https://threadnauts.io" target="_blank" rel="noopener" title="threadnauts.io">${TC}</a>
|
|
2211
|
-
<header class="toolbar">
|
|
2212
|
-
<button class="btn icon ghost" id="btn-shot" title="Screenshot (P)">${de.camera}</button>
|
|
2213
|
-
<button class="btn icon ghost" id="btn-record" title="Record video (R)" aria-pressed="false">${de.record}</button>
|
|
2214
|
-
<button class="btn icon ghost" id="btn-help" title="Help (?)">${de.help}</button>
|
|
2215
|
-
<button class="btn icon ghost" id="btn-hide" title="Hide all UI (H)">${de.eye}</button>
|
|
2216
|
-
<button class="btn icon ghost" id="btn-settings" title="Settings (S)" aria-pressed="false">${de.settings}</button>
|
|
2217
|
-
</header>
|
|
2218
|
-
|
|
2219
|
-
<div class="stats">
|
|
2220
|
-
<a class="btn btn-compact" id="btn-threadgauge" target="${Df}" title="Open Threadgauge in its own tab" hidden>${EC} Open Threadgauge dashboard</a>
|
|
2221
|
-
</div>
|
|
2222
|
-
|
|
2223
|
-
<div class="side-body">
|
|
2224
|
-
<div class="projects-pane">
|
|
2225
|
-
<div class="sec-head"><span class="sec-label">Repos</span><span class="sec-count">0</span></div>
|
|
2226
|
-
<div class="projects"></div>
|
|
2227
|
-
</div>
|
|
2228
|
-
|
|
2229
|
-
<div class="project-detail">
|
|
2230
|
-
<button class="btn ghost back" id="btn-close-project" title="Back to every repo (Esc)">${de.back} All repos</button>
|
|
2231
|
-
<div class="who">
|
|
2232
|
-
<i class="icon repo-icon">${de.folder}</i>
|
|
2233
|
-
<div class="text">
|
|
2234
|
-
<div class="name"></div>
|
|
2235
|
-
<div class="path"></div>
|
|
2236
|
-
</div>
|
|
2237
|
-
<button class="btn icon ghost" id="btn-locate" title="Fly to this zone">${de.locate}</button>
|
|
2238
|
-
</div>
|
|
2239
|
-
<div class="project-actions">
|
|
2240
|
-
<button class="btn primary" id="btn-new-session" title="Start a new thread in this folder (C)">${de.plus} New conversation</button>
|
|
2241
|
-
<div class="pair">
|
|
2242
|
-
<button class="btn" id="btn-reveal" title="Show this folder in ${jd}">${de.folder} ${jd}</button>
|
|
2243
|
-
<button class="btn" id="btn-copy-path" title="Copy the folder path">${de.copy} Copy path</button>
|
|
2244
|
-
</div>
|
|
2245
|
-
<button class="btn" id="btn-hide-project" title="Take this repo off the map. Its threads keep running, and it stays in the repo list with a Show button.">${de.eyeOff} Hide from colony</button>
|
|
2246
|
-
</div>
|
|
2247
|
-
<div class="threads-head"></div>
|
|
2248
|
-
<div class="threads"></div>
|
|
2249
|
-
</div>
|
|
2250
|
-
</div>
|
|
2251
|
-
|
|
2252
|
-
</aside>
|
|
2253
|
-
|
|
2254
|
-
<div class="rail panel">
|
|
2255
|
-
<button class="btn icon" id="btn-home" title="Reset the view (0)">${de.home}</button>
|
|
2256
|
-
<button class="btn icon" id="btn-next" title="Next bot waiting on you (N)">${de.next}</button>
|
|
2257
|
-
<div class="sep"></div>
|
|
2258
|
-
<button class="btn icon" id="btn-orbit" title="Orbit mode — sweep around the colony (O)" aria-pressed="false">${de.orbit}</button>
|
|
2259
|
-
<button class="btn icon" id="btn-planet" title="Change planet (Tab)">${de.globe}</button>
|
|
2260
|
-
<button class="btn icon" id="btn-time" title="Change the time of day (L)">${de.sun}</button>
|
|
2261
|
-
<div class="sep"></div>
|
|
2262
|
-
<button class="btn icon" id="btn-sound" title="Mute (M)" aria-pressed="true">${de.sound}</button>
|
|
2263
|
-
</div>
|
|
2264
|
-
|
|
2265
|
-
<div class="settings panel closed" inert>
|
|
2266
|
-
<header>Settings <button class="btn icon ghost" id="btn-close-settings" title="Close">${de.close}</button></header>
|
|
2267
|
-
<div class="body"></div>
|
|
2268
|
-
</div>
|
|
2269
|
-
|
|
2270
|
-
<div class="thread-pop panel">
|
|
2271
|
-
<i class="nib"></i>
|
|
2272
|
-
<div class="top">
|
|
2273
|
-
<div class="portrait">
|
|
2274
|
-
<div class="avatar"><canvas></canvas></div>
|
|
2275
|
-
</div>
|
|
2276
|
-
<div class="info">
|
|
2277
|
-
<div class="card-head">
|
|
2278
|
-
<div class="card-status"></div>
|
|
2279
|
-
<button type="button" class="ctx-mini" id="btn-context" title="Open in Threadgauge dashboard" aria-label="Open in Threadgauge dashboard" hidden><span class="ctx-mini-value"></span>${AC}</button>
|
|
2280
|
-
<button class="btn icon ghost" id="btn-deselect" title="Deselect (Esc)" aria-label="Deselect">${de.close}</button>
|
|
2281
|
-
</div>
|
|
2282
|
-
<div class="title"><span class="title-harness"></span><span class="title-text"></span></div>
|
|
2283
|
-
</div>
|
|
2284
|
-
</div>
|
|
2285
|
-
<div class="meta-row"></div>
|
|
2286
|
-
<div class="now"></div>
|
|
2287
|
-
<div class="actions">
|
|
2288
|
-
<button class="btn primary" id="btn-open" title="Open this thread in the harness it came from (Enter)">${de.open} Open</button>
|
|
2289
|
-
<button class="btn icon" id="btn-follow" title="Follow selected bot" aria-label="Follow selected bot" aria-pressed="false">${de.locate}</button>
|
|
2290
|
-
<button class="btn icon" id="btn-viewed" title="Mark viewed: stop this thread asking for you until it moves on again (V)" aria-label="Mark viewed">${de.eye}</button>
|
|
2291
|
-
<button class="btn icon" id="btn-archive" title="Archive: this bot flies back to the ship (A)" aria-label="Archive">${de.archive}</button>
|
|
2292
|
-
</div>
|
|
2293
|
-
</div>
|
|
2294
|
-
|
|
2295
|
-
<div class="toasts"></div>
|
|
2296
|
-
<div class="fps panel"></div>
|
|
2297
|
-
<div class="hint-pill panel"></div>
|
|
2298
|
-
|
|
2299
|
-
<div class="help" role="dialog" aria-modal="true" aria-label="Help">
|
|
2300
|
-
<div class="sheet panel">
|
|
2301
|
-
<div class="help-body">
|
|
2302
|
-
<h2>${Ff}</h2>
|
|
2303
|
-
<p class="sub">Every coding-agent thread on this machine is a bot. They fly out of the ship, claim a plot for their repo, and build. Click one to open its thread; click a zone — its deck or its name — for the repo itself, and start a new conversation there. Hide a repo from that panel if you would rather not see it — its threads stay in your harness, and you can show it again from the list. <span id="help-nav"></span></p>
|
|
2304
|
-
<div class="help-grid">
|
|
2305
|
-
<section>
|
|
2306
|
-
<h3>The view</h3>
|
|
2307
|
-
<div class="k"><span id="help-drag"></span><kbd>drag</kbd></div>
|
|
2308
|
-
<div class="k"><span id="help-right-drag"></span><kbd>right-drag</kbd></div>
|
|
2309
|
-
<div class="k"><span> </span><kbd>⌃ or ⇧ + drag</kbd></div>
|
|
2310
|
-
<div class="k"><span>Zoom to cursor</span><kbd>scroll</kbd></div>
|
|
2311
|
-
<div class="k"><span>Move / zoom</span><kbd>arrows</kbd> <kbd>+ −</kbd></div>
|
|
2312
|
-
<div class="k"><span>Reset view</span><kbd>0</kbd></div>
|
|
2313
|
-
<div class="k"><span>Orbit mode</span><kbd>O</kbd></div>
|
|
2314
|
-
<div class="k"><span>Change world</span><kbd>Tab</kbd></div>
|
|
2315
|
-
<div class="k"><span>Time of day</span><kbd>L</kbd></div>
|
|
2316
|
-
<div class="k"><span>Hide all UI</span><kbd>H</kbd> <kbd>${Of?"⌘":"Ctrl"}\\</kbd></div>
|
|
2317
|
-
</section>
|
|
2318
|
-
<section>
|
|
2319
|
-
<h3>Threads</h3>
|
|
2320
|
-
<div class="k"><span>Next needing you</span><kbd>N</kbd></div>
|
|
2321
|
-
<div class="k"><span>Open thread</span><kbd>Enter</kbd></div>
|
|
2322
|
-
<div class="k"><span>Mark viewed</span><kbd>V</kbd></div>
|
|
2323
|
-
<div class="k"><span>Archive</span><kbd>A</kbd></div>
|
|
2324
|
-
<div class="k"><span>New conversation</span><kbd>C</kbd></div>
|
|
2325
|
-
<div class="k"><span>Deselect</span><kbd>Esc</kbd></div>
|
|
2326
|
-
<h3>The app</h3>
|
|
2327
|
-
<div class="k"><span>Settings</span><kbd>S</kbd></div>
|
|
2328
|
-
<div class="k"><span>Screenshot</span><kbd>P</kbd></div>
|
|
2329
|
-
<div class="k"><span>Record video</span><kbd>R</kbd></div>
|
|
2330
|
-
<div class="k"><span>Mute</span><kbd>M</kbd></div>
|
|
2331
|
-
<div class="k"><span>This sheet</span><kbd>?</kbd></div>
|
|
2332
|
-
</section>
|
|
2333
|
-
<section class="legend">
|
|
2334
|
-
<h3>Badges</h3>
|
|
2335
|
-
<div class="legend-row"><i class="badge" style="background:var(--asking-plate);color:var(--asking)">${Qs(fe.asking)}</i> stopped on a question or permission only you can answer</div>
|
|
2336
|
-
<div class="legend-row"><i class="badge" style="background:var(--done-plate);color:var(--done)">${Qs(fe.done)}</i> done, and ready for you to read — click to open the thread</div>
|
|
2337
|
-
<div class="legend-row"><i class="badge" style="background:var(--error-plate);color:var(--error)">${Qs(fe.error)}</i> the session hit an error</div>
|
|
2338
|
-
<div class="legend-row"><i class="badge" style="background:var(--working-plate);color:var(--working)">${Qs(fe.working)}</i> running right now, building</div>
|
|
2339
|
-
<div class="legend-row"><i class="badge" style="background:var(--delegating-plate);color:var(--delegating)">${Qs(fe.delegating)}</i> waiting on other agents to report back</div>
|
|
2340
|
-
<div class="legend-row"><i class="badge" style="background:var(--celebrating-plate);color:var(--celebrating)">${Qs(fe.celebrating)}</i> its pull request landed</div>
|
|
2341
|
-
<div class="legend-row"><i class="badge" style="background:var(--idle-plate);color:var(--idle)">${Qs(fe.sleeping)}</i> nothing for three days</div>
|
|
2342
|
-
</section>
|
|
2343
|
-
</div>
|
|
2344
|
-
</div>
|
|
2345
|
-
<div class="help-foot">
|
|
2346
|
-
<button class="btn primary" id="btn-help-close">Got it</button>
|
|
2347
|
-
</div>
|
|
2348
|
-
</div>
|
|
2349
|
-
</div>
|
|
2350
|
-
|
|
2351
|
-
<div class="upgrade" role="dialog" aria-modal="true" aria-labelledby="upgrade-title">
|
|
2352
|
-
<div class="sheet panel">
|
|
2353
|
-
<div class="upgrade-world"></div>
|
|
2354
|
-
<h3 id="upgrade-title"></h3>
|
|
2355
|
-
<p class="sub"></p>
|
|
2356
|
-
<div class="upgrade-actions">
|
|
2357
|
-
<button class="btn" id="btn-upgrade-later">Not now</button>
|
|
2358
|
-
<a class="btn primary" id="btn-get-pro" href="${x0}" target="_blank" rel="noopener">Get Pro</a>
|
|
2359
|
-
</div>
|
|
2360
|
-
<div class="upgrade-key">
|
|
2361
|
-
<p class="upgrade-key-label">Already have Pro? Enter your license key.</p>
|
|
2362
|
-
</div>
|
|
2363
|
-
</div>
|
|
2364
|
-
</div>
|
|
2365
|
-
`,DC='<svg class="loader-bot-hull" viewBox="-99.4 -106.2 198.8 166.6" aria-hidden="true"><defs><linearGradient id="LOADER-s" x1="0" y1="-60" x2="0" y2="62" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#ffffff"/><stop offset="1" stop-color="#d9dfe8"/></linearGradient><radialGradient id="LOADER-v" cx="-9.7" cy="-17.3" r="55.2" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#2f4466"/><stop offset="0.6" stop-color="#141e33"/><stop offset="1" stop-color="#0b1120"/></radialGradient><linearGradient id="LOADER-wingTips" x1="0" y1="-60" x2="0" y2="62" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#d27d60"/><stop offset="1" stop-color="#b1583a"/></linearGradient><linearGradient id="LOADER-engineBands" x1="0" y1="-60" x2="0" y2="62" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#d27d60"/><stop offset="1" stop-color="#b1583a"/></linearGradient><linearGradient id="LOADER-sideDomes" x1="0" y1="-60" x2="0" y2="62" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#d27d60"/><stop offset="1" stop-color="#b1583a"/></linearGradient><linearGradient id="LOADER-faceTrim" x1="0" y1="-60" x2="0" y2="62" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#d27d60"/><stop offset="1" stop-color="#b1583a"/></linearGradient><filter id="LOADER-g" x="-1" y="-1" width="3" height="3"><feGaussianBlur stdDeviation="3.2"/></filter><filter id="LOADER-h" x="-1" y="-1" width="3" height="3"><feGaussianBlur stdDeviation="5"/></filter></defs><path d="M80.5,56.4C80.8,55.7 81.2,55 81.2,54.3C80.6,45.6 79.6,37 78.7,28.4C78.5,27.1 78.1,25.8 77.9,24.5C76.7,24 75.6,23.5 74.5,23.2C67.8,21.4 61,19.9 54.4,18C52.4,17.4 50.4,16.5 48.4,15.6C46.8,14.9 45.3,14.1 43.8,13.3C44,13.5 44.2,13.7 44.3,14C44.1,14.7 44,15.5 43.6,16.2C43.4,16.5 43,16.9 42.6,17C41.8,17.1 41.1,17.1 40.3,17C39.4,16.8 38.5,16.5 37.5,16.3C41.8,20.8 46,25.4 50.3,29.9C58.1,38.1 66,46.1 73.9,54.2C72.8,52.9 71.7,51.6 70.6,50.3C72.6,52.8 74.5,55.3 76.7,57.6C77.1,57.9 77.6,57.9 78.1,57.9C78.6,57.9 79.2,57.6 79.7,57.5C80,57.1 80.3,56.8 80.5,56.4Z" fill="url(#LOADER-s)"/><path d="M80.5,56.4C80.8,55.7 81.2,55 81.2,54.3C81.1,52 80.7,49.8 80.5,47.6C80.3,48.3 80.1,49 79.9,49.7C79.3,50 78.9,50.6 78.3,50.7C77,50.9 75.6,50.9 74.3,50.8C73.1,50.7 71.8,50.5 70.6,50.3C63.7,42.4 57.4,33.9 50.1,26.4C46.4,22.5 41.7,19.7 37.5,16.3C41.8,20.8 46,25.4 50.3,29.9C58.1,38.1 66,46.1 73.9,54.2C72.8,52.9 71.7,51.6 70.6,50.3C72.6,52.8 74.5,55.3 76.7,57.6C77.1,57.9 77.6,57.9 78.1,57.9C78.6,57.9 79.2,57.6 79.7,57.5C80,57.1 80.3,56.8 80.5,56.4Z" fill="url(#LOADER-wingTips)"/><path d="M-80.9,55.1C-80.8,55.5 -80.7,56 -80.5,56.4C-80.3,56.8 -80.1,57.2 -79.7,57.5C-79.3,57.8 -78.9,57.9 -78.4,57.9C-77.8,57.9 -77.1,58 -76.7,57.6C-74.4,55.4 -72.6,52.8 -70.6,50.3C-71.7,51.6 -72.8,52.9 -73.9,54.2C-66,46.1 -58.1,38.1 -50.3,29.9C-46,25.4 -41.8,20.8 -37.5,16.3C-38.5,16.5 -39.4,16.8 -40.3,17C-41.1,17.1 -41.8,17.1 -42.6,17C-43,16.9 -43.4,16.5 -43.6,16.2C-44,15.5 -44.1,14.7 -44.3,14C-44.2,13.7 -44,13.5 -43.8,13.3C-45.3,14.1 -46.8,14.9 -48.4,15.6C-50.4,16.5 -52.4,17.4 -54.4,18C-61,19.9 -67.8,21.4 -74.5,23.2C-75.6,23.5 -76.7,24 -77.9,24.5C-78.1,25.8 -78.5,27.1 -78.7,28.4C-79.1,31.6 -79.4,34.9 -79.7,38.1C-80.2,43.5 -80.8,48.9 -81.2,54.3C-81.2,54.6 -81,54.8 -80.9,55.1Z" fill="url(#LOADER-s)"/><path d="M-80.9,55.1C-80.8,55.5 -80.7,56 -80.5,56.4C-80.3,56.8 -80.1,57.2 -79.7,57.5C-79.3,57.8 -78.9,57.9 -78.4,57.9C-77.8,57.9 -77.1,58 -76.7,57.6C-74.4,55.4 -72.6,52.8 -70.6,50.3C-71.8,50.5 -73.1,50.7 -74.3,50.8C-75.6,50.9 -77,50.9 -78.3,50.7C-78.9,50.6 -79.3,50 -79.9,49.7C-80.1,49 -80.3,48.3 -80.5,47.6C-80.7,49.8 -81,52 -81.2,54.3C-81.2,54.6 -81,54.8 -80.9,55.1ZM-73.9,54.2C-64.8,44.8 -55.6,35.4 -46.5,26C-43.4,22.8 -40.5,19.5 -37.5,16.3C-41.7,19.7 -46.4,22.5 -50.1,26.4C-58.6,35.2 -66,44.9 -73.9,54.2Z" fill="url(#LOADER-wingTips)"/><path d="M99.1,-60.1C98.9,-60.7 98.7,-61.3 98.4,-61.8C98.2,-62.1 98,-62.4 97.7,-62.5C97.2,-62.8 96.7,-62.8 96.2,-62.9C96.7,-62.8 97.2,-62.7 97.7,-62.6C97.2,-62.7 96.7,-62.9 96.2,-62.9C95.8,-62.9 95.4,-62.8 95.1,-62.5C92.1,-60.2 89.4,-57.5 86.5,-55.1C72.2,-43.5 57.9,-32 43.6,-20.5C44.4,-20.8 45.1,-21.1 45.9,-21.2C46.6,-21.3 47.3,-21.4 47.9,-21.2C48.4,-21.1 48.7,-20.8 49,-20.5C49.4,-19.8 49.6,-19 50,-18.2C49.8,-18 49.7,-17.8 49.6,-17.6C53.2,-19.2 56.7,-21 60.4,-22.3C66.6,-24.5 72.9,-25.9 79.1,-27.9C80.3,-28.2 81.7,-28.3 82.6,-29.2C83.8,-30.2 84.4,-31.8 85.1,-33.1C90,-41.8 94.7,-50.6 99.4,-59.3C99.3,-59.6 99.2,-59.8 99.1,-60.1Z" fill="url(#LOADER-s)"/><path d="M99.1,-60.1C98.9,-60.7 98.7,-61.3 98.4,-61.8C98.2,-62.1 98,-62.4 97.7,-62.5C97.2,-62.8 96.7,-62.8 96.2,-62.9C96.7,-62.8 97.2,-62.7 97.7,-62.6C97.2,-62.7 96.7,-62.9 96.2,-62.9C95.8,-62.9 95.4,-62.8 95.1,-62.5C92.1,-60.2 89.4,-57.5 86.5,-55.1C72.2,-43.5 57.9,-32 43.6,-20.5C48.5,-23.9 53.6,-26.9 58.3,-30.7C68,-38.5 76.7,-47.3 86.5,-55.1C87.3,-55.7 88.6,-55.5 89.7,-55.6C90.9,-55.7 92.1,-55.8 93.2,-55.6C93.8,-55.5 94.4,-55.1 94.8,-54.6C95.3,-54 95.4,-53.2 95.7,-52.5C96.9,-54.7 98.2,-57 99.4,-59.3C99.3,-59.6 99.2,-59.8 99.1,-60.1Z" fill="url(#LOADER-wingTips)"/><path d="M-98.6,-61.4C-98.9,-60.7 -99.1,-60 -99.4,-59.3C-94.7,-50.6 -90,-41.8 -85.1,-33.1C-84.4,-31.8 -83.8,-30.2 -82.6,-29.2C-81.7,-28.3 -80.3,-28.2 -79.1,-27.9C-72.9,-25.9 -66.6,-24.5 -60.4,-22.3C-56.7,-21 -53.2,-19.2 -49.6,-17.6C-49.7,-17.8 -49.8,-18 -50,-18.2C-49.6,-19 -49.4,-19.8 -49,-20.5C-48.7,-20.8 -48.4,-21.1 -47.9,-21.2C-47.3,-21.4 -46.6,-21.3 -45.9,-21.2C-45.1,-21.1 -44.4,-20.8 -43.6,-20.5C-57.9,-32 -72.2,-43.5 -86.5,-55.1C-89.4,-57.5 -92.1,-60.2 -95.1,-62.5C-95.5,-62.9 -96.2,-62.9 -96.7,-62.9C-97.1,-62.9 -97.4,-62.7 -97.7,-62.5C-97.2,-62.7 -96.7,-62.8 -96.2,-62.9C-96.7,-62.8 -97.2,-62.7 -97.7,-62.6C-98,-62.2 -98.3,-61.8 -98.6,-61.4Z" fill="url(#LOADER-s)"/><path d="M-98.6,-61.4C-98.9,-60.7 -99.1,-60 -99.4,-59.3C-98.2,-57 -96.9,-54.7 -95.7,-52.5C-95.4,-53.2 -95.3,-54 -94.8,-54.6C-94.4,-55.1 -93.8,-55.5 -93.2,-55.6C-92.1,-55.8 -90.9,-55.7 -89.7,-55.6C-88.6,-55.5 -87.3,-55.7 -86.5,-55.1C-76.7,-47.3 -68,-38.5 -58.3,-30.7C-53.6,-26.9 -48.5,-23.9 -43.6,-20.5C-57.9,-32 -72.2,-43.5 -86.5,-55.1C-89.4,-57.5 -92.1,-60.2 -95.1,-62.5C-95.5,-62.9 -96.2,-62.9 -96.7,-62.9C-97.1,-62.9 -97.4,-62.7 -97.7,-62.5C-97.2,-62.7 -96.7,-62.8 -96.2,-62.9C-96.7,-62.8 -97.2,-62.7 -97.7,-62.6C-98,-62.2 -98.3,-61.8 -98.6,-61.4Z" fill="url(#LOADER-wingTips)"/><path d="M28.1,17.9C26.2,17.7 24.3,17.4 22.3,17.4C21.7,17.4 21.1,17.6 20.6,17.7C18.8,18.1 17,18.3 15.3,19C13.6,19.6 12,20.6 10.6,21.7C9.2,22.9 7.9,24.3 6.9,25.8C5.8,27.3 5,29 4.5,30.7C3.9,32.5 3.6,34.3 3.7,36.1C3.7,38.6 3.9,41.1 4.7,43.4C5.5,46 6.7,48.4 8.3,50.5C10,52.7 12,54.7 14.3,56.2C16.5,57.7 19.1,58.7 21.7,59.5C23.7,60.1 25.8,60.3 27.8,60.2C30.3,60 32.8,59.7 35.1,58.8C37.1,58.1 38.9,56.8 40.6,55.5C42,54.4 43.2,53.1 44.2,51.6C45.3,49.9 46.2,48.1 46.7,46.2C47.3,44.3 47.6,42.3 47.5,40.4C47.4,37.8 47,35.3 46.1,33C45.2,30.4 43.7,28.1 42,26C40.8,24.4 39.1,23.2 37.5,21.8C36.9,21.4 36.3,21 35.7,20.7C33.9,19.8 32,19 30.1,18.3C29.5,18 28.8,18 28.1,17.9ZM26.3,42.7C26.6,41.9 26.9,41.2 27.3,40.6C27.8,39.9 28.3,39.3 28.9,38.8C29.5,38.3 30.2,37.9 30.9,37.7C31.7,37.4 32.4,37.2 33.2,37.2C34,37.1 34.7,37.2 35.5,37.4C36.2,37.6 36.8,38 37.5,38.3C36.2,37.2 34.9,36 33.5,35C32.9,34.6 32.2,34.3 31.4,34.1C30.7,33.9 29.9,33.8 29.1,33.9C28.3,33.9 27.5,34.1 26.8,34.4C26,34.7 25.3,35.1 24.7,35.6C24.1,36.1 23.5,36.7 23.1,37.3C22.6,38 22.3,38.8 22,39.5C21.8,40.3 21.7,41.1 21.7,41.9C21.7,42.7 21.8,43.5 22.1,44.2C22.3,45 22.7,45.7 23.2,46.3C23.6,46.9 24.2,47.4 24.8,47.9C26.2,48.9 27.7,49.9 29.1,50.8C28.5,50.3 27.9,49.9 27.5,49.3C27,48.7 26.6,48 26.4,47.3C26.1,46.5 26,45.7 26,45C26,44.2 26.1,43.4 26.3,42.7Z" fill="url(#LOADER-s)"/><path d="M42,26C43,27.8 44.4,29.5 45.1,31.5C45.8,33.5 46.2,35.6 46.2,37.8C46.2,39.9 45.9,42.1 45.3,44.2C44.7,46.3 43.8,48.3 42.5,50.1C41.3,52 39.8,53.6 38.1,55C36.4,56.3 34.5,57.4 32.4,58.2C30.4,59 28.3,59.4 26.2,59.5C24.1,59.6 22,59.1 19.9,58.8C20.5,59.1 21.1,59.4 21.7,59.5C23.7,59.8 25.8,60.3 27.8,60.2C29.9,60.1 31.9,59.6 33.9,58.9C35.8,58.1 37.7,57.1 39.4,55.7C41,54.4 42.5,52.8 43.7,51C44.9,49.3 45.8,47.3 46.4,45.3C47,43.3 47.3,41.1 47.2,39C47.2,37 46.9,34.9 46.1,33C45.1,30.5 43.4,28.3 42,26Z" fill="url(#LOADER-engineBands)"/><path d="M-20.6,17.7C-21.1,17.6 -21.7,17.4 -22.3,17.4C-24.9,17.5 -27.6,17.7 -30.1,18.3C-32.1,18.8 -33.9,19.8 -35.7,20.7C-36.3,21 -36.9,21.4 -37.5,21.8C-39.1,23.2 -40.8,24.4 -42,26C-43.7,28.1 -45.2,30.4 -46.1,33C-47,35.3 -47.4,37.8 -47.5,40.4C-47.6,42.3 -47.3,44.3 -46.7,46.2C-46.2,48.1 -45.3,50 -44.2,51.6C-43.1,53.2 -41.7,54.7 -40.2,55.9C-38.6,57.1 -36.9,58.2 -35.1,58.8C-32.7,59.6 -30.3,60 -27.8,60.2C-25.8,60.3 -23.7,60.1 -21.7,59.5C-19.1,58.7 -16.5,57.7 -14.3,56.2C-12,54.7 -10,52.7 -8.3,50.5C-6.7,48.4 -5.5,46 -4.7,43.4C-3.9,41.1 -3.7,38.6 -3.7,36.1C-3.6,34.3 -3.9,32.5 -4.5,30.7C-5,29 -5.8,27.3 -6.9,25.8C-7.9,24.3 -9.2,22.9 -10.6,21.7C-12,20.6 -13.6,19.6 -15.3,19C-17,18.3 -18.8,18.1 -20.6,17.7ZM-22,39.5C-22.3,38.8 -22.6,38 -23.1,37.3C-23.5,36.7 -24.1,36.1 -24.7,35.6C-25.3,35.1 -26,34.7 -26.8,34.4C-27.5,34.1 -28.3,33.9 -29.1,33.9C-29.9,33.8 -30.7,33.9 -31.4,34.1C-32.2,34.3 -32.9,34.6 -33.5,35C-34.9,36 -36.2,37.2 -37.5,38.3C-36.8,38 -36.2,37.6 -35.5,37.4C-34.7,37.2 -34,37.1 -33.2,37.2C-32.4,37.2 -31.7,37.4 -30.9,37.7C-30.2,37.9 -29.5,38.3 -28.9,38.8C-28.3,39.3 -27.8,39.9 -27.3,40.6C-26.9,41.2 -26.6,41.9 -26.3,42.7C-26.1,43.4 -26,44.2 -26,45C-26,45.7 -26.1,46.5 -26.4,47.3C-26.6,48 -27,48.7 -27.5,49.3C-27.9,49.9 -28.5,50.3 -29.1,50.8C-27.7,49.9 -26.2,48.9 -24.8,47.9C-24.2,47.4 -23.6,46.9 -23.2,46.3C-22.7,45.7 -22.3,45 -22.1,44.2C-21.8,43.5 -21.7,42.7 -21.7,41.9C-21.7,41.1 -21.8,40.3 -22,39.5Z" fill="url(#LOADER-s)"/><path d="M-42,26C-43.4,28.3 -45.1,30.5 -46.1,33C-46.9,34.9 -47.2,37 -47.2,39C-47.3,41.1 -47,43.3 -46.4,45.3C-45.8,47.3 -44.9,49.3 -43.7,51C-42.5,52.8 -41,54.4 -39.4,55.7C-37.7,57.1 -35.8,58.1 -33.9,58.9C-31.9,59.6 -29.9,60.1 -27.8,60.2C-25.8,60.3 -23.7,59.8 -21.7,59.5C-21.1,59.4 -20.5,59.1 -19.9,58.8C-22,59.1 -24.1,59.6 -26.2,59.5C-28.3,59.4 -30.4,59 -32.4,58.2C-34.5,57.4 -36.4,56.3 -38.1,55C-39.8,53.6 -41.3,52 -42.5,50.1C-43.8,48.3 -44.7,46.3 -45.3,44.2C-45.9,42.1 -46.2,39.9 -46.2,37.8C-46.2,35.6 -45.8,33.5 -45.1,31.5C-44.4,29.5 -43,27.8 -42,26Z" fill="url(#LOADER-engineBands)"/><path d="M30.1,-17.1C32.4,-17.1 34.7,-17.5 36.9,-18.2C38.7,-18.8 40.4,-19.7 41.9,-20.9C43.4,-22 44.8,-23.4 45.9,-25C47.1,-26.6 48,-28.3 48.6,-30.2C49.2,-32 49.4,-34 49.4,-35.9C49.4,-37.8 49.1,-39.8 48.5,-41.6C47.9,-43.4 47,-45.1 45.9,-46.7C44.8,-48.2 43.3,-49.4 41.9,-50.7C41.6,-51 41.3,-51.3 41,-51.5C39.3,-52.4 37.6,-53.5 35.8,-54.1C33.5,-54.7 31.1,-55.1 28.8,-55C26.9,-55 24.9,-54.6 23.1,-54C21.1,-53.2 19.1,-52.2 17.3,-50.9C15.8,-49.8 14.5,-48.4 13.5,-46.9C12.4,-45.4 11.6,-43.7 11,-41.9C10.5,-40.1 10.2,-38.3 10.2,-36.4C10.2,-34.6 10.5,-32.7 11,-31C11.6,-29.2 12.4,-27.6 13.5,-26.1C14.8,-24.2 16.3,-22.4 18.1,-21.1C20,-19.7 22.1,-18.7 24.4,-17.9C26.2,-17.3 28.1,-17 30.1,-17.1ZM30.3,-38.2C30.7,-38.8 31.2,-39.3 31.8,-39.8C32.3,-40.2 33,-40.5 33.6,-40.8C34.3,-41 35,-41.1 35.7,-41.2C36.4,-41.2 37.1,-41 37.8,-40.9C36.8,-41.2 35.8,-41.7 34.7,-42C34,-42.2 33.3,-42.3 32.6,-42.3C31.8,-42.3 31.1,-42.1 30.4,-41.9C29.7,-41.7 29.1,-41.3 28.5,-40.9C27.9,-40.4 27.4,-39.9 27,-39.3C26.5,-38.7 26.2,-38 26,-37.3C25.8,-36.6 25.7,-35.8 25.7,-35.1C25.7,-34.4 25.8,-33.6 26,-32.9C26.2,-32.2 26.5,-31.6 27,-31C27.4,-30.4 27.9,-29.9 28.5,-29.4C29.1,-29 29.7,-28.7 30.4,-28.4C31.5,-28.1 32.6,-27.9 33.6,-27.7C33,-28 32.3,-28.2 31.8,-28.6C31.2,-29.1 30.7,-29.6 30.3,-30.1C29.9,-30.7 29.5,-31.4 29.3,-32C29.1,-32.7 29,-33.4 29,-34.2C29,-34.9 29.1,-35.6 29.3,-36.3C29.5,-37 29.9,-37.6 30.3,-38.2Z" fill="url(#LOADER-s)"/><path d="M30.1,-17.1C32.3,-17.4 34.7,-17.5 36.9,-18.2C38.7,-18.8 40.4,-19.7 41.9,-20.9C43.4,-22 44.8,-23.4 45.9,-25C47,-26.6 47.9,-28.3 48.5,-30.2C49.1,-32 49.4,-34 49.4,-35.9C49.4,-37.8 49.1,-39.8 48.5,-41.6C47.9,-43.4 47.1,-45.2 45.9,-46.7C44.5,-48.5 42.6,-49.9 41,-51.5C42.4,-50.1 44,-49 45.1,-47.4C46.3,-45.8 47.2,-44 47.8,-42.1C48.4,-40.3 48.7,-38.3 48.7,-36.3C48.7,-34.3 48.4,-32.3 47.8,-30.4C47.2,-28.5 46.3,-26.7 45.1,-25C44,-23.4 42.6,-22 41,-20.8C39.4,-19.6 37.6,-18.7 35.8,-18C33.9,-17.4 32,-17.4 30.1,-17.1Z" fill="url(#LOADER-engineBands)"/><path d="M-36.9,-18.2C-34.7,-17.5 -32.4,-17.1 -30.1,-17.1C-28.1,-17 -26.2,-17.6 -24.4,-17.9C-23.9,-18 -23.5,-18.3 -23.1,-18.5C-21.4,-19.3 -19.6,-20 -18.1,-21.1C-16.5,-22.2 -15.2,-23.6 -14.1,-25.2C-12.8,-26.9 -11.7,-28.9 -11,-31C-10.4,-32.7 -10.2,-34.6 -10.2,-36.4C-10.2,-38.3 -10.5,-40.1 -11,-41.9C-11.6,-43.7 -12.4,-45.4 -13.5,-46.9C-14.5,-48.4 -15.8,-49.8 -17.3,-50.9C-19.1,-52.2 -21.1,-53.2 -23.1,-54C-24.9,-54.6 -26.9,-55 -28.8,-55C-31.1,-55.1 -33.5,-54.7 -35.8,-54.1C-37.6,-53.5 -39.3,-52.4 -41,-51.5C-41.3,-51.3 -41.6,-51 -41.9,-50.7C-43.3,-49.4 -44.8,-48.2 -45.9,-46.7C-47,-45.1 -47.9,-43.4 -48.5,-41.6C-49.1,-39.6 -49.4,-37.6 -49.4,-35.5C-49.4,-33.7 -49.2,-31.9 -48.6,-30.2C-48,-28.3 -47.1,-26.6 -45.9,-25C-44.8,-23.4 -43.4,-22 -41.9,-20.9C-40.4,-19.7 -38.7,-18.8 -36.9,-18.2ZM-27,-39.3C-27.4,-39.9 -27.9,-40.4 -28.5,-40.9C-29.1,-41.3 -29.7,-41.7 -30.4,-41.9C-31.1,-42.1 -31.8,-42.3 -32.6,-42.3C-33.3,-42.3 -34,-42.2 -34.7,-42C-35.8,-41.7 -36.8,-41.2 -37.8,-40.9C-37.1,-41 -36.4,-41.2 -35.7,-41.2C-35,-41.1 -34.3,-41 -33.6,-40.8C-33,-40.5 -32.3,-40.2 -31.8,-39.8C-31.2,-39.3 -30.7,-38.8 -30.3,-38.2C-29.9,-37.6 -29.5,-37 -29.3,-36.3C-29.1,-35.6 -29,-34.9 -29,-34.2C-29,-33.4 -29.1,-32.7 -29.3,-32C-29.5,-31.4 -29.9,-30.7 -30.3,-30.1C-30.7,-29.6 -31.2,-29.1 -31.8,-28.6C-32.3,-28.2 -33,-28 -33.6,-27.7C-32.6,-27.9 -31.5,-28.1 -30.4,-28.4C-29.7,-28.7 -29.1,-29 -28.5,-29.4C-27.9,-29.9 -27.4,-30.4 -27,-31C-26.5,-31.6 -26.2,-32.2 -26,-32.9C-25.8,-33.6 -25.7,-34.4 -25.7,-35.1C-25.7,-35.8 -25.8,-36.6 -26,-37.3C-26.2,-38 -26.5,-38.7 -27,-39.3Z" fill="url(#LOADER-s)"/><path d="M-30.1,-17.1C-32,-17.4 -33.9,-17.4 -35.8,-18C-37.6,-18.7 -39.4,-19.6 -41,-20.8C-42.6,-22 -44,-23.4 -45.1,-25C-46.3,-26.7 -47.2,-28.5 -47.8,-30.4C-48.4,-32.3 -48.7,-34.3 -48.7,-36.3C-48.7,-38.3 -48.4,-40.3 -47.8,-42.1C-47.2,-44 -46.3,-45.8 -45.1,-47.4C-44,-49 -42.4,-50.1 -41,-51.5C-42.6,-49.9 -44.5,-48.5 -45.9,-46.7C-47.1,-45.2 -47.9,-43.4 -48.5,-41.6C-49.1,-39.8 -49.4,-37.8 -49.4,-35.9C-49.4,-34 -49.1,-32 -48.5,-30.2C-47.9,-28.3 -47,-26.6 -45.9,-25C-44.8,-23.4 -43.4,-22 -41.9,-20.9C-40.4,-19.7 -38.7,-18.8 -36.9,-18.2C-34.7,-17.5 -32.3,-17.4 -30.1,-17.1Z" fill="url(#LOADER-engineBands)"/><path d="M0.8,-106.2C0.4,-106.2 -0.1,-106.4 -0.6,-106.2C-1.1,-106.1 -1.4,-105.6 -1.8,-105.3C-2,-104.6 -2.2,-103.9 -2.2,-103.2C-2.4,-85.1 -2.3,-67 -2.3,-48.9C-2.2,-49.5 -2.2,-50.1 -2.1,-50.8C-1.9,-51 -1.6,-51.2 -1.4,-51.4C-0.5,-51.4 0.3,-51.4 1.1,-51.4C1.4,-51.2 1.7,-51 1.9,-50.8C2,-68.9 2.1,-87.1 2.1,-105.3C2,-105.7 1.8,-105.9 1.7,-106.2C1.4,-106.2 1.1,-106.2 0.8,-106.2Z" fill="url(#LOADER-s)"/><path d="M61.4,22.2C63.2,20.2 65.4,18.5 66.9,16.1C68.5,13.6 69.6,10.7 70.4,7.7C71,5.2 71.1,2.6 71.1,0C71.1,-2.6 71,-5.2 70.4,-7.7C69.6,-10.7 68.5,-13.6 66.9,-16.1C65.4,-18.5 63.2,-20.2 61.4,-22.2C61.7,-21.2 62.1,-20.2 62.3,-19.1C62.6,-17.1 62.9,-15 63,-12.9C63.3,-8.6 63.4,-4.3 63.4,0C63.4,4.3 63.3,8.6 63,12.9C62.9,15 62.6,17.1 62.3,19.1C62.1,20.2 61.7,21.2 61.4,22.2ZM62.8,-21.8C62.6,-23 62.5,-24.2 62.2,-25.4C61.9,-26.7 61.4,-28 61,-29.4C59.4,-30.5 57.7,-31.6 56,-32.7C55.8,-32.8 55.6,-32.9 55.4,-33C55.2,-32.6 54.8,-32.4 54.7,-32C54.3,-30.2 53.8,-28.4 53.6,-26.5C53.1,-21.7 52.8,-16.8 52.5,-12C52.3,-8 52.3,-4 52.3,0C52.3,4 52.3,8 52.5,12C52.8,16.8 53.1,21.7 53.6,26.5C53.8,28.4 54.3,30.2 54.7,32C54.8,32.4 55.2,32.6 55.4,33C57.3,31.8 59.1,30.6 61,29.4C61.4,28 61.9,26.7 62.2,25.4C62.5,24.2 62.6,23 62.8,21.8C63.1,18.5 63.4,15.2 63.5,11.9C63.7,8 63.8,4 63.8,0C63.8,-4 63.7,-8 63.5,-11.9C63.4,-15.2 63.1,-18.5 62.8,-21.8ZM54.1,-19.9C54.2,-21.2 54.5,-22.5 54.9,-23.8C55,-24.1 55.2,-24.3 55.4,-24.5C55.5,-24.4 55.7,-24.3 55.9,-24.3C52.4,-26.5 48.9,-28.7 45.4,-30.9C45.1,-29.9 44.6,-29 44.5,-28C44,-24.1 43.6,-20.3 43.4,-16.4C43.1,-9 43,-1.7 43.1,5.7C43.2,12.1 43.6,18.5 44.1,24.9C44.2,26.7 44.6,28.3 45,30C45,30.3 45.3,30.6 45.4,30.9C48.9,28.7 52.4,26.5 55.9,24.3C55.7,24.3 55.5,24.4 55.4,24.5C55.1,23.8 54.6,23.1 54.5,22.3C54.1,20.5 53.9,18.6 53.7,16.8C53.5,14.2 53.3,11.6 53.2,9C53.1,3 53,-3 53.2,-9C53.3,-12.7 53.6,-16.3 54.1,-19.9Z" fill="url(#LOADER-s)"/><path d="M61.4,22.2C63.2,20.2 65.4,18.5 66.9,16.1C68.5,13.6 69.6,10.7 70.4,7.7C71,5.2 71.1,2.6 71.1,0C71.1,-2.6 71,-5.2 70.4,-7.7C69.6,-10.7 68.5,-13.6 66.9,-16.1C65.4,-18.5 63.2,-20.2 61.4,-22.2C61.7,-21.2 62.1,-20.2 62.3,-19.1C62.6,-17.1 62.9,-15 63,-12.9C63.3,-8.6 63.4,-4.3 63.4,0C63.4,4.3 63.3,8.6 63,12.9C62.9,15 62.6,17.1 62.3,19.1C62.1,20.2 61.7,21.2 61.4,22.2Z" fill="url(#LOADER-sideDomes)"/><path d="M-61.4,22.2C-61.7,21.2 -62.1,20.2 -62.3,19.1C-62.6,17.1 -62.9,15 -63,12.9C-63.3,8.6 -63.4,4.3 -63.4,0C-63.4,-4.3 -63.3,-8.6 -63,-12.9C-62.9,-15 -62.6,-17.1 -62.3,-19.1C-62.1,-20.2 -61.7,-21.2 -61.4,-22.2C-63.2,-20.2 -65.4,-18.5 -66.9,-16.1C-68.5,-13.6 -69.6,-10.7 -70.4,-7.7C-71,-5.2 -71.1,-2.6 -71.1,0C-71.1,2.6 -71,5.2 -70.4,7.7C-69.6,10.7 -68.5,13.6 -66.9,16.1C-65.4,18.5 -63.2,20.2 -61.4,22.2ZM-62.2,-25.4C-62.9,-20.9 -63.2,-16.4 -63.5,-11.9C-63.8,-8 -63.8,-4 -63.8,0C-63.8,4 -63.7,8 -63.5,11.9C-63.4,15.2 -63.1,18.5 -62.8,21.8C-62.6,23 -62.5,24.2 -62.2,25.4C-61.9,26.7 -61.4,28 -61,29.4C-59.1,30.6 -57.3,31.8 -55.4,33C-55.2,32.6 -54.8,32.4 -54.7,32C-54.3,30.2 -53.8,28.4 -53.6,26.5C-53.1,21.7 -52.8,16.8 -52.5,12C-52.3,8 -52.3,4 -52.3,0C-52.3,-4 -52.3,-8 -52.5,-12C-52.8,-16.8 -53.1,-21.7 -53.6,-26.5C-53.8,-28.4 -54.3,-30.2 -54.7,-32C-54.8,-32.4 -55.2,-32.6 -55.4,-33C-57.3,-31.8 -59.1,-30.6 -61,-29.4C-61.4,-28 -62,-26.8 -62.2,-25.4ZM-54.5,-22.3C-54.1,-20.5 -53.9,-18.6 -53.7,-16.8C-53.5,-14.2 -53.3,-11.6 -53.2,-9C-53.1,-3 -53.1,3 -53.2,9C-53.3,11.6 -53.5,14.2 -53.7,16.8C-53.9,18.6 -54.1,20.5 -54.5,22.3C-54.6,23.1 -55.1,23.8 -55.4,24.5C-55.5,24.4 -55.7,24.3 -55.9,24.3C-52.4,26.5 -48.9,28.7 -45.4,30.9C-45.3,30.6 -45,30.3 -45,30C-44.6,28.3 -44.2,26.7 -44.1,24.9C-43.6,18.5 -43.2,12.1 -43.1,5.7C-43,-1.7 -43.1,-9 -43.4,-16.4C-43.6,-20.3 -44,-24.1 -44.5,-28C-44.6,-29 -45.1,-29.9 -45.4,-30.9C-45.6,-30.8 -45.8,-30.8 -45.9,-30.7C-49.3,-28.5 -52.5,-26.4 -55.9,-24.3C-55.7,-24.3 -55.5,-24.4 -55.4,-24.5C-55.1,-23.8 -54.6,-23.1 -54.5,-22.3Z" fill="url(#LOADER-s)"/><path d="M-61.4,22.2C-61.7,21.2 -62.1,20.2 -62.3,19.1C-62.6,17.1 -62.9,15 -63,12.9C-63.3,8.6 -63.4,4.3 -63.4,0C-63.4,-4.3 -63.3,-8.6 -63,-12.9C-62.9,-15 -62.6,-17.1 -62.3,-19.1C-62.1,-20.2 -61.7,-21.2 -61.4,-22.2C-63.2,-20.2 -65.4,-18.5 -66.9,-16.1C-68.5,-13.6 -69.6,-10.7 -70.4,-7.7C-71,-5.2 -71.1,-2.6 -71.1,0C-71.1,2.6 -71,5.2 -70.4,7.7C-69.6,10.7 -68.5,13.6 -66.9,16.1C-65.4,18.5 -63.2,20.2 -61.4,22.2Z" fill="url(#LOADER-sideDomes)"/><path d="M47.3,6.2C47.3,-1.8 47.5,-9.8 47.7,-17.7C47.8,-20.8 48.1,-23.9 48.5,-26.9C48.7,-28.8 49.2,-30.6 49.5,-32.5C47.8,-29.1 45.6,-25.9 44.2,-22.4C42.7,-18.9 41.7,-15.2 40.9,-11.5C40.2,-7.7 40,-3.8 40,0C40,3.8 40.2,7.7 40.9,11.5C41.7,15.2 42.7,18.9 44.2,22.4C45.6,25.9 47.8,29.1 49.5,32.5C49,29.2 48.4,26 48.1,22.7C47.6,17.2 47.4,11.7 47.3,6.2ZM23.5,55.7C27.2,54.2 30.8,52.3 34.1,50C37.4,47.8 40.5,45.3 43.3,42.4C46,39.6 48.4,36.4 50.7,33.2C51,32.8 51.2,32.2 51.3,31.7C51.9,27.7 52.5,23.6 52.7,19.6C53.2,13.1 53.3,6.5 53.3,0C53.3,-6.5 53.2,-13.1 52.7,-19.6C52.5,-23.6 51.9,-27.7 51.3,-31.7C51.2,-32.2 50.9,-32.7 50.7,-33.2C50.5,-33.3 50.3,-33.3 50.1,-33.5C47.5,-36.5 45.4,-39.8 42.6,-42.6C39.8,-45.4 36.8,-47.9 33.5,-50.1C30.2,-52.3 26.7,-54.2 23.1,-55.7C19.4,-57.2 15.5,-58 11.8,-59.1C11.6,-58.3 11.4,-57.5 11.2,-56.7C14.8,-55.6 18.5,-54.9 21.9,-53.4C25.4,-52 28.7,-50.3 31.8,-48.2C34.9,-46.1 37.7,-43.8 40.4,-41.1C43,-38.5 45,-35.4 47.4,-32.6C48.5,-32.8 49.6,-33 50.7,-33.2C48.2,-36.3 46,-39.6 43.3,-42.4C40.5,-45.3 37.4,-47.8 34.1,-50C30.8,-52.3 27.2,-54.2 23.5,-55.7C19.8,-57.2 15.8,-58 12,-59.2C11.2,-61.8 10.4,-64.3 9.7,-66.9C6.4,-67.2 3.2,-68 0,-68C-3.2,-68 -6.4,-67.2 -9.7,-66.9C-10.4,-64.3 -11.2,-61.8 -12,-59.2C-15.8,-58 -19.8,-57.2 -23.5,-55.7C-27.2,-54.2 -30.8,-52.3 -34.1,-50C-37.4,-47.8 -40.5,-45.3 -43.3,-42.4C-46,-39.6 -48.2,-36.3 -50.7,-33.2C-49.6,-33 -48.5,-32.8 -47.4,-32.6C-45,-35.4 -43,-38.5 -40.4,-41.1C-37.7,-43.8 -34.9,-46.1 -31.8,-48.2C-28.7,-50.3 -25.4,-52 -21.9,-53.4C-18.5,-54.9 -14.8,-55.6 -11.2,-56.7C-11.1,-56.8 -11.1,-56.9 -11,-57C-11.3,-57.7 -11.5,-58.4 -11.8,-59.1C-15.5,-58 -19.4,-57.2 -23.1,-55.7C-26.7,-54.2 -30.2,-52.3 -33.5,-50.1C-36.8,-47.9 -39.8,-45.4 -42.6,-42.6C-45.4,-39.8 -47.5,-36.5 -50.1,-33.5C-50.3,-33.3 -50.5,-33.3 -50.7,-33.2C-51.1,-31.8 -51.6,-30.3 -51.8,-28.8C-52.3,-25.7 -52.6,-22.7 -52.7,-19.6C-53.1,-13.1 -53.3,-6.5 -53.3,0C-53.3,6.5 -53.2,13.1 -52.7,19.6C-52.5,23.6 -51.9,27.7 -51.3,31.7C-51.2,32.2 -51,32.8 -50.7,33.2C-48.4,36.4 -46,39.6 -43.3,42.4C-40.5,45.3 -37.4,47.8 -34.1,50C-30.8,52.3 -27.2,54.2 -23.5,55.7C-19.8,57.2 -15.9,58.4 -12,59.2C-8.1,60 -4,60.4 0,60.4C4,60.4 8.1,60 12,59.2C15.9,58.4 19.8,57.2 23.5,55.7ZM-47.3,0C-47.3,4 -47.3,8.1 -47.5,12.1C-47.6,15.7 -47.7,19.2 -48.1,22.7C-48.4,26 -49,29.2 -49.5,32.5C-47.8,29.1 -45.6,25.9 -44.2,22.4C-42.7,18.9 -41.9,15.2 -40.9,11.5C-40.7,10.4 -40.6,9.3 -40.5,8.2C-40.3,5.5 -39.9,2.7 -40,0C-40,-3.6 -40.1,-7.2 -40.8,-10.8C-41.5,-14.8 -42.7,-18.7 -44.2,-22.4C-45.6,-26 -47.8,-29.1 -49.5,-32.5C-49,-29.2 -48.4,-26 -48.1,-22.7C-47.7,-19.2 -47.6,-15.7 -47.5,-12.1C-47.3,-8.1 -47.3,-4 -47.3,0Z" fill="url(#LOADER-s)"/><path d="M23.5,55.7C27.2,54.2 30.8,52.3 34.1,50C37.4,47.8 40.5,45.3 43.3,42.4C46,39.6 48.6,36.6 50.7,33.2C51.5,31.9 51.6,30.3 51.8,28.8C52.1,27.5 52.2,26.1 52.3,24.7C52.6,21 52.8,17.3 53.1,13.6C50.7,14.9 48.3,16.2 45.9,17.5C44.9,17.3 44,17.1 43,16.9C42.8,21.5 42.5,26.1 42.3,30.6C39.3,32.6 36.5,34.8 33.3,36.4C30,38.1 26.4,39.6 22.8,40.7C19,41.9 15.1,42.8 11.2,43.4C7.5,44 3.7,44.4 0,44.4C-3.7,44.4 -7.5,44 -11.2,43.4C-15.1,42.8 -19,41.9 -22.8,40.7C-26.4,39.6 -30,38.1 -33.3,36.4C-36.5,34.8 -39.3,32.6 -42.3,30.6C-42.5,26.1 -42.8,21.5 -43,16.9C-44,17.1 -44.9,17.3 -45.9,17.5C-48.3,16.2 -50.7,14.9 -53.1,13.6C-52.8,17.3 -52.6,21 -52.3,24.7C-52.2,26.1 -52.1,27.5 -51.8,28.8C-51.6,30.3 -51.5,31.9 -50.7,33.2C-48.6,36.6 -46,39.6 -43.3,42.4C-40.5,45.3 -37.4,47.8 -34.1,50C-30.8,52.3 -27.2,54.2 -23.5,55.7C-19.8,57.2 -15.9,58.4 -12,59.2C-8.1,60 -4,60.4 0,60.4C4,60.4 8.1,60 12,59.2C15.9,58.4 19.8,57.2 23.5,55.7Z" fill="url(#LOADER-s)"/><path d="M45.9,-17.5C44.9,-17.3 44,-17.1 43,-16.9C43.1,-8.4 43.2,0.1 43.2,8.6C44.2,8.8 45.1,9.1 46.1,9C47.3,8.9 48.5,8.3 49.7,8C49.7,5.3 49.8,2.7 49.8,0C49.7,-5.2 49.6,-10.4 49.5,-15.5C48.3,-16.2 47.1,-16.9 45.9,-17.5ZM34.1,-40.4C36.9,-38.8 39.5,-36.7 42.2,-34.9C42.1,-35.6 42.1,-36.3 42,-36.9C39.3,-38.9 36.8,-41.1 33.9,-42.7C30.9,-44.5 27.7,-46 24.4,-47.1C21,-48.3 17.6,-49.3 14,-49.8C9.4,-50.5 4.7,-50.8 0,-50.8C-4.7,-50.8 -9.4,-50.5 -14,-49.8C-17.6,-49.3 -21,-48.3 -24.4,-47.1C-27.7,-46 -30.9,-44.5 -33.9,-42.7C-36.8,-41.1 -39.3,-38.9 -42,-36.9C-42.1,-36.3 -42.1,-35.6 -42.2,-34.9C-39.5,-36.7 -36.9,-38.8 -34.1,-40.4C-31,-42 -27.9,-43.4 -24.6,-44.5C-21.2,-45.6 -17.7,-46.6 -14.1,-47.1C-9.4,-47.7 -4.7,-47.9 0,-47.9C4.7,-47.9 9.4,-47.7 14.1,-47.1C17.7,-46.6 21.2,-45.6 24.6,-44.5C27.9,-43.4 31,-42 34.1,-40.4ZM-43.2,-8.6C-43.2,-11.4 -43.1,-14.1 -43,-16.9C-44,-17.1 -44.9,-17.3 -45.9,-17.5C-47.1,-16.9 -48.3,-16.2 -49.5,-15.5C-49.6,-7.7 -49.6,0.1 -49.7,8C-48.5,8.3 -47.3,8.9 -46.1,9C-45.1,9.1 -44.2,8.8 -43.2,8.6C-43.2,2.9 -43.3,-2.9 -43.2,-8.6Z" fill="url(#LOADER-faceTrim)"/><path d="M33.3,36.4C36.5,34.8 39.3,32.6 42.3,30.6C42.5,26.1 42.9,21.5 43,16.9C43.2,11.2 43.3,5.6 43.3,0C43.3,-5.6 43.2,-11.2 43,-16.9C42.9,-21.5 42.5,-26.1 42.3,-30.6C39.3,-32.6 36.5,-34.8 33.3,-36.4C30,-38.1 26.4,-39.6 22.8,-40.7C19,-41.9 15.1,-42.8 11.2,-43.4C7.5,-44 3.7,-44.4 0,-44.4C-3.7,-44.4 -7.5,-44 -11.2,-43.4C-15.1,-42.8 -19,-41.9 -22.8,-40.7C-26.4,-39.6 -30,-38.1 -33.3,-36.4C-36.5,-34.8 -39.3,-32.6 -42.3,-30.6C-42.5,-26.1 -42.9,-21.5 -43,-16.9C-43.2,-11.2 -43.3,-5.6 -43.3,0C-43.3,5.6 -43.2,11.2 -43,16.9C-42.9,21.5 -42.5,26.1 -42.3,30.6C-39.3,32.6 -36.5,34.8 -33.3,36.4C-30,38.1 -26.4,39.6 -22.8,40.7C-19,41.9 -15.1,42.8 -11.2,43.4C-7.5,44 -3.7,44.4 0,44.4C3.7,44.4 7.5,44 11.2,43.4C15.1,42.8 19,41.9 22.8,40.7C26.4,39.6 30,38.1 33.3,36.4Z" fill="#c3cbd8" stroke="#c3cbd8" stroke-width="7" stroke-linejoin="round"/><path d="M33.3,36.4C36.5,34.8 39.3,32.6 42.3,30.6C42.5,26.1 42.9,21.5 43,16.9C43.2,11.2 43.3,5.6 43.3,0C43.3,-5.6 43.2,-11.2 43,-16.9C42.9,-21.5 42.5,-26.1 42.3,-30.6C39.3,-32.6 36.5,-34.8 33.3,-36.4C30,-38.1 26.4,-39.6 22.8,-40.7C19,-41.9 15.1,-42.8 11.2,-43.4C7.5,-44 3.7,-44.4 0,-44.4C-3.7,-44.4 -7.5,-44 -11.2,-43.4C-15.1,-42.8 -19,-41.9 -22.8,-40.7C-26.4,-39.6 -30,-38.1 -33.3,-36.4C-36.5,-34.8 -39.3,-32.6 -42.3,-30.6C-42.5,-26.1 -42.9,-21.5 -43,-16.9C-43.2,-11.2 -43.3,-5.6 -43.3,0C-43.3,5.6 -43.2,11.2 -43,16.9C-42.9,21.5 -42.5,26.1 -42.3,30.6C-39.3,32.6 -36.5,34.8 -33.3,36.4C-30,38.1 -26.4,39.6 -22.8,40.7C-19,41.9 -15.1,42.8 -11.2,43.4C-7.5,44 -3.7,44.4 0,44.4C3.7,44.4 7.5,44 11.2,43.4C15.1,42.8 19,41.9 22.8,40.7C26.4,39.6 30,38.1 33.3,36.4Z" fill="url(#LOADER-v)"/></svg>',VC='<svg viewBox="-99.4 -106.2 198.8 166.6" aria-hidden="true"><path d="M-30.4,-15.1 A33.8,34.6 0 0 1 -12.2,-32.3" fill="none" stroke="#fff" stroke-opacity="0.28" stroke-width="4.4" stroke-linecap="round"/></svg>',Xd=360,NC=1280,WC={dunes:"Piling up the dunes",island:"Raising the islands",coast:"Shaping the coast",headland:"Shaping the coast",fjord:"Carving the fjords",crags:"Carving the crags",shallows:"Smoothing the shallows"},HC={city:"Bolting the platform together"},UC={island:"Filling the sea",coast:"Filling the sea",headland:"Filling the sea",fjord:"Filling the sea",shallows:"Flooding the shallows"},jC={verb:"Planting",noun:"trees and rocks"},xi={verb:"Placing",noun:"rocks"},Yd={verb:"Placing",noun:"rocks and ice blocks"},qC={rocks:xi,lava:xi,arrakesh:xi,lt4260:xi,lt2230:xi,pluto:Yd,horth:Yd,roost:xi,desert:{verb:"Planting",noun:"cacti and rocks"},glimmer:{verb:"Planting",noun:"mushrooms and ferns"},undersea:{verb:"Planting",noun:"kelp and coral"},crystal:{verb:"Growing",noun:"crystals"},garden:{verb:"Growing",noun:"giant flowers"},sugarvale:{verb:"Planting",noun:"candy canes and lollipops"},deadstar:{verb:"Raising",noun:"gun towers"},qubitron:{verb:"Placing",noun:"steel shards and conduits"},jakhara:{verb:"Scattering",noun:"scrap and rocks"},north:{verb:"Planting",noun:"pines and white-barked trees"},oz:{verb:"Planting",noun:"poppies and trees"},yavora:{verb:"Growing",noun:"jungle trees"},challenger:{verb:"Settling",noun:"sea cucumbers and xenophyophores"},titanic:{verb:"Scattering",noun:"wreckage"},basalt:{verb:"Scattering",noun:"grass and stones"}},GC=["idle","strollLookLeft","strollLookRight","happy","wink","think1","love","whistle","sleep","alert","cheer"],ZC=al.idle.eye,XC=[2.8,.9,1.6];function Hf(s){return Math.round(s).toLocaleString("en-US")}function Tl(s,e,t){return`${Hf(s)} ${s===1?e:t}`}function YC(s){return s.length<3?s.join(" and "):`${s.slice(0,-1).join(", ")}, and ${s[s.length-1]}`}function QC(s){return/^moon$/i.test(s)?"the Moon":/\s[a-z]/.test(s)?`${/^[aeiou]/i.test(s)?"an":"a"} ${s.toLowerCase()}`:s}function Uf(s){return qC[s?.scatter]||jC}function KC(s,e={},t={}){switch(s){case"sky":{const i=(e.companions||[]).filter(n=>!n.on).map(n=>n.name).filter(Boolean).map(QC);return i.length?`Hanging ${YC(i)} in the sky`:"Lighting the sky"}case"ground":return WC[e.shape]||"Shaping the ground";case"island":return HC[e.skyIsland?.style]||"Floating the island";case"water":return e.water?.glow?"Pouring the lava":UC[e.shape]||"Filling the lakes";case"scatter":{const i=Uf(e);return`${i.verb} the ${i.noun}`}case"grass":return"Growing the grass";case"paths":return t.bots>0?`Mapping paths for ${Tl(t.bots,"bot","bots")}`:"Mapping the paths";case"horizon":return e.skyline?"Raising the horizon":"Rolling in the mist";case"shaders":return t.shaders>0?`Warming up ${Tl(t.shaders,"shader","shaders")}`:"Warming up the shaders";case"landing":return"Touching down";default:return"Building the world"}}function JC(s,e={}){const t=[];return e.scatter>0&&t.push(`${Hf(e.scatter)} ${Uf(s).noun}`),e.grass>0&&t.push(Tl(e.grass,"blade of grass","blades of grass")),t.join(" · ")}function ex(s,e){return e>0?Math.min(1,Math.max(0,s/e)):0}function tx(s,e,t){const[i,n,r]=D(s,t).match(/\w\w/g).map(o=>parseInt(o,16));return`rgba(${i}, ${n}, ${r}, ${e})`}function sx(s={}){return{"--loading-glow":tx(s.sky?.bottom??s.horizon,.22,"#1d2230")}}function ix([s,e,t]){const i=o=>Math.round(255*(o<=.0031308?o*12.92:1.055*o**.4166666666666667-.055)),n=l3([s,e,t].map(o=>o*jl*.77)).map(i),r=Math.max(s,e,t,.001);return{core:`rgb(${n.join(", ")})`,halo:`rgb(${[s,e,t].map(o=>i(o/r)).join(", ")})`}}const Ee=s=>Math.round(s*1e3)/1e3;let nx=0,rx=0;function ox(s,e=[0,0]){const t=`bot-eye${(++nx).toString(36)}`,i=u0(s);i[2]+=e[0],i[3]+=e[1];let n="",r="";return f0(i).forEach(({cx:o,cy:a,w:l,h:c,lidY:h,lidSlope:d,smileTop:u,smileRadius:f},p)=>{n+=`<clipPath id="${t}e${p}"><ellipse cx="${Ee(o)}" cy="${Ee(a)}" rx="${Ee(l/2)}" ry="${Ee(c/2)}"/></clipPath>`,n+=`<clipPath id="${t}l${p}"><path d="M${Ee(o-l)} ${Ee(h-d*l)}L${Ee(o+l)} ${Ee(h+d*l)}L${Ee(o+l)} ${Ee(a+c)}L${Ee(o-l)} ${Ee(a+c)}Z"/></clipPath>`;const m=u+f;r+=`<g clip-path="url(#${t}e${p})"><path clip-path="url(#${t}l${p})" fill-rule="evenodd" d="M${Ee(o-l)} ${Ee(a-c)}h${Ee(l*2)}v${Ee(c*2)}h${Ee(-l*2)}Z M${Ee(o+f)} ${Ee(m)}A${Ee(f)} ${Ee(f)} 0 1 0 ${Ee(o-f)} ${Ee(m)}A${Ee(f)} ${Ee(f)} 0 1 0 ${Ee(o+f)} ${Ee(m)}Z"/></g>`}),`<svg viewBox="0 0 1 1" aria-hidden="true" style="opacity:${Ee(.7+.3*i[9])}"><defs>${n}</defs>${r}</svg>`}function ax(s,e){const t=ix(s==="love"?XC:ZC);return`--beat:${e};--bot-eye:${t.core};--bot-eye-glow:${t.halo}`}function lx(){return GC.map((s,e)=>`<span class="loader-face" data-face="${s}" style="${ax(s,e)}">${ox(s)}</span>`).join("")}const cx=()=>`
|
|
2366
|
-
<div class="world-loading-card">
|
|
2367
|
-
<div class="loader-bot" aria-hidden="true">
|
|
2368
|
-
<span class="loader-bot-shadow"></span>
|
|
2369
|
-
<span class="loader-bot-head">
|
|
2370
|
-
${DC}
|
|
2371
|
-
<span class="loader-bot-light-dim"><span class="loader-bot-light"></span></span>
|
|
2372
|
-
<span class="loader-bot-screen"><span class="loader-bot-eyes">${lx()}</span></span>
|
|
2373
|
-
<span class="loader-bot-glass">${VC}</span>
|
|
2374
|
-
</span>
|
|
2375
|
-
</div>
|
|
2376
|
-
<p class="world-loading-kicker">Next stop</p>
|
|
2377
|
-
<h2 class="world-loading-name"></h2>
|
|
2378
|
-
<p class="world-loading-stage"></p>
|
|
2379
|
-
<div class="world-loading-bar"><i></i></div>
|
|
2380
|
-
<p class="world-loading-tally"></p>
|
|
2381
|
-
</div>`;class hx{constructor(e){this.el=document.createElement("div"),this.el.className="world-loading",this.el.hidden=!0,this.el.setAttribute("role","status"),this.el.innerHTML=cx().replaceAll("LOADER-",`loader${++rx}-`),e.appendChild(this.el),this.nameEl=this.el.querySelector(".world-loading-name"),this.stageEl=this.el.querySelector(".world-loading-stage"),this.barEl=this.el.querySelector(".world-loading-bar > i"),this.tallyEl=this.el.querySelector(".world-loading-tally"),this.planetId=null,this.hideTimer=0,this.stillTimer=0,this.still=null}holdFrame(e){const{width:t,height:i}=e;if(!t||!i)return;const n=Math.min(1,NC/Math.max(t,i)),r=this.still??=document.createElement("canvas");r.className="world-loading-still",r.width=Math.max(1,Math.round(t*n)),r.height=Math.max(1,Math.round(i*n));try{r.getContext("2d",{alpha:!1}).drawImage(e,0,0,r.width,r.height)}catch{return}clearTimeout(this.stillTimer),r.previousElementSibling!==e&&e.after(r),r.hidden=!1,r.classList.add("on")}releaseFrame(){const e=this.still;!e||e.hidden||(e.classList.remove("on"),clearTimeout(this.stillTimer),this.stillTimer=setTimeout(()=>{e.hidden=!0,e.width=e.height=1},Xd))}show({planet:e,stage:t,done:i=0,total:n=0,facts:r={}}){clearTimeout(this.hideTimer),e.id!==this.planetId&&this._paint(e),this.stageEl.textContent=KC(t,e,r),this.tallyEl.textContent=JC(e,r),this.barEl.style.transform=`scaleX(${ex(i,n)})`,this.el.hidden&&(this.el.hidden=!1,getComputedStyle(this.el).opacity),this.el.classList.add("on")}hide(){clearTimeout(this.hideTimer),this.barEl.style.transform="scaleX(1)",this.el.classList.remove("on"),this.releaseFrame(),this.planetId=null,this.hideTimer=setTimeout(()=>{this.el.hidden=!0,this.barEl.style.transform="scaleX(0)"},Xd)}_paint(e){this.planetId=e.id;for(const[t,i]of Object.entries(sx(e)))this.el.style.setProperty(t,i);this.nameEl.textContent=e.name||"a new world"}}const dx=5,ux=.5,fx=Math.PI*2,L=(s,e)=>s+Math.random()*(e-s);function px(s){const e=s.sampleRate,t=Math.floor(dx*e),i=Math.floor(ux*e),n=t+i,r=new Float32Array(n),o=new Float32Array(n),a=new Float32Array(n);let l=0,c=0,h=0,d=0,u=0,f=0,p=0,m=0;for(let w=0;w<n;w++){const b=Math.random()*2-1;r[w]=b,l=.99886*l+b*.0555179,c=.99332*c+b*.0750759,h=.969*h+b*.153852,d=.8665*d+b*.3104856,u=.55*u+b*.5329522,f=-.7616*f-b*.016898,o[w]=(l+c+h+d+u+f+p+b*.5362)*.11,p=b*.115926,m=(m+.02*b)/1.02,a[w]=m*3.5}const g={};for(const[w,b]of[["white",r],["pink",o],["brown",a]]){const y=s.createBuffer(1,t,e),C=y.getChannelData(0);let _=0;for(let M=0;M<t;M++)_+=b[M];_/=t;let x=1e-6;for(let M=0;M<t;M++){let k=b[M]-_;if(M<i){const A=M/i*Math.PI*.5;k=(b[t+M]-_)*Math.cos(A)+k*Math.sin(A)}C[M]=k,Math.abs(k)>x&&(x=Math.abs(k))}const T=.9/x;for(let M=0;M<t;M++)C[M]*=T;g[w]=y}return g}class st{constructor(e,t){this.ctx=e,this.out=e.createGain(),this.out.connect(t),this.until=1/0,this.isSample=!1,this._sources=[],this._nodes=[this.out]}source(e){return this._sources.push(e),e}node(e){return this._nodes.push(e),e}update(e,t){}setLevel(e){}stop(e){for(let t=0;t<this._sources.length;t++)try{this._sources[t].stop(e)}catch{}}dispose(){this.stop(this.ctx.currentTime);for(let e=0;e<this._nodes.length;e++)try{this._nodes[e].disconnect()}catch{}}}class mx extends st{constructor(e,t,i,n,r){super(e,t),this.isSample=!0;const o=e.createBufferSource();o.buffer=i;const a=Array.isArray(n?.trim)?n.trim:null,l=a?Math.max(0,a[0]):0,c=a?Math.min(i.duration,a[1]):i.duration;o.connect(this.out);const h=e.currentTime;r?(o.loop=!0,o.loopStart=l,o.loopEnd=c,o.start(h,l+Math.random()*Math.max(0,c-l-.1))):(o.start(h,l,Math.max(.01,c-l)),this.until=h+(c-l)),this.source(o)}}function Zt(s,e,t){const i=s.createBufferSource();return i.buffer=e,i.loop=!0,i.connect(t),i.start(s.currentTime,Math.random()*e.duration*.9),i}function Je(s,e,t,i,n){const r=s.createBufferSource();r.buffer=e,r.connect(t);const o=Math.random()*Math.max(0,e.duration-n-.05);return r.start(i,o,n),r}function He(s,e,t,i,n){const r=s.createOscillator();return r.type=e,r.frequency.value=t,r.connect(i),r.start(n),r}function le(s,e,t,i=1){const n=s.createBiquadFilter();return n.type=e,n.frequency.value=t,n.Q.value=i,n}function te(s,e,t){const i=s.createGain();return i.gain.value=e,t&&i.connect(t),i}function Pe(s,e,t,i,n,r=0){return s.setValueAtTime(0,e),s.linearRampToValueAtTime(t,e+i),s.setTargetAtTime(0,e+i+r,n/4),e+i+r+n}function ye(s,e,t,i){const n=te(s,0,e),r=s.createOscillator();r.type=i.type||"sine",r.frequency.setValueAtTime(i.start,t),i.middle!==void 0&&r.frequency.exponentialRampToValueAtTime(i.middle,t+i.duration*.4),r.frequency.exponentialRampToValueAtTime(i.end,t+i.duration),r.connect(n),r.start(t);let o=Pe(n.gain,t,i.gain,i.attack??.01,i.decay??.08,Math.max(0,(i.hold??i.duration)-(i.attack??.01)));if(r.stop(o+.05),i.wobble){const a=s.createOscillator();a.frequency.value=i.wobble[0];const l=te(s,i.wobble[1],r.frequency);a.connect(l),a.start(t),a.stop(o+.05)}return o}function Mi(s,e,t,i,n,r){let o=t;for(const[a,l,c]of n){const h=te(s,0,e),d=He(s,"sine",i*a,h,t),u=Pe(h.gain,t,r*l,.002,c);d.stop(u+.02),o=Math.max(o,u)}return o}function jf(s,e,t,i){const n=te(s,0,e),r=s.createOscillator();r.type=i.type||"sine";const[[,o],...a]=i.contour;r.frequency.setValueAtTime(o,t);for(const[h,d]of a)r.frequency.exponentialRampToValueAtTime(d,t+h);r.connect(n),r.start(t);const l=He(s,"sine",i.vibrato[0],te(s,i.vibrato[1],r.frequency),t),c=Pe(n.gain,t,i.gain,i.attack,i.decay,i.hold);return r.stop(c+.05),l.stop(c+.05),c}class fs extends st{constructor(e,t,i,n){super(e,t),this.lo=n.lo,this.hi=n.hi,this.base=n.base,this.swell=n.swell,this.rate=n.rate??1,this.cutoff=(n.lo+n.hi)*.5,this.level=.5,this.velocity=0,this.acc=0,this.filter=this.node(le(e,n.type||"lowpass",this.cutoff,n.q??.7)),this.filter.connect(this.out),this.source(Zt(e,i[n.noise||"pink"],this.filter)),this.out.gain.value=n.base}update(e,t){if(this.velocity+=(Math.random()-.5)*3*this.rate*e,this.velocity*=1-.8*e,this.level+=this.velocity*e,this.level<0?(this.level=0,this.velocity=Math.abs(this.velocity)*.3):this.level>1&&(this.level=1,this.velocity=-Math.abs(this.velocity)*.3),this.acc+=e,this.acc<.08)return;this.acc=0;const i=this.lo+(this.hi-this.lo)*this.level;this.filter.frequency.setTargetAtTime(i,t,.25),this.out.gain.setTargetAtTime(this.base*(1-this.swell+this.swell*this.level),t,.25)}}class Ia extends st{constructor(e,t,i,n){super(e,t),this.base=n.base,this.periodLo=n.period[0],this.periodHi=n.period[1],this.period=L(this.periodLo,this.periodHi),this.phase=Math.random(),this.acc=0;const r=this.node(le(e,n.type||"bandpass",n.center,n.q??.5));r.connect(this.out),this.source(Zt(e,i[n.noise||"brown"],r)),this.out.gain.value=n.base*.3}update(e,t){if(this.phase+=e/this.period,this.phase>=1&&(this.phase-=1,this.period=L(this.periodLo,this.periodHi)),this.acc+=e,this.acc<.08)return;this.acc=0;const i=this.phase,n=i<.7?Math.pow(i/.7,2.2):Math.pow(1-(i-.7)/.3,1.4);this.out.gain.setTargetAtTime(this.base*(.18+.82*n),t,.2)}}class Da extends st{constructor(e,t,i,n){super(e,t),this.base=n.base,this.depth=n.depth,this.speed=n.speed,this.acc=0;const r=this.node(le(e,n.type||"bandpass",n.center,n.q??.6));r.connect(this.out),this.source(Zt(e,i[n.noise||"white"],r)),this.out.gain.value=n.base}update(e,t){this.acc+=e,!(this.acc<1/this.speed)&&(this.acc=0,this.out.gain.setTargetAtTime(this.base*(1-this.depth+this.depth*Math.random()),t,.5/this.speed))}}class gx extends st{constructor(e,t,i,n){super(e,t),this.base=n.base,this.on=!1,this.timer=L(.2,1);const r=this.node(te(e,0,this.out)),o=this.node(te(e,.5,r)),a=this.node(te(e,.5,o.gain));this.source(He(e,"square",n.rate??28,a,e.currentTime)),this.source(He(e,"sine",n.freq??L(3900,4500),o,e.currentTime)),this.burst=r,this.out.gain.value=1}update(e,t){this.timer-=e,!(this.timer>0)&&(this.on=!this.on,this.timer=this.on?L(.45,.8):L(.3,1.4),this.burst.gain.setTargetAtTime(this.on?this.base:0,t,.02))}}class wx extends st{constructor(e,t,i,n){super(e,t),this.base=n.base,this.timer=L(.3,1.5),this.tone=this.node(le(e,"lowpass",900,.8)),this.tone.connect(this.out),this.out.gain.value=1,this.pitches=[L(170,220),L(260,320),L(380,460)]}update(e,t){if(this.timer-=e,this.timer>0)return;this.timer=L(.25,1.6);const i=this.pitches[Math.random()*this.pitches.length|0],n=2+(Math.random()*4|0),r=this.base*L(.5,1);for(let o=0;o<n;o++)ye(this.ctx,this.tone,t+o*.055,{start:i*1.08,end:i*.92,duration:.035,gain:r,type:"sawtooth",attack:.004,decay:.03})}}class bx extends st{constructor(e,t,i,n){super(e,t),this.base=n.base,this.center=3500,this.acc=0,this.tweet=L(1,4),this.filter=this.node(le(e,"bandpass",this.center,9)),this.filter.connect(this.out),this.source(Zt(e,i.white,this.filter)),this.out.gain.value=n.base}update(e,t){this.acc+=e,this.tweet-=e,this.tweet<=0&&(this.tweet=L(1.5,6),ye(this.ctx,this.out,t,{start:L(2600,4200),end:L(3e3,5e3),duration:.09,gain:this.base*.9,wobble:[60,300]})),!(this.acc<.12)&&(this.acc=0,this.center+=(Math.random()-.5)*900,this.center=Math.min(5500,Math.max(2400,this.center)),this.filter.frequency.setTargetAtTime(this.center,t,.3),this.out.gain.setTargetAtTime(this.base*L(.55,1),t,.3))}}class Va extends st{constructor(e,t,i,n){if(super(e,t),this.base=n.base,this.kinds=n.kinds,this.every=n.every,this.timer=L(n.every[0]*.3,n.every[1]*.6),n.hiss){const r=this.node(le(e,"bandpass",4e3,.4));r.connect(this.out),this.source(Zt(e,i.pink,r)),this.out.gain.value=n.hiss}else this.out.gain.value=1;this.callGain=this.node(te(e,1,t))}update(e,t){if(this.timer-=e,this.timer>0)return;this.timer=L(this.every[0],this.every[1]);const i=this.kinds[Math.random()*this.kinds.length|0];_l[i](this.ctx,this.callGain,t,this.base)}}class vx extends st{constructor(e,t,i,n){super(e,t),this.base=n.base,this.pop=L(1,4),this.acc=0;const r=this.node(le(e,"lowpass",120,.8));r.connect(this.out),this.source(Zt(e,i.brown,r)),this.out.gain.value=n.base}update(e,t){this.pop-=e,this.pop<=0&&(this.pop=L(1.5,6),ye(this.ctx,this.out,t,{start:L(55,80),end:28,duration:.16,gain:this.base*1.6,attack:.005,decay:.2})),this.acc+=e,!(this.acc<.15)&&(this.acc=0,this.out.gain.setTargetAtTime(this.base*L(.7,1),t,.4))}}class yx extends st{constructor(e,t,i,n){super(e,t),this.base=n.base,this.vent=L(3,9),this.venting=0;const r=this.node(le(e,"highpass",3800,.7));r.connect(this.out),this.source(Zt(e,i.white,r)),this.out.gain.value=n.base}update(e,t){this.vent-=e,!(this.vent>0)&&(this.venting?(this.venting=0,this.vent=L(4,11),this.out.gain.setTargetAtTime(this.base,t,.8)):(this.venting=1,this.vent=L(1.5,3.5),this.out.gain.setTargetAtTime(this.base*2.6,t,.6)))}}class Cx extends st{constructor(e,t,i,n){super(e,t),this.base=n.base,this.phase=Math.random()*fx;const r=e.currentTime,o=this.node(te(e,1,this.out)),a=this.node(te(e,.25,this.out));if(this.source(He(e,"sine",n.freq??48,o,r)),this.source(He(e,"sine",(n.freq??48)*2.01,a,r)),n.radio){const l=this.node(le(e,"bandpass",1800,1.2)),c=this.node(te(e,n.radio,this.out));l.connect(c),this.source(Zt(e,i.pink,l))}this.out.gain.value=n.base,this.acc=0}update(e,t){this.phase+=e*.35,this.acc+=e,!(this.acc<.1)&&(this.acc=0,this.out.gain.setTargetAtTime(this.base*(.8+.2*Math.sin(this.phase)),t,.3))}}class xx extends st{constructor(e,t,i,n){super(e,t),this.base=n.base,this.center=n.center,this.periodLo=n.period[0],this.periodHi=n.period[1],this.period=L(this.periodLo,this.periodHi),this.phase=Math.random(),this.acc=0;const r=e.currentTime;this.band=this.node(le(e,"bandpass",n.center,3.5));const o=this.node(te(e,.5,this.out));this.band.connect(o),this.source(He(e,"sawtooth",L(120,160),this.node(te(e,.35,o.gain)),r)),this.source(He(e,"sine",L(4,7),this.node(te(e,.15,o.gain)),r)),this.source(Zt(e,i.white,this.band)),this.out.gain.value=n.base*.1}update(e,t){if(this.phase+=e/this.period,this.phase>=1&&(this.phase-=1,this.period=L(this.periodLo,this.periodHi)),this.acc+=e,this.acc<.08)return;this.acc=0;const i=this.phase,n=i<.35?i/.35:i<.75?1:1-(i-.75)/.25,r=n*n*(3-2*n);this.band.frequency.setTargetAtTime(this.center*(.9+.1*r),t,.3),this.out.gain.setTargetAtTime(this.base*(.1+.9*r),t,.3)}}class Mx extends fs{constructor(e,t,i,n){super(e,t,i,n);const r=this.node(le(e,"lowpass",110,.7));r.connect(this.node(te(e,n.rumble,this.out))),this.source(Zt(e,i.brown,r))}}class kx extends fs{constructor(e,t,i,n){super(e,t,i,n),this.bubbleLevel=n.bubbles,this.bubble=L(.5,3),this.muffle=this.node(le(e,"lowpass",1200,.7)),this.muffle.connect(this.out)}update(e,t){if(super.update(e,t),this.bubble-=e,this.bubble>0)return;this.bubble=L(.6,4);const i=1+(Math.random()*3|0);for(let n=0;n<i;n++){const r=L(250,600);ye(this.ctx,this.muffle,t+n*L(.05,.12),{start:r,end:r*L(1.6,2.2),duration:.03,gain:this.bubbleLevel*L(.4,1),attack:.003,decay:.04})}}}class Tx extends st{constructor(e,t,i,n){super(e,t),this.acc=0,this.bees=[];const r=e.currentTime;for(let o=0;o<n.count;o++){const a=this.node(le(e,"lowpass",800,1)),l=this.node(te(e,0,this.out));a.connect(l);const c=L(170,250);this.bees.push({wings:this.source(He(e,"sawtooth",c,a,r)),tone:a,level:l,pitch:c,near:Math.random(),drift:0})}this.out.gain.value=n.base}update(e,t){for(let i=0;i<this.bees.length;i++){const n=this.bees[i];n.drift+=(Math.random()-.5)*2*e,n.drift*=1-.6*e,n.near+=n.drift*e,n.near<0?(n.near=0,n.drift=Math.abs(n.drift)*.3):n.near>1&&(n.near=1,n.drift=-Math.abs(n.drift)*.3)}if(this.acc+=e,!(this.acc<.1)){this.acc=0;for(let i=0;i<this.bees.length;i++){const n=this.bees[i];n.wings.frequency.setTargetAtTime(n.pitch*(1+n.drift*.4),t,.3),n.tone.frequency.setTargetAtTime(500+1500*n.near,t,.3),n.level.gain.setTargetAtTime(.05+.95*n.near*n.near,t,.3)}}}}class _x extends st{constructor(e,t,i,n){super(e,t),this.noise=i,this.base=n.base,this.next=e.currentTime+L(0,.4),this.taps=0,this.acc=0;const r=this.node(le(e,"bandpass",3200,2.5));this.crackle=this.node(te(e,.02,this.out)),r.connect(this.crackle),this.source(Zt(e,i.white,r)),this.out.gain.value=1}update(e,t){const i=this.ctx;for(;this.next<t+.25;){const n=Math.max(this.next,t),r=te(i,0,this.out),o=le(i,"highpass",2600,.8);o.connect(r),Je(i,this.noise.white,o,n,.035),Pe(r.gain,n,this.base*.55,.002,.05);const a=te(i,0,this.out),l=He(i,"sine",180,a,n);l.frequency.exponentialRampToValueAtTime(110,n+.06),l.stop(Pe(a.gain,n,this.base,.003,.09)+.02),this.next=n+1/2.2+L(-.06,.06),++this.taps%8===0&&(this.next+=L(.6,1.6))}this.acc+=e,!(this.acc<.1)&&(this.acc=0,this.crackle.gain.setTargetAtTime(this.base*L(0,.07),t,.05))}}class Sx extends st{constructor(e,t,i,n){super(e,t),this.base=n.base,this.cutoff=170,this.acc=0;const r=e.currentTime;this.filter=this.node(le(e,"lowpass",this.cutoff,5)),this.filter.connect(this.out);const o=this.node(te(e,.5,this.filter));this.source(He(e,"sawtooth",55,o,r)),this.source(He(e,"sawtooth",55.6,o,r));const a=this.node(te(e,.12,this.filter));this.source(He(e,"sawtooth",110.3,a,r)),this.out.gain.value=n.base}update(e,t){this.acc+=e,!(this.acc<.2)&&(this.acc=0,this.cutoff+=(Math.random()-.5)*30,this.cutoff=Math.min(230,Math.max(130,this.cutoff)),this.filter.frequency.setTargetAtTime(this.cutoff,t,.6))}}class $x extends st{constructor(e,t,i,n){super(e,t),this.base=n.base;const r=e.currentTime,o=this.node(le(e,"lowpass",2400,.7));o.connect(this.out);const a=this.node(te(e,.65,o)),l=this.node(te(e,.35,a.gain));this.source(He(e,"sine",55,l,r)),this.sine=this.source(He(e,"sine",210,a,r));const c=this.node(te(e,.22,a));this.saw=this.source(He(e,"sawtooth",210,c,r)),this.out.gain.value=n.base}setLevel(e){const t=210*(.92+.16*e),i=this.ctx.currentTime;this.sine.frequency.setTargetAtTime(t,i,.3),this.saw.frequency.setTargetAtTime(t,i,.3)}}class Ax extends st{constructor(e,t,i,n){super(e,t),this.base=n.base,this.timer=L(.5,2);const r=this.node(le(e,"bandpass",700,.7));r.connect(this.out),this.source(Zt(e,i.brown,r)),this.out.gain.value=n.base*.2}update(e,t){if(this.timer-=e,this.timer>0)return;this.timer=L(1.5,4);const i=this.out.gain;i.cancelScheduledValues(t),i.setTargetAtTime(this.base*L(.6,1),t,.12),i.setTargetAtTime(this.base*.2,t+.35,.3)}}const _l={gull(s,e,t,i){let n=t;const r=2+(Math.random()*2|0);for(let o=0;o<r;o++)ye(s,e,n,{start:L(1400,1700),end:L(850,1e3),duration:.34,gain:i*.5,attack:.03,decay:.12,wobble:[28,70]}),n+=L(.4,.6);return n+.2},parrot(s,e,t,i){let n=t;const r=1+(Math.random()*2|0);for(let o=0;o<r;o++)ye(s,e,n,{start:L(1e3,1300),middle:L(1500,1900),end:L(800,1e3),duration:.28,gain:i*.45,attack:.01,decay:.06,wobble:[180,420]}),n+=L(.3,.5);return n+.2},crow(s,e,t,i){let n=t;const r=2+(Math.random()*2|0);for(let o=0;o<r;o++)ye(s,e,n,{start:L(650,750),end:L(450,520),duration:.26,gain:i*.5,attack:.02,decay:.07,wobble:[95,320]}),n+=L(.32,.45);return n+.2},songbird(s,e,t,i){let n=t;const r=3+(Math.random()*4|0);for(let o=0;o<r;o++){const a=Math.random()<.5,l=L(2500,4200),c=l*(a?L(1.2,1.6):L(.65,.85));ye(s,e,n,{start:l,end:c,duration:L(.06,.12),gain:i*.35,attack:.008,decay:.05,wobble:[40,90]}),n+=L(.1,.2)}return n+.2},owl(s,e,t,i){return ye(s,e,t,{start:390,end:340,duration:.32,gain:i*.6,attack:.06,decay:.15}),ye(s,e,t+.55,{start:380,end:320,duration:.55,gain:i*.6,attack:.08,decay:.25}),t+1.6},thrush(s,e,t,i){let n=t;const r=2+(Math.random()*3|0);for(let o=0;o<r;o++){const a=L(1800,2600);ye(s,e,n,{start:a,middle:a*L(1.15,1.35),end:a*L(.8,.95),duration:L(.18,.3),gain:i*.32,attack:.02,decay:.08}),n+=L(.3,.45)}return n+.2},dove(s,e,t,i){let n=t;for(const[r,o,a]of[[520,560,.28],[600,470,.5],[470,450,.32],[470,450,.32]])ye(s,e,n,{start:r,end:o,duration:a,gain:i*.35,attack:.06,decay:.12}),n+=a+.12;return n+.2},cuckoo(s,e,t,i){return ye(s,e,t,{start:720,end:700,duration:.22,gain:i*.45,attack:.03,decay:.12}),ye(s,e,t+.32,{start:580,end:560,duration:.36,gain:i*.45,attack:.03,decay:.2}),t+1},curlew(s,e,t,i){let n=t;const r=2+(Math.random()*2|0);for(let a=0;a<r;a++){const l=L(1400,1600)+a*120;ye(s,e,n,{start:l,end:l*L(1.3,1.45),duration:L(.32,.42),gain:i*.28,attack:.06,decay:.14}),n+=L(.55,.75)}return ye(s,e,n,{start:L(1700,1900),middle:L(2600,2800),end:L(2300,2500),duration:L(1.4,1.9),gain:i*.3,attack:.2,decay:.35,wobble:[L(14,18),200]})+.2},loon(s,e,t,i){const n=L(.9,1.1),r=L(1,1.5),o=[[0,600*n],[.5,880*n],[1.4,860*n],[1.7,1150*n],[1.7+r,1120*n],[2.3+r,720*n]],a=le(s,"lowpass",1300,.7);a.connect(e);let l=t;for(let c=0;c<3;c++)l=jf(s,c?a:e,t+c*.45,{contour:o,type:"triangle",gain:i*.4*.3**c,attack:.3,hold:1.8+r,decay:.8,vibrato:[5.5,7]});return l}},Ex=[[1,.48,.6],[1.48,.35,.45],[2.15,.16,.3],[2.91,.11,.22],[3.84,.06,.15]],Px=[[1,1,2.4],[2.76,.35,.9],[5.4,.12,.35]],Qd=[0,2,4,7,9,12],Kd=[[1,.5,4.5],[1.0013,.35,4],[2.32,.25,3],[2.3225,.15,2.6],[4.25,.12,1.8],[6.63,.06,1],[9.38,.04,.45]],zx=[[.5,.2,8],[.5025,.12,7.5],[1,.35,7],[1.006,.25,6.5],[1.19,.22,5.5],[1.5,.2,4.5],[2,.45,4],[2.012,.35,3.5],[2.52,.25,2.5],[2.67,.2,2.2],[3.02,.18,1.6],[4.07,.12,1],[5.33,.06,.6]],Lx=[[1,1,1.2],[2,.12,.5],[6.27,.2,.12]],Rx=[0,2,4,7,9,12,14,16,19],Oe={thunder(s,e,t,i,n){const r=le(s,"lowpass",160,.9),o=te(s,0,e);r.connect(o);const a=L(3.5,5.5);Je(s,n.brown,r,t,a+1),r.frequency.setValueAtTime(220,t),r.frequency.exponentialRampToValueAtTime(70,t+a);const l=Pe(o.gain,t,i,.35,a,.4),c=te(s,0,e);return He(s,"sine",36,c,t).stop(Pe(c.gain,t,i*.5,.5,a*.7,.2)+.1),l},gust(s,e,t,i,n){const r=le(s,"bandpass",500,.8),o=te(s,0,e);return r.connect(o),Je(s,n.pink,r,t,4),r.frequency.setValueAtTime(400,t),r.frequency.exponentialRampToValueAtTime(1500,t+1.1),r.frequency.exponentialRampToValueAtTime(450,t+3.2),Pe(o.gain,t,i,1.1,2.2,.2)},wave(s,e,t,i,n){const r=le(s,"bandpass",900,.6),o=te(s,0,e);r.connect(o),Je(s,n.brown,r,t,3.5);const a=Pe(o.gain,t,i,.45,2.4,.1),l=le(s,"highpass",2800,.7),c=te(s,0,e);return l.connect(c),Je(s,n.white,l,t+.3,3.2),Pe(c.gain,t+.3,i*.35,.6,2,.3),a},splash(s,e,t,i,n){const r=le(s,"bandpass",2500,1),o=te(s,0,e);r.connect(o),Je(s,n.white,r,t,.4);const a=Pe(o.gain,t,i*.7,.005,.3);return ye(s,e,t,{start:600,end:180,duration:.07,gain:i*.6,attack:.003,decay:.05}),a},drip(s,e,t,i){const n=L(900,1400),r=ye(s,e,t,{start:n,end:n*2.2,duration:.05,gain:i*.5,attack:.002,decay:.06});return Math.random()<.5&&ye(s,e,t+L(.18,.35),{start:n*.9,end:n*1.9,duration:.04,gain:i*.25,attack:.002,decay:.05}),r+.4},geyser(s,e,t,i,n){const r=le(s,"bandpass",1400,.6),o=te(s,0,e);r.connect(o),Je(s,n.white,r,t,5.5),r.frequency.setValueAtTime(600,t),r.frequency.exponentialRampToValueAtTime(2200,t+1.2),r.frequency.exponentialRampToValueAtTime(900,t+4.5);const a=Pe(o.gain,t,i,.9,2.2,1.8),l=le(s,"lowpass",140,.8),c=te(s,0,e);return l.connect(c),Je(s,n.brown,l,t,5),Pe(c.gain,t,i*.8,.7,2,1.5),a},ember(s,e,t,i,n){let r=t;const o=1+(Math.random()*3|0);for(let a=0;a<o;a++){const l=le(s,"highpass",2200,.8),c=te(s,0,e);l.connect(c),Je(s,n.white,l,r,.04),Pe(c.gain,r,i*.5,.002,.03),ye(s,e,r,{start:L(700,1100),end:250,duration:.05,gain:i*.4,attack:.002,decay:.04}),r+=L(.12,.5)}return r+.1},iceCrack(s,e,t,i,n){const r=le(s,"highpass",3e3,.8),o=te(s,0,e);r.connect(o),Je(s,n.white,r,t,.03),Pe(o.gain,t,i*.6,.001,.025);const a=le(s,"bandpass",L(1500,2100),24),l=te(s,0,e);return a.connect(l),Je(s,n.white,a,t,.05),Pe(l.gain,t,i*1.2,.002,.45),ye(s,e,t+.01,{start:140,end:60,duration:.08,gain:i*.5,attack:.002,decay:.08}),t+.6},woodpecker(s,e,t,i,n){const r=12+(Math.random()*8|0),o=L(15,19),a=L(900,1300);for(let l=0;l<r;l++){const c=t+l/o,h=1-l/r*.6,d=le(s,"bandpass",a,6),u=te(s,0,e);d.connect(u),Je(s,n.white,d,c,.03),Pe(u.gain,c,i*.9*h,.001,.035),ye(s,e,c,{start:a*.35,end:a*.25,duration:.02,gain:i*.25*h,attack:.001,decay:.03})}return t+r/o+.2},deepCall(s,e,t,i){const n=le(s,"lowpass",700,.8),r=te(s,0,e);n.connect(r);const o=s.createOscillator();o.type="sawtooth",o.frequency.setValueAtTime(L(70,85),t),o.frequency.exponentialRampToValueAtTime(L(110,140),t+1.8),o.frequency.exponentialRampToValueAtTime(L(60,75),t+4.2),o.connect(n),o.start(t);const a=He(s,"sine",4,te(s,3,o.frequency),t),l=Pe(r.gain,t,i*.35,1.2,1.8,1.4);return o.stop(l+.05),a.stop(l+.05),l},coyote(s,e,t,i){const n=le(s,"lowpass",1500,.7),r=te(s,0,e);n.connect(r);const o=s.createOscillator();o.frequency.setValueAtTime(480,t),o.frequency.exponentialRampToValueAtTime(920,t+.55),o.frequency.exponentialRampToValueAtTime(860,t+1.4),o.frequency.exponentialRampToValueAtTime(560,t+2.1),o.connect(n),o.start(t);const a=He(s,"sine",5.5,te(s,14,o.frequency),t),l=Pe(r.gain,t,i*.5,.25,.5,1.6);return o.stop(l+.05),a.stop(l+.05),l},wolf(s,e,t,i){const n=L(.9,1.1),r=L(1.8,2.8),o=[[0,340*n],[.7,560*n],[.7+r,600*n],[1.3+r,520*n],[1.9+r,380*n]],a=le(s,"lowpass",1200,.7);a.connect(e);const l=le(s,"lowpass",800,.7);l.connect(e);let c=t;for(let h=0;h<2;h++)c=jf(s,h?l:a,t+h*.6,{contour:o,type:"triangle",gain:i*.5*.3**h,attack:.4,hold:.9+r,decay:1,vibrato:[4.5,5]});return c},distantRoar(s,e,t,i,n){const r=L(.9,1.1),o=le(s,"lowpass",420,.8);o.connect(e);const a=te(s,0,o),l=te(s,.7,a),c=s.createOscillator();c.type="sawtooth",c.frequency.setValueAtTime(110*r,t),c.frequency.exponentialRampToValueAtTime(190*r,t+.45),c.frequency.exponentialRampToValueAtTime(150*r,t+1.4),c.frequency.exponentialRampToValueAtTime(85*r,t+2.4),c.connect(l),c.start(t);const h=He(s,"sine",L(24,32),te(s,.3,l.gain),t),d=le(s,"bandpass",500,.7);d.connect(te(s,.5,a)),Je(s,n.pink,d,t,3);const u=Pe(a.gain,t,i*.5,.4,1.4,1.1);c.stop(u+.05),h.stop(u+.05);let f=t+2.6+L(.2,.4);const p=3+(Math.random()*3|0);for(let m=0;m<p;m++)ye(s,o,f,{start:130*r,end:85*r,duration:.22,gain:i*.45*(1-m/p*.6),type:"sawtooth",attack:.03,decay:.15}),f+=.55+m*.12;return Math.max(u,f+.3)},cowbell(s,e,t,i,n){let r=t;for(let o=0;o<2;o++){const a=o?L(.5,.8):L(0,.25),l=le(s,"lowpass",5e3-a*4e3,.7);l.connect(e);const c=o?L(380,470):L(520,640);let h=t+(o?L(.3,1.2):0);const d=2+(Math.random()*3|0);for(let u=0;u<d;u++){const f=i*(1-a*.7)*L(.5,1);r=Math.max(r,Mi(s,l,h,c,Ex,f));const p=le(s,"bandpass",c*4,2),m=te(s,0,l);p.connect(m),Je(s,n.white,p,h,.02),Pe(m.gain,h,f*.6,.001,.02),h+=L(.22,.55)}}return r},windChimes(s,e,t,i,n){const r=L(560,760),o=L(1.6,2.6),a=5+(Math.random()*6|0);let l=t;for(let d=0;d<a;d++){const u=(Math.random()+Math.random())*.5,f=r*2**(Qd[Math.random()*Qd.length|0]/12);l=Math.max(l,Mi(s,e,t+u*o,f,Px,i*L(.13,.26)*(.4+.6*Math.sin(u*Math.PI))))}const c=le(s,"bandpass",900,.7),h=te(s,0,e);return c.connect(h),Je(s,n.pink,c,t,o+1),Pe(h.gain,t,i*.05,o*.4,o*.8,o*.2),l},bubbles(s,e,t,i){const n=6+(Math.random()*8|0);let r=t,o=t;for(let a=0;a<n;a++){const l=a/n,c=L(400,800)*(1+l*.8);o=Math.max(o,ye(s,e,r,{start:c,end:c*L(1.5,2.2),duration:L(.03,.06),gain:i*L(.25,.45)*(1-l*.5),attack:.003,decay:.05})),r+=L(.03,.12)}return o+.1},crystalChime(s,e,t,i){const n=L(1100,1500),r=le(s,"lowpass",2400,.7);r.connect(e);let o=Mi(s,e,t,n,Kd,i*.4);for(const[a,l]of[[.29,.22],[.67,.09]])o=Math.max(o,Mi(s,r,t+a,n,Kd,i*.4*l));return o},templeBell(s,e,t,i,n){const r=L(120,150),o=le(s,"lowpass",1800,.7);o.connect(e);const a=Mi(s,o,t,r,zx,i*.3);ye(s,o,t,{start:r*1.6,end:r*.7,duration:.06,gain:i*.25,attack:.003,decay:.12});const l=le(s,"lowpass",600,.7),c=te(s,0,o);return l.connect(c),Je(s,n.brown,l,t,.12),Pe(c.gain,t,i*.3,.004,.12),a},twinkle(s,e,t,i){const n=L(880,1100),r=4+(Math.random()*3|0),o=Math.random()*3|0,a=Math.random()<.25;let l=t,c=t;for(let h=0;h<r;h++){const d=Rx[o+(a?r-1-h:h)];c=Math.max(c,Mi(s,e,l,n*2**(d/12),Lx,i*(h===r-1?.3:.22))),l+=L(.08,.11)+h*.01}return c},droneDrop(s,e,t,i,n){const r=te(s,0,e);He(s,"square",2400,r,t).stop(Pe(r.gain,t,i*.12,.002,.03)+.02);const a=le(s,"highpass",4e3,.8),l=te(s,0,e);return a.connect(l),Je(s,n.white,a,t,.02),Pe(l.gain,t,i*.25,.001,.02),ye(s,e,t+.09,{start:140,end:55,duration:.1,gain:i*.8,attack:.004,decay:.12}),t+.4},servoWhirr(s,e,t,i,n,r){const o=Math.min(1,Math.max(0,r?.speed??.5)),a=240+o*260,l=.16+o*.14,c=te(s,0,e),h=le(s,"lowpass",1500+o*1500,.9);h.connect(c);const d=He(s,"sawtooth",a*.85,h,t);d.frequency.setValueAtTime(a*.85,t),d.frequency.linearRampToValueAtTime(a*1.25,t+l*.6),d.frequency.linearRampToValueAtTime(a,t+l);const u=He(s,"square",a*2,te(s,.25,h),t);u.frequency.setValueAtTime(a*2,t),u.frequency.linearRampToValueAtTime(a*2.5,t+l*.6);const f=Pe(c.gain,t,i*.06,.02,l*.8,l*.4);return d.stop(f+.02),u.stop(f+.02),f},botClunk(s,e,t,i,n,r){const o=r?.soft?.45:1;ye(s,e,t,{start:170,end:70,duration:.09,gain:i*.7*o,attack:.003,decay:.16});const a=le(s,"bandpass",1400,1.2),l=te(s,0,e);return a.connect(l),Je(s,n.white,a,t,.04),Pe(l.gain,t,i*.16*o,.001,.05),ye(s,e,t+.005,{start:2100,end:1900,duration:.05,gain:i*.05*o,attack:.002,decay:.12}),t+.3},powerDown(s,e,t,i){return ye(s,e,t,{start:1400,end:120,duration:.7,gain:i*.14,attack:.01,decay:.75,type:"triangle"}),ye(s,e,t+.68,{start:90,end:50,duration:.08,gain:i*.35,attack:.004,decay:.12}),t+.95},powerUp(s,e,t,i){return ye(s,e,t,{start:160,end:1300,duration:.45,gain:i*.12,attack:.02,decay:.5,type:"triangle"}),ye(s,e,t+.5,{start:1760,end:1760,duration:.05,gain:i*.12,attack:.003,decay:.08}),ye(s,e,t+.6,{start:2350,end:2350,duration:.06,gain:i*.12,attack:.003,decay:.1}),t+.8}};function cs(s){return(e,t,i,n)=>(_l[s]||_l.songbird)(e,t,i,n)}function Tr(s){return(e,t,i,n,r,o,a)=>{const l=o?.pitch??1;let c=i;for(const[h,d,u]of s)ye(e,t,c,{start:h*l,end:d*l,duration:u,gain:n*.5,attack:.008,decay:u*.9}),a?.push([c-i,c-i+u]),c+=u+.035;return c+.15}}function Jd(s){return(e,t,i,n,r,o,a)=>{const l=o?.pitch??1;let c=i;for(const[h,d]of s){const u=h*l;ye(e,t,c,{start:u,end:u*.94,duration:d,gain:n*.42,attack:.006,decay:d*.7}),ye(e,t,c,{start:u*2,end:u*1.9,duration:d*.6,gain:n*.09,attack:.004,decay:d*.4}),a?.push([c-i,c-i+d]),c+=d+.05}return c+.12}}const Bx={C:-9,D:-7,E:-5,F:-4,G:-2,A:0,B:2};function Na(s){if(typeof s=="number")return s;const e=typeof s=="string"?/^([A-G])(#?)(\d)$/.exec(s):null;if(!e)throw new Error(`[audio] "${s}" is not a pitch: use Hz, or a note such as "E5" or "D#6"`);return 440*2**((Bx[e[1]]+(e[2]?1:0)+(Number(e[3])-4)*12)/12)}const eu=["start","middle","end","duration","gap","gain","type","wobble","hold"];function Fx(s){return s=s.map((e,t)=>{for(const i of Object.keys(e))if(!eu.includes(i))throw new Error(`[audio] syllable ${t+1} has an unknown property "${i}": use ${eu.join(", ")}`);for(const i of["start","end","duration"])if(e[i]===void 0)throw new Error(`[audio] syllable ${t+1} needs a "${i}"`);return{...e,start:Na(e.start),middle:e.middle===void 0?void 0:Na(e.middle),end:Na(e.end)}}),(e,t,i,n,r,o,a)=>{const l=o?.pitch??1;let c=i;for(const h of s)c+=h.gap??0,ye(e,t,c,{start:h.start*l,middle:h.middle===void 0?void 0:h.middle*l,end:h.end*l,duration:h.duration,hold:h.hold,type:h.type,gain:n*(h.gain??.5),attack:.008,decay:h.duration*.9,wobble:h.wobble&&[h.wobble[0],h.wobble[1]*l]}),a?.push([c-i,c-i+h.duration]),c+=h.duration+.035;return c+.15}}const Ox={"bot-ask-1":[{start:"A5",end:830,duration:.07},{start:"F#5",end:"F#6",duration:.2}],"bot-ask-2":[{start:1180,end:1180,duration:.05},{start:990,end:990,duration:.05},{start:700,middle:760,end:1560,duration:.24}],"bot-ask-3":[{start:1320,end:1e3,duration:.1},{start:900,end:"A6",duration:.18,wobble:[16,35]}],"bot-alarm-1":[{start:700,end:1700,duration:.06,gain:.45},{start:1600,end:1450,duration:.24,wobble:[24,120],gain:.42},{start:760,end:"F#5",duration:.11,gap:.08},{start:540,end:380,duration:.26}],"bot-alarm-2":[{start:900,end:1900,duration:.05,gain:.45},{start:1800,middle:1950,end:1100,duration:.3,wobble:[20,110],gain:.42},{start:620,end:420,duration:.3,gap:.06}],"bot-alarm-3":[{start:1e3,end:1300,duration:.04},{start:1300,end:1700,duration:.04,gap:-.02},{start:1700,end:2400,duration:.05,gap:-.02},{start:2300,end:2100,duration:.2,wobble:[30,220]},{start:600,end:400,duration:.3,gap:.1}],"bot-confirm-1":[{start:"F#6",end:"A#6",duration:.1,gain:.55},{start:"D#6",end:"D#6",duration:.15,gap:.04}],"bot-confirm-2":[{start:"G6",end:"G6",duration:.1,gain:.55},{start:"D6",end:"D6",duration:.11,gap:.02}],"bot-confirm-3":[{start:"C6",end:"C6",duration:.07},{start:"G6",end:"G6",duration:.12,gain:.6},{start:"E6",end:"E6",duration:.1,gap:.03}],"bot-worried-1":[{start:"C6",end:1020,duration:.07},{start:"B5",end:960,duration:.07,gap:.04},{start:"A#5",end:900,duration:.07,gap:.04},{start:"A5",end:860,duration:.16,wobble:[14,20]}],"bot-worried-2":[{start:"B5",end:970,duration:.05},{start:"B5",end:970,duration:.05,gap:-.01},{start:"G#5",end:800,duration:.18,gap:.12,wobble:[16,22]}],"bot-worried-3":[{start:"D6",end:1150,duration:.04},{start:"D6",end:1150,duration:.04,gap:-.015},{start:"D6",end:1150,duration:.04,gap:-.015},{start:"B5",end:950,duration:.07,gap:.05},{start:"A#5",end:"A5",duration:.14,wobble:[15,18]}],"bot-busy-1":[{start:1200,end:1150,duration:.05},{start:900,end:860,duration:.07}],"bot-busy-2":[{start:1e3,end:1300,duration:.05},{start:1300,end:1e3,duration:.06},{start:1e3,end:1e3,duration:.05}],"bot-busy-3":[{start:1400,end:1400,duration:.04},{start:1400,end:1400,duration:.04},{start:1050,end:1e3,duration:.08}],"bot-happy-1":[{start:"C6",end:"C6",duration:.06},{start:"E6",end:"E6",duration:.06},{start:"G6",end:"G6",duration:.06},{start:"C7",end:2240,duration:.16}],"bot-happy-2":[{start:"E6",end:"E6",duration:.045},{start:"G6",end:"G6",duration:.045,gap:-.015},{start:"E6",end:"E6",duration:.045,gap:-.015},{start:"G6",end:"G6",duration:.045,gap:-.015},{start:"C7",end:"C7",duration:.08},{start:"G6",end:"G6",duration:.12}],"bot-happy-3":[{start:"G6",end:"G6",duration:.06},{start:"G6",end:"G6",duration:.06},{start:"C7",end:"C7",duration:.18,wobble:[10,15],gain:.45}],"bot-annoyed-1":[{start:"E5",middle:"D5",end:"D5",duration:.2,type:"triangle",gain:.45},{start:"G5",end:"G5",duration:.08,gap:.26},{start:"A5",end:"F6",duration:.24,gain:.6}],"bot-annoyed-2":[{start:"D6",end:"D6",duration:.06},{start:"D6",end:"D6",duration:.06},{start:"A6",end:"G6",duration:.11,gain:.6,gap:.01},{start:"F#6",end:"C#7",duration:.2,gain:.55}],"bot-annoyed-3":[{start:"G6",end:"G6",duration:.1,gain:.6},{start:"D6",end:"D6",duration:.05},{start:"E6",end:"B6",duration:.18,gain:.6}],"bot-sleeping-1":[{start:560,end:700,duration:.1,type:"triangle",gain:.4},{start:700,middle:340,end:"A1",duration:.9,hold:.25,type:"triangle",gain:.4,gap:-.03},{start:75,end:"A1",duration:.07,type:"triangle",gain:.35,gap:.02}],"bot-sleeping-2":[{start:800,end:620,duration:.12,type:"triangle",gain:.4},{start:620,middle:300,end:50,duration:.85,hold:.25,type:"triangle",gain:.4,gap:-.02}],"bot-sleeping-3":[{start:660,end:640,duration:.06,type:"triangle",gain:.4},{start:520,end:500,duration:.06,type:"triangle",gain:.4},{start:480,middle:"A3",end:45,duration:.95,hold:.3,type:"triangle",gain:.4,wobble:[6,8]}]};function pe(s){return(e,t,i,n)=>{const r=new st(e,t),o=[];return r.until=s(e,r.out,e.currentTime,1,n,i,o)+.05,o.length&&(r.syllables=o),r}}function qf(s){return pe(Fx(s))}const Ix={"wind-soft":(s,e,t,i)=>new fs(s,e,i,{lo:240,hi:900,base:.5,swell:.4,rate:.7}),"wind-desert":(s,e,t,i)=>new fs(s,e,i,{lo:350,hi:1500,base:.55,swell:.6,rate:1.3}),"wind-arctic":(s,e,t,i)=>new fs(s,e,i,{lo:600,hi:2200,base:.45,swell:.55,rate:1,q:1.8}),"wind-high":(s,e,t,i)=>new fs(s,e,i,{lo:500,hi:1800,base:.45,swell:.35,rate:.9,q:1.2}),"snow-wind":(s,e,t,i)=>new fs(s,e,i,{lo:300,hi:1100,base:.35,swell:.5,rate:.6,q:1.5}),"mars-wind":(s,e,t,i)=>new fs(s,e,i,{lo:1800,hi:3800,base:.22,swell:.6,rate:1.4,q:1.5,type:"bandpass",noise:"white"}),"cherry-breeze":(s,e,t,i)=>new fs(s,e,i,{lo:200,hi:700,base:.28,swell:.5,rate:.5}),"autumn-rustle":(s,e,t,i)=>new Da(s,e,i,{center:2600,q:.8,base:.22,depth:.7,speed:9}),surf:(s,e,t,i)=>new Ia(s,e,i,{center:500,base:.6,period:[7,13]}),"surf-gentle":(s,e,t,i)=>new Ia(s,e,i,{center:380,base:.32,period:[8,13]}),"ocean-swell":(s,e,t,i)=>new Ia(s,e,i,{center:220,base:.45,period:[9,16],type:"lowpass",q:.8}),stream:(s,e,t,i)=>new Da(s,e,i,{center:1300,q:.6,base:.3,depth:.25,speed:12}),"jungle-insects":(s,e,t,i)=>new bx(s,e,i,{base:.16}),"jungle-birds":(s,e,t,i)=>new Va(s,e,i,{base:.5,kinds:["parrot","songbird","songbird"],every:[3,9],hiss:.05}),"meadow-birds":(s,e,t,i)=>new Va(s,e,i,{base:.35,kinds:["songbird"],every:[4,12]}),"forest-birds":(s,e,t,i)=>new Va(s,e,i,{base:.4,kinds:["songbird","thrush","songbird","dove","thrush"],every:[1.5,5],hiss:.03}),"rainforest-rain":(s,e,t,i)=>new Da(s,e,i,{center:1800,q:.3,base:.35,depth:.15,speed:4}),crickets:(s,e,t,i)=>new gx(s,e,i,{base:.18}),frogs:(s,e,t,i)=>new wx(s,e,i,{base:.16}),"lava-rumble":(s,e,t,i)=>new vx(s,e,i,{base:.6}),"volcanic-hiss":(s,e,t,i)=>new yx(s,e,i,{base:.12}),"lunar-silence":(s,e,t,i)=>new Cx(s,e,i,{base:.07,freq:48,radio:.05}),cicadas:(s,e,t,i)=>new xx(s,e,i,{base:.6,center:L(4800,5800),period:[12,22]}),waterfall:(s,e,t,i)=>new Mx(s,e,i,{lo:900,hi:1600,base:.35,swell:.15,rate:.5,q:.5,rumble:.5}),underwater:(s,e,t,i)=>new kx(s,e,i,{lo:150,hi:450,base:.35,swell:.5,rate:.4,noise:"brown",bubbles:.25}),bees:(s,e,t,i)=>new Tx(s,e,i,{base:.06,count:3}),gull:pe(cs("gull")),parrot:pe(cs("parrot")),crow:pe(cs("crow")),songbird:pe(cs("songbird")),owl:pe(cs("owl")),"bird-call":pe((s,e,t,i,n,r)=>cs(r?.kind)(s,e,t,i)),"thunder-distant":pe(Oe.thunder),"wind-gust":pe(Oe.gust),"wave-crash":pe(Oe.wave),"fish-splash":pe(Oe.splash),geyser:pe(Oe.geyser),drip:pe(Oe.drip),"ember-pop":pe(Oe.ember),"ice-crack":pe(Oe.iceCrack),coyote:pe(Oe.coyote),woodpecker:pe(Oe.woodpecker),cuckoo:pe(cs("cuckoo")),"deep-call":pe(Oe.deepCall),cowbell:pe(Oe.cowbell),"wind-chimes":pe(Oe.windChimes),bubbles:pe(Oe.bubbles),"distant-roar":pe(Oe.distantRoar),loon:pe(cs("loon")),wolf:pe(Oe.wolf),curlew:pe(cs("curlew")),"crystal-chime":pe(Oe.crystalChime),"temple-bell":pe(Oe.templeBell),twinkle:pe(Oe.twinkle),"drone-drop":pe(Oe.droneDrop),"servo-whirr":pe(Oe.servoWhirr),"bot-clunk":pe(Oe.botClunk),"power-down":pe(Oe.powerDown),"power-up":pe(Oe.powerUp),"select-1":pe(Tr([[880,1320,.09],[1320,1180,.12]])),"select-2":pe(Jd([[1318,.08],[659,.13]])),"select-3":pe(Jd([[784,.07],[1046,.07],[1568,.11]])),"select-4":pe(Tr([[520,780,.08],[780,1040,.08],[1040,1300,.12]])),"select-5":pe(Tr([[980,980,.07],[980,980,.07],[1470,1240,.14]])),"select-6":pe(Tr([[1200,900,.1],[600,1e3,.16]])),...Object.fromEntries(Object.entries(Ox).map(([s,e])=>[s,qf(e)])),"work-hammer":(s,e,t,i)=>new _x(s,e,i,{base:.5}),"ship-hum":(s,e,t,i)=>new Sx(s,e,i,{base:.2}),"drone-whine":(s,e,t,i)=>new $x(s,e,i,{base:.22}),"shore-lap":(s,e,t,i)=>new Ax(s,e,i,{base:.4})},tu={"wind-soft":{kind:"bed",gain:1},"wind-desert":{kind:"bed",gain:1},"wind-arctic":{kind:"bed",gain:1},"wind-high":{kind:"bed",gain:1},surf:{kind:"bed",gain:1},"surf-gentle":{kind:"bed",gain:1},"ocean-swell":{kind:"bed",gain:1},"jungle-insects":{kind:"bed",gain:1},"jungle-birds":{kind:"bed",gain:1},"rainforest-rain":{kind:"bed",gain:1},crickets:{kind:"bed",gain:1},frogs:{kind:"bed",gain:1},"meadow-birds":{kind:"bed",gain:1},"forest-birds":{kind:"bed",gain:1},"lava-rumble":{kind:"bed",gain:1},"volcanic-hiss":{kind:"bed",gain:1},"snow-wind":{kind:"bed",gain:1},"autumn-rustle":{kind:"bed",gain:1},"cherry-breeze":{kind:"bed",gain:1},"lunar-silence":{kind:"bed",gain:1},"mars-wind":{kind:"bed",gain:1},stream:{kind:"bed",gain:1},cicadas:{kind:"bed",gain:1},waterfall:{kind:"bed",gain:1},underwater:{kind:"bed",gain:1},bees:{kind:"bed",gain:1},gull:{kind:"event",gain:.8,volume:"wildlifeVolume"},parrot:{kind:"event",gain:.8,volume:"wildlifeVolume"},crow:{kind:"event",gain:.8,volume:"wildlifeVolume"},songbird:{kind:"event",gain:.8,volume:"wildlifeVolume"},owl:{kind:"event",gain:.8,volume:"wildlifeVolume"},"thunder-distant":{kind:"event",gain:.9},"wind-gust":{kind:"event",gain:.7},"wave-crash":{kind:"event",gain:.8},"fish-splash":{kind:"event",gain:.6,volume:"wildlifeVolume"},geyser:{kind:"event",gain:.8},drip:{kind:"event",gain:.6},"ember-pop":{kind:"event",gain:.6},"ice-crack":{kind:"event",gain:.7},"wind-chimes":{kind:"event",gain:.6},bubbles:{kind:"event",gain:.6},"crystal-chime":{kind:"event",gain:.6},"temple-bell":{kind:"event",gain:.8},twinkle:{kind:"event",gain:.6},coyote:{kind:"event",gain:.6,volume:"wildlifeVolume"},woodpecker:{kind:"event",gain:.6,volume:"wildlifeVolume"},cuckoo:{kind:"event",gain:.7,volume:"wildlifeVolume"},"deep-call":{kind:"event",gain:.8,volume:"wildlifeVolume"},cowbell:{kind:"event",gain:.6,volume:"wildlifeVolume"},"distant-roar":{kind:"event",gain:.8,volume:"wildlifeVolume"},loon:{kind:"event",gain:.6,volume:"wildlifeVolume"},wolf:{kind:"event",gain:.6,volume:"wildlifeVolume"},curlew:{kind:"event",gain:.8,volume:"wildlifeVolume"},"bird-call":{kind:"event",gain:.8,volume:"wildlifeVolume"},"drone-drop":{kind:"event",gain:.7,volume:"dronesVolume"},"servo-whirr":{kind:"event",gain:.7,volume:"machineryVolume"},"bot-clunk":{kind:"event",gain:.8,volume:"machineryVolume"},"power-down":{kind:"event",gain:.7,volume:"machineryVolume"},"power-up":{kind:"event",gain:.7,volume:"machineryVolume"},"select-1":{kind:"event",gain:.55,volume:"botVoicesVolume",falloff:!1},"select-2":{kind:"event",gain:.55,volume:"botVoicesVolume",falloff:!1},"select-3":{kind:"event",gain:.55,volume:"botVoicesVolume",falloff:!1},"select-4":{kind:"event",gain:.55,volume:"botVoicesVolume",falloff:!1},"select-5":{kind:"event",gain:.55,volume:"botVoicesVolume",falloff:!1},"select-6":{kind:"event",gain:.55,volume:"botVoicesVolume",falloff:!1},"bot-ask-1":{kind:"event",gain:.6,volume:"botVoicesVolume",falloff:!1},"bot-ask-2":{kind:"event",gain:.6,volume:"botVoicesVolume",falloff:!1},"bot-ask-3":{kind:"event",gain:.6,volume:"botVoicesVolume",falloff:!1},"bot-alarm-1":{kind:"event",gain:.55,volume:"botVoicesVolume",falloff:!1},"bot-alarm-2":{kind:"event",gain:.55,volume:"botVoicesVolume",falloff:!1},"bot-alarm-3":{kind:"event",gain:.55,volume:"botVoicesVolume",falloff:!1},"bot-confirm-1":{kind:"event",gain:.55,volume:"botVoicesVolume",falloff:!1},"bot-confirm-2":{kind:"event",gain:.55,volume:"botVoicesVolume",falloff:!1},"bot-confirm-3":{kind:"event",gain:.55,volume:"botVoicesVolume",falloff:!1},"bot-worried-1":{kind:"event",gain:.55,volume:"botVoicesVolume",falloff:!1},"bot-worried-2":{kind:"event",gain:.55,volume:"botVoicesVolume",falloff:!1},"bot-worried-3":{kind:"event",gain:.55,volume:"botVoicesVolume",falloff:!1},"bot-busy-1":{kind:"event",gain:.55,volume:"botVoicesVolume",falloff:!1},"bot-busy-2":{kind:"event",gain:.55,volume:"botVoicesVolume",falloff:!1},"bot-busy-3":{kind:"event",gain:.55,volume:"botVoicesVolume",falloff:!1},"bot-happy-1":{kind:"event",gain:.55,volume:"botVoicesVolume",falloff:!1},"bot-happy-2":{kind:"event",gain:.55,volume:"botVoicesVolume",falloff:!1},"bot-happy-3":{kind:"event",gain:.55,volume:"botVoicesVolume",falloff:!1},"bot-annoyed-1":{kind:"event",gain:.55,volume:"botVoicesVolume",falloff:!1},"bot-annoyed-2":{kind:"event",gain:.55,volume:"botVoicesVolume",falloff:!1},"bot-annoyed-3":{kind:"event",gain:.55,volume:"botVoicesVolume",falloff:!1},"bot-sleeping-1":{kind:"event",gain:.55,volume:"botVoicesVolume",falloff:!1},"bot-sleeping-2":{kind:"event",gain:.55,volume:"botVoicesVolume",falloff:!1},"bot-sleeping-3":{kind:"event",gain:.55,volume:"botVoicesVolume",falloff:!1},"work-hammer":{kind:"loop",gain:1,volume:"workingVolume"},"ship-hum":{kind:"loop",gain:1,volume:"shipVolume"},"drone-whine":{kind:"loop",gain:1,volume:"dronesVolume"},"shore-lap":{kind:"loop",gain:1,bus:"ambience"}},Bs={};for(const s of Object.keys(tu)){const e=Ix[s];if(typeof e!="function")throw new Error(`[audio] "${s}" is registered without a synth`);const{kind:t,gain:i,volume:n=null,bus:r=null,falloff:o=!0}=tu[s];Bs[s]={kind:t,gain:i,volume:n,bus:r,falloff:o,synth:e}}Object.freeze(Object.keys(Bs));function zi(s){return Array.isArray(s)?{kind:"event",gain:.55,volume:"botVoicesVolume",bus:null,falloff:!1,synth:qf(s)}:Bs[s]}const su="/",Dx="audio/manifest.json",_r=10,iu=3,nu=.13,Vx=.6,ru=14,Nx=75,Wx=.12,Wa=1.5,ou=[10,24],un={panningModel:"equalpower",distanceModel:"inverse",refDistance:7,rolloffFactor:1.15,maxDistance:300},Vr=Object.freeze([]),Hx=Object.freeze({night:0,sources:Vr,water:null}),au=Math.PI/2,lu=Object.freeze({gain:1}),Sr=(s,e)=>s+Math.random()*(e-s),Ha=s=>s<0?0:s>1?1:s,Ux=["masterVolume","ambienceVolume","effectsVolume",...new Set(Object.values(Bs).map(s=>s.volume).filter(Boolean))];class jx{constructor(e){this.settings=e,this.ctx=null,this.master=null,this.mute=null,this.compressor=null,this.ambienceBus=null,this.effectsBus=null,this._channels=new Map,this._speaking=new Map,this._enabled=this._flag("sound",!0),this._visible=typeof document>"u"?!0:!document.hidden,this._planet=null,this._beds=null,this._retiring=[],this._events=[],this._pool=[],this._byId=new Map,this._oneshots=[],this._auditions=[],this._buffers=new Map,this._manifest=null,this._noise=null,this._warned=new Set,this._sleepTimer=0,this._frame=0,this._sweepAt=0,this._night=-1,this._slots=[];for(let t=0;t<_r;t++)this._slots.push({src:null,d:0});if(this._slotCount=0,this._shore=[],this._shoreMix=1,this._water=null,this._shot={x:0,y:0,z:0,gain:1,kind:void 0},this._shot2d={gain:1,kind:void 0},this._lx=0,this._ly=0,this._lz=0,this._fx=0,this._fy=0,this._fz=-1,this._ux=0,this._uy=1,this._uz=0,this._listenerSet=!1,this._unsub=typeof e?.onChange=="function"?e.onChange(t=>this._onSettings(t)):null,typeof document<"u"&&document.addEventListener&&(this._onGesture=()=>this.unlock(),document.addEventListener("pointerdown",this._onGesture,{passive:!0}),document.addEventListener("keydown",this._onGesture,{passive:!0}),this._onVisibility=()=>{this._visible=!document.hidden,this._applyMute()},document.addEventListener("visibilitychange",this._onVisibility)),typeof fetch=="function")try{fetch(su+Dx).then(t=>t.ok?t.json():null).then(t=>{t&&t.sounds&&typeof t.sounds=="object"&&(this._manifest=t)}).catch(()=>{})}catch{}}unlock(){const e=typeof globalThis<"u"?globalThis.AudioContext||globalThis.webkitAudioContext:null;if(e){if(!this.ctx){try{try{this.ctx=new e({latencyHint:"playback"})}catch{this.ctx=new e}}catch(t){this._warn("ctx",`[ambience] no audio: ${t?.message||t}`);return}this._buildMixer(),this._enabled&&this._startBeds(this._planet?.audio,0)}if(this._enabled)if(this.ctx.state!=="running"&&typeof this.ctx.resume=="function")try{const t=this.ctx.resume();t&&typeof t.then=="function"&&t.then(()=>{this.ctx&&this.ctx.state==="running"&&this._dropGestureListeners()}).catch(()=>{})}catch{}else this._dropGestureListeners()}}get ready(){return!!this.ctx&&this.ctx.state==="running"}setPlanet(e){if(e===this._planet&&this._planet)return;this._planet=e||null;const t=e?.audio||null;this._events.length=0;const i=t?.events||Vr;for(let n=0;n<i.length;n++){const r=i[n];if(!r||!Bs[r.sound]){this._warn("event:"+r?.sound,`[ambience] unknown event sound "${r?.sound}"`);continue}const o=Math.max(.5,r.every?.[0]??10),a=Math.max(o,r.every?.[1]??o*2);this._events.push({sound:r.sound,min:o,max:a,gain:r.gain??1,when:r.when||"any",where:r.where||"ring",kind:r.kind,timer:Sr(o,a)*Sr(.2,.8)})}this._shore.length=0,this.ctx&&this._enabled&&this._startBeds(t,iu)}update(e,t,i){if(!this.ctx||!this._enabled)return;i=i||Hx;const n=this.ctx.currentTime,r=Ha(i.night??0);this._updateListener(t,n),this._updateBeds(e,n,r,i.water),this._updateEvents(e,r),this._updatePool(e,n,i),n>=this._sweepAt&&(this._sweepAt=n+.5,this._sweepOneshots(n)),this._auditions.length&&this._tickAuditions(e,n)}play(e,t){return this._shoot(e,t||lu,this.effectsBus)}speak(e,t,i){const n=this._speaking.get(e);if(n&&this.ctx&&this.ctx.currentTime<n.until)return null;const r=this.play(t,i);return r&&this._speaking.set(e,r),r}audition(e,t=8){const i=Bs[e];if(this.unlock(),!i||!this.ctx||!this._enabled)return()=>{};if(i.kind==="event")return this.play(e,{gain:1}),()=>{};const n=this.ctx,r=this._start(e,this._channel(e,this.effectsBus),lu,!0),o=r.out.gain,a=n.currentTime,l=Math.max(1e-4,this._baseGain(e,r));o.setValueAtTime(1e-4,a),o.exponentialRampToValueAtTime(l,a+.6);const c={voice:r,stopAt:a+t,done:!1};return c.stop=()=>{if(c.done)return;c.done=!0;const h=n.currentTime;o.cancelScheduledValues(h),o.setValueAtTime(Math.max(1e-4,o.value),h),o.exponentialRampToValueAtTime(1e-4,h+.5),r.stop(h+.55),typeof setTimeout=="function"&&setTimeout(()=>r.dispose(),700)},this._auditions.push(c),c.stop}sourceOf(e){const t=this._entry(e);return this._buffers.get(e)||t&&typeof t.file=="string"&&t._state!=="failed"?"sample":"synth"}_tickAuditions(e,t){const i=this._auditions;for(let n=i.length-1;n>=0;n--){const r=i[n];r.done||r.voice.update?.(e,t),!r.done&&t>=r.stopAt&&r.stop(),r.done&&t>r.stopAt+1&&i.splice(n,1)}}setEnabled(e){e=!!e,this._enabled!==e&&(this._enabled=e,this._sleepTimer&&(clearTimeout(this._sleepTimer),this._sleepTimer=0),this.ctx&&(this._applyMute(),e?this._wake():typeof setTimeout=="function"?this._sleepTimer=setTimeout(()=>{this._sleepTimer=0,this._sleep()},600):this._sleep()))}dispose(){if(this._sleepTimer&&clearTimeout(this._sleepTimer),this._sleepTimer=0,this._unsub?.(),this._unsub=null,this._dropGestureListeners(),this._onVisibility&&typeof document<"u"&&(document.removeEventListener("visibilitychange",this._onVisibility),this._onVisibility=null),this.ctx){this._stopEverything();try{this.ctx.close?.()?.catch?.(()=>{})}catch{}this.ctx=null}this._buffers.clear(),this._noise=null}_flag(e,t){const i=this.settings?.get?.(e);return i==null?t:!!i}_vol(e,t){const i=this.settings?.get?.(e);return typeof i=="number"&&Number.isFinite(i)?Ha(i):t}_onSettings(e){e.has("sound")&&this.setEnabled(this._flag("sound",!0)),Ux.some(t=>e.has(t))&&this._applyVolumes()}recordingStream(){if(!this.ctx||!this.compressor||!this._enabled)return null;const e=this.ctx.createMediaStreamDestination();return this.compressor.connect(e),{track:e.stream.getAudioTracks()[0],release:()=>this.compressor.disconnect(e)}}_buildMixer(){const e=this.ctx,t=e.createDynamicsCompressor();t.threshold.value=-12,t.ratio.value=3,t.knee.value=12,t.attack.value=.01,t.release.value=.25,t.connect(e.destination);const i=e.createGain();i.gain.value=this._enabled&&this._visible?1:0,i.connect(t);const n=e.createGain();n.gain.value=this._vol("masterVolume",.6),n.connect(i);const r=e.createGain();r.gain.value=this._vol("ambienceVolume",.8),r.connect(n);const o=e.createGain();o.gain.value=this._vol("effectsVolume",.8),o.connect(n),this.compressor=t,this.mute=i,this.master=n,this.ambienceBus=r,this.effectsBus=o,this._channels=new Map}_applyMute(){if(!this.mute)return;const e=this._enabled&&this._visible?1:0;this.mute.gain.setTargetAtTime(e,this.ctx.currentTime,.12)}_applyVolumes(){if(!this.master)return;const e=this.ctx.currentTime;this.master.gain.setTargetAtTime(this._vol("masterVolume",.6),e,.05),this.ambienceBus.gain.setTargetAtTime(this._vol("ambienceVolume",.8),e,.05),this.effectsBus.gain.setTargetAtTime(this._vol("effectsVolume",.8),e,.05);for(const[t,i]of this._channels)for(const n of i.values())n.gain.setTargetAtTime(this._vol(t,.8),e,.05)}_channel(e,t){const i=zi(e)?.volume;if(!i||!t)return t;const n=t===this.effectsBus?this.master:t;let r=this._channels.get(i);r||(r=new Map,this._channels.set(i,r));let o=r.get(n);return o||(o=this.ctx.createGain(),o.gain.value=this._vol(i,.8),o.connect(n),r.set(n,o)),o}_wake(){if(this.ctx.state!=="running"&&typeof this.ctx.resume=="function")try{this.ctx.resume()?.catch?.(()=>{})}catch{}this._beds||this._startBeds(this._planet?.audio,0)}_sleep(){if(!(!this.ctx||this._enabled)){this._stopEverything();try{this.ctx.suspend?.()?.catch?.(()=>{})}catch{}}}_stopEverything(){this._beds&&this._disposeGroup(this._beds),this._beds=null;for(let e=0;e<this._retiring.length;e++)this._disposeGroup(this._retiring[e]);this._retiring.length=0;for(let e=0;e<this._pool.length;e++)this._disposeVoice(this._pool[e]);this._pool.length=0,this._byId.clear();for(let e=0;e<this._oneshots.length;e++)this._disposeOneshot(this._oneshots[e]);this._oneshots.length=0}_dropGestureListeners(){!this._onGesture||typeof document>"u"||(document.removeEventListener("pointerdown",this._onGesture),document.removeEventListener("keydown",this._onGesture),this._onGesture=null)}_warn(e,t){this._warned.has(e)||(this._warned.add(e),typeof console<"u"&&console.warn(t))}_noiseBuffers(){return this._noise||(this._noise=px(this.ctx)),this._noise}_entry(e){return this._manifest?this._manifest.sounds[e]:void 0}_start(e,t,i,n){const r=zi(e),o=this._buffers.get(e);if(o){const a=this._entry(e);return new mx(this.ctx,t,o,a,typeof a?.loop=="boolean"?a.loop:n)}return this._load(e),r.synth(this.ctx,t,i,this._noiseBuffers())}_baseGain(e,t){const i=zi(e);if(!t.isSample)return i.gain;const n=this._entry(e);return i.gain*(typeof n?.gain=="number"?n.gain:1)}_load(e){const t=this._entry(e);if(!t||t._state||typeof t.file!="string"||typeof fetch!="function")return;t._state="loading";const i=t.file,n=/^(https?:)?\/\//.test(i)||i.startsWith("/")?i:su+i,r=this.ctx;fetch(n).then(o=>{if(!o.ok)throw new Error(`HTTP ${o.status}`);return o.arrayBuffer()}).then(o=>new Promise((a,l)=>{const c=r.decodeAudioData(o,a,l);c&&typeof c.then=="function"&&c.then(a,l)})).then(o=>{this.ctx===r&&(t._state="ready",this._buffers.set(e,o),this._onBufferReady(e))}).catch(o=>{t._state="failed",this._warn("load:"+e,`[ambience] "${e}": could not use ${i} (${o?.message||o}); the synth plays instead`)})}_onBufferReady(e){const t=this._beds;if(!t)return;const i=this.ctx.currentTime;for(let n=0;n<t.layers.length;n++){const r=t.layers[n];if(r.spec.sound!==e||r.voice.isSample||r.retiring)continue;const o=this._start(e,r.gain,r.spec,!0);o.out.gain.value=0,o.out.gain.setTargetAtTime(1,i,Wa/3),r.voice.out.gain.setTargetAtTime(0,i,Wa/3),r.retiring=r.voice,r.retireAt=i+Wa+.3,r.voice=o,r.base=this._baseGain(e,o),r.gain.gain.setTargetAtTime(this._layerLevel(r,Math.max(0,this._night)),i,.3)}}_startBeds(e,t){const i=this.ctx;this._beds&&(this._beds.dir=-1,this._retiring.push(this._beds),this._beds=null);const n={mix:i.createGain(),layers:[],progress:t>0?0:1,dir:t>0?1:0,rate:1/iu};n.mix.gain.value=t>0?0:1,n.mix.connect(this.ambienceBus);const r=Math.max(0,this._night),o=e?.beds||Vr;for(let a=0;a<o.length;a++){const l=o[a];if(!l||!Bs[l.sound]){this._warn("bed:"+l?.sound,`[ambience] unknown bed sound "${l?.sound}"`);continue}const c=l.gain??1,h={spec:l,gain:i.createGain(),voice:null,retiring:null,retireAt:0,day:l.day??c,night:l.night??c,base:1};h.gain.connect(n.mix),h.voice=this._start(l.sound,h.gain,l,!0),h.base=this._baseGain(l.sound,h.voice),h.gain.gain.value=this._layerLevel(h,r),n.layers.push(h)}this._beds=n}_layerLevel(e,t){const i=e.spec.shore?this._shoreMix:1;return e.base*(e.day+(e.night-e.day)*t)*i}_shoreMixFor(e){const t=e?.points?.[0];if(!t||e.focusX===void 0)return 1;const i=Math.hypot(t.x-e.focusX,t.z-e.focusZ);return 1-Math.min(1,Math.max(0,(i-ru)/(Nx-ru)))*(1-Wx)}_disposeGroup(e){for(let t=0;t<e.layers.length;t++){const i=e.layers[t];i.voice?.dispose(),i.retiring?.dispose();try{i.gain.disconnect()}catch{}}try{e.mix.disconnect()}catch{}}_updateBeds(e,t,i,n){const r=this._shoreMixFor(n),o=Math.abs(r-this._shoreMix)>.01;o&&(this._shoreMix=r);const a=Math.abs(i-this._night)>.004||o;a&&(this._night=i);const l=this._beds;l&&(l.dir>0&&(l.progress+=e*l.rate,l.progress>=1&&(l.progress=1,l.dir=0),l.mix.gain.setTargetAtTime(Math.sin(l.progress*au),t,.05)),this._tickLayers(l,e,t,i,a));for(let c=this._retiring.length-1;c>=0;c--){const h=this._retiring[c];if(h.progress-=e*h.rate,h.progress<=0){this._disposeGroup(h),this._retiring[c]=this._retiring[this._retiring.length-1],this._retiring.pop();continue}h.mix.gain.setTargetAtTime(Math.sin(h.progress*au),t,.05),this._tickLayers(h,e,t,i,a)}}_tickLayers(e,t,i,n,r){for(let o=0;o<e.layers.length;o++){const a=e.layers[o];r&&a.gain.gain.setTargetAtTime(this._layerLevel(a,n),i,.5),a.voice.update(t,i),a.retiring&&i>=a.retireAt&&(a.retiring.dispose(),a.retiring=null)}}_updateEvents(e,t){for(let i=0;i<this._events.length;i++){const n=this._events[i];n.timer-=e,!(n.timer>0)&&(n.timer=Sr(n.min,n.max),!(n.when==="night"&&t<.5)&&(n.when==="day"&&t>=.5||this._fireEvent(n)))}}_fireEvent(e){if(!this.ready)return;let t=this._shot2d;if(e.where==="water"||e.where==="ring"){const i=this._shot,n=e.where==="water"?this._water:null,r=n?.points;if(r&&r.length){const o=r[Math.random()*r.length|0];i.x=o.x,i.y=n.level??0,i.z=o.z}else{const o=Math.random()*Math.PI*2,a=Sr(ou[0],ou[1]);i.x=this._lx+Math.cos(o)*a,i.y=this._ly,i.z=this._lz+Math.sin(o)*a}t=i}t.gain=e.gain,t.kind=e.kind,this._shoot(e.sound,t,this.ambienceBus)}_shoot(e,t,i){const n=zi(e);if(!n)return this._warn("sound:"+e,`[ambience] unknown sound "${e}"`),null;if(!this.ready||!this._enabled||!i)return null;const r=this.ctx,o=r.currentTime,a=typeof t.x=="number"&&typeof t.z=="number",l=this._channel(e,i);let c=l,h=null;a&&(h=this._createPanner(n),this._place(h,t.x,t.y??0,t.z,o,!0),h.connect(l),c=h);const d=r.createGain();d.connect(c);const u=this._start(e,d,t,n.kind!=="event");d.gain.value=this._baseGain(e,u)*(t.gain??1),Number.isFinite(u.until)||(u.until=o+8,d.gain.setTargetAtTime(0,o+7,.25));const f={voice:u,level:d,panner:h};return this._oneshots.push(f),f.voice}_sweepOneshots(e){const t=this._oneshots;for(let i=t.length-1;i>=0;i--)e<t[i].voice.until||(this._disposeOneshot(t[i]),t[i]=t[t.length-1],t.pop())}_disposeOneshot(e){e.voice.dispose();try{e.level.disconnect(),e.panner?.disconnect()}catch{}}_createPanner(e){const t=this.ctx.createPanner();return t.panningModel=un.panningModel,t.distanceModel=un.distanceModel,t.refDistance=un.refDistance,t.rolloffFactor=e?.falloff===!1?0:un.rolloffFactor,t.maxDistance=un.maxDistance,t}_place(e,t,i,n,r,o){e.positionX?o?(e.positionX.setValueAtTime(t,r),e.positionY.setValueAtTime(i,r),e.positionZ.setValueAtTime(n,r)):(e.positionX.setTargetAtTime(t,r,.05),e.positionY.setTargetAtTime(i,r,.05),e.positionZ.setTargetAtTime(n,r,.05)):e.setPosition&&e.setPosition(t,i,n)}_updateListener(e,t){const i=e?.matrixWorld?.elements;if(!i)return;const n=i[12],r=i[13],o=i[14];let a=-i[8],l=-i[9],c=-i[10],h=Math.hypot(a,l,c)||1;a/=h,l/=h,c/=h;let d=i[4],u=i[5],f=i[6],p=Math.hypot(d,u,f)||1;d/=p,u/=p,f/=p;const m=.001;if(!(!this._listenerSet||Math.abs(n-this._lx)>m||Math.abs(r-this._ly)>m||Math.abs(o-this._lz)>m||Math.abs(a-this._fx)>m||Math.abs(l-this._fy)>m||Math.abs(c-this._fz)>m||Math.abs(d-this._ux)>m||Math.abs(u-this._uy)>m||Math.abs(f-this._uz)>m))return;this._lx=n,this._ly=r,this._lz=o,this._fx=a,this._fy=l,this._fz=c,this._ux=d,this._uy=u,this._uz=f;const w=this.ctx.listener;if(w){if(w.positionX){const b=!this._listenerSet,y=.03;b?(w.positionX.setValueAtTime(n,t),w.positionY.setValueAtTime(r,t),w.positionZ.setValueAtTime(o,t),w.forwardX.setValueAtTime(a,t),w.forwardY.setValueAtTime(l,t),w.forwardZ.setValueAtTime(c,t),w.upX.setValueAtTime(d,t),w.upY.setValueAtTime(u,t),w.upZ.setValueAtTime(f,t)):(w.positionX.setTargetAtTime(n,t,y),w.positionY.setTargetAtTime(r,t,y),w.positionZ.setTargetAtTime(o,t,y),w.forwardX.setTargetAtTime(a,t,y),w.forwardY.setTargetAtTime(l,t,y),w.forwardZ.setTargetAtTime(c,t,y),w.upX.setTargetAtTime(d,t,y),w.upY.setTargetAtTime(u,t,y),w.upZ.setTargetAtTime(f,t,y))}else w.setPosition&&(w.setPosition(n,r,o),w.setOrientation(a,l,c,d,u,f));this._listenerSet=!0}}_updatePool(e,t,i){this._frame++,this._slotCount=0,this._water=i.water||null;const n=i.sources||Vr;for(let c=0;c<n.length;c++){const h=n[c];h&&h.id&&h.sound&&this._consider(h)}const r=this._planet?.audio?.shore?i.water:null,o=r?.points;if(o&&o.length){if(this._shore.length!==o.length){this._shore.length=0;for(let c=0;c<o.length;c++)this._shore.push({id:"shore:"+c,sound:"shore-lap",x:0,y:0,z:0,gain:1})}for(let c=0;c<o.length;c++){const h=this._shore[c];h.x=o[c].x,h.y=r.level??0,h.z=o[c].z,this._consider(h)}}else this._shore.length&&(this._shore.length=0);const a=this._frame;for(let c=0;c<this._slotCount;c++){const h=this._slots[c].src,d=this._byId.get(h.id);d&&(d.seen=a,d.src=h,d.dying&&(d.dying=!1,d.level=-1))}const l=this._pool;for(let c=0;c<l.length;c++){const h=l[c];h.seen!==a&&!h.dying&&(h.dying=!0,h.stopAt=t+Vx,h.gain.gain.setTargetAtTime(0,t,nu))}if(this.ready)for(let c=0;c<this._slotCount&&l.length<_r;c++){const h=this._slots[c].src;this._byId.has(h.id)||this._addVoice(h,t)}for(let c=l.length-1;c>=0;c--){const h=l[c];if(h.dying){t>=h.stopAt&&(this._disposeVoice(h),this._byId.delete(h.id),l[c]=l[l.length-1],l.pop());continue}const d=h.src,u=d.gain??1,f=h.base*u;Math.abs(f-h.level)>.004&&(h.level=f,h.gain.gain.setTargetAtTime(f,t,nu),h.voice.setLevel(Ha(u))),(d.x!==h.x||d.y!==h.y||d.z!==h.z)&&(h.x=d.x,h.y=d.y,h.z=d.z,this._place(h.panner,d.x,d.y??0,d.z,t,!1)),h.voice.update(e,t)}}_consider(e){const t=e.x-this._lx,i=(e.y??0)-this._ly,n=e.z-this._lz;let r=t*t+i*i+n*n;const o=this._byId.get(e.id);o&&!o.dying&&(r*=.8);const a=this._slots;let l=this._slotCount;if(l===_r){if(r>=a[l-1].d)return;l=_r-1}let c=l;for(;c>0&&a[c-1].d>r;)a[c].src=a[c-1].src,a[c].d=a[c-1].d,c--;a[c].src=e,a[c].d=r,this._slotCount=l+1}_addVoice(e,t){const i=Bs[e.sound];if(!i||i.kind==="event"){this._warn("source:"+e.sound,`[ambience] "${e.sound}" cannot be a positional source`);return}const n=this.ctx,r=this._createPanner(i);r.connect(this._channel(e.sound,this._loopBus(i))),this._place(r,e.x,e.y??0,e.z,t,!0);const o=n.createGain();o.gain.value=0,o.connect(r);const a=this._start(e.sound,o,e,!0),l={id:e.id,src:e,voice:a,gain:o,panner:r,base:this._baseGain(e.sound,a),level:0,x:e.x,y:e.y,z:e.z,dying:!1,stopAt:0,seen:this._frame};this._pool.push(l),this._byId.set(e.id,l)}_loopBus(e){return e.bus==="ambience"?this.ambienceBus:this.effectsBus}_disposeVoice(e){e.voice.dispose();try{e.gain.disconnect(),e.panner.disconnect()}catch{}}}function qx(s){const e=i=>{if(!s._enabled)return"sound is off: press M in the page, or turn Sound on in settings";if(!s.ready)return"the browser has not allowed sound yet: click or press a key in the page itself";if(!s._visible)return"the page is hidden, so sound is muted until it is visible again";for(const n of["masterVolume",zi(i)?.volume])if(n&&s._vol(n,.8)===0)return`the ${n} setting is at 0`;return null},t=async(i,n)=>{if(typeof i=="string"&&!zi(i))throw new Error(`[audio] there is no sound called "${i}"`);if(s.unlock(),s.ctx&&s._enabled&&!s.ready){const a=Promise.resolve(s.ctx.resume?.()).catch(()=>{});await Promise.race([a,new Promise(l=>setTimeout(l,500))])}const r=s.play(i,n),o=e(i);return o&&console.warn(`[audio] ${o}`),r};return new Proxy(s,{get:(i,n)=>n==="play"?t:Reflect.get(i,n)})}const Sl={select:6,"bot-ask":3,"bot-alarm":3,"bot-confirm":3,"bot-worried":3,"bot-busy":3,"bot-happy":3,"bot-sleeping":3,"bot-annoyed":3},Gx={asking:"bot-ask",done:"bot-ask",error:"bot-worried",working:"bot-busy",delegating:"bot-busy",celebrating:"bot-happy",sleeping:"bot-sleeping"},Gf={asking:"bot-ask",done:"bot-ask",error:"bot-alarm",working:"bot-confirm"};Object.entries(Sl).flatMap(([s,e])=>Array.from({length:e},(t,i)=>`${s}-${i+1}`));function Zf(s){return Object.hasOwn(Gf,s)}function Zx(s=Math.random){let e=null;const t=i=>{const n=Sl[i];let r=1+Math.floor(s()*n);return`${i}-${r}`===e&&(r=r%n+1),e=`${i}-${r}`,e};return{reply:i=>t(Gx[i]??"select"),call:i=>Zf(i)?t(Gf[i]):null,annoyed:()=>t("bot-annoyed"),say:i=>Object.hasOwn(Sl,i)?t(i):null}}const Xx=5,Xf=4;function Yx({clicks:s=Xx,linger:e=Xf}={}){let t={id:null,count:0};const i=new Map,n=(r,o)=>(i.get(r)??-1/0)>o;return{poke(r,o){return i.has(r)&&!n(r,o)&&(i.delete(r),t.id===r&&(t={id:r,count:0})),t.id!==r&&(t={id:r,count:0}),t.count+=1,t.count>=s&&i.set(r,o+e),n(r,o)},interrupt(){t={id:null,count:0}},annoyed:n}}function $l(s,e){if(s===e)return!0;if(Array.isArray(s)&&Array.isArray(e))return s.length===e.length&&s.every((t,i)=>$l(t,e[i]));if(s&&e&&typeof s=="object"&&typeof e=="object"){const t=Object.keys(s),i=Object.keys(e);return t.length===i.length&&t.every(n=>$l(s[n],e[n]))}return!1}const Ua=s=>Array.isArray(s)?s:[],_n=s=>s&&typeof s=="object"&&!Array.isArray(s)?s:{};function ja(s,e,t){const i=new Set(Ua(s)),n=new Set(Ua(e)),r=new Set([...i].filter(l=>!n.has(l))),o=[],a=new Set;for(const l of Ua(t))r.has(l)||a.has(l)||(a.add(l),o.push(l));for(const l of n)i.has(l)||a.has(l)||(a.add(l),o.push(l));return o}function fn(s,e,t){const i=_n(s),n=_n(e),r={..._n(t)};for(const[o,a]of Object.entries(n))o in i&&$l(i[o],a)||(r[o]=a);for(const o of Object.keys(i))o in n||delete r[o];return r}function Qx(s,e){const t={..._n(e)};for(const[i,n]of Object.entries(_n(s)))t[i]=Math.max(Number(t[i])||0,Number(n)||0);return t}function Kx(s,e,t){const i=s||{},n=e||{},r=t||{};return{version:r.version??n.version??2,archived:ja(i.archived,n.archived,r.archived),archivedAt:fn(i.archivedAt,n.archivedAt,r.archivedAt),opened:ja(i.opened,n.opened,r.opened),plots:fn(i.plots,n.plots,r.plots),otherPlots:fn(i.otherPlots,n.otherPlots,r.otherPlots),seen:fn(i.seen,n.seen,r.seen),hiddenProjects:ja(i.hiddenProjects,n.hiddenProjects,r.hiddenProjects),viewedAt:fn(i.viewedAt,n.viewedAt,r.viewedAt),trinkets:Qx(n.trinkets,r.trinkets),districts:(Number(n.districts)||0)!==(Number(i.districts)||0)?Number(n.districts)||0:Number(r.districts)||0,settings:n.settings&&typeof n.settings=="object"?n.settings:r.settings??null}}async function mi(s,e){const t=await fetch(s,e),i=await t.json().catch(()=>({}));if(!t.ok)throw new Error(i.error||`${t.status} ${t.statusText}`);return i}const Yn=(s,e)=>mi(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),Jx=()=>mi("/api/threads"),e7=()=>mi("/api/threadgauge"),t7=()=>mi("/api/threadgauge/contexts"),Yf=()=>mi("/api/license"),s7=()=>mi("/api/pro"),i7=s=>Yn("/api/license",{key:s}),n7=()=>Yn("/api/license/renew",{});let Qf=0,Al=null;function El(s,e){Qf=Number(e??s?.updatedAt)||0,Al=structuredClone(s)}const r7=async()=>{const s=await mi("/api/state");return El(s),s},o7=3;async function a7(s){if(Al===null)throw new Error("Refusing to save a colony that was never read");let e=s;for(let t=0;t<o7;t++){const i=await fetch("/api/state",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,baseUpdatedAt:Qf})}),n=await i.json().catch(()=>({}));if(i.status===409){e=Kx(Al,e,n),El(n);continue}if(!i.ok)throw new Error(n.error||`${i.status} ${i.statusText}`);return El(e,n.updatedAt),e}throw new Error("Could not save the colony — another tab kept writing first")}const l7=(s,e)=>Yn("/api/open",{harness:s.harness,ref:s.ref,via:e}),c7=(s,e,t)=>Yn("/api/new-session",{folder:s,harness:e,via:t}),h7=s=>Yn("/api/reveal",{folder:s}),d7=(s,e)=>`${s}:errand:${e}`;function u7(s){const e=[];for(const t of s||[]){const i=t.subagents||[];e.push(i.length?{...t,subagents:void 0}:t);for(const n of i)!n||!n.id||e.push({...t,id:d7(t.id,n.id),title:n.task||"Errand",preview:"",subagents:void 0,parentId:t.id,lastActivityAt:n.lastActivityAt??t.lastActivityAt,running:!0,unread:!1,needsInput:!1,awaitingSubagents:!1,hasError:!1,prState:null,archived:!1,hasTranscript:!1,sizeBytes:0,canOpen:!1,ref:null})}return e}const cu=s=>{const e=String(s||"").replace(/^\\\\\?\\(?=[A-Za-z]:)/,"").replace(/\\/g,"/").replace(/\/+$/,"");return/^[A-Za-z]:\//.test(e)?e.toLowerCase():e};function f7(s,e,t){const i=cu(e);if(!i)return t;const n=s.filter(o=>{const a=cu(o.cwd);return a===i||a.startsWith(`${i}/`)}),[r]=n.sort((o,a)=>+!!o.archived-+!!a.archived||(o.createdAt||0)-(a.createdAt||0));return r?.title||String(e).split(/[\\/]/).filter(Boolean).pop()||t}const hu=864e5,p7="state sheet",Pl=["working","delegating","asking","done","error","celebrating","idle","sleeping"],m7={working:"Working",delegating:"Waiting on agents",asking:"Needs you",done:"Done",error:"Error",celebrating:"Shipped",idle:"Idle",sleeping:"Dormant"},g7={working:{running:!0},delegating:{awaitingSubagents:!0},asking:{needsInput:!0},done:{unread:!0},error:{hasError:!0},celebrating:{prState:"MERGED"}},zl=s=>`state-sheet:${s}`;function Kf(s=Date.now()){return Pl.map((e,t)=>({id:zl(e),harness:"state-sheet",harnessName:"State sheet",title:m7[e],preview:"",project:p7,projectPath:"",worktree:"",cwd:"",gitBranch:"",model:"",createdAt:s-hu+t*1e3,lastActivityAt:e==="sleeping"?s-4*hu:s-6e4,lastFocusedAt:0,running:!1,unread:!1,needsInput:!1,awaitingSubagents:!1,hasError:!1,prState:null,archived:!1,sizeBytes:4e5,canOpen:!1,...g7[e]}))}function Jf(s,e){const t={};for(const n of e)t[n]=(t[n]??0)+1;const i=[];for(const[n,r]of Object.entries(s)){const o=n==="agents"?e.length:ac(n).reduce((a,l)=>a+(t[l]??0),0);r!==o&&i.push({key:n,shown:r,bots:o})}return i}const w7={quiet:"idle"},$r=48,ep=new Set(["working","delegating","asking","done","error","celebrating"]),b7=16,v7=s=>[1,3,5].map(e=>parseInt(s.slice(e,e+2),16)),y7=s=>"#"+s.map(e=>e.toString(16).padStart(2,"0")).join("");function tp(s=document){return Object.fromEntries([...s.querySelectorAll(".stats .stat")].map(e=>[e.dataset.key,Number(e.querySelector(".n").textContent)]))}function sp(s){return s.astronauts.agents.filter(e=>e.status!=="leaving"&&e.state!=="gone")}function ip(s,e,t,i,n){return n.set(e,t,i),ai(n),n.project(s.camera)}function C7(s,e){s.composer.render();const t=s.renderer.getContext(),i=t.drawingBufferWidth,n=t.drawingBufferHeight,r=new Uint8Array(i*n*4);t.readPixels(0,0,i,n,t.RGBA,t.UNSIGNED_BYTE,r);const o=new F,a=[];for(const l of e){const c=ot[l.status];if(!ep.has(l.status)||l.badgeY===void 0)continue;if(ip(s,l.pos.x,l.badgeY,l.pos.z,o),Math.abs(o.x)>1||Math.abs(o.y)>1||o.z>1){a.push({id:l.id,status:l.status,want:c,shown:null,exact:0});continue}const h=Math.round((o.x*.5+.5)*i),d=Math.round((o.y*.5+.5)*n),u=v7(c);let f=null,p=1/0,m=0;for(let g=Math.max(0,d-$r);g<=Math.min(n-1,d+$r);g++)for(let w=Math.max(0,h-$r);w<=Math.min(i-1,h+$r);w++){const b=(g*i+w)*4,y=Math.hypot(r[b]-u[0],r[b+1]-u[1],r[b+2]-u[2]);y===0&&m++,y<p&&(p=y,f=[r[b],r[b+1],r[b+2]])}a.push({id:l.id,status:l.status,want:c,shown:y7(f),exact:m})}return a}function np({engine:s,colony:e}){const t=sp(e);return{mismatches:Jf(tp(),t.map(i=>i.status)),badges:C7(s,t)}}function x7({engine:s,colony:e,rig:t,root:i=document.body}){const n=document.createElement("div");n.className="state-sheet",n.innerHTML='<div class="state-sheet-head"><b>State sheet</b><button class="btn" type="button">Check colors</button></div><table><thead><tr><th></th><th>HUD</th><th>bots</th><th>badge</th></tr></thead><tbody></tbody></table>',i.appendChild(n);const r=n.querySelector("tbody"),o=document.createElement("div");o.className="state-sheet-labels",s.canvas.after(o);const a=new Map(Pl.map(f=>{const p=document.createElement("div");return p.className=`state-sheet-label ${f==="sleeping"?"idle":f}`,p.textContent=f,o.appendChild(p),[zl(f),p]}));let l=new Map,c=0;const h=new F;function d(){const f=Pl.map(g=>e.astronauts.byId.get(zl(g))).filter(g=>g&&ep.has(g.status));if(!f.length)return;const p=f.reduce((g,w)=>g+w.pos.x,0)/f.length,m=f.reduce((g,w)=>g+w.pos.z,0)/f.length;t.desiredTarget.set(p,0,m),t.desiredDistance=b7,t.desiredPolar=1,t.settle()}function u(){const f=sp(e),p=tp(),m=new Map(Jf(p,f.map(g=>g.status)).map(g=>[g.key,g]));r.innerHTML=[...document.querySelectorAll(".stats .stat")].map(g=>{const w=g.dataset.key,b=w7[w]??w,y=ot[b]?`<i style="background:var(--${b})"></i>`:"<i></i>",C=m.get(w),_=l.get(b),x=_?_.every(T=>T.exact>0)?"exact":_.map(T=>T.shown??"off screen").join(" "):"";return`<tr class="${C?"off":""}"><td>${y}${g.querySelector(".lbl").textContent}</td><td>${p[w]}</td><td>${C?C.bots:p[w]}</td><td>${x}</td></tr>`}).join("")}return n.querySelector("button").addEventListener("click",()=>{d(),l=new Map;for(const f of np({engine:s,colony:e}).badges)l.set(f.status,[...l.get(f.status)??[],f]);u()}),d(),{update(f,p){p>=c&&(c=p+1,u());const m=s.canvas.getBoundingClientRect(),g=o.getBoundingClientRect();for(const[w,b]of a){const y=e.astronauts.byId.get(w);if(!y||y.state==="gone"){b.style.display="none";continue}ip(s,y.pos.x,y.pos.y,y.pos.z,h),b.style.display=h.z>1?"none":"",b.style.transform=`translate(${(m.left-g.left+(h.x*.5+.5)*m.width).toFixed(1)}px, ${(m.top-g.top+(-h.y*.5+.5)*m.height).toFixed(1)}px) translate(-50%, 6px)`}}}}const M7=5e3,k7=3600*1e3,T7=30*1e3,_7=5*1e3,S7=document.title,dc=document.getElementById("app");await new Promise(s=>{requestAnimationFrame(()=>setTimeout(s)),setTimeout(s,100)});const ae=new Sm,Hs=new URLSearchParams(location.search).has("sheet"),rp=!1,Us={proThrough:0};let hi={proThrough:Us.proThrough,renewalDue:!1};hi=await Yf().catch(()=>hi);Us.proThrough=hi.proThrough;let qa=null,Ll="";function uc(){return Hs?Promise.resolve(!1):(qa??=s7().then(s=>s?.ready?vm(()=>import("./pro-CzWQdIWB.js"),__vite__mapDeps([0,1])):Promise.reject(new Error(s?.error||"unavailable"))).then(s=>(s.installProWorlds(),Ll="",ae.held.planet&&ae.set("planet",ae.held.planet),!0)).catch(s=>(qa=null,Ll=m5(s.message),!1)),qa)}Us.proThrough>0&&await uc();(Hs||rp)&&(ae.saving=!1);const $7=window.matchMedia("(max-width: 600px)").matches||window.matchMedia("(pointer: coarse)").matches&&window.innerWidth<900,op=!Am();op&&ae.applyPreset($7?"low":ym);ae.allow=c5(ae,Us,Wt,kf);ae.set("planet",ae.get("planet"));gm();const ce=new Hm(ae).mount(dc);ce.setPlanetGrade(Wt[ae.get("planet")]?.grade);const oe=new e1(ce.camera,ce.canvas,ae),pn=by(ce),I=new t5(ce.scene,ae,ce.camera,ce.renderer);I.sceneTarget=()=>ce.sceneTarget();oe.groundAt=(s,e)=>I.groundAt(s,e);let Me={archived:[],archivedAt:{},opened:[],plots:{},seen:{},hiddenProjects:[],viewedAt:{},trinkets:{}},Qe=[],ti=[],du="",Ie=null,ht=null;const A7=Z6();let uu=0,ap=!1;const ki={busy:!1,tick:0};let Rn=0;const E7=new F,rt={worldOpen:s=>dl(s,Us),chooseWorld:async s=>{if(!Wt[s]&&!await uc())return Z.toast(Ll,"err");ae.set("planet",s)},orgAccent:s=>I.orgAccent(s),districtOf:s=>I.districtOf(s),hoverOrg:s=>I.setHoveredOrg(s),hoverProject:s=>I.setHoveredPlot(s?I.plots.get(s):null),activateLicense:async s=>{const e=await i7(s).catch(()=>({...hi,error:"offline"}));return lp({proThrough:e.proThrough,renewalDue:e.renewalDue}),e},viewportChanged:({width:s,height:e,right:t,bottom:i,left:n,top:r,visible:o})=>{oe.setViewportInsets(s,e,{right:t,bottom:i,left:n,top:r},{visible:o}),ce.tiltShift?.setCamera(ce.camera)},resetView:()=>{oe.following&&mt(null,{}),oe.resetView(I.middle,I.footprint())},screenshot:()=>{ce.renderFrame(),Mu(ce.canvas.toDataURL("image/png"),`threadnauts-${I.planet.id}-${ku()}.png`),Z.toast("Screenshot saved")},record:async()=>{if(!ki.busy){ki.busy=!0;try{if(pn.recording){clearInterval(ki.tick),Z.setRecording(!1),Z.toast("Saving video…");const{blob:s,extension:e}=await pn.stop(),t=URL.createObjectURL(s);Mu(t,`threadnauts-${I.planet.id}-${ku()}.${e}`),setTimeout(()=>URL.revokeObjectURL(t),6e4),Z.toast("Video saved")}else await pn.start(ae.get("sound")?Cs.recordingStream():null),Z.setRecording(!0),Z.hint("Recording — press R again to stop"),ki.tick=setInterval(()=>{Z.setRecordTime(pn.seconds),pn.seconds>=py&&rt.record()},250)}catch(s){console.error(s),clearInterval(ki.tick),Z.setRecording(!1),Z.toast("Could not record a video in this browser","err")}finally{ki.busy=!1}}},toggleOrbit:()=>{const s=oe.toggleOrbit();return Z.hint(s?"Orbit mode on — drag or press O to stop":"Orbit mode off"),s},cyclePlanet:()=>{const s=um.filter(t=>dl(t,Us)&&Wt[t]),e=s[(s.indexOf(ae.get("planet"))+1)%s.length];ae.set("planet",e),Z.hint(`${Wt[e].name} — ${Wt[e].blurb}`)},cycleTime:()=>{ae.set("autoTime",!1),ae.set("clockTime",!1);const s=ae.get("timeOfDay"),e=Oi.find(t=>t.value>s+.005)||Oi[0];ae.set("timeOfDay",e.value),Z.hint(e.label)},focusStatus:s=>{const e=A7(I.astronauts.agents,s,Date.now());if(!e){Z.hint(j6[s]||`Nobody is ${s} right now`);return}mt(e.id,{fly:!0})},focusProject:s=>{const e=I.plots.get(s);e&&(oe.following&&mt(null,{}),oe.focus(e.middle||e.center,{distance:30}))},pickProject:s=>hp(s,{fly:!0}),closeProject:()=>{ht=null,mt(null,{}),Fn()},select:s=>mt(s,{}),focusThread:s=>mt(s,{fly:!0}),newConversation:async()=>{const s=ht,e=s&&Nr(s);if(!e){Z.toast("No folder on disk for that project","err");return}try{const t=R7(s),i=await c7(e,t,ae.get("openIn")),n=L7(t);Z.toast(`New thread in ${s} — ${i.via==="terminal"?`${n} in a terminal`:`opening ${n}`}`),setTimeout(oi,6e3)}catch(t){Z.toast(t.message||"Could not start a thread there","err")}},revealProject:async()=>{const s=ht&&Nr(ht);if(s)try{await h7(s)}catch(e){Z.toast(e.message||"Could not open that folder","err")}},markViewed:()=>{const s=Qe.find(e=>e.id===Ie);s&&(Me.viewedAt={...Me.viewedAt||{},[s.id]:Date.now()},bs(),ws(Qe),Z.toast(`Marked ${s.title.slice(0,40)} as viewed`))},hideProject:()=>{const s=ht;s&&(Me.hiddenProjects=H3(Me.hiddenProjects||[],s),bs(),Ie&&Qe.find(t=>t.id===Ie)?.project===s&&mt(null,{}),ht=null,ws(Qe),Z.toast(`Hidden ${s} — still in your harness, gone from the colony`,"",{label:"Undo",run:()=>rt.unhideProject(s)}))},unhideProject:s=>{s&&(Me.hiddenProjects=U3(Me.hiddenProjects||[],s),bs(),ws(Qe),Z.toast(`Showing ${s} again`))},copyProjectPath:async()=>{const s=ht&&Nr(ht);if(s)try{await navigator.clipboard.writeText(s),Z.toast("Path copied")}catch{const e=X7(s);Z.toast(e?"Path copied":"Could not reach the clipboard",e?"":"err")}},openThread:async()=>{const s=Qe.find(e=>e.id===Ie);if(s)try{const e=await l7(s,ae.get("openIn"));I.astronauts.celebrate(s.id);const t=s.harnessName||"your harness";Z.toast(e.via==="terminal"?`Opened ${t} in a terminal`:`Opened in ${t}`),setTimeout(oi,1800)}catch(e){Z.toast(e.message||"Could not open that thread","err")}},archiveThread:()=>{const s=Qe.find(e=>e.id===Ie);s&&(Me.archived=[...new Set([...Me.archived,s.id])],Me.archivedAt={...Me.archivedAt,[s.id]:Date.now()},bs(),mt(null,{}),ws(Qe),Z.toast("Archived — heading home"),I.ship.ping())},uiVisibility:s=>I.setUiVisible(s)},Cs=new jx(ae);Cs.setPlanet(I.planet);I.onSound=(s,e,t,i)=>Cs.play(s,{x:e,y:t,z:i,kind:I.fauna.flock?.kind});const Z=new SC(dc,ae,rt);Z.setLicense(hi);const _o=new hx(dc);function lp(s){hi=s,Us.proThrough=s.proThrough,ae.set("planet",ae.held.planet??ae.get("planet")),Us.proThrough>0&&uc(),Z.setLicense(hi),Z.syncSettings()}async function Ga(){if(Hs)return;const s=await e7().catch(()=>null);Z.setThreadgauge(s?.url??null),fc()}let Rl={};async function fc(){if(Hs||!Ie||!Z.hasThreadgauge)return;Rl=(await t7().catch(()=>null))?.contexts||{},Z.setContext(Ie?Rl[Ie]:null)}async function fu(){let s=await Yf().catch(()=>null);s?.renewalDue&&(s=await n7().catch(()=>s)),s&&lp(s)}I.onWorldStage=s=>{_o.show(s),Rn=s.build,s.stage==="landing"?z7(s.build):ce.stop()};function P7(){ce.renderFrame(),_o.holdFrame(ce.canvas)}async function z7(s){ce.start(),await pu(),await pu(),Rn===s&&(Rn=0,_o.hide())}function pu(){return new Promise(s=>requestAnimationFrame(s))}const Bn=Zx(),Gi=Yx();window.addEventListener("keydown",()=>Gi.interrupt(),!0);window.addEventListener("wheel",()=>Gi.interrupt(),{capture:!0,passive:!0});window.addEventListener("pointerdown",s=>{s.target!==ce.canvas&&Gi.interrupt()},!0);function mu(s){const e=Gi.poke(s.id,performance.now()/1e3);return e&&I.astronauts.annoy(s.id,Xf),e}function pc(s,e,t){const i=s.acting?.voicePitch??1,n=Cs.speak(s.id,e,{x:s.pos.x,y:s.pos.y+t,z:s.pos.z,gain:.9,pitch:i});n?.syllables&&I.astronauts.speak(s.id,n.syllables)}let gu=0;I.astronauts.onSay=(s,e)=>{const t=Date.now(),i=Bn.say(e);!i||t-gu<2500||(gu=t,pc(s,i,1))};I.astronauts.onMachine=(s,e,t)=>{Cs.play(e,{x:s.pos.x,y:s.pos.y+.6,z:s.pos.z,...t})};I.astronauts.onTrinket=(s,e)=>{Me.trinkets={...Me.trinkets||{},[s]:Math.max(Me.trinkets?.[s]??0,e)},bs()};function cp(s,e=!1){const t=Qe.find(r=>r.id===s.id)||s.thread,i=t?An(t):"idle",n=e?Bn.annoyed():Bn.reply(i);pc(s,n,.8)}function mt(s,{fly:e=!1,zoomIn:t=!1,voice:i=!0,annoyed:n=!1}={}){Ie=s;const r=s?I.agentFor(s):null;if(!r){Ie=null,oe.setFollow(null),I.astronauts.setSelected(null),Z.setSelection(null,null),Fn();return}I.astronauts.setSelected(r);const o=Qe.find(a=>a.id===s)||r.thread;Z.setSelection(r,o),Z.setContext(Rl[s]),fc(),i&&cp(r,n),o?.project&&I.plots.has(o.project)&&(ht=o.project),Fn(),e&&oe.focus(new F(r.pos.x,r.pos.y+Vu,r.pos.z),{distance:t?wn:Math.min(oe.desiredDistance,26),keepHeight:!0}),oe.setFollow(ae.get("followSelected")?r:null)}function hp(s,{fly:e=!1}={}){if(!s||!I.plots.has(s))return;ht=s;const t=Qe.find(i=>i.id===Ie);t&&t.project!==s?mt(null,{}):Fn(),e&&rt.focusProject(s)}function L7(s){for(const e of I.threads.values())if(e.harness===s&&e.harnessName)return e.harnessName;return"your harness"}function R7(s){const e=new Map;for(const n of I.threads.values())n.project!==s||!n.harness||e.set(n.harness,(e.get(n.harness)??0)+1);let t="",i=0;for(const[n,r]of e)r<=i||(t=n,i=r);return t}function Nr(s){const e=new Map;for(const n of I.threads.values()){if(n.project!==s)continue;const r=n.projectPath||n.cwd;r&&e.set(r,(e.get(r)??0)+1)}let t="",i=0;for(const[n,r]of e)r<=i||(t=n,i=r);return t}function Fn(){const s=(o,a)=>G3(o,Qe).map(l=>({...l,off:a,org:Ul(Qe,l.name)})),e=[...s(Me.hiddenProjects||[],"hidden"),...s([...I.dormantProjects||[]],"quiet")],t=l0([...ti,...e],{everyOrg:!0});for(const o of[...ti,...e])o.label=t.get(o.name);const i=ht?I.plots.get(ht):null;if(I.setSelectedPlot(i),!i){ht=null,Z.setProject(null),Z.setLegend(ti,null,e);return}const n=Date.now(),r=[...I.threads.values()].filter(o=>o.project===i.name).map(o=>({id:o.id,title:o.title,worktree:o.worktree,lastActivityAt:o.lastActivityAt,status:An(o,n)})).sort((o,a)=>cl.indexOf(o.status)-cl.indexOf(a.status)||(a.lastActivityAt??0)-(o.lastActivityAt??0));Z.setProject({name:i.name,accent:i.accent,org:ti.find(o=>o.name===i.name)?.org??null,label:ti.find(o=>o.name===i.name)?.label??i.name,path:Nr(i.name),threads:r,selectedId:Ie}),Z.setLegend(ti,ht,e)}const Ks=new F,wu=new F,bu=new F;function B7(s){if(ai(Ks.set(s.pos.x,s.pos.y+.95,s.pos.z)),bu.setFromMatrixColumn(ce.camera.matrixWorld,0).normalize(),wu.copy(Ks).addScaledVector(bu,w3).project(ce.camera),Ks.project(ce.camera),Ks.z>1)return null;const{w:e,h:t}=ce.viewport;return{x:(Ks.x*.5+.5)*e,y:(-Ks.y*.5+.5)*t,reach:Math.abs(wu.x-Ks.x)*e/2}}const F7=12;function mc(s){const e=ce.canvas.getBoundingClientRect();return{x:(s.clientX-e.left)/e.width*2-1,y:-((s.clientY-e.top)/e.height)*2+1,aspect:e.width/e.height,reach:2*F7/e.height}}ce.canvas.addEventListener("pointermove",s=>{if(oe.interacting){ce.canvas.style.cursor=oe._mode==="orbit"?"move":"grabbing";return}const e=mc(s),t=I.pick(e.x,e.y,e.aspect,e.reach);t?.id,I.astronauts.setHover(t);const i=gc(s,e);I.setHoveredPlot(i),ce.canvas.style.cursor=t?"pointer":"grab"});function gc(s,e){const t=I.pickLabel(e.x,e.y);if(t&&t.label.material.opacity>.3)return t;const i=oe.groundPoint(s.clientX,s.clientY,E7),n=oe.pointerRay(s.clientX,s.clientY);return n&&I.plotOnRay(n,i?n.origin.distanceTo(i):1/0)||(i?I.plotAt(i.x,i.z):null)||t}const O7=250,I7=10,D7=1.1,dp=3902034,V7=9974836,up=5220454,N7=12074815,O={timer:0,candidate:null,startX:0,startY:0,lifted:!1,name:null,cells:null,grab:null,dq:0,dr:0,turns:0,wheel:0,valid:!0,plan:null,swallowClick:!1,ghost:null,pendingThreads:null},Wr=new F;function vu(s,e){const t=o=>{const a=Math.PI/6+o*Math.PI/3;return new Se(s*Math.sin(a),s*Math.cos(a))},i=(o,a,l)=>o.clone().lerp(a,Math.min(l/o.distanceTo(a),.5)),n=new pm;for(let o=0;o<6;o++){const a=t((o+5)%6),l=t(o),c=t((o+1)%6),h=i(l,a,e),d=i(l,c,e);o===0?n.moveTo(h.x,h.y):n.lineTo(h.x,h.y),n.quadraticCurveTo(l.x,l.y,d.x,d.y)}n.closePath();const r=new mm(n,6);return r.rotateX(-Math.PI/2),r}function W7(s){const e=vu(pt*.94,pt*.1),t=vu(pt*.9,pt*.096),i=new dt({color:dp,transparent:!0,opacity:.38,depthWrite:!1}),n=new dt({color:up,transparent:!0,opacity:.85,depthWrite:!1}),r=new Pt,o=[];for(let a=0;a<s;a++){const l=new ke(e,n),c=new ke(t,i);c.position.y=.01,l.add(c),o.push(l),r.add(l)}ce.scene.add(r),O.ghost={group:r,meshes:o,material:i,rim:n,geometry:e,inner:t}}function fp(){const{meshes:s}=O.ghost;Hl(O.cells,O.dq,O.dr,{turns:O.turns,pivot:O.grab}).forEach((e,t)=>{const{x:i,z:n}=Vi(e.q,e.r);s[t].position.set(i,$t+.12,n)}),O.ghost.material.color.setHex(O.valid?dp:V7),O.ghost.rim.color.setHex(O.valid?up:N7)}function H7(){O.ghost&&(ce.scene.remove(O.ghost.group),O.ghost.geometry.dispose(),O.ghost.inner.dispose(),O.ghost.material.dispose(),O.ghost.rim.dispose(),O.ghost=null)}function Qn(){clearTimeout(O.timer),O.timer=0,O.candidate=null,O.lifted||(oe.suppressed=!1)}function U7(){O.timer=0;const s=I.plots.get(O.candidate);if(O.candidate=null,!s)return;O.lifted=!0,O.name=s.name,O.cells=s.cells;const e=oe.groundPoint(O.startX,O.startY,Wr);O.grab=e?Cn(e.x,e.z):{...s.cells[0]},O.dq=0,O.dr=0,O.turns=0,O.wheel=0,O.valid=!0,oe.suppressed=!0,I.setPlotLift(O.name,D7),W7(O.cells.length),fp(),ce.canvas.style.cursor="grabbing"}function So(s){I.setPlotLift(O.name,0),H7(),s&&O.plan&&I.applyLayout(O.plan);const e=O.pendingThreads;O.lifted=!1,O.pendingThreads=null,O.name=null,O.cells=null,O.grab=null,O.plan=null,O.turns=0,O.wheel=0,(s||e)&&ws(e||Qe),ce.canvas.style.cursor="grab"}ce.canvas.addEventListener("pointerdown",s=>{if(O.timer&&Qn(),O.lifted){So(!1),O.swallowClick=!0;return}if(s.button!==0||s.ctrlKey||s.shiftKey||s.altKey||s.metaKey)return;const e=mc(s);if(I.pick(e.x,e.y,e.aspect,e.reach))return;const t=gc(s,e);!t||!oe.inView(n0(t.cells))||(O.candidate=t.name,O.startX=s.clientX,O.startY=s.clientY,O.timer=setTimeout(U7,O7),oe.suppressed=!0)});window.addEventListener("pointermove",s=>{if(O.timer&&Math.hypot(s.clientX-O.startX,s.clientY-O.startY)>I7&&Qn(),!O.lifted||!oe.groundPoint(s.clientX,s.clientY,Wr))return;const e=Cn(Wr.x,Wr.z),t=e.q-O.grab.q,i=e.r-O.grab.r;t===O.dq&&i===O.dr||(O.dq=t,O.dr=i,pp())});function pp(){O.plan=Tg(I.visibleLayout(),O.name,O.dq,O.dr,{turns:O.turns,pivot:O.grab}),O.valid=!!O.plan,fp()}const j7=50;window.addEventListener("wheel",s=>{if(!O.lifted)return;s.preventDefault(),s.stopPropagation();const e=s.deltaMode===1?16:s.deltaMode===2?100:1;O.wheel+=s.deltaY*e,!(Math.abs(O.wheel)<j7)&&(O.turns+=O.wheel<0?1:-1,O.wheel=0,pp())},{capture:!0,passive:!1});window.addEventListener("pointerup",()=>{O.timer&&Qn(),O.lifted&&So(O.valid&&(O.dq!==0||O.dr!==0||O.turns%6!==0)),O.swallowClick=!1});window.addEventListener("pointercancel",()=>{O.timer&&Qn(),O.lifted&&So(!1)});let lo=null,mn=null;ce.canvas.addEventListener("pointerup",s=>{lo=s.button===0&&oe.wasClick&&!O.lifted&&!O.swallowClick?s:null,lo||Gi.interrupt()});ce.canvas.addEventListener("click",s=>{const e=lo;if(lo=null,!e)return;if(s.detail>=2){if(!mn)return;const r=mu(mn);s.detail===2&&mt(mn.id,{fly:!0,zoomIn:!0,voice:!1}),r&&cp(mn,!0);return}const t=mc(e),i=I.pick(t.x,t.y,t.aspect,t.reach);if(mn=i,i){I.astronauts.notice(i.id),mt(i.id,{annoyed:mu(i)});return}Gi.interrupt(),Ie&&mt(null,{});const n=gc(e,t);n?hp(n.name,{}):rt.closeProject()});ce.canvas.addEventListener("pointerleave",()=>{I.astronauts.setHover(null),I.setHoveredPlot(null)});window.addEventListener("keydown",s=>{const e=s.target;if(!(e instanceof HTMLInputElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement)){if((s.metaKey||s.ctrlKey)&&s.key==="\\"){s.preventDefault(),Z.toggleUi();return}if(!(s.metaKey||s.ctrlKey||s.altKey))switch(s.key){case"h":case"H":Z.toggleUi();break;case"s":case"S":Z.toggleSettings();break;case"n":case"N":rt.focusStatus("wanted");break;case"p":case"P":rt.screenshot();break;case"r":case"R":rt.record();break;case"l":case"L":rt.cycleTime();break;case"o":case"O":Z.setOrbit(rt.toggleOrbit());break;case"m":case"M":ae.set("sound",!ae.get("sound")),Z.hint(ae.get("sound")?"Sound on":"Muted");break;case"Tab":s.preventDefault(),rt.cyclePlanet();break;case"0":rt.resetView(),Z.setOrbit(!1);break;case"Enter":Ie&&rt.openThread();break;case"a":case"A":Ie&&rt.archiveThread();break;case"v":case"V":Ie&&rt.markViewed();break;case"c":case"C":ht&&rt.newConversation();break;case"?":Z.toggleHelp();break;case"ArrowUp":case"ArrowDown":case"ArrowLeft":case"ArrowRight":{s.preventDefault();const t=oe.distance*.09,i=new F(Math.sin(oe.azimuth),0,Math.cos(oe.azimuth)),n=new F(i.z,0,-i.x);s.key==="ArrowUp"&&oe.desiredTarget.addScaledVector(i,-t),s.key==="ArrowDown"&&oe.desiredTarget.addScaledVector(i,t),s.key==="ArrowLeft"&&oe.desiredTarget.addScaledVector(n,-t),s.key==="ArrowRight"&&oe.desiredTarget.addScaledVector(n,t),oe._clampTarget(),oe.idleFor=0;break}case"+":case"=":oe.desiredDistance=Math.max(4,oe.desiredDistance*.82);break;case"-":case"_":oe.desiredDistance=Math.min(150,oe.desiredDistance*1.22);break;case"Escape":O.lifted||O.timer?(Qn(),O.lifted&&(So(!1),O.swallowClick=!0)):Z.upgradeOpen?Z.closeUpgrade():document.querySelector(".help.open")?Z.toggleHelp(!1):Ie?mt(null,{}):ht&&rt.closeProject();break}}});function ws(s){if(O.lifted){O.pendingThreads=s;return}s=u7(s);const e=Me.viewedAt||{};Qe=s.map(h=>{const d=e[h.id];return d&&h.lastActivityAt<=d?{...h,unread:!1}:h}),s=Qe;const t=new Set(Me.archived),i=new Set(Me.hiddenProjects||[]),n=new Set(Object.keys(Me.seen||{}));let r=!1;for(const h of s)Me.seen?.[h.id]||(Me.seen={...Me.seen||{},[h.id]:Date.now()},r=!0);r&&bs();const o=ae.get("districts")?1:0;if(o!==(Me.districts?1:0)){const h=Me.otherPlots||{};Me.otherPlots=I.layoutForSave(),Me.districts=o,I.restoreLayout(h),I.arrangeDistricts=Object.keys(h).length===0,bs()}const a=I.setThreads(s,t,i,n);if(Z.setStats(a),q7(s,t,i),ti=I.plotOrder.map(h=>({name:h.name,accent:h.accent,count:s.filter(d=>!d.archived&&!t.has(d.id)&&d.project===h.name).length,urgent:I.urgentPlots?.has(h.id)??!1,org:Ul(s,h.name)})).sort((h,d)=>d.count-h.count),Ie){const h=I.agentFor(Ie);h?Z.setSelection(h,s.find(d=>d.id===Ie)||h.thread):mt(null,{})}Fn();const l=I.layoutForSave(),c=JSON.stringify(l);c!==du&&(du=c,Me.plots=l,bs())}const Za=new Map;let yu=!1,Cu=0;function q7(s,e,t){const i=Date.now(),n=new Map;for(const r of s){if(e.has(r.id)||t.has(r.project))continue;const o=An(r,i);Zf(o)&&n.set(r.id,o)}if(yu){const r=[...n].filter(([o,a])=>Za.get(o)!==a);r.sort(([,o],[,a])=>(o==="working")-(a==="working"));for(const[o,a]of r){if(i-Cu<2500)break;Cu=i;const l=I.agentFor(o);l?pc(l,Bn.call(a),1):Cs.play(Bn.call(a),{gain:.9})}}yu=!0,Za.clear();for(const[r,o]of n)Za.set(r,o)}let Xa=!1;async function oi(){if(!Xa){Xa=!0;try{const s=Hs?{threads:Kf()}:await Jx();ws(s.threads||[]),document.title=f7(s.threads||[],s.worktreePath,S7),Z.removeBoot()}catch(s){Z.toast(s.message||"Could not reach the thread scanner","err"),Z.removeBoot()}finally{Xa=!1}}}function bs(){Hs||rp||!ap||(clearTimeout(uu),uu=setTimeout(async()=>{try{Me=await a7(Me),I.astronauts.setTrinkets(Me.trinkets)}catch{}},500))}async function G7(){const s=i=>i.then(()=>null,n=>n),[,e,t]=await Promise.all([r7().then(i=>{Me=i,I.restoreLayout(Me.plots),I.astronauts.setTrinkets(Me.trinkets),op&&Me.settings&&ae.applyAll(Me.settings),ap=!0}).catch(()=>{Z.toast("Could not read the saved colony — archiving is off until you reload","err")}),s(fm()),s(s3())]);if((e||t)&&(Z.toast("Couldn’t load the 3D models. Restart Threadnauts, or update it with npx @threadcrumbs/threadnauts@latest.","err"),console.error(e||t)),Hs&&(Me.seen=Object.fromEntries(Kf().map(i=>[i.id,1])),ae.set("planet","moon"),ae.set("autoTime",!1),ae.set("clockTime",!1),ae.set("timeOfDay",.45)),I.astronauts.setModel(i3()),e||I.onAssetsReady(),await oi(),oe.resetView(I.middle,I.footprint()),oe.settle(),Hs&&ce.add(x7({engine:ce,colony:I,rig:oe})),setInterval(oi,M7),fu(),setInterval(fu,k7),Ga(),setInterval(Ga,T7),setInterval(fc,_7),window.addEventListener("focus",oi),window.addEventListener("focus",Ga),document.addEventListener("visibilitychange",()=>{document.hidden||oi()}),!localStorage.getItem("seen-help"))Z.toggleHelp(!0),localStorage.setItem("seen-help","1");else{const i=ae.get("leftDrag")==="pan"?"Drag to move":"Drag to orbit · right-drag to move";Z.hint(`${i} · click a bot · H hides everything`,5200)}}ae.onChange((s,e)=>{Me.settings=ae.saved(),bs();const t=s.has("planet")&&!Rn;t&&P7(),(e.render||s.has("fov"))&&ce.applySettings(),s.has("planet")&&ce.setPlanetGrade(Wt[ae.get("planet")]?.grade),I.onSettingsChanged(s,e),t&&!Rn&&_o.releaseFrame(),s.has("planet")&&Cs.setPlanet(I.planet),s.has("showFps")&&Z.syncSettings(),s.has("followSelected")&&oe.setFollow(ae.get("followSelected")?I.agentFor(Ie):null),s.has("hideDormant")&&ws(Qe),s.has("districts")&&ws(Qe),s.has("maxAgents")&&ws(Qe)});ce.add({update(s,e){if(oe.setFollow(ae.get("followSelected")?I.agentFor(Ie):null),oe.update(s),cm(oe.target,oe.azimuth,ae.get("worldCurve")*hm),I.update(s,e,oe.target),ce.setFocusDistance(oe.distance),Ie){Z.updateAvatar(I.astronauts.faceTexture.image);const t=I.agentFor(Ie);t?Z.placeCard(B7(t)):mt(null,{})}Z.setFps(ce.perf,ce.viewport,`${I.astronauts.visibleCount} bots · ${I.particles.liveCount} bits`),Cs.update(s,ce.camera,Z7())}});const Ar=[],gn={level:0,points:[]},xu=Js();function Z7(){let s=0;const e=(i,n,r,o,a,l=1)=>{const c=Ar[s]||(Ar[s]={id:"",sound:"",x:0,y:0,z:0,gain:1});c.id=i,c.sound=n,c.x=r,c.y=o,c.z=a,c.gain=l,s++};for(const i of I.astronauts.agents)i.state==="at-site"&&i.status==="working"&&i.scale>.5&&e(`work:${i.id}`,"work-hammer",i.pos.x,i.pos.y+.6,i.pos.z,.9);e("ship","ship-hum",xu.x,I.ship.group.position.y+3,xu.z,.7),I.fauna.drones.forEach((i,n)=>e(`drone:${n}`,"drone-whine",i.x,i.y,i.z,i.busy?1:.35)),Ar.length=s;let t=null;if(I.planet.water&&I.planet.audio?.shore){const i=dm(I.planet),n=oe.target;gn.points=i.map(r=>({p:r,d:(r.x-n.x)*(r.x-n.x)+(r.z-n.z)*(r.z-n.z)})).sort((r,o)=>r.d-o.d).slice(0,6).map(r=>r.p),gn.level=I.planet.water.level,gn.focusX=n.x,gn.focusZ=n.z,t=gn}return{night:I.sky.nightFactor??0,sources:Ar,water:t}}ce.start();G7();window.debug={engine:ce,rig:oe,colony:I,settings:ae,hud:Z,sounds:qx(Cs),poll:oi,states:()=>np({engine:ce,colony:I}),get threads(){return Qe}};function X7(s){const e=document.createElement("textarea");e.value=s,e.setAttribute("readonly",""),e.style.cssText="position:fixed;top:0;opacity:0;pointer-events:none",document.body.appendChild(e),e.select();let t=!1;try{t=document.execCommand("copy")}catch{t=!1}return e.remove(),t}function Mu(s,e){const t=document.createElement("a");t.href=s,t.download=e,t.click()}function ku(){const s=new Date,e=t=>String(t).padStart(2,"0");return`${s.getFullYear()}${e(s.getMonth()+1)}${e(s.getDate())}-${e(s.getHours())}${e(s.getMinutes())}${e(s.getSeconds())}`}
|